@buoy-gg/mcp 7.0.63 → 7.0.64

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,9 +1,9 @@
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 l=this._buffers[s++];let u=Math.min(l.length,o.length-a);l.copy(c,a,0,u);a+=u;if(u!==l.length){this._buffers[--s]=l.slice(u)}}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 l=0;l<n.length;l++){let u=n[l];let d=s*u.x.length;let h=c*u.y.length;for(let w=0;w<u.x.length;w++){if(u.x[w]<o){d++}else{break}}for(let w=0;w<u.y.length;w++){if(u.y[w]<a){h++}else{break}}if(d>0&&h>0){i.push({width:d,height:h,index:l})}}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 l=(i-c)/n[o].y.length*8+n[o].y[c];return s*4+l*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 l=Math.abs(a-o);if(s<=c&&s<=l){return r}if(c<=l){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 l=a*s;if(c!==8){l=Math.ceil(l/(8/c))}return l}var o=n.exports=function(a,s){let c=a.width;let l=a.height;let u=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(u){let w=t.getImagePasses(c,l);for(let p=0;p<w.length;p++){this._images.push({byteWidth:i(w[p].width,d,h),height:w[p].height,lineIndex:0})}}else{this._images.push({byteWidth:i(c,d,h),height:l,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 l=this._xComparison;let u=l-1;for(let d=0;d<c;d++){let h=a[1+d];let w=d>u?s[d-l]:0;s[d]=h+w}};o.prototype._unFilterType2=function(a,s,c){let l=this._lastLine;for(let u=0;u<c;u++){let d=a[1+u];let h=l?l[u]:0;s[u]=d+h}};o.prototype._unFilterType3=function(a,s,c){let l=this._xComparison;let u=l-1;let d=this._lastLine;for(let h=0;h<c;h++){let w=a[1+h];let p=d?d[h]:0;let g=h>u?s[h-l]:0;let m=Math.floor((g+p)/2);s[h]=w+m}};o.prototype._unFilterType4=function(a,s,c){let l=this._xComparison;let u=l-1;let d=this._lastLine;for(let h=0;h<c;h++){let w=a[1+h];let p=d?d[h]:0;let g=h>u?s[h-l]:0;let m=h>u&&d?d[h-l]:0;let f=r(g,p,m);s[h]=w+f}};o.prototype._reverseFilterLine=function(a){let s=a[0];let c;let l=this._images[this._imageIndex];let u=l.byteWidth;if(s===0){c=a.slice(1,u+1)}else{c=Buffer.alloc(u);switch(s){case 1:this._unFilterType1(a,c,u);break;case 2:this._unFilterType2(a,c,u);break;case 3:this._unFilterType3(a,c,u);break;case 4:this._unFilterType4(a,c,u);break;default:throw new Error("Unrecognised filter type - "+s)}}this.write(c);l.lineIndex++;if(l.lineIndex>=l.height){this._lastLine=null;this._imageIndex++;l=this._images[this._imageIndex]}else{this._lastLine=c}if(l){this.read(l.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(l){s.push(l)},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 u=4;u<8;u++){c+=String.fromCharCode(o[u])}let l=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(!l){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 l=o[9];let u=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(!(l in t.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(u!==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=l;let w=t.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=true;this.metadata({width:a,height:s,depth:c,interlace:Boolean(h),palette:Boolean(l&t.COLORTYPE_PALETTE),color:Boolean(l&t.COLORTYPE_COLOR),alpha:Boolean(l&t.COLORTYPE_ALPHA),bpp:w,colorType:l});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,l,u){if(u===c.length){throw new Error("Ran out of data")}let d=c[u];s[l]=d;s[l+1]=d;s[l+2]=d;s[l+3]=255},function(s,c,l,u){if(u+1>=c.length){throw new Error("Ran out of data")}let d=c[u];s[l]=d;s[l+1]=d;s[l+2]=d;s[l+3]=c[u+1]},function(s,c,l,u){if(u+2>=c.length){throw new Error("Ran out of data")}s[l]=c[u];s[l+1]=c[u+1];s[l+2]=c[u+2];s[l+3]=255},function(s,c,l,u){if(u+3>=c.length){throw new Error("Ran out of data")}s[l]=c[u];s[l+1]=c[u+1];s[l+2]=c[u+2];s[l+3]=c[u+3]}];var r=[function(){},function(s,c,l,u){let d=c[0];s[l]=d;s[l+1]=d;s[l+2]=d;s[l+3]=u},function(s,c,l){let u=c[0];s[l]=u;s[l+1]=u;s[l+2]=u;s[l+3]=c[1]},function(s,c,l,u){s[l]=c[0];s[l+1]=c[1];s[l+2]=c[2];s[l+3]=u},function(s,c,l){s[l]=c[0];s[l+1]=c[1];s[l+2]=c[2];s[l+3]=c[3]}];function i(s,c){let l=[];let u=0;function d(){if(u===s.length){throw new Error("Ran out of data")}let h=s[u];u++;let w,p,g,m,f,v,y,b;switch(c){default:throw new Error("unrecognised depth");case 16:y=s[u];u++;l.push((h<<8)+y);break;case 4:y=h&15;b=h>>4;l.push(b,y);break;case 2:f=h&3;v=h>>2&3;y=h>>4&3;b=h>>6&3;l.push(b,y,v,f);break;case 1:w=h&1;p=h>>1&1;g=h>>2&1;m=h>>3&1;f=h>>4&1;v=h>>5&1;y=h>>6&1;b=h>>7&1;l.push(b,y,v,f,m,g,p,w);break}}return{get:function(h){while(l.length<h){d()}let w=l.slice(0,h);l=l.slice(h);return w},resetAfterLine:function(){l.length=0},end:function(){if(u!==s.length){throw new Error("extra data found")}}}}function o(s,c,l,u,d,h){let w=s.width;let p=s.height;let g=s.index;for(let m=0;m<p;m++){for(let f=0;f<w;f++){let v=l(f,m,g);t[u](c,d,v,h);h+=u}}return h}function a(s,c,l,u,d,h){let w=s.width;let p=s.height;let g=s.index;for(let m=0;m<p;m++){for(let f=0;f<w;f++){let v=d.get(u);let y=l(f,m,g);r[u](c,v,y,h)}d.resetAfterLine()}}e.dataToBitMap=function(s,c){let l=c.width;let u=c.height;let d=c.depth;let h=c.bpp;let w=c.interlace;let p;if(d!==8){p=i(s,d)}let g;if(d<=8){g=Buffer.alloc(l*u*4)}else{g=new Uint16Array(l*u*4)}let m=Math.pow(2,d)-1;let f=0;let v;let y;if(w){v=n.getImagePasses(l,u);y=n.getInterlaceIterator(l,u)}else{let b=0;y=function(){let $=b;b+=4;return $};v=[{width:l,height:u}]}for(let b=0;b<v.length;b++){if(d===8){f=o(v[b],g,y,h,s,f)}else{a(v[b],g,y,h,p,m)}}if(d===8){if(f!==s.length){throw new Error("extra data found")}}else{p.end()}return g}}});var require_format_normaliser=__commonJS({"../../node_modules/pngjs/lib/format-normaliser.js"(e,n){"use strict";function t(o,a,s,c,l){let u=0;for(let d=0;d<c;d++){for(let h=0;h<s;h++){let w=l[o[u]];if(!w){throw new Error("index "+o[u]+" not in palette")}for(let p=0;p<4;p++){a[u+p]=w[p]}u+=4}}}function r(o,a,s,c,l){let u=0;for(let d=0;d<c;d++){for(let h=0;h<s;h++){let w=false;if(l.length===1){if(l[0]===o[u]){w=true}}else if(l[0]===o[u]&&l[1]===o[u+1]&&l[2]===o[u+2]){w=true}if(w){for(let p=0;p<4;p++){a[u+p]=0}}u+=4}}}function i(o,a,s,c,l){let u=255;let d=Math.pow(2,l)-1;let h=0;for(let w=0;w<c;w++){for(let p=0;p<s;p++){for(let g=0;g<4;g++){a[h+g]=Math.floor(o[h+g]*u/d+.5)}h+=4}}}n.exports=function(o,a,s=false){let c=a.depth;let l=a.width;let u=a.height;let d=a.colorType;let h=a.transColor;let w=a.palette;let p=o;if(d===3){t(o,p,l,u,w)}else{if(h){r(o,p,l,u,h)}if(c!==8&&!s){if(c===16){p=Buffer.alloc(l*u*4)}i(o,p,l,u,c)}}return p}}});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 l=n.exports=function(u){i.call(this);this._parser=new a(u,{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=u;this.writable=true;this._parser.start()};t.inherits(l,i);l.prototype._handleError=function(u){this.emit("error",u);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};l.prototype._inflateData=function(u){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 w=Math.max(h,r.Z_MIN_CHUNK);this._inflate=r.createInflate({chunkSize:w});let p=h;let g=this.emit.bind(this,"error");this._inflate.on("error",function(f){if(!p){return}g(f)});this._filter.on("complete",this._complete.bind(this));let m=this._filter.write.bind(this._filter);this._inflate.on("data",function(f){if(!p){return}if(f.length>p){f=f.slice(0,p)}p-=f.length;m(f)});this._inflate.on("end",this._filter.end.bind(this._filter))}}this._inflate.write(u)};l.prototype._handleMetaData=function(u){this._metaData=u;this._bitmapInfo=Object.create(u);this._filter=new o(this._bitmapInfo)};l.prototype._handleTransColor=function(u){this._bitmapInfo.transColor=u};l.prototype._handlePalette=function(u){this._bitmapInfo.palette=u};l.prototype._simpleTransparency=function(){this._metaData.alpha=true};l.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};l.prototype._finished=function(){if(this.errord){return}if(!this._inflate){this.emit("error","No Inflate block")}else{this._inflate.end()}};l.prototype._complete=function(u){if(this.errord){return}let d;try{let h=s.dataToBitMap(u,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 l=255;let u=t.COLORTYPE_TO_BPP_MAP[a.inputColorType];if(u===4&&!a.inputHasAlpha){u=3}let d=t.COLORTYPE_TO_BPP_MAP[a.colorType];if(a.bitDepth===16){l=65535;d*=2}let h=Buffer.alloc(i*o*d);let w=0;let p=0;let g=a.bgColor||{};if(g.red===void 0){g.red=l}if(g.green===void 0){g.green=l}if(g.blue===void 0){g.blue=l}function m(){let f;let v;let y;let b=l;switch(a.inputColorType){case t.COLORTYPE_COLOR_ALPHA:b=c[w+3];f=c[w];v=c[w+1];y=c[w+2];break;case t.COLORTYPE_COLOR:f=c[w];v=c[w+1];y=c[w+2];break;case t.COLORTYPE_ALPHA:b=c[w+1];f=c[w];v=f;y=f;break;case t.COLORTYPE_GRAYSCALE:f=c[w];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/=l;f=Math.min(Math.max(Math.round((1-b)*g.red+b*f),0),l);v=Math.min(Math.max(Math.round((1-b)*g.green+b*v),0),l);y=Math.min(Math.max(Math.round((1-b)*g.blue+b*y),0),l)}}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=m(c,w);switch(a.colorType){case t.COLORTYPE_COLOR_ALPHA:case t.COLORTYPE_COLOR:if(a.bitDepth===8){h[p]=y.red;h[p+1]=y.green;h[p+2]=y.blue;if(s){h[p+3]=y.alpha}}else{h.writeUInt16BE(y.red,p);h.writeUInt16BE(y.green,p+2);h.writeUInt16BE(y.blue,p+4);if(s){h.writeUInt16BE(y.alpha,p+6)}}break;case t.COLORTYPE_ALPHA:case t.COLORTYPE_GRAYSCALE:{let b=(y.red+y.green+y.blue)/3;if(a.bitDepth===8){h[p]=b;if(s){h[p+1]=y.alpha}}else{h.writeUInt16BE(b,p);if(s){h.writeUInt16BE(y.alpha,p+2)}}break}default:throw new Error("unrecognised color Type "+a.colorType)}w+=u;p+=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(g,m,f,v,y){for(let b=0;b<f;b++){v[y+b]=g[m+b]}}function i(g,m,f){let v=0;let y=m+f;for(let b=m;b<y;b++){v+=Math.abs(g[b])}return v}function o(g,m,f,v,y,b){for(let $=0;$<f;$++){let T=$>=b?g[m+$-b]:0;let _=g[m+$]-T;v[y+$]=_}}function a(g,m,f,v){let y=0;for(let b=0;b<f;b++){let $=b>=v?g[m+b-v]:0;let T=g[m+b]-$;y+=Math.abs(T)}return y}function s(g,m,f,v,y){for(let b=0;b<f;b++){let $=m>0?g[m+b-f]:0;let T=g[m+b]-$;v[y+b]=T}}function c(g,m,f){let v=0;let y=m+f;for(let b=m;b<y;b++){let $=m>0?g[b-f]:0;let T=g[b]-$;v+=Math.abs(T)}return v}function l(g,m,f,v,y,b){for(let $=0;$<f;$++){let T=$>=b?g[m+$-b]:0;let _=m>0?g[m+$-f]:0;let x=g[m+$]-(T+_>>1);v[y+$]=x}}function u(g,m,f,v){let y=0;for(let b=0;b<f;b++){let $=b>=v?g[m+b-v]:0;let T=m>0?g[m+b-f]:0;let _=g[m+b]-($+T>>1);y+=Math.abs(_)}return y}function d(g,m,f,v,y,b){for(let $=0;$<f;$++){let T=$>=b?g[m+$-b]:0;let _=m>0?g[m+$-f]:0;let x=m>0&&$>=b?g[m+$-(f+b)]:0;let A=g[m+$]-t(T,_,x);v[y+$]=A}}function h(g,m,f,v){let y=0;for(let b=0;b<f;b++){let $=b>=v?g[m+b-v]:0;let T=m>0?g[m+b-f]:0;let _=m>0&&b>=v?g[m+b-(f+v)]:0;let x=g[m+b]-t($,T,_);y+=Math.abs(x)}return y}var w={0:r,1:o,2:s,3:l,4:d};var p={0:i,1:a,2:c,3:u,4:h};n.exports=function(g,m,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 $=m*y;let T=0;let _=0;let x=Buffer.alloc(($+1)*f);let A=b[0];for(let I=0;I<f;I++){if(b.length>1){let E=Infinity;for(let S=0;S<b.length;S++){let k=p[b[S]](g,_,$,y);if(k<E){A=b[S];E=k}}}x[T]=A;T++;w[A](g,_,$,x,T,y);T+=$;_+=$}return x}}});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,l,u){let d=i(c,l,u,this._options);let h=t.COLORTYPE_TO_BPP_MAP[this._options.colorType];let w=o(d,l,u,this._options,h);return w};s.prototype._packChunk=function(c,l){let u=l?l.length:0;let d=Buffer.alloc(u+12);d.writeUInt32BE(u,0);d.writeUInt32BE(c,4);if(l){l.copy(d,8)}d.writeInt32BE(r.crc32(d.slice(4,d.length-4)),d.length-4);return d};s.prototype.packGAMA=function(c){let l=Buffer.alloc(4);l.writeUInt32BE(Math.floor(c*t.GAMMA_DIVISION),0);return this._packChunk(t.TYPE_gAMA,l)};s.prototype.packIHDR=function(c,l){let u=Buffer.alloc(13);u.writeUInt32BE(c,0);u.writeUInt32BE(l,4);u[8]=this._options.bitDepth;u[9]=this._options.colorType;u[10]=0;u[11]=0;u[12]=0;return this._packChunk(t.TYPE_IHDR,u)};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,l,u){this.emit("data",Buffer.from(i.PNG_SIGNATURE));this.emit("data",this._packer.packIHDR(c,l));if(u){this.emit("data",this._packer.packGAMA(u))}let d=this._packer.filterData(s,c,l);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,w){if(typeof w==="function"){return r.Inflate._processChunk.call(this,d,h,w)}let p=this;let g=d&&d.length;let m=this._chunkSize-this._offset;let f=this._maxLength;let v=0;let y=[];let b=0;let $;this.on("error",function(A){$=A});function T(A,I){if(p._hadError){return}let E=m-I;t(E>=0,"have should not go down");if(E>0){let S=p._buffer.slice(p._offset,p._offset+E);p._offset+=E;if(S.length>f){S=S.slice(0,f)}y.push(S);b+=S.length;f-=S.length;if(f===0){return false}}if(I===0||p._offset>=p._chunkSize){m=p._chunkSize;p._offset=0;p._buffer=Buffer.allocUnsafe(p._chunkSize)}if(I===0){v+=g-A;g=A;return true}return false}t(this._handle,"zlib binding closed");let _;do{_=this._handle.writeSync(h,d,v,g,this._buffer,this._offset,m);_=_||this._writeState}while(!this._hadError&&T(_[0],_[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 x=Buffer.concat(y,b);c(this);return x};i.inherits(a,r.Inflate);function l(d,h){if(typeof h==="string"){h=Buffer.from(h)}if(!(h instanceof Buffer)){throw new TypeError("Not a string or buffer")}let w=d._finishFlushFlag;if(w==null){w=r.Z_FINISH}return d._processChunk(h,w)}function u(d,h){return l(new a(h),d)}n.exports=e=u;e.Inflate=a;e.createInflate=s;e.inflateSync=u}});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 l=require_format_normaliser();n.exports=function(u,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 w(M){h=M}let p;function g(M){p=M}function m(M){p.transColor=M}function f(M){p.palette=M}function v(){p.alpha=true}let y;function b(M){y=M}let $=[];function T(M){$.push(M)}let _=new o(u);let x=new s(d,{read:_.read.bind(_),error:w,metadata:g,gamma:b,palette:f,transColor:m,inflateData:T,simpleTransparency:v});x.start();_.process();if(h){throw h}let A=Buffer.concat($);$.length=0;let I;if(p.interlace){I=r.inflateSync(A)}else{let M=(p.width*p.bpp*p.depth+7>>3)+1;let D=M*p.height;I=i(A,{chunkSize:D,maxLength:D})}A=null;if(!I||!I.length){throw new Error("bad png - invalid inflate data response")}let E=a.process(I,p);A=null;let S=c.dataToBitMap(E,p);E=null;let k=l(S,p,d.skipRescale);p.data=k;p.gamma=y||0;return p}}});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 l=new o(c);let u=[];u.push(Buffer.from(i.PNG_SIGNATURE));u.push(l.packIHDR(a.width,a.height));if(a.gamma){u.push(l.packGAMA(a.gamma))}let d=l.filterData(a.data,a.width,a.height);let h=r.deflateSync(d,l.getDeflateOptions());d=null;if(!h||!h.length){throw new Error("bad png - invalid compressed data response")}u.push(l.packIDAT(h));u.push(l.packIEND());return Buffer.concat(u)}}});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 l,u;l=function(d){this.removeListener("error",u);this.data=d;c(null,this)}.bind(this);u=function(d){this.removeListener("parsed",l);c(d,null)}.bind(this);this.once("parsed",l);this.once("error",u)}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,l,u,d,h,w,p){l|=0;u|=0;d|=0;h|=0;w|=0;p|=0;if(l>s.width||u>s.height||l+d>s.width||u+h>s.height){throw new Error("bitblt reading outside image")}if(w>c.width||p>c.height||w+d>c.width||p+h>c.height){throw new Error("bitblt writing outside image")}for(let g=0;g<h;g++){s.data.copy(c.data,(p+g)*c.width+w<<2,(u+g)*s.width+l<<2,(u+g)*s.width+l+d<<2)}};a.prototype.bitblt=function(s,c,l,u,d,h,w){a.bitblt(this,s,c,l,u,d,h,w);return this};a.adjustGamma=function(s){if(s.gamma){for(let c=0;c<s.height;c++){for(let l=0;l<s.width;l++){let u=s.width*c+l<<2;for(let d=0;d<3;d++){let h=s.data[u+d]/255;h=Math.pow(h,1/2.2/s.gamma);s.data[u+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 l=s.claims.tier==="free"?"free":"pro";this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`dev:${s.claims.sid}`,valid:true,tier:l,isPro:l==="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 l=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(l).toISOString(),cachedAt:c,lastValidatedAt:c});this.persistCache();this.retry=0;this.nextCheck=Math.max(c+6e4,l-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 u of s){if(u.deviceId&&u.tier==="locked")this.lockDevice(String(u.deviceId));else if(u.deviceId&&(u.tier==="free"||u.tier==="pro")){c=this.lockedDevices.delete(String(u.deviceId))||c}}this.devices=s;const l=Date.now();for(const u of s)if(u.deviceId)this.lastSeen.set(u.deviceId,l);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 l=this.snapshotWaiters.get(c);if(l&&l.length){this.snapshotWaiters.set(c,[]);for(const u of l)u(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)}peekProjectDevice(){if(!this.admitted)return null;if(this.sessionDevice)return this.sessionDevice;const e=this.connectedDevices().filter(t=>!this.lockedDevices.has(t.deviceId)&&t.tools.length>0);const n=process.env.BUOY_PROJECT_ROOT||process.cwd();return pickByProject(e.map(t=>({deviceId:t.deviceId,root:this.devServerRoots.get(t.deviceId)})),n)??null}resolveDevice(e){this.requireAdmission();if(e){this.requireDeviceAccount(e);return e}const n=(l,u)=>new Error(`${NOT_READY_MARK} "${l}" (${u}) 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 l=this.devices.find(u=>u.deviceId===this.sessionDevice);if(l&&l.isConnected!==false)return this.sessionDevice;throw n(this.sessionDevice,"the device this session was using")}const t=this.connectedDevices();const r=t.filter(l=>!this.lockedDevices.has(l.deviceId));const i=r.filter(l=>l.tools.length>0);const o=process.env.BUOY_PROJECT_ROOT||process.cwd();const a=pickByProject(i.map(l=>({deviceId:l.deviceId,root:this.devServerRoots.get(l.deviceId)})),o);if(a)return this.sessionDevice=a;const s=pickByProject(this.devices.filter(l=>l.deviceId&&l.isConnected===false&&!this.lockedDevices.has(l.deviceId)).map(l=>({deviceId:l.deviceId,root:this.devServerRoots.get(l.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(l=>l.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 l=r.map(u=>u.deviceName).join(", ");throw new Error(`Connected devices (${l}) are not exposing any Buoy tools yet. Make sure the app is in the foreground with devtools mounted, then retry.`)}const c=i.map(l=>`${l.deviceName} (${l.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 l=this.healthOf(r);if(Date.now()-l.lastFullBudgetAt>RECOVERY_PROBE_MS){l.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((l,u)=>{const d=Date.now();const h=()=>{this.pendingActions.delete(a);if(o!==ALL_DEVICES&&!i.silent)this.noteTimeout(o);u(new Error(`Action "${e}.${n}" got no answer in ${Date.now()-d}ms. `+(o===ALL_DEVICES?"No device responded.":this.unresponsiveNote(o))))};const w=setTimeout(h,s);this.pendingActions.set(a,{resolve:l,reject:u,timer:w,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.63"?"7.0.63":"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 l=c.trim();if(l)n.push(Buffer.from(l,"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(l=>l.dataPath?webViewInstallIds(import_node_path4.default.join(l.dataPath,"Containers","Data","Application")):Promise.resolve([])));c.forEach((l,u)=>{if(l.includes(t))s.push(n[u])});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 l=c;return{ok:false,error:`Crop failed: ${l?.stderr||l?.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,l]=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:l-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 l=0;for(const u of[c.desc,c.text,c.id.split("/").pop()??""]){const d=u.trim().toLowerCase();if(!d)continue;if(d===t)l=Math.max(l,3);else if(d.startsWith(t))l=Math.max(l,2);else if(d.includes(t))l=Math.max(l,1)}return l};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,l)=>a.findIndex(u=>JSON.stringify(u.bounds)===JSON.stringify(c.bounds))===l);if(s.length>1){const c=s.filter(l=>[l.desc,l.text,l.id.split("/").pop()??""].some(u=>u.trim()===n.trim()));if(c.length)s=c}if(s.length>1){const c=s.filter(l=>l.clickable||/EditText|Button/.test(l.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 l=await import_node_fs5.promises.readFile(import_node_path6.default.join(s,"origin")).then(u=>u.toString("hex"),()=>"");if(l)n.push({db:c,origin:l})}}}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 l=new import_ws.WebSocket(a.webSocketDebuggerUrl);const u=setTimeout(()=>{l.close();c(new Error("the WebView did not answer"))},5e3);l.on("open",()=>l.send(JSON.stringify({id:1,method:"Runtime.evaluate",params:{expression:t,returnByValue:true}})));l.on("message",d=>{const h=JSON.parse(String(d));if(h.id!==1)return;clearTimeout(u);l.close();if(h.result?.exceptionDetails)c(new Error("the WebView script failed"));else s(h.result?.result?.value)});l.on("error",d=>{clearTimeout(u);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,n){if(!n){const t=await simsHoldingOf(e,["rn"]);return t.length?t:simsHoldingOf(e,["webview"])}return simsHoldingOf(e,n)}async function simsHoldingOf(e,n){let t=[];try{const i=JSON.parse(await simctl(["list","devices","booted","-j"])).devices;t=Object.entries(i).filter(([o])=>/iOS/.test(o)).flatMap(([,o])=>o.filter(a=>a.state==="Booted"))}catch{return[]}const r=await Promise.all(t.map(i=>findIosContainer(e,i.udid,i.dataPath,n)));return t.flatMap((i,o)=>r[o]?[{udid:i.udid,name:i.name,found:r[o]}]:[])}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,t,r){const i=tailOf(e);if(!i)return null;if(!t){try{const c=JSON.parse(await simctl(["list","devices","-j"])).devices;t=Object.values(c).flat().find(l=>l.udid===n)?.dataPath}catch{return null}}if(!t)return null;const o=import_node_path7.default.join(t,"Containers","Data","Application");let a=[];try{a=await import_node_fs6.promises.readdir(o)}catch{return null}const s=await Promise.all(a.map(c=>iosContainerHolds(import_node_path7.default.join(o,c),i,r)));for(const[c,l]of a.entries()){const u=import_node_path7.default.join(o,l);if(!s[c])continue;let d=null;try{d=(await sh("plutil",["-extract","MCMMetadataIdentifier","raw","-o","-",import_node_path7.default.join(u,".com.apple.mobile_container_manager.metadata.plist")])).trim()||null}catch{}return{container:u,bundleId:d,kind:s[c]}}return null}async function iosContainerHolds(e,n,t=["rn","webview"]){if(t.includes("rn")){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"rn"}catch{}}if(!t.includes("webview"))return null;return(await containerWebViewInstallIds(e).catch(()=>[])).includes(n)?"webview":null}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,l,u)=>!!c&&u.indexOf(c)===l).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}var finding=new Map;function findHost(e,n,t={}){if(t.udid||t.serial||t.bundleId)return findHostNow(e,n,t);const r=`${e}|${n??""}`;const i=finding.get(r);if(i)return i;const o=findHostNow(e,n,t).finally(()=>finding.delete(r));finding.set(r,o);return o}async function findHostNow(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 l=await simsHolding(e,r.idKind?[r.idKind]:void 0);if(l.length>1)throw cloneError(e,l);if(!l.some(u=>u.udid===r.udid)){hosts.delete(e);throw new Error(`The sim no longer holds "${e}". Try the host scan again.`)}}return r}if(r)hosts.delete(e);if(n==="android"){const l=await findAndroid(e,t);if(!l){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,l);return l}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??"";let a=null;if(!i){const l=await simsHolding(e);a=l.length===1?l[0]:null;if(l.length>1)throw cloneError(e,l);const u=l.length===1?{ok:true,udid:l[0].udid,how:`matched ${e} to "${l[0].name}"`}:await resolveSimUdid(e);if(!u.ok||!/^matched /.test(u.how)){const d=await findPhone(e).catch(()=>null);if(d){hosts.set(e,d);return d}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 s=a?.udid===i?await iosContainerHolds(a.found.container,tailOf(e),[a.found.kind])?a.found:null:await findIosContainer(e,i);if(!s)throw new Error(`Simulator ${i} does not hold "${e}".`);const c={platform:"ios",udid:i,name:o,bundleId:t.bundleId??s?.bundleId??null,container:s?.container??null,picked:!!t.udid,idKind:s.kind};hosts.set(e,c);return c}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!!await 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 l=Math.floor(c*s);const u=Math.max(l+1,Math.floor((c+1)*s));for(let d=0;d<r;d++){const h=Math.floor(d*a);const w=Math.max(h+1,Math.floor((d+1)*a));const p=[0,0,0,0];let g=0;for(let f=l;f<u;f++){for(let v=h;v<w;v++){const y=(f*e.width+v)*4;for(let b=0;b<4;b++)p[b]+=e.data[y+b];g++}}const m=(c*r+d)*4;for(let f=0;f<4;f++)o.data[m+f]=Math.round(p[f]/g)}}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 l=a==="aapt2"?c.trim().split("\n")[0]:/package: name='([^']+)'/.exec(c)?.[1]??"";if(l)return l}}}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 u=(await simctl(["get_app_container",e.udid,r,"data"]).catch(()=>"")).trim();if(u)s=await copyBuoyFiles(import_node_path7.default.join(u,"Documents"),a);if(u&&!s){try{c=await iosReadWebKeep(u)}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(u){throw new Error(`The app was removed, but installing ${import_node_path7.default.basename(i)} failed: ${u.message}. Install it again by hand.`)}let l="";if(a&&s){try{const u=(await simctl(["get_app_container",e.udid,r,"data"])).trim();await copyBuoyFiles(a,import_node_path7.default.join(u,"Documents"));e.container=u;l=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(u){l=` Buoy's sign-in could not be restored (${u.message}): sign in to Buoy again in the app.`}}else if(c.length){try{const u=(await simctl(["get_app_container",e.udid,r,"data"])).trim();await simctl(["launch",e.udid,r]);const d=await iosWaitForLocalStorage(u);await simctl(["terminate",e.udid,r]).catch(()=>void 0);if(!d||!await iosWriteWebKeep(u,c))throw new Error("the app made no WebView storage");e.container=u;l=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(u){l=` Buoy's sign-in could not be restored (${u.message}): sign in to Buoy again in the app.`}}else if(t){l=" 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.${l}`}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 l=c.split("\n").map(u=>u.trim()).filter(u=>u.startsWith("files/buoy-license/")||/react-buoy\/@react_buoy_(sync_device_id|install)\.json$/.test(u));for(const u of l){const d=await adbShell(e.serial,`run-as ${q(n)} base64 ${q(u)}`).catch(()=>"");if(d.trim())o.push({rel:u,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 l=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(l)} && 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 l of o){let u;try{u=await readAppFile(e.udid,n,l)}catch(h){throw new Error(`Could not back up Buoy's ${import_node_path7.default.basename(l)} from the iPhone (${h.message}). Nothing was changed.`)}if(!u)continue;const d=import_node_path7.default.join(a,l.replace(/\//g,"__"));await import_node_fs6.promises.writeFile(d,u,{mode:384});s.push({rel:l,local:d})}}await phoneQuit(e.udid,n).catch(()=>false);await phoneUninstall(e.udid,n);try{await phoneInstall(e.udid,t)}catch(l){throw new Error(`The app was removed, but installing ${import_node_path7.default.basename(t)} failed: ${l.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 l=s.some(d=>d.rel.includes("buoy-license"));const u=s.some(d=>d.rel.includes("sync_device_id"));c=l?` Kept Buoy's sign-in${u?" 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(l){c=` Buoy's sign-in could not be restored (${l.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 l=c instanceof Error?c.message:String(c);const u=l.startsWith(NOT_READY_MARK)&&/is not connected right now/.test(l)?/"([^"]+)"/.exec(l)?.[1]:void 0;const d=u?e.listDevices().some(h=>h.deviceId===u&&h.isPro):false;if(!r.allowOffline||!u||!d)throw c;i=u;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","native_inspect"],...!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/pinch (by query, testID, nativeTag or x/y; not label)","native_inspect (the app's side only)"]}}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/pinch","native_inspect"]:[]],...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 w=0;i.length===0&&w<10;w++){await new Promise(p=>setTimeout(p,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(w=>!w.isConnected).length;if(!t.includeDisconnected)i=i.filter(w=>w.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(w=>w.platform==="ios").map(w=>w.deviceId)).catch(()=>new Map);const s=i.filter(w=>w.isConnected);const c=s.some(w=>w.isPro);const l=s.some(w=>w.tier!=="locked");const u=s.filter(w=>w.collision);const d=await Promise.all(i.map(w=>w.isConnected?hostSummary(w,a.get(w.deviceId)).catch(()=>void 0):void 0));const h=i.map((w,p)=>{const g=a.get(w.deviceId);const m=d[p];return{deviceId:w.deviceId,deviceName:w.deviceName,platform:w.platform,isConnected:w.isConnected,isPro:w.isPro,tier:w.tier,access:n.accessState(w.deviceId),...g?{simulator:g}:{},...m?{host:m}:{},...w.collision?{collision:true}:{},tools:t.details?w.tools:w.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).`:""}`},...u.length>0?{warning:`${u.map(w=>`"${w.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:l?"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(u=>!i||u.deviceId===i);if(c.length===0)return fail(i?`No connected device "${i}". Call list_devices.`:"No devices are connected. Call list_devices.");const l=c.map(u=>[`**${u.deviceName}** (${u.deviceId})`,...u.tools.map(d=>`- ${d.toolId}: ${d.actions.join(", ")}`)].join("\n"));return{content:[{type:"text",text:`${l.join("\n\n")}
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 __esm=(e,n)=>function t(){return e&&(n=(0,e[__getOwnPropNames(e)[0]])(e=0)),n};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 l=this._buffers[s++];let u=Math.min(l.length,o.length-a);l.copy(c,a,0,u);a+=u;if(u!==l.length){this._buffers[--s]=l.slice(u)}}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 l=0;l<n.length;l++){let u=n[l];let d=s*u.x.length;let h=c*u.y.length;for(let w=0;w<u.x.length;w++){if(u.x[w]<o){d++}else{break}}for(let w=0;w<u.y.length;w++){if(u.y[w]<a){h++}else{break}}if(d>0&&h>0){i.push({width:d,height:h,index:l})}}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 l=(i-c)/n[o].y.length*8+n[o].y[c];return s*4+l*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 l=Math.abs(a-o);if(s<=c&&s<=l){return r}if(c<=l){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 l=a*s;if(c!==8){l=Math.ceil(l/(8/c))}return l}var o=n.exports=function(a,s){let c=a.width;let l=a.height;let u=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(u){let w=t.getImagePasses(c,l);for(let p=0;p<w.length;p++){this._images.push({byteWidth:i(w[p].width,d,h),height:w[p].height,lineIndex:0})}}else{this._images.push({byteWidth:i(c,d,h),height:l,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 l=this._xComparison;let u=l-1;for(let d=0;d<c;d++){let h=a[1+d];let w=d>u?s[d-l]:0;s[d]=h+w}};o.prototype._unFilterType2=function(a,s,c){let l=this._lastLine;for(let u=0;u<c;u++){let d=a[1+u];let h=l?l[u]:0;s[u]=d+h}};o.prototype._unFilterType3=function(a,s,c){let l=this._xComparison;let u=l-1;let d=this._lastLine;for(let h=0;h<c;h++){let w=a[1+h];let p=d?d[h]:0;let g=h>u?s[h-l]:0;let m=Math.floor((g+p)/2);s[h]=w+m}};o.prototype._unFilterType4=function(a,s,c){let l=this._xComparison;let u=l-1;let d=this._lastLine;for(let h=0;h<c;h++){let w=a[1+h];let p=d?d[h]:0;let g=h>u?s[h-l]:0;let m=h>u&&d?d[h-l]:0;let f=r(g,p,m);s[h]=w+f}};o.prototype._reverseFilterLine=function(a){let s=a[0];let c;let l=this._images[this._imageIndex];let u=l.byteWidth;if(s===0){c=a.slice(1,u+1)}else{c=Buffer.alloc(u);switch(s){case 1:this._unFilterType1(a,c,u);break;case 2:this._unFilterType2(a,c,u);break;case 3:this._unFilterType3(a,c,u);break;case 4:this._unFilterType4(a,c,u);break;default:throw new Error("Unrecognised filter type - "+s)}}this.write(c);l.lineIndex++;if(l.lineIndex>=l.height){this._lastLine=null;this._imageIndex++;l=this._images[this._imageIndex]}else{this._lastLine=c}if(l){this.read(l.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(l){s.push(l)},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 u=4;u<8;u++){c+=String.fromCharCode(o[u])}let l=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(!l){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 l=o[9];let u=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(!(l in t.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(u!==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=l;let w=t.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=true;this.metadata({width:a,height:s,depth:c,interlace:Boolean(h),palette:Boolean(l&t.COLORTYPE_PALETTE),color:Boolean(l&t.COLORTYPE_COLOR),alpha:Boolean(l&t.COLORTYPE_ALPHA),bpp:w,colorType:l});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,l,u){if(u===c.length){throw new Error("Ran out of data")}let d=c[u];s[l]=d;s[l+1]=d;s[l+2]=d;s[l+3]=255},function(s,c,l,u){if(u+1>=c.length){throw new Error("Ran out of data")}let d=c[u];s[l]=d;s[l+1]=d;s[l+2]=d;s[l+3]=c[u+1]},function(s,c,l,u){if(u+2>=c.length){throw new Error("Ran out of data")}s[l]=c[u];s[l+1]=c[u+1];s[l+2]=c[u+2];s[l+3]=255},function(s,c,l,u){if(u+3>=c.length){throw new Error("Ran out of data")}s[l]=c[u];s[l+1]=c[u+1];s[l+2]=c[u+2];s[l+3]=c[u+3]}];var r=[function(){},function(s,c,l,u){let d=c[0];s[l]=d;s[l+1]=d;s[l+2]=d;s[l+3]=u},function(s,c,l){let u=c[0];s[l]=u;s[l+1]=u;s[l+2]=u;s[l+3]=c[1]},function(s,c,l,u){s[l]=c[0];s[l+1]=c[1];s[l+2]=c[2];s[l+3]=u},function(s,c,l){s[l]=c[0];s[l+1]=c[1];s[l+2]=c[2];s[l+3]=c[3]}];function i(s,c){let l=[];let u=0;function d(){if(u===s.length){throw new Error("Ran out of data")}let h=s[u];u++;let w,p,g,m,f,v,y,b;switch(c){default:throw new Error("unrecognised depth");case 16:y=s[u];u++;l.push((h<<8)+y);break;case 4:y=h&15;b=h>>4;l.push(b,y);break;case 2:f=h&3;v=h>>2&3;y=h>>4&3;b=h>>6&3;l.push(b,y,v,f);break;case 1:w=h&1;p=h>>1&1;g=h>>2&1;m=h>>3&1;f=h>>4&1;v=h>>5&1;y=h>>6&1;b=h>>7&1;l.push(b,y,v,f,m,g,p,w);break}}return{get:function(h){while(l.length<h){d()}let w=l.slice(0,h);l=l.slice(h);return w},resetAfterLine:function(){l.length=0},end:function(){if(u!==s.length){throw new Error("extra data found")}}}}function o(s,c,l,u,d,h){let w=s.width;let p=s.height;let g=s.index;for(let m=0;m<p;m++){for(let f=0;f<w;f++){let v=l(f,m,g);t[u](c,d,v,h);h+=u}}return h}function a(s,c,l,u,d,h){let w=s.width;let p=s.height;let g=s.index;for(let m=0;m<p;m++){for(let f=0;f<w;f++){let v=d.get(u);let y=l(f,m,g);r[u](c,v,y,h)}d.resetAfterLine()}}e.dataToBitMap=function(s,c){let l=c.width;let u=c.height;let d=c.depth;let h=c.bpp;let w=c.interlace;let p;if(d!==8){p=i(s,d)}let g;if(d<=8){g=Buffer.alloc(l*u*4)}else{g=new Uint16Array(l*u*4)}let m=Math.pow(2,d)-1;let f=0;let v;let y;if(w){v=n.getImagePasses(l,u);y=n.getInterlaceIterator(l,u)}else{let b=0;y=function(){let $=b;b+=4;return $};v=[{width:l,height:u}]}for(let b=0;b<v.length;b++){if(d===8){f=o(v[b],g,y,h,s,f)}else{a(v[b],g,y,h,p,m)}}if(d===8){if(f!==s.length){throw new Error("extra data found")}}else{p.end()}return g}}});var require_format_normaliser=__commonJS({"../../node_modules/pngjs/lib/format-normaliser.js"(e,n){"use strict";function t(o,a,s,c,l){let u=0;for(let d=0;d<c;d++){for(let h=0;h<s;h++){let w=l[o[u]];if(!w){throw new Error("index "+o[u]+" not in palette")}for(let p=0;p<4;p++){a[u+p]=w[p]}u+=4}}}function r(o,a,s,c,l){let u=0;for(let d=0;d<c;d++){for(let h=0;h<s;h++){let w=false;if(l.length===1){if(l[0]===o[u]){w=true}}else if(l[0]===o[u]&&l[1]===o[u+1]&&l[2]===o[u+2]){w=true}if(w){for(let p=0;p<4;p++){a[u+p]=0}}u+=4}}}function i(o,a,s,c,l){let u=255;let d=Math.pow(2,l)-1;let h=0;for(let w=0;w<c;w++){for(let p=0;p<s;p++){for(let g=0;g<4;g++){a[h+g]=Math.floor(o[h+g]*u/d+.5)}h+=4}}}n.exports=function(o,a,s=false){let c=a.depth;let l=a.width;let u=a.height;let d=a.colorType;let h=a.transColor;let w=a.palette;let p=o;if(d===3){t(o,p,l,u,w)}else{if(h){r(o,p,l,u,h)}if(c!==8&&!s){if(c===16){p=Buffer.alloc(l*u*4)}i(o,p,l,u,c)}}return p}}});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 l=n.exports=function(u){i.call(this);this._parser=new a(u,{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=u;this.writable=true;this._parser.start()};t.inherits(l,i);l.prototype._handleError=function(u){this.emit("error",u);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};l.prototype._inflateData=function(u){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 w=Math.max(h,r.Z_MIN_CHUNK);this._inflate=r.createInflate({chunkSize:w});let p=h;let g=this.emit.bind(this,"error");this._inflate.on("error",function(f){if(!p){return}g(f)});this._filter.on("complete",this._complete.bind(this));let m=this._filter.write.bind(this._filter);this._inflate.on("data",function(f){if(!p){return}if(f.length>p){f=f.slice(0,p)}p-=f.length;m(f)});this._inflate.on("end",this._filter.end.bind(this._filter))}}this._inflate.write(u)};l.prototype._handleMetaData=function(u){this._metaData=u;this._bitmapInfo=Object.create(u);this._filter=new o(this._bitmapInfo)};l.prototype._handleTransColor=function(u){this._bitmapInfo.transColor=u};l.prototype._handlePalette=function(u){this._bitmapInfo.palette=u};l.prototype._simpleTransparency=function(){this._metaData.alpha=true};l.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};l.prototype._finished=function(){if(this.errord){return}if(!this._inflate){this.emit("error","No Inflate block")}else{this._inflate.end()}};l.prototype._complete=function(u){if(this.errord){return}let d;try{let h=s.dataToBitMap(u,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 l=255;let u=t.COLORTYPE_TO_BPP_MAP[a.inputColorType];if(u===4&&!a.inputHasAlpha){u=3}let d=t.COLORTYPE_TO_BPP_MAP[a.colorType];if(a.bitDepth===16){l=65535;d*=2}let h=Buffer.alloc(i*o*d);let w=0;let p=0;let g=a.bgColor||{};if(g.red===void 0){g.red=l}if(g.green===void 0){g.green=l}if(g.blue===void 0){g.blue=l}function m(){let f;let v;let y;let b=l;switch(a.inputColorType){case t.COLORTYPE_COLOR_ALPHA:b=c[w+3];f=c[w];v=c[w+1];y=c[w+2];break;case t.COLORTYPE_COLOR:f=c[w];v=c[w+1];y=c[w+2];break;case t.COLORTYPE_ALPHA:b=c[w+1];f=c[w];v=f;y=f;break;case t.COLORTYPE_GRAYSCALE:f=c[w];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/=l;f=Math.min(Math.max(Math.round((1-b)*g.red+b*f),0),l);v=Math.min(Math.max(Math.round((1-b)*g.green+b*v),0),l);y=Math.min(Math.max(Math.round((1-b)*g.blue+b*y),0),l)}}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=m(c,w);switch(a.colorType){case t.COLORTYPE_COLOR_ALPHA:case t.COLORTYPE_COLOR:if(a.bitDepth===8){h[p]=y.red;h[p+1]=y.green;h[p+2]=y.blue;if(s){h[p+3]=y.alpha}}else{h.writeUInt16BE(y.red,p);h.writeUInt16BE(y.green,p+2);h.writeUInt16BE(y.blue,p+4);if(s){h.writeUInt16BE(y.alpha,p+6)}}break;case t.COLORTYPE_ALPHA:case t.COLORTYPE_GRAYSCALE:{let b=(y.red+y.green+y.blue)/3;if(a.bitDepth===8){h[p]=b;if(s){h[p+1]=y.alpha}}else{h.writeUInt16BE(b,p);if(s){h.writeUInt16BE(y.alpha,p+2)}}break}default:throw new Error("unrecognised color Type "+a.colorType)}w+=u;p+=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(g,m,f,v,y){for(let b=0;b<f;b++){v[y+b]=g[m+b]}}function i(g,m,f){let v=0;let y=m+f;for(let b=m;b<y;b++){v+=Math.abs(g[b])}return v}function o(g,m,f,v,y,b){for(let $=0;$<f;$++){let T=$>=b?g[m+$-b]:0;let _=g[m+$]-T;v[y+$]=_}}function a(g,m,f,v){let y=0;for(let b=0;b<f;b++){let $=b>=v?g[m+b-v]:0;let T=g[m+b]-$;y+=Math.abs(T)}return y}function s(g,m,f,v,y){for(let b=0;b<f;b++){let $=m>0?g[m+b-f]:0;let T=g[m+b]-$;v[y+b]=T}}function c(g,m,f){let v=0;let y=m+f;for(let b=m;b<y;b++){let $=m>0?g[b-f]:0;let T=g[b]-$;v+=Math.abs(T)}return v}function l(g,m,f,v,y,b){for(let $=0;$<f;$++){let T=$>=b?g[m+$-b]:0;let _=m>0?g[m+$-f]:0;let x=g[m+$]-(T+_>>1);v[y+$]=x}}function u(g,m,f,v){let y=0;for(let b=0;b<f;b++){let $=b>=v?g[m+b-v]:0;let T=m>0?g[m+b-f]:0;let _=g[m+b]-($+T>>1);y+=Math.abs(_)}return y}function d(g,m,f,v,y,b){for(let $=0;$<f;$++){let T=$>=b?g[m+$-b]:0;let _=m>0?g[m+$-f]:0;let x=m>0&&$>=b?g[m+$-(f+b)]:0;let I=g[m+$]-t(T,_,x);v[y+$]=I}}function h(g,m,f,v){let y=0;for(let b=0;b<f;b++){let $=b>=v?g[m+b-v]:0;let T=m>0?g[m+b-f]:0;let _=m>0&&b>=v?g[m+b-(f+v)]:0;let x=g[m+b]-t($,T,_);y+=Math.abs(x)}return y}var w={0:r,1:o,2:s,3:l,4:d};var p={0:i,1:a,2:c,3:u,4:h};n.exports=function(g,m,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 $=m*y;let T=0;let _=0;let x=Buffer.alloc(($+1)*f);let I=b[0];for(let D=0;D<f;D++){if(b.length>1){let E=Infinity;for(let S=0;S<b.length;S++){let k=p[b[S]](g,_,$,y);if(k<E){I=b[S];E=k}}}x[T]=I;T++;w[I](g,_,$,x,T,y);T+=$;_+=$}return x}}});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,l,u){let d=i(c,l,u,this._options);let h=t.COLORTYPE_TO_BPP_MAP[this._options.colorType];let w=o(d,l,u,this._options,h);return w};s.prototype._packChunk=function(c,l){let u=l?l.length:0;let d=Buffer.alloc(u+12);d.writeUInt32BE(u,0);d.writeUInt32BE(c,4);if(l){l.copy(d,8)}d.writeInt32BE(r.crc32(d.slice(4,d.length-4)),d.length-4);return d};s.prototype.packGAMA=function(c){let l=Buffer.alloc(4);l.writeUInt32BE(Math.floor(c*t.GAMMA_DIVISION),0);return this._packChunk(t.TYPE_gAMA,l)};s.prototype.packIHDR=function(c,l){let u=Buffer.alloc(13);u.writeUInt32BE(c,0);u.writeUInt32BE(l,4);u[8]=this._options.bitDepth;u[9]=this._options.colorType;u[10]=0;u[11]=0;u[12]=0;return this._packChunk(t.TYPE_IHDR,u)};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,l,u){this.emit("data",Buffer.from(i.PNG_SIGNATURE));this.emit("data",this._packer.packIHDR(c,l));if(u){this.emit("data",this._packer.packGAMA(u))}let d=this._packer.filterData(s,c,l);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,w){if(typeof w==="function"){return r.Inflate._processChunk.call(this,d,h,w)}let p=this;let g=d&&d.length;let m=this._chunkSize-this._offset;let f=this._maxLength;let v=0;let y=[];let b=0;let $;this.on("error",function(I){$=I});function T(I,D){if(p._hadError){return}let E=m-D;t(E>=0,"have should not go down");if(E>0){let S=p._buffer.slice(p._offset,p._offset+E);p._offset+=E;if(S.length>f){S=S.slice(0,f)}y.push(S);b+=S.length;f-=S.length;if(f===0){return false}}if(D===0||p._offset>=p._chunkSize){m=p._chunkSize;p._offset=0;p._buffer=Buffer.allocUnsafe(p._chunkSize)}if(D===0){v+=g-I;g=I;return true}return false}t(this._handle,"zlib binding closed");let _;do{_=this._handle.writeSync(h,d,v,g,this._buffer,this._offset,m);_=_||this._writeState}while(!this._hadError&&T(_[0],_[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 x=Buffer.concat(y,b);c(this);return x};i.inherits(a,r.Inflate);function l(d,h){if(typeof h==="string"){h=Buffer.from(h)}if(!(h instanceof Buffer)){throw new TypeError("Not a string or buffer")}let w=d._finishFlushFlag;if(w==null){w=r.Z_FINISH}return d._processChunk(h,w)}function u(d,h){return l(new a(h),d)}n.exports=e=u;e.Inflate=a;e.createInflate=s;e.inflateSync=u}});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 l=require_format_normaliser();n.exports=function(u,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 w(M){h=M}let p;function g(M){p=M}function m(M){p.transColor=M}function f(M){p.palette=M}function v(){p.alpha=true}let y;function b(M){y=M}let $=[];function T(M){$.push(M)}let _=new o(u);let x=new s(d,{read:_.read.bind(_),error:w,metadata:g,gamma:b,palette:f,transColor:m,inflateData:T,simpleTransparency:v});x.start();_.process();if(h){throw h}let I=Buffer.concat($);$.length=0;let D;if(p.interlace){D=r.inflateSync(I)}else{let M=(p.width*p.bpp*p.depth+7>>3)+1;let A=M*p.height;D=i(I,{chunkSize:A,maxLength:A})}I=null;if(!D||!D.length){throw new Error("bad png - invalid inflate data response")}let E=a.process(D,p);I=null;let S=c.dataToBitMap(E,p);E=null;let k=l(S,p,d.skipRescale);p.data=k;p.gamma=y||0;return p}}});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 l=new o(c);let u=[];u.push(Buffer.from(i.PNG_SIGNATURE));u.push(l.packIHDR(a.width,a.height));if(a.gamma){u.push(l.packGAMA(a.gamma))}let d=l.filterData(a.data,a.width,a.height);let h=r.deflateSync(d,l.getDeflateOptions());d=null;if(!h||!h.length){throw new Error("bad png - invalid compressed data response")}u.push(l.packIDAT(h));u.push(l.packIEND());return Buffer.concat(u)}}});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 l,u;l=function(d){this.removeListener("error",u);this.data=d;c(null,this)}.bind(this);u=function(d){this.removeListener("parsed",l);c(d,null)}.bind(this);this.once("parsed",l);this.once("error",u)}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,l,u,d,h,w,p){l|=0;u|=0;d|=0;h|=0;w|=0;p|=0;if(l>s.width||u>s.height||l+d>s.width||u+h>s.height){throw new Error("bitblt reading outside image")}if(w>c.width||p>c.height||w+d>c.width||p+h>c.height){throw new Error("bitblt writing outside image")}for(let g=0;g<h;g++){s.data.copy(c.data,(p+g)*c.width+w<<2,(u+g)*s.width+l<<2,(u+g)*s.width+l+d<<2)}};a.prototype.bitblt=function(s,c,l,u,d,h,w){a.bitblt(this,s,c,l,u,d,h,w);return this};a.adjustGamma=function(s){if(s.gamma){for(let c=0;c<s.height;c++){for(let l=0;l<s.width;l++){let u=s.width*c+l<<2;for(let d=0;d<3;d++){let h=s.data[u+d]/255;h=Math.pow(h,1/2.2/s.gamma);s.data[u+d]=Math.round(h*255)}}}s.gamma=0}};a.prototype.adjustGamma=function(){a.adjustGamma(this)}}});var PROTOCOL_VERSION,FarmError;var init_types=__esm({"../sim-farm/src/types.ts"(){"use strict";PROTOCOL_VERSION=1;FarmError=class extends Error{constructor(e,n,t,r=false){super(n);this.code=e;this.next=t;this.retryable=r;this.name="FarmError"}toJSON(){return{code:this.code,message:this.message,next:this.next,retryable:this.retryable}}}}});var import_node_crypto7;var init_profiles=__esm({"../sim-farm/src/profiles.ts"(){"use strict";import_node_crypto7=require("crypto")}});function run4(e,n,t={}){const{timeoutMs:r=3e4,maxBytes:i=4*1024*1024}=t;return new Promise(o=>{const a=(0,import_node_child_process17.spawn)(e,n,{env:t.env??process.env,stdio:[t.input==null?"ignore":"pipe","pipe","pipe"]});liveChildren.add(a);let s="";let c="";let l=false;a.stdout.on("data",d=>{if(s.length<i)s+=d.toString("utf8")});a.stderr.on("data",d=>{if(c.length<i)c+=d.toString("utf8")});if(t.input!=null)a.stdin.end(t.input);const u=setTimeout(()=>{l=true;a.kill("SIGTERM");setTimeout(()=>a.kill("SIGKILL"),2e3).unref?.()},r);a.on("error",d=>{liveChildren.delete(a);clearTimeout(u);o({code:null,stdout:s,stderr:c+String(d),timedOut:l})});a.on("close",d=>{liveChildren.delete(a);clearTimeout(u);o({code:d,stdout:s,stderr:c,timedOut:l})})})}async function pidStart(e){const n=await run4("ps",["-o","lstart=","-p",String(e)],{timeoutMs:5e3});const t=n.stdout.trim().replace(/\s+/g," ");return n.code===0&&t?t:null}async function pidAlive(e,n){if(!Number.isInteger(e)||e<=0)return false;try{process.kill(e,0)}catch(t){if(t.code!=="EPERM")return false}if(!n)return true;return await pidStart(e)===n}var import_node_child_process17,liveChildren,sleep2;var init_proc=__esm({"../sim-farm/src/proc.ts"(){"use strict";import_node_child_process17=require("child_process");liveChildren=new Set;sleep2=e=>new Promise(n=>setTimeout(n,e))}});var import_node_fs14,import_node_path15,import_node_crypto8,DISABLED_STORE_ROOT;var init_disabledStore=__esm({"../sim-farm/src/disabledStore.ts"(){"use strict";import_node_fs14=require("fs");import_node_path15=__toESM(require("path"));import_node_crypto8=require("crypto");init_proc();DISABLED_STORE_ROOT=process.env.BUOY_FARM_DISABLED_ROOT||"/private/var/tmp"}});var import_node_fs15,import_node_path16,import_node_crypto9;var init_seed=__esm({"../sim-farm/src/seed.ts"(){"use strict";import_node_fs15=require("fs");import_node_path16=__toESM(require("path"));import_node_crypto9=require("crypto");init_proc()}});function farmHome(){return process.env.BUOY_FARM_HOME||import_node_path17.default.join(import_node_os11.default.homedir(),".buoy","farm")}function ensureHome(e=farmHome()){(0,import_node_fs16.mkdirSync)(e,{recursive:true,mode:448});try{(0,import_node_fs16.chmodSync)(e,448)}catch{}}function readOrCreateToken(e=farmHome()){const n=paths(e).token;try{const t=(0,import_node_fs16.readFileSync)(n,"utf8").trim();if(t)return t}catch{}ensureHome(e);try{(0,import_node_fs16.writeFileSync)(n,(0,import_node_crypto10.randomBytes)(24).toString("hex")+"\n",{mode:384,flag:"wx"})}catch(t){if(t.code!=="EEXIST")throw t}for(let t=0;t<20;t++){const r=(0,import_node_fs16.readFileSync)(n,"utf8").trim();if(r)return r;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,25)}throw new Error(`farm token at ${n} is empty`)}async function readOwner(e=farmHome()){try{return JSON.parse(await import_node_fs16.promises.readFile(paths(e).lockOwner,"utf8"))}catch{return null}}async function ownerAlive(e){return!!e&&await pidAlive(e.pid,e.start)}var import_node_fs16,import_node_os11,import_node_path17,import_node_crypto10,paths;var init_store=__esm({"../sim-farm/src/store.ts"(){"use strict";import_node_fs16=require("fs");import_node_os11=__toESM(require("os"));import_node_path17=__toESM(require("path"));import_node_crypto10=require("crypto");init_proc();init_types();paths=(e=farmHome())=>({home:e,lock:import_node_path17.default.join(e,"owner.lock"),lockOwner:import_node_path17.default.join(e,"owner.lock","owner.json"),socket:import_node_path17.default.join(e,"farmd.sock"),token:import_node_path17.default.join(e,"token"),state:import_node_path17.default.join(e,"state.json"),journal:import_node_path17.default.join(e,"journal.ndjson"),log:import_node_path17.default.join(e,"farmd.log"),shots:import_node_path17.default.join(e,"shots")})}});var import_node_fs17,import_node_path18,import_node_crypto11,GB;var init_engine=__esm({"../sim-farm/src/engine.ts"(){"use strict";import_node_fs17=require("fs");import_node_path18=__toESM(require("path"));import_node_crypto11=require("crypto");init_disabledStore();init_profiles();init_proc();init_seed();init_store();init_types();GB=1024**3}});var import_node_fs18,import_node_os12,import_node_path19;var init_host=__esm({"../sim-farm/src/host.ts"(){"use strict";import_node_fs18=require("fs");import_node_os12=__toESM(require("os"));import_node_path19=__toESM(require("path"));init_disabledStore();init_proc()}});var import_node_net,import_node_fs19,import_node_crypto12;var init_server=__esm({"../sim-farm/src/server.ts"(){"use strict";import_node_net=__toESM(require("net"));import_node_fs19=require("fs");import_node_crypto12=require("crypto");init_engine();init_host();init_store();init_types();init_proc()}});function nodeLauncher(e,n=["farmd"]){return()=>{const t=(0,import_node_child_process18.spawn)(process.execPath,[...process.execArgv,e,...n],{detached:true,stdio:"ignore",env:{...process.env}});t.unref()}}async function connectFarm(e){return new FarmClient(e).connect()}var import_node_net2,import_node_fs20,import_node_child_process18,import_node_crypto13,FarmClient;var init_client=__esm({"../sim-farm/src/client.ts"(){"use strict";import_node_net2=__toESM(require("net"));import_node_fs20=require("fs");import_node_child_process18=require("child_process");import_node_crypto13=require("crypto");init_store();init_proc();init_types();FarmClient=class{constructor(e){this.opts=e;this.sock=null;this.nextId=1;this.pending=new Map;this.buf="";this.renewals=new Map;this.reconnecting=null;this.closed=false;this.home=e.home??farmHome();this.clientIdValue=`c-${(0,import_node_crypto13.randomBytes)(5).toString("hex")}`}get clientId(){return this.owner?.clientId}async connect(){this.token=readOrCreateToken(this.home);this.owner={clientId:this.clientIdValue,pid:process.pid,pidStart:await pidStart(process.pid)??void 0,label:this.opts.label};if(await this.tryOpen())return this.checkVersion();const e=await readOwner(this.home);if(!await ownerAlive(e)){if(!this.opts.launcher)throw new FarmError("HOST_ERROR","The farm is not running.","Start it from Buoy Desktop or `pnpm farm status`.");this.opts.launcher()}const n=Date.now()+(this.opts.startTimeoutMs??2e4);while(Date.now()<n){await sleep2(250);if(await this.tryOpen())return this.checkVersion()}throw new FarmError("HOST_ERROR","The farm did not start in time.",`Check ${paths(this.home).log}.`)}async checkVersion(){const e=await this.send("hello",void 0,{});if(e.protocol<PROTOCOL_VERSION&&this.opts.launcher){const n=await this.send("shutdown",{ifIdle:true},{});if(n.stopping){this.close();await sleep2(500);return this.connect()}}return this}tryOpen(){const e=paths(this.home).socket;if(!(0,import_node_fs20.existsSync)(e))return Promise.resolve(false);return new Promise(n=>{const t=import_node_net2.default.createConnection(e);t.once("connect",()=>{this.sock=t;t.on("data",r=>this.onData(r));t.on("close",()=>this.onClose());t.on("error",()=>{});n(true)});t.once("error",()=>n(false))})}onData(e){this.buf+=e.toString("utf8");let n;while((n=this.buf.indexOf("\n"))>=0){const t=this.buf.slice(0,n);this.buf=this.buf.slice(n+1);let r;try{r=JSON.parse(t)}catch{continue}const i=this.pending.get(r.id);if(!i)continue;this.pending.delete(r.id);clearTimeout(i.timer);if(r.ok)i.resolve(r.result);else{const o=r.error??{};i.reject(new FarmError(o.code??"HOST_ERROR",o.message??"farm error",o.next,o.retryable))}}}onClose(){this.sock=null;for(const[,e]of this.pending){clearTimeout(e.timer);e.reject(new FarmError("HOST_ERROR","Lost the connection to the farm.",void 0,true))}this.pending.clear()}reconnect(){if(!this.reconnecting){this.reconnecting=this.connect().then(()=>void 0).finally(()=>{this.reconnecting=null})}return this.reconnecting}async call(e,n,t={}){if(!this.sock&&!this.closed)await this.reconnect();return this.send(e,n,t)}send(e,n,t){if(!this.sock)return Promise.reject(new FarmError("HOST_ERROR","Not connected to the farm.",void 0,true));const r=this.nextId++;const i={id:r,v:PROTOCOL_VERSION,token:this.token,client:this.owner,method:e,params:n,requestId:t.requestId};return new Promise((o,a)=>{const s=setTimeout(()=>{this.pending.delete(r);a(new FarmError("HOST_ERROR",`Farm call ${e} timed out.`,void 0,true))},t.timeoutMs??3e4);this.pending.set(r,{resolve:o,reject:a,timer:s});this.sock.write(JSON.stringify(i)+"\n")})}async acquire(e){const{requestId:n,...t}=e;const r=n??`acq-${(0,import_node_crypto13.randomBytes)(4).toString("hex")}`;const i=await this.call("acquire",t,{timeoutMs:15*6e4+(e.waitMs??0),requestId:r});if(this.renewals.has(i.leaseId))return i;const o=setInterval(()=>{this.call("renew",{leaseId:i.leaseId,epoch:i.epoch}).catch(a=>{if(a.code==="LEASE_EXPIRED"||a.code==="STALE_EPOCH")this.stopRenew(i.leaseId)})},15e3);o.unref?.();this.renewals.set(i.leaseId,o);return i}stopRenew(e){const n=this.renewals.get(e);if(n)clearInterval(n);this.renewals.delete(e)}async release(e,n,t="fast"){this.stopRenew(e);return this.call("release",{leaseId:e,epoch:n,reset:t},{timeoutMs:6e4,requestId:`rel-${e}-${n}`})}close(){this.closed=true;for(const e of[...this.renewals.keys()])this.stopRenew(e);this.sock?.end();this.sock=null}}}});var import_node_path20,import_node_os13,import_node_fs21;var init_discover=__esm({"../sim-farm/src/discover.ts"(){"use strict";import_node_path20=__toESM(require("path"));import_node_os13=__toESM(require("os"));import_node_fs21=require("fs");init_proc();init_seed();init_profiles()}});var init_src=__esm({"../sim-farm/src/index.ts"(){"use strict";init_types();init_profiles();init_engine();init_host();init_server();init_client();init_store();init_discover()}});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 l=s.claims.tier==="free"?"free":"pro";this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`dev:${s.claims.sid}`,valid:true,tier:l,isPro:l==="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 l=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(l).toISOString(),cachedAt:c,lastValidatedAt:c});this.persistCache();this.retry=0;this.nextCheck=Math.max(c+6e4,l-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 u of s){if(u.deviceId&&u.tier==="locked")this.lockDevice(String(u.deviceId));else if(u.deviceId&&(u.tier==="free"||u.tier==="pro")){c=this.lockedDevices.delete(String(u.deviceId))||c}}this.devices=s;const l=Date.now();for(const u of s)if(u.deviceId)this.lastSeen.set(u.deviceId,l);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 l=this.snapshotWaiters.get(c);if(l&&l.length){this.snapshotWaiters.set(c,[]);for(const u of l)u(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)}peekProjectDevice(){if(!this.admitted)return null;if(this.sessionDevice)return this.sessionDevice;const e=this.connectedDevices().filter(t=>!this.lockedDevices.has(t.deviceId)&&t.tools.length>0);const n=process.env.BUOY_PROJECT_ROOT||process.cwd();return pickByProject(e.map(t=>({deviceId:t.deviceId,root:this.devServerRoots.get(t.deviceId)})),n)??null}resolveDevice(e){this.requireAdmission();if(e){this.requireDeviceAccount(e);return e}const n=(l,u)=>new Error(`${NOT_READY_MARK} "${l}" (${u}) 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 l=this.devices.find(u=>u.deviceId===this.sessionDevice);if(l&&l.isConnected!==false)return this.sessionDevice;throw n(this.sessionDevice,"the device this session was using")}const t=this.connectedDevices();const r=t.filter(l=>!this.lockedDevices.has(l.deviceId));const i=r.filter(l=>l.tools.length>0);const o=process.env.BUOY_PROJECT_ROOT||process.cwd();const a=pickByProject(i.map(l=>({deviceId:l.deviceId,root:this.devServerRoots.get(l.deviceId)})),o);if(a)return this.sessionDevice=a;const s=pickByProject(this.devices.filter(l=>l.deviceId&&l.isConnected===false&&!this.lockedDevices.has(l.deviceId)).map(l=>({deviceId:l.deviceId,root:this.devServerRoots.get(l.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(l=>l.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 l=r.map(u=>u.deviceName).join(", ");throw new Error(`Connected devices (${l}) are not exposing any Buoy tools yet. Make sure the app is in the foreground with devtools mounted, then retry.`)}const c=i.map(l=>`${l.deviceName} (${l.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 l=this.healthOf(r);if(Date.now()-l.lastFullBudgetAt>RECOVERY_PROBE_MS){l.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((l,u)=>{const d=Date.now();const h=()=>{this.pendingActions.delete(a);if(o!==ALL_DEVICES&&!i.silent)this.noteTimeout(o);u(new Error(`Action "${e}.${n}" got no answer in ${Date.now()-d}ms. `+(o===ALL_DEVICES?"No device responded.":this.unresponsiveNote(o))))};const w=setTimeout(h,s);this.pendingActions.set(a,{resolve:l,reject:u,timer:w,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_zod37=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.64"?"7.0.64":"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 l=c.trim();if(l)n.push(Buffer.from(l,"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(l=>l.dataPath?webViewInstallIds(import_node_path4.default.join(l.dataPath,"Containers","Data","Application")):Promise.resolve([])));c.forEach((l,u)=>{if(l.includes(t))s.push(n[u])});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 l=c;return{ok:false,error:`Crop failed: ${l?.stderr||l?.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,l]=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:l-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 l=0;for(const u of[c.desc,c.text,c.id.split("/").pop()??""]){const d=u.trim().toLowerCase();if(!d)continue;if(d===t)l=Math.max(l,3);else if(d.startsWith(t))l=Math.max(l,2);else if(d.includes(t))l=Math.max(l,1)}return l};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,l)=>a.findIndex(u=>JSON.stringify(u.bounds)===JSON.stringify(c.bounds))===l);if(s.length>1){const c=s.filter(l=>[l.desc,l.text,l.id.split("/").pop()??""].some(u=>u.trim()===n.trim()));if(c.length)s=c}if(s.length>1){const c=s.filter(l=>l.clickable||/EditText|Button/.test(l.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 l=await import_node_fs5.promises.readFile(import_node_path6.default.join(s,"origin")).then(u=>u.toString("hex"),()=>"");if(l)n.push({db:c,origin:l})}}}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 l=new import_ws.WebSocket(a.webSocketDebuggerUrl);const u=setTimeout(()=>{l.close();c(new Error("the WebView did not answer"))},5e3);l.on("open",()=>l.send(JSON.stringify({id:1,method:"Runtime.evaluate",params:{expression:t,returnByValue:true}})));l.on("message",d=>{const h=JSON.parse(String(d));if(h.id!==1)return;clearTimeout(u);l.close();if(h.result?.exceptionDetails)c(new Error("the WebView script failed"));else s(h.result?.result?.value)});l.on("error",d=>{clearTimeout(u);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,n){if(!n){const t=await simsHoldingOf(e,["rn"]);return t.length?t:simsHoldingOf(e,["webview"])}return simsHoldingOf(e,n)}async function simsHoldingOf(e,n){let t=[];try{const i=JSON.parse(await simctl(["list","devices","booted","-j"])).devices;t=Object.entries(i).filter(([o])=>/iOS/.test(o)).flatMap(([,o])=>o.filter(a=>a.state==="Booted"))}catch{return[]}const r=await Promise.all(t.map(i=>findIosContainer(e,i.udid,i.dataPath,n)));return t.flatMap((i,o)=>r[o]?[{udid:i.udid,name:i.name,found:r[o]}]:[])}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,t,r){const i=tailOf(e);if(!i)return null;if(!t){try{const c=JSON.parse(await simctl(["list","devices","-j"])).devices;t=Object.values(c).flat().find(l=>l.udid===n)?.dataPath}catch{return null}}if(!t)return null;const o=import_node_path7.default.join(t,"Containers","Data","Application");let a=[];try{a=await import_node_fs6.promises.readdir(o)}catch{return null}const s=await Promise.all(a.map(c=>iosContainerHolds(import_node_path7.default.join(o,c),i,r)));for(const[c,l]of a.entries()){const u=import_node_path7.default.join(o,l);if(!s[c])continue;let d=null;try{d=(await sh("plutil",["-extract","MCMMetadataIdentifier","raw","-o","-",import_node_path7.default.join(u,".com.apple.mobile_container_manager.metadata.plist")])).trim()||null}catch{}return{container:u,bundleId:d,kind:s[c]}}return null}async function iosContainerHolds(e,n,t=["rn","webview"]){if(t.includes("rn")){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"rn"}catch{}}if(!t.includes("webview"))return null;return(await containerWebViewInstallIds(e).catch(()=>[])).includes(n)?"webview":null}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,l,u)=>!!c&&u.indexOf(c)===l).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}var finding=new Map;function findHost(e,n,t={}){if(t.udid||t.serial||t.bundleId)return findHostNow(e,n,t);const r=`${e}|${n??""}`;const i=finding.get(r);if(i)return i;const o=findHostNow(e,n,t).finally(()=>finding.delete(r));finding.set(r,o);return o}async function findHostNow(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 l=await simsHolding(e,r.idKind?[r.idKind]:void 0);if(l.length>1)throw cloneError(e,l);if(!l.some(u=>u.udid===r.udid)){hosts.delete(e);throw new Error(`The sim no longer holds "${e}". Try the host scan again.`)}}return r}if(r)hosts.delete(e);if(n==="android"){const l=await findAndroid(e,t);if(!l){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,l);return l}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??"";let a=null;if(!i){const l=await simsHolding(e);a=l.length===1?l[0]:null;if(l.length>1)throw cloneError(e,l);const u=l.length===1?{ok:true,udid:l[0].udid,how:`matched ${e} to "${l[0].name}"`}:await resolveSimUdid(e);if(!u.ok||!/^matched /.test(u.how)){const d=await findPhone(e).catch(()=>null);if(d){hosts.set(e,d);return d}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 s=a?.udid===i?await iosContainerHolds(a.found.container,tailOf(e),[a.found.kind])?a.found:null:await findIosContainer(e,i);if(!s)throw new Error(`Simulator ${i} does not hold "${e}".`);const c={platform:"ios",udid:i,name:o,bundleId:t.bundleId??s?.bundleId??null,container:s?.container??null,picked:!!t.udid,idKind:s.kind};hosts.set(e,c);return c}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!!await 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 l=Math.floor(c*s);const u=Math.max(l+1,Math.floor((c+1)*s));for(let d=0;d<r;d++){const h=Math.floor(d*a);const w=Math.max(h+1,Math.floor((d+1)*a));const p=[0,0,0,0];let g=0;for(let f=l;f<u;f++){for(let v=h;v<w;v++){const y=(f*e.width+v)*4;for(let b=0;b<4;b++)p[b]+=e.data[y+b];g++}}const m=(c*r+d)*4;for(let f=0;f<4;f++)o.data[m+f]=Math.round(p[f]/g)}}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 l=a==="aapt2"?c.trim().split("\n")[0]:/package: name='([^']+)'/.exec(c)?.[1]??"";if(l)return l}}}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 u=(await simctl(["get_app_container",e.udid,r,"data"]).catch(()=>"")).trim();if(u)s=await copyBuoyFiles(import_node_path7.default.join(u,"Documents"),a);if(u&&!s){try{c=await iosReadWebKeep(u)}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(u){throw new Error(`The app was removed, but installing ${import_node_path7.default.basename(i)} failed: ${u.message}. Install it again by hand.`)}let l="";if(a&&s){try{const u=(await simctl(["get_app_container",e.udid,r,"data"])).trim();await copyBuoyFiles(a,import_node_path7.default.join(u,"Documents"));e.container=u;l=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(u){l=` Buoy's sign-in could not be restored (${u.message}): sign in to Buoy again in the app.`}}else if(c.length){try{const u=(await simctl(["get_app_container",e.udid,r,"data"])).trim();await simctl(["launch",e.udid,r]);const d=await iosWaitForLocalStorage(u);await simctl(["terminate",e.udid,r]).catch(()=>void 0);if(!d||!await iosWriteWebKeep(u,c))throw new Error("the app made no WebView storage");e.container=u;l=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(u){l=` Buoy's sign-in could not be restored (${u.message}): sign in to Buoy again in the app.`}}else if(t){l=" 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.${l}`}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 l=c.split("\n").map(u=>u.trim()).filter(u=>u.startsWith("files/buoy-license/")||/react-buoy\/@react_buoy_(sync_device_id|install)\.json$/.test(u));for(const u of l){const d=await adbShell(e.serial,`run-as ${q(n)} base64 ${q(u)}`).catch(()=>"");if(d.trim())o.push({rel:u,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 l=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(l)} && 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 l of o){let u;try{u=await readAppFile(e.udid,n,l)}catch(h){throw new Error(`Could not back up Buoy's ${import_node_path7.default.basename(l)} from the iPhone (${h.message}). Nothing was changed.`)}if(!u)continue;const d=import_node_path7.default.join(a,l.replace(/\//g,"__"));await import_node_fs6.promises.writeFile(d,u,{mode:384});s.push({rel:l,local:d})}}await phoneQuit(e.udid,n).catch(()=>false);await phoneUninstall(e.udid,n);try{await phoneInstall(e.udid,t)}catch(l){throw new Error(`The app was removed, but installing ${import_node_path7.default.basename(t)} failed: ${l.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 l=s.some(d=>d.rel.includes("buoy-license"));const u=s.some(d=>d.rel.includes("sync_device_id"));c=l?` Kept Buoy's sign-in${u?" 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(l){c=` Buoy's sign-in could not be restored (${l.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 l=c instanceof Error?c.message:String(c);const u=l.startsWith(NOT_READY_MARK)&&/is not connected right now/.test(l)?/"([^"]+)"/.exec(l)?.[1]:void 0;const d=u?e.listDevices().some(h=>h.deviceId===u&&h.isPro):false;if(!r.allowOffline||!u||!d)throw c;i=u;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","native_inspect"],...!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/pinch (by query, testID, nativeTag or x/y; not label)","native_inspect (the app's side only)"]}}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/pinch","native_inspect"]:[]],...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 w=0;i.length===0&&w<10;w++){await new Promise(p=>setTimeout(p,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(w=>!w.isConnected).length;if(!t.includeDisconnected)i=i.filter(w=>w.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(w=>w.platform==="ios").map(w=>w.deviceId)).catch(()=>new Map);const s=i.filter(w=>w.isConnected);const c=s.some(w=>w.isPro);const l=s.some(w=>w.tier!=="locked");const u=s.filter(w=>w.collision);const d=await Promise.all(i.map(w=>w.isConnected?hostSummary(w,a.get(w.deviceId)).catch(()=>void 0):void 0));const h=i.map((w,p)=>{const g=a.get(w.deviceId);const m=d[p];return{deviceId:w.deviceId,deviceName:w.deviceName,platform:w.platform,isConnected:w.isConnected,isPro:w.isPro,tier:w.tier,access:n.accessState(w.deviceId),...g?{simulator:g}:{},...m?{host:m}:{},...w.collision?{collision:true}:{},tools:t.details?w.tools:w.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).`:""}`},...u.length>0?{warning:`${u.map(w=>`"${w.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:l?"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(u=>!i||u.deviceId===i);if(c.length===0)return fail(i?`No connected device "${i}". Call list_devices.`:"No devices are connected. Call list_devices.");const l=c.map(u=>[`**${u.deviceName}** (${u.deviceId})`,...u.tools.map(d=>`- ${d.toolId}: ${d.actions.join(", ")}`)].join("\n"));return{content:[{type:"text",text:`${l.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(l=>l.tools.map(u=>u.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:l}=await n.getSnapshot(a,s,{timeoutMs:o});return json({toolId:a,deviceId:s,...l?{stale:l}:{},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 l=t??r;if(!l)return fail("call_action needs toolId (see list_tool_actions).");const u=actionParams(o??a);const d=n.requireProDevice(s);const h=await n.callAction(l,i,u,d,{timeoutMs:c});return json({toolId:l,action:i,ok:true,result:h??null})}catch(l){return fail(errMsg(l))}})}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.");var coreTool=()=>process.env.BUOY_LOAD_CORE_TOOLS==="0"?void 0:{"anthropic/alwaysLoad":true};function clampLimit(e,n){return typeof e==="number"&&e>0?e:n}function staleHeader(e){return e?`${e}
5
5
 
6
- `:""}function inactiveToolMessage(e){return`No ${e.toolId} result from the device. The ${e.toolId} tool may be inactive, or the app needs a newer Buoy (${e.mcpTool} requires the ${e.action} action).`}function withDevice(e,n){return async t=>{try{const r=e.requireProDevice(t.deviceId);return await n(t,r)}catch(r){return fail2(errMsg2(r))}}}function lastSyncAfterDrop(e,n,t){const r=n instanceof Error?n.message:String(n);if(!/is not connected right now/.test(r))return void 0;const i=/"([^"]+)"/.exec(r)?.[1];if(!i||!e.listDevices().some(s=>s.deviceId===i&&s.isPro))return void 0;const o=e.lastSync(i,t);if(!o)return void 0;const a=o.ageMs==null?"earlier":`${Math.round(o.ageMs/1e3)}s ago`;return{deviceId:i,payload:o.payload,stale:`\u26A0\uFE0F "${i}" is not connected, so this is the last data it sent (${a}). If it dropped right after an action, the app likely hit a fatal error (a red error screen): look for it below, then reload_app to recover.`}}var PERF_TOOL_ID="perf-monitor";var clamp2=(e,n,t)=>Math.max(n,Math.min(t,e));var WARMUP_CASE_NAME="__batch_warmup__";var THERMAL_MARK={nominal:"\u{1F7E2} nominal",fair:"\u{1F7E1} fair",serious:"\u{1F7E0} serious",critical:"\u{1F534} critical",unknown:"\u2014"};var FALLBACK={perCaseDurationMs:5e3,settleMs:600,navTimeoutMs:5e3,runsPerCase:3,coolDownMs:2e3,discardWarmupRuns:0};function pick(e,n,t){return e??n??t}function buildAutomationConfig(e,n={}){const t=[];const r=(e.targetRoute||"").trim();if(!r)throw new Error("targetRoute is required (the screen to benchmark).");let i=(e.bounceRoute||"").trim();if(!i)i=r==="/"?"/_buoy_bounce":"/";if(i===r){throw new Error(`bounceRoute ("${i}") must differ from targetRoute \u2014 it's the screen we bounce to so the test screen fully remounts each run.`)}if(!Array.isArray(e.cases)||e.cases.length===0){throw new Error("At least one case is required.")}const o=e.cases.map((d,h)=>{const w=(d.name||"").trim()||`case ${h+1}`;return{id:`case-${h}`,name:w,params:d.params??{},route:d.route}});const a=clamp2(Math.round(pick(e.runsPerCase,n.runsPerCase,FALLBACK.runsPerCase)),1,10);const s=clamp2(Math.round(pick(e.coolDownMs,n.coolDownMs,FALLBACK.coolDownMs)),0,3e4);const c=clamp2(Math.round(pick(e.discardWarmupRuns,n.discardWarmupRuns,FALLBACK.discardWarmupRuns)),0,a-1);const l=e.shuffleCases??n.shuffleCases??o.length>3;if(o.length>3&&l===false){t.push("shuffleCases is off with >3 cases \u2014 later cases may be thermally throttled, biasing results. Consider enabling it.")}if(a===1){t.push("runsPerCase=1 \u2014 no median/variance; a single noisy run can mislead. 3+ is recommended.")}const u={targetRoute:r,bounceRoute:i,perCaseDurationMs:clamp2(Math.round(pick(e.perCaseDurationMs,n.perCaseDurationMs,FALLBACK.perCaseDurationMs)),1e3,6e4),settleMs:clamp2(Math.round(pick(e.settleMs,n.settleMs,FALLBACK.settleMs)),0,1e4),navTimeoutMs:clamp2(Math.round(pick(e.navTimeoutMs,n.navTimeoutMs,FALLBACK.navTimeoutMs)),1e3,3e4),cases:o,runsPerCase:a,coolDownMs:s,discardWarmupRuns:c,discardWarmupCase:e.discardWarmupCase??n.discardWarmupCase??true,shuffleCases:l,reloadBetweenCases:e.reloadBetweenCases??n.reloadBetweenCases??false,captureRenders:e.captureRenders??n.captureRenders??true};return{config:u,warnings:t}}function describeBenchmarkSettings(e){const n=c=>c>=1e3?`${(c/1e3).toFixed(c%1e3?1:0)}s`:`${c}ms`;const t=e.runsPerCase??1;const r=estimateBatchMs(e);const i=r/6e4;const o=i>=1?`~${i.toFixed(1)} min`:`~${Math.round(r/1e3)}s`;const a=[`**${n(e.perCaseDurationMs)} measured per page**`,t>1?`**${t} runs each** (median taken)`:`**1 run each** (no median \u2014 noisier)`,e.reloadBetweenCases?"**full reload between pages** (no state leaks across tests)":"no reload between pages",e.shuffleCases?"shuffled order (cancels thermal bias)":"fixed order",e.captureRenders!==false?"render capture on (per-component why-data)":"render capture off"];const s=e.settleMs+e.perCaseDurationMs+(e.coolDownMs??0)+1800;return`${a.join(", ")}. That's ~${n(s)} wall-clock per page; for ${e.cases.length} page(s) \xD7 ${t} run(s), **${o}** total.`}function estimateBatchMs(e){const n=1800;const t=e.settleMs+e.perCaseDurationMs+e.coolDownMs+n;let r=e.cases.length*(e.runsPerCase??1)*t;if(e.reloadBetweenCases)r+=e.cases.length*3e3;return r}function computeFlags(e){const n=[];const t=e.deviceMaxRefreshRate;if(e.uiFps!=null&&t&&e.uiFps<t*.95){n.push("UI thread drops frames")}else if(e.uiJank!=null&&e.uiJank>=2){n.push("UI jank spikes")}if(e.cpu!=null&&e.cpu>=90)n.push("CPU near cap");if(e.jsJank!=null&&e.jsJank>=5)n.push("JS thread stalls");return n}function computeWebFlags(e){const n=[];const t=e.deviceMaxRefreshRate;if(e.jsFps!=null&&t&&e.jsFps<t*.95){n.push("Low main-thread frame rate")}else if(e.longFrames!=null&&e.frames>0&&e.longFrames/e.frames>=.02){n.push("Frequent long frames")}const r=Math.max(e.frameGapMaxMs??0,e.edgeSilenceMs??0);if(r>=100)n.push(`Freeze of ${Math.round(r)} ms`);if(e.longTaskPct!=null&&e.longTaskPct>=20)n.push("Long tasks block the main thread");if(e.forcedLayoutMs!=null&&e.forcedLayoutMs>=50){n.push(`Forced layout in scripts (${Math.round(e.forcedLayoutMs)} ms)`)}if(e.styleLayoutMs!=null&&e.styleLayoutMs>=100){n.push(`Style and layout in slow frames (${Math.round(e.styleLayoutMs)} ms)`)}if(e.worstInteractionMs!=null&&e.worstInteractionMs>=200){n.push(`Slow response to input (${Math.round(e.worstInteractionMs)} ms)`)}if(e.layoutShift!=null&&e.layoutShift>=.1)n.push(`Layout shifts (${e.layoutShift})`);if(e.domGrowth!=null&&e.domGrowth>0){n.push(`DOM grew every run (+${e.domGrowth} nodes): check for a leak`)}return n}function domGrowthAcrossRuns(e){const n=e.filter(r=>!r.batchFailureReason&&!r.discardedWarmup).sort((r,i)=>(r.runIndex??0)-(i.runIndex??0)).map(r=>r.webRun?.domNodesStart).filter(r=>typeof r==="number");if(n.length<3)return null;for(let r=1;r<n.length;r++)if(n[r]<=n[r-1])return null;const t=n[n.length-1]-n[0];return t>=Math.max(50,n[0]*.05)?t:null}function pickBaseline(e,n){const t=e.find(i=>i.isBaseline);if(t)return t;const r=n?.[0]?.name;if(r){const i=e.filter(o=>o.caseName===r);if(i.length===1)return i[0]}return e[0]}function rankBatchFromIndex(e,n,t,r=[]){const i=e.filter(f=>f.batchId===n);const o=new Map(r.map(f=>[f.index,f.reason]));const a=Array.from(new Set(i.map(f=>f.batchIndex??0))).sort((f,v)=>f-v);const s=f=>{const v=i.filter($=>($.batchIndex??0)===f);if(v.length===0)return void 0;const y=v.filter($=>!$.batchFailureReason&&!$.discardedWarmup);const b=y.filter($=>$.webRun?.fps!=null);if(b.length>0&&b.length===y.length){const $=[...b].sort((T,_)=>T.webRun.fps-_.webRun.fps);return $[Math.floor(($.length-1)/2)]}if(y.length>0){return y.find($=>$.isMedianRun===true)??y.find($=>$.runIndex===0||$.runIndex===void 0)??y[0]}return v.find($=>$.batchFailureReason)??v[0]};const c=f=>typeof f==="number"?f:null;const l=a.map(f=>{const v=s(f);const y=i.filter(R=>(R.batchIndex??0)===f);const b=y.length;const $=y.filter(R=>!R.batchFailureReason&&!R.discardedWarmup);const T=R=>R.webRun?R.webRun.fps??R.jsFpsAvg:R.uiFpsAvg;const _=$.map(T).filter(R=>typeof R==="number");const x=v?.name??t?.[f]?.name??`case ${f+1}`;const A=i.some(R=>(R.batchIndex??0)===f&&R.isBaseline===true);const I=o.get(f)??v?.batchFailureReason;const E=y.every(R=>R.batchFailureReason||R.discardedWarmup);const S=Boolean(I)||!v||E;const k={batchIndex:f,caseName:x,params:v?.params??{},runs:b,failed:S,...v?.route?{route:v.route}:{},...A?{isBaseline:true}:{},failureReason:S?I??(E&&v?"only warmup runs were saved":"no run recorded"):void 0,uiFps:c(v?.uiFpsAvg),jsFps:c(v?.jsFpsAvg),cpu:c(v?.cpuAvg),memMb:c(v?.memMaxMb),jsJank:c(v?.jsJankFrames),uiJank:c(v?.uiJankFrames),deviceMaxRefreshRate:c(v?.deviceMaxRefreshRate),deltaUiFps:null,deltaJsFps:null,validRuns:$.length,fpsMin:_.length?round(Math.min(..._),1):null,fpsMax:_.length?round(Math.max(..._),1):null,...v?.thermalState?{thermalState:v.thermalState}:{},renderCommits:c(v?.renderCommits),renderWasted:v?.renderWasted,topRenderers:v?.topRenderers??[]};const M=v?.webRun;if(!M)return{...k,flags:S?[]:computeFlags(k)};const D=[...M.longTasksSupported?[]:["long tasks"],...M.heapSupported?[]:["JS heap"],...M.loaf===null?["long animation frames"]:[]];const P={...k,platform:"web",uiFps:null,uiJank:null,jsJank:null,cpu:null,memMb:M.heapSupported?k.memMb:null,deviceMaxRefreshRate:Math.max(k.deviceMaxRefreshRate??0,M.refreshHz??0)||null,longTaskPct:M.longTaskPct,frameGapP95Ms:M.frameGapP95Ms,frameGapMaxMs:M.frameGapMaxMs,edgeSilenceMs:M.edgeSilenceMs??null,jsFps:M.fps??k.jsFps,longFrames:M.longFrames,...D.length?{missingMetrics:D}:{},loafBlockingMs:M.loaf?.blockingMs??null,styleLayoutMs:M.loaf?.styleLayoutMs??null,forcedLayoutMs:M.loaf?.forcedLayoutMs??null,topScripts:M.loaf?.topScripts??[],worstInteractionMs:M.interactions?.worstMs??null,layoutShift:M.layoutShift??null,domNodes:M.domNodesEnd??null,domGrowth:domGrowthAcrossRuns(y),pageLoad:M.pageLoad??null,refreshCalibrated:M.refreshCalibrated??null};return{...P,flags:S?[]:computeWebFlags({...P,frames:M.frames})}}).filter(f=>f.caseName!==WARMUP_CASE_NAME).map((f,v)=>({...f,batchIndex:v}));const u=pickBaseline(l,t);if(u){u.isBaseline=true;for(const f of l){if(f===u)continue;if(f.uiFps!=null&&u.uiFps!=null)f.deltaUiFps=round(f.uiFps-u.uiFps,1);if(f.jsFps!=null&&u.jsFps!=null)f.deltaJsFps=round(f.jsFps-u.jsFps,1)}}const d=l.filter(f=>!f.failed);const h=(f,v)=>{let y;let b=NaN;for(const $ of d){const T=f($);if(T==null)continue;if(y===void 0||v(T,b)){y=$;b=T}}return y?.caseName};const w=f=>f.platform==="web"?f.longFrames??null:f.jsJank==null&&f.uiJank==null?null:(f.jsJank??0)+(f.uiJank??0);const p={uiFps:h(f=>f.uiFps,(f,v)=>f>v),jsFps:h(f=>f.jsFps,(f,v)=>f>v),lowestCpu:h(f=>f.cpu,(f,v)=>f<v),lowestMem:h(f=>f.memMb,(f,v)=>f<v),fewestJank:h(w,(f,v)=>f<v),fewestLongTasks:h(f=>f.longTaskPct??null,(f,v)=>f<v)};const g=d.filter(f=>f.flags.length>0).map(f=>({caseName:f.caseName,flags:f.flags}));const m=d.filter(f=>f.flags.length===0).sort((f,v)=>(v.uiFps??v.jsFps??0)-(f.uiFps??f.jsFps??0)||(f.cpu??f.longTaskPct??Infinity)-(v.cpu??v.longTaskPct??Infinity)||(f.memMb??Infinity)-(v.memMb??Infinity)).map(f=>f.caseName);return{batchId:n,baselineName:u?.caseName??null,deviceMaxRefreshRate:d.find(f=>f.deviceMaxRefreshRate!=null)?.deviceMaxRefreshRate??null,rows:l,leaders:p,flagged:g,balanced:m}}function pageLoadLines(e){const n=e.filter(a=>!a.failed);if(n.length===0)return[];const t=n.map(a=>a.pageLoad?.navigationId);if(t.some(a=>a==null)||new Set(t).size!==t.length)return[];if(n.some(a=>(a.pageLoad?.pageAgeMs??Infinity)>3e4))return[];const r=a=>(a??"").replace(/\/+$/,"")||"/";const i=a=>{const s=a.pageLoad;if(!s?.loadPath||r(s.loadPath)!==r(a.route))return false;const c=new URLSearchParams(s.loadSearch??"");const l=[...c.keys()];if(new Set(l).size!==l.length)return false;const u=Object.entries(a.params);return l.length===u.length&&u.every(([d,h])=>c.get(d)===h)};if(n.some(a=>!i(a)))return[];const o=a=>a==null?"\u2014":String(Math.round(a));return[`**Page load** (each case started on a fresh page load):`,"",`| Case | TTFB ms | FCP ms | LCP ms | DOM ready ms | Script KB | Total KB |`,`|------|--------:|-------:|-------:|-------------:|----------:|---------:|`,...n.map(a=>{const s=a.pageLoad;return`| ${a.caseName} | ${o(s.ttfbMs)} | ${o(s.fcpMs)} | ${o(s.lcpMs)} | ${o(s.domContentLoadedMs)} | ${o(s.scriptKb)} | ${o(s.totalKb)} |`}),"",`_KB is bytes over the network. 0 can mean the file came from cache, so compare cold loads with cold loads._`]}function closeCallNote(e){const n=o=>o.platform==="web"?o.jsFps:o.uiFps;const t=e.filter(o=>!o.failed&&n(o)!=null&&o.fpsMin!=null&&o.fpsMax!=null).sort((o,a)=>(n(a)??0)-(n(o)??0));if(t.length<2)return null;const[r,i]=t;if((r.validRuns??0)<2||(i.validRuns??0)<2){return`**Too few runs to separate the top cases.** ${r.caseName} and ${i.caseName} each need 2+ valid runs before their FPS gap means anything.`}if((i.fpsMax??0)>=(r.fpsMin??0)||(n(r)??0)-(n(i)??0)<=2){return`**Too close to call:** ${r.caseName} (${r.fpsMin}\u2013${r.fpsMax} FPS) and ${i.caseName} (${i.fpsMin}\u2013${i.fpsMax} FPS) overlap or sit within 2 FPS. No clear winner between them; more runs may separate them.`}return null}function formatRankingMarkdown(e){const n=(h,w=1)=>h==null?"\u2014":h.toFixed(w);const t=h=>h==null?"":h>0?` (+${h.toFixed(1)})`:` (${h.toFixed(1)})`;const r=[];r.push(`### Benchmark batch \`${e.batchId}\``);if(e.rows.some(h=>h.platform==="web")){formatWebTable(e,r);return r.join("\n")}r.push(`**No single winner \u2014 weigh the trade-offs.** UI-thread health matters more than raw averages: a cheap run that drops UI frames is worse than a pricier one that holds them.`);r.push("");const i=e.rows.some(h=>h.thermalState);const o=i?" Thermal |":"";const a=i?"-------|":"";r.push(`| # | Case | UI FPS | JS FPS | CPU % | Mem MB | JS jank | UI jank |${o} Flags |`);r.push(`|---|------|-------:|-------:|------:|-------:|--------:|--------:|${a}-------|`);for(const h of e.rows){const w=i?` ${THERMAL_MARK[h.thermalState??"unknown"]??"\u2014"} |`:"";if(h.failed){r.push(`| ${h.batchIndex} | ${h.caseName} | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 |${w} \u274C FAILED (${h.failureReason}) |`);continue}const p=h.flags.length?`\u26A0\uFE0F ${h.flags.join("; ")}`:"no flags";r.push(`| ${h.batchIndex} | ${h.caseName} | ${n(h.uiFps)}${t(h.deltaUiFps)} | ${n(h.jsFps)}${t(h.deltaJsFps)} | ${n(h.cpu)} | ${n(h.memMb)} | ${n(h.jsJank,0)} | ${n(h.uiJank,0)} |${w} ${p} |`)}const s=closeCallNote(e.rows);if(s){r.push("");r.push(s)}const c=e.rows.filter(h=>h.thermalState==="serious"||h.thermalState==="critical");if(c.length){r.push("");r.push(`**\u{1F525} Thermally throttled: ${c.map(h=>h.caseName).join(", ")}.** A throttled device runs SLOWER at a LOWER cpu%, so these cases can look like the cheapest in the batch while actually delivering fewer frames \u2014 check their UI FPS and jank, and re-run them on a cool device before drawing any conclusion.`)}r.push("");const l=e.leaders;const u=[l.uiFps&&`UI FPS \u2192 **${l.uiFps}**`,l.jsFps&&`JS FPS \u2192 **${l.jsFps}**`,l.lowestCpu&&`lowest CPU \u2192 **${l.lowestCpu}**`,l.lowestMem&&`lowest mem \u2192 **${l.lowestMem}**`,l.fewestJank&&`fewest jank \u2192 **${l.fewestJank}**`].filter(Boolean).join(" \xB7 ");if(u)r.push(`**Per-metric best:** ${u}`);r.push(e.balanced.length?`**No configured risk flags:** ${e.balanced.join(", ")}. Check missing metrics and workload requirements before choosing.`:`**No configured risk flags:** no candidates listed. Review failures, available metrics and flags before choosing.`);if(e.flagged.length){r.push(`**\u26A0\uFE0F At-risk:** ${e.flagged.map(h=>`${h.caseName} (${h.flags.join("; ")})`).join(" \xB7 ")}`)}const d=e.rows.filter(h=>!h.failed&&(h.renderCommits!=null||h.topRenderers.length>0)).map(h=>{const w=h.topRenderers.map(m=>`${m.name} \xD7${m.renders} (${m.totalMs}ms${m.cause?`, ${m.cause}`:""})`).join(", ");const p=h.renderCommits!=null?`${h.renderCommits} commits`:"";const g=h.renderWasted!=null?`${h.renderWasted} wasted`:"";return`- **${h.caseName}** \u2014 ${[p,g,w].filter(Boolean).join(": ")}`});if(d.length){r.push("");r.push("**Renders (median run)** \u2014 `wasted` = parent cascades + identity-only prop churn (removable). Cause per component: `propsUnstable` means a parent handed it a fresh function/object with unchanged values \u2014 fix upstream.");r.push(...d)}r.push("");r.push(`_Deltas vs baseline (\`${e.baselineName??"case #0"}\`). Don't pick on one metric \u2014 explain the trade-off (e.g. "A is cheapest but drops UI frames \u2192 jank risk; B costs more CPU but caps nothing")._`);return r.join("\n")}function compareReportStats(e,n){const t=(r,i)=>({a:{avg:round(r.avg,1),p95:round(r.p95,1)},b:{avg:round(i.avg,1),p95:round(i.p95,1)},deltaAvg:round(i.avg-r.avg,1)});return{a:e.name,b:n.name,uiFps:t(e.stats.uiFps,n.stats.uiFps),jsFps:t(e.stats.jsFps,n.stats.jsFps),cpuUsage:t(e.stats.cpuUsage,n.stats.cpuUsage),memoryUsage:t(e.stats.memoryUsage,n.stats.memoryUsage),jsJankFrames:{a:e.stats.jsJankFrames,b:n.stats.jsJankFrames,delta:n.stats.jsJankFrames-e.stats.jsJankFrames},uiJankFrames:{a:e.stats.uiJankFrames,b:n.stats.uiJankFrames,delta:n.stats.uiJankFrames-e.stats.uiJankFrames},...compareRenders(e.renders,n.renders)}}function compareWebReports(e,n){const t=(a,s,c)=>({a:a??null,b:s??null,delta:a!=null&&s!=null?round(s-a,1):null,better:c});const r=a=>a.webRun.heapSupported?round(a.stats.memoryUsage.max,1):null;const i=e.webRun;const o=n.webRun;return{a:e.name,b:n.name,platform:"web",note:"Browser runs: FPS is the main thread's whole-run requestAnimationFrame rate; long tasks % is not CPU. null = this browser couldn't measure it.",fps:t(i.fps??e.stats.jsFps.avg,o.fps??n.stats.jsFps.avg,"higher"),frameGapP95Ms:t(i.frameGapP95Ms,o.frameGapP95Ms,"lower"),frameGapMaxMs:t(i.frameGapMaxMs,o.frameGapMaxMs,"lower"),longFrames:t(i.longFrames,o.longFrames,"lower"),longTaskPct:t(i.longTaskPct,o.longTaskPct,"lower"),slowFrameBlockingMs:t(i.loaf?.blockingMs,o.loaf?.blockingMs,"lower"),styleLayoutPaintMs:t(i.loaf?.styleLayoutMs,o.loaf?.styleLayoutMs,"lower"),forcedLayoutMs:t(i.loaf?.forcedLayoutMs,o.loaf?.forcedLayoutMs,"lower"),worstInteractionMs:t(i.interactions?.worstMs,o.interactions?.worstMs,"lower"),layoutShift:t(i.layoutShift,o.layoutShift,"lower"),domNodes:t(i.domNodesEnd,o.domNodesEnd,"lower"),jsHeapMb:t(r(e),r(n),"lower"),topScripts:{a:i.loaf?.topScripts??[],b:o.loaf?.topScripts??[]},...compareRenders(e.renders,n.renders)}}function compareRenders(e,n){if(!e&&!n)return null;const t=r=>r??0;return{renders:{total:{a:t(e?.totalRenders),b:t(n?.totalRenders),delta:t(n?.totalRenders)-t(e?.totalRenders)},commits:{a:t(e?.totalCommits),b:t(n?.totalCommits),delta:t(n?.totalCommits)-t(e?.totalCommits)},wasted:{a:t(e?.wastedRenders),b:t(n?.wastedRenders),delta:t(n?.wastedRenders)-t(e?.wastedRenders)},causes:{a:e?.causes??{},b:n?.causes??{}}}}}function round(e,n){const t=Math.pow(10,n);return Math.round(e*t)/t}function formatWebTable(e,n){const t=(u,d=1)=>u==null?"\u2014":u.toFixed(d);const r=u=>u==null?"":u>0?` (+${u.toFixed(1)})`:` (${u.toFixed(1)})`;n.push(`**How to read this.** This is a browser run. FPS is the main thread's frame rate (requestAnimationFrame); it can't see frames dropped later by the GPU or compositor. Long tasks % is time the main thread was blocked by tasks over 50 ms, not CPU use. For Chrome's own dropped-frame count, use run_web_benchmark.`);n.push("");n.push(`| # | Case | FPS | p95 frame gap ms | Worst gap ms | Long frames | Long tasks % | JS heap MB | Flags |`);n.push(`|---|------|----:|-----------------:|-------------:|------------:|-------------:|--------:|-------|`);for(const u of e.rows){const d=u.isBaseline?`${u.caseName} (baseline)`:u.caseName;if(u.failed){n.push(`| ${u.batchIndex} | ${d} | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u274C FAILED (${u.failureReason}) |`);continue}const h=u.flags.length?`\u26A0\uFE0F ${u.flags.join("; ")}`:"no flags";n.push(`| ${u.batchIndex} | ${d} | ${t(u.jsFps)}${r(u.deltaJsFps)} | ${t(u.frameGapP95Ms)} | ${t(u.frameGapMaxMs)} | ${t(u.longFrames,0)} | ${t(u.longTaskPct)} | ${t(u.memMb)} | ${h} |`)}const i=e.rows.filter(u=>!u.failed).map(u=>{const d=[u.loafBlockingMs!=null&&u.loafBlockingMs>0&&`slow frames blocked input ${u.loafBlockingMs} ms`,u.styleLayoutMs!=null&&u.styleLayoutMs>0&&`style + layout ${u.styleLayoutMs} ms`,u.forcedLayoutMs!=null&&u.forcedLayoutMs>0&&`forced layout ${u.forcedLayoutMs} ms`,u.worstInteractionMs!=null&&`slowest input ${u.worstInteractionMs} ms`,u.layoutShift!=null&&u.layoutShift>0&&`layout shift ${u.layoutShift}`,u.domNodes!=null&&`${u.domNodes} DOM nodes${u.domGrowth?` (+${u.domGrowth} over the runs)`:""}`,u.topScripts&&u.topScripts.length>0&&`top scripts: ${u.topScripts.slice(0,3).map(h=>`${h.name} ${h.ms} ms`).join(", ")}`].filter(Boolean);return d.length?`- **${u.caseName}**: ${d.join(" \xB7 ")}`:null}).filter(Boolean);if(i.length){n.push("");n.push(`**Why frames were slow** (Long Animation Frames, Event Timing, DOM size; slow frames that ran past a run's end are left out):`);n.push(...i)}const o=pageLoadLines(e.rows);if(o.length){n.push("");n.push(...o)}const a=closeCallNote(e.rows);if(a){n.push("");n.push(a)}const s=Array.from(new Set(e.rows.flatMap(u=>u.missingMetrics??[])));if(s.length){n.push("");n.push(`**Not measured in this browser:** ${s.join(", ")}. These show as \u2014 and can't win or lose.`)}if(e.rows.some(u=>u.refreshCalibrated===false)){n.push("");n.push(`**Refresh rate not checked on an idle screen:** the batch couldn't reach its bounce screen first, so the screen rate (and frame budgets) may read low.`)}if(e.deviceMaxRefreshRate){n.push("");n.push(`Screen rate: ${e.deviceMaxRefreshRate} Hz. A frame gap over ${(1500/e.deviceMaxRefreshRate).toFixed(1)} ms missed at least one frame.`)}n.push("");const c=e.leaders;const l=[c.jsFps&&`FPS \u2192 **${c.jsFps}**`,c.fewestJank&&`fewest long frames \u2192 **${c.fewestJank}**`,c.fewestLongTasks&&`fewest long tasks \u2192 **${c.fewestLongTasks}**`,c.lowestMem&&`lowest heap \u2192 **${c.lowestMem}**`].filter(Boolean).join(" \xB7 ");if(l)n.push(`**Per-metric leaders:** ${l}`);if(e.flagged.length){n.push(`**\u26A0\uFE0F At-risk:** ${e.flagged.map(u=>`${u.caseName} (${u.flags.join("; ")})`).join(" \xB7 ")}`)}n.push(e.balanced.length?`**No configured risk flags:** ${e.balanced.join(", ")}. Check missing metrics and workload requirements before choosing.`:`**No configured risk flags:** no candidates listed. Review failures, available metrics and flags before choosing.`);n.push("");n.push(`_Deltas vs baseline (\`${e.baselineName??"case #0"}\`). Confirm finalists on a real phone browser: desktop numbers don't predict mobile GPU, memory or heat._`)}var POLL_INTERVAL_MS=1500;var delay2=e=>new Promise(n=>setTimeout(n,e));var json2=e=>({content:[{type:"text",text:JSON.stringify(e,null,2)}]});var caseSchema=import_zod3.z.object({name:import_zod3.z.string().describe("Display name for this variant (becomes the saved run's name)."),params:import_zod3.z.record(import_zod3.z.string()).optional().describe('Query params applied to the route for this case, e.g. { "renderer": "v2", "count": "100" }.'),route:import_zod3.z.string().optional().describe("Optional per-case route override; defaults to targetRoute.")});async function readDeviceSettings(e,n){try{const t=await e.callAction(PERF_TOOL_ID,"getAutomationConfig",{},n);if(!t)return{};const{perCaseDurationMs:r,settleMs:i,navTimeoutMs:o,runsPerCase:a,coolDownMs:s,discardWarmupRuns:c,shuffleCases:l,reloadBetweenCases:u,captureRenders:d}=t;return{perCaseDurationMs:r,settleMs:i,navTimeoutMs:o,runsPerCase:a,coolDownMs:s,discardWarmupRuns:c,shuffleCases:l,reloadBetweenCases:u,captureRenders:d}}catch{return{}}}async function readPerfSnapshot(e,n){const{payload:t}=await e.getSnapshot(PERF_TOOL_ID,n,{timeoutMs:4e3});return t}function batchIdsIn(e){const n=new Set;for(const t of e??[])if(t.batchId)n.add(t.batchId);return n}function runCountFor(e,n){return(e??[]).filter(t=>t.batchId===n).length}function newestBatchId(e){let n=null;for(const t of e??[]){if(t.batchId&&(!n||t.createdAt>n.at))n={id:t.batchId,at:t.createdAt}}return n?.id??null}function failuresFromIndex(e,n){const t=new Map;for(const r of e??[]){if(r.batchId===n&&r.batchFailureReason&&!t.has(r.batchIndex??0)){t.set(r.batchIndex??0,r.batchFailureReason)}}return[...t.entries()].map(([r,i])=>({index:r,reason:i}))}function expectedRunsFor(e){const n=e.cases.length+(e.discardWarmupCase===true?1:0);return n*(e.runsPerCase??1)}var SETTLE_WAIT_MS=1e4;function isRunnerBusy(e){return!!e&&e!=="idle"&&e!=="done"&&e!=="cancelled"}async function waitForRunnerSettled(e,n,t,r=SETTLE_WAIT_MS){const i=Date.now();while(Date.now()-i<r){const o=await readPerfSnapshot(e,n).catch(()=>null);if(o&&!isRunnerBusy(o.live?.automation?.phase))return true;await delay2(POLL_INTERVAL_MS)}t(`automation still busy after ${Math.round(r/1e3)}s`);return false}async function waitForBatchByIndex(e,n,t){const{preBatchIds:r,expectedRuns:i,maxWaitMs:o,log:a}=t;const s=t.reloadsBetweenCases?10:3;const c=Date.now();let l="";let u=false;let d=0;while(Date.now()-c<o){let p;try{p=await readPerfSnapshot(e,n)}catch{await delay2(POLL_INTERVAL_MS);continue}const g=p.index??[];const m=p.live?.automation?.phase??"idle";const f=p.live?.automationCompleted;if(f?.phase==="cancelled"&&!r.has(f.batchId)){return{batchId:f.batchId,failures:[],cancelled:true}}if(f?.phase==="done"&&!r.has(f.batchId)){return{batchId:f.batchId,failures:f.failures??failuresFromIndex(g,f.batchId)}}if(m!=="idle")u=true;if(m!==l){l=m;a(`automation phase: ${m}`)}const v=[...batchIdsIn(g)].find(y=>!r.has(y));if(v){const y=runCountFor(g,v);if(i>0&&y>=i){await waitForRunnerSettled(e,n,a);a(`batch ${v} complete (${y}/${i} runs saved)`);return{batchId:v,failures:failuresFromIndex(g,v)}}const b=(g??[]).filter(x=>x.batchId===v&&x.name!==WARMUP_CASE_NAME).length;const $=p.live?.pendingBatchId===v;const T=Boolean(p.live&&"pendingBatchId"in p.live);const _=!t.reloadsBetweenCases||T;if(m==="idle"&&u&&b>0&&!$&&_){if(++d>=s){a(`batch ${v} settled (${y} runs, automation idle)`);return{batchId:v,failures:failuresFromIndex(g,v)}}}else{d=0}}await delay2(POLL_INTERVAL_MS)}const h=await readPerfSnapshot(e,n).catch(()=>null);const w=h?[...batchIdsIn(h.index)].find(p=>!r.has(p)):void 0;if(w&&h)return{batchId:w,failures:failuresFromIndex(h.index,w),timedOut:true};throw new Error(`Batch did not start within ${Math.round(o/1e3)}s (last phase: ${l||"idle"}). Check get_automation_status \u2014 the device may not have navigated.`)}function registerPerfMonitorTools(e,n){e.registerTool("run_benchmark_batch",{description:"Run a perf-monitor benchmark batch and return per-metric leaders, risk flags and a comparison of available case results. Give it a target route and a matrix of cases (each a name + query params that select a variant on that route); it navigates, records, and benchmarks each case on the device, then ranks them. This blocks until the batch completes (can be minutes for large batches). The app must have the target route render its variants from the params.",inputSchema:{targetRoute:import_zod3.z.string().describe('The screen to benchmark, e.g. "/perf-test". Reads case params to pick a variant.'),cases:import_zod3.z.array(caseSchema).min(1).describe("The variants to compare. Case #0 is the baseline for deltas."),bounceRoute:import_zod3.z.string().optional().describe('Screen to bounce to between runs so the test screen fully remounts. Defaults to "/" (or a stub if target is "/").'),runsPerCase:import_zod3.z.number().optional().describe("Runs per case; the median becomes the canonical result. Default 3 (1\u201310)."),perCaseDurationMs:import_zod3.z.number().optional().describe("How long to record each run. Default 5000."),settleMs:import_zod3.z.number().optional().describe("Idle gap after navigation before recording. Default 600."),coolDownMs:import_zod3.z.number().optional().describe("Idle between runs/cases for thermal recovery. Default 2000."),navTimeoutMs:import_zod3.z.number().optional().describe("Max wait for navigation per run. Default 5000."),discardWarmupRuns:import_zod3.z.number().optional().describe("Discard first N runs of each case before taking the median. Default 0."),shuffleCases:import_zod3.z.boolean().optional().describe("Interleave and shuffle case order to reduce order-related bias. Default on for >3 cases."),reloadBetweenCases:import_zod3.z.boolean().optional().describe("Fully reload JS between cases (needs <AutomationResumer/> mounted). Default false."),captureRenders:import_zod3.z.boolean().optional().describe("Capture per-component render counts/durations during each run (needs @buoy-gg/highlight-updates installed; dev builds only). Adds instrumentation overhead that can vary with the workload. Default true."),deviceId:import_zod3.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."),maxWaitMs:import_zod3.z.number().optional().describe("Safety cap for how long to wait for completion. Defaults to ~3\xD7 the estimate + 60s.")}},async t=>{const r=i=>process.stderr.write(`[buoy-mcp] ${i}
6
+ `:""}function inactiveToolMessage(e){return`No ${e.toolId} result from the device. The ${e.toolId} tool may be inactive, or the app needs a newer Buoy (${e.mcpTool} requires the ${e.action} action).`}function withDevice(e,n){return async t=>{try{const r=e.requireProDevice(t.deviceId);return await n(t,r)}catch(r){return fail2(errMsg2(r))}}}function lastSyncAfterDrop(e,n,t){const r=n instanceof Error?n.message:String(n);if(!/is not connected right now/.test(r))return void 0;const i=/"([^"]+)"/.exec(r)?.[1];if(!i||!e.listDevices().some(s=>s.deviceId===i&&s.isPro))return void 0;const o=e.lastSync(i,t);if(!o)return void 0;const a=o.ageMs==null?"earlier":`${Math.round(o.ageMs/1e3)}s ago`;return{deviceId:i,payload:o.payload,stale:`\u26A0\uFE0F "${i}" is not connected, so this is the last data it sent (${a}). If it dropped right after an action, the app likely hit a fatal error (a red error screen): look for it below, then reload_app to recover.`}}var PERF_TOOL_ID="perf-monitor";var clamp2=(e,n,t)=>Math.max(n,Math.min(t,e));var WARMUP_CASE_NAME="__batch_warmup__";var THERMAL_MARK={nominal:"\u{1F7E2} nominal",fair:"\u{1F7E1} fair",serious:"\u{1F7E0} serious",critical:"\u{1F534} critical",unknown:"\u2014"};var FALLBACK={perCaseDurationMs:5e3,settleMs:600,navTimeoutMs:5e3,runsPerCase:3,coolDownMs:2e3,discardWarmupRuns:0};function pick(e,n,t){return e??n??t}function buildAutomationConfig(e,n={}){const t=[];const r=(e.targetRoute||"").trim();if(!r)throw new Error("targetRoute is required (the screen to benchmark).");let i=(e.bounceRoute||"").trim();if(!i)i=r==="/"?"/_buoy_bounce":"/";if(i===r){throw new Error(`bounceRoute ("${i}") must differ from targetRoute \u2014 it's the screen we bounce to so the test screen fully remounts each run.`)}if(!Array.isArray(e.cases)||e.cases.length===0){throw new Error("At least one case is required.")}const o=e.cases.map((d,h)=>{const w=(d.name||"").trim()||`case ${h+1}`;return{id:`case-${h}`,name:w,params:d.params??{},route:d.route}});const a=clamp2(Math.round(pick(e.runsPerCase,n.runsPerCase,FALLBACK.runsPerCase)),1,10);const s=clamp2(Math.round(pick(e.coolDownMs,n.coolDownMs,FALLBACK.coolDownMs)),0,3e4);const c=clamp2(Math.round(pick(e.discardWarmupRuns,n.discardWarmupRuns,FALLBACK.discardWarmupRuns)),0,a-1);const l=e.shuffleCases??n.shuffleCases??o.length>3;if(o.length>3&&l===false){t.push("shuffleCases is off with >3 cases \u2014 later cases may be thermally throttled, biasing results. Consider enabling it.")}if(a===1){t.push("runsPerCase=1 \u2014 no median/variance; a single noisy run can mislead. 3+ is recommended.")}const u={targetRoute:r,bounceRoute:i,perCaseDurationMs:clamp2(Math.round(pick(e.perCaseDurationMs,n.perCaseDurationMs,FALLBACK.perCaseDurationMs)),1e3,6e4),settleMs:clamp2(Math.round(pick(e.settleMs,n.settleMs,FALLBACK.settleMs)),0,1e4),navTimeoutMs:clamp2(Math.round(pick(e.navTimeoutMs,n.navTimeoutMs,FALLBACK.navTimeoutMs)),1e3,3e4),cases:o,runsPerCase:a,coolDownMs:s,discardWarmupRuns:c,discardWarmupCase:e.discardWarmupCase??n.discardWarmupCase??true,shuffleCases:l,reloadBetweenCases:e.reloadBetweenCases??n.reloadBetweenCases??false,captureRenders:e.captureRenders??n.captureRenders??true};return{config:u,warnings:t}}function describeBenchmarkSettings(e){const n=c=>c>=1e3?`${(c/1e3).toFixed(c%1e3?1:0)}s`:`${c}ms`;const t=e.runsPerCase??1;const r=estimateBatchMs(e);const i=r/6e4;const o=i>=1?`~${i.toFixed(1)} min`:`~${Math.round(r/1e3)}s`;const a=[`**${n(e.perCaseDurationMs)} measured per page**`,t>1?`**${t} runs each** (median taken)`:`**1 run each** (no median \u2014 noisier)`,e.reloadBetweenCases?"**full reload between pages** (no state leaks across tests)":"no reload between pages",e.shuffleCases?"shuffled order (cancels thermal bias)":"fixed order",e.captureRenders!==false?"render capture on (per-component why-data)":"render capture off"];const s=e.settleMs+e.perCaseDurationMs+(e.coolDownMs??0)+1800;return`${a.join(", ")}. That's ~${n(s)} wall-clock per page; for ${e.cases.length} page(s) \xD7 ${t} run(s), **${o}** total.`}function estimateBatchMs(e){const n=1800;const t=e.settleMs+e.perCaseDurationMs+e.coolDownMs+n;let r=e.cases.length*(e.runsPerCase??1)*t;if(e.reloadBetweenCases)r+=e.cases.length*3e3;return r}function computeFlags(e){const n=[];const t=e.deviceMaxRefreshRate;if(e.uiFps!=null&&t&&e.uiFps<t*.95){n.push("UI thread drops frames")}else if(e.uiJank!=null&&e.uiJank>=2){n.push("UI jank spikes")}if(e.cpu!=null&&e.cpu>=90)n.push("CPU near cap");if(e.jsJank!=null&&e.jsJank>=5)n.push("JS thread stalls");return n}function computeWebFlags(e){const n=[];const t=e.deviceMaxRefreshRate;if(e.jsFps!=null&&t&&e.jsFps<t*.95){n.push("Low main-thread frame rate")}else if(e.longFrames!=null&&e.frames>0&&e.longFrames/e.frames>=.02){n.push("Frequent long frames")}const r=Math.max(e.frameGapMaxMs??0,e.edgeSilenceMs??0);if(r>=100)n.push(`Freeze of ${Math.round(r)} ms`);if(e.longTaskPct!=null&&e.longTaskPct>=20)n.push("Long tasks block the main thread");if(e.forcedLayoutMs!=null&&e.forcedLayoutMs>=50){n.push(`Forced layout in scripts (${Math.round(e.forcedLayoutMs)} ms)`)}if(e.styleLayoutMs!=null&&e.styleLayoutMs>=100){n.push(`Style and layout in slow frames (${Math.round(e.styleLayoutMs)} ms)`)}if(e.worstInteractionMs!=null&&e.worstInteractionMs>=200){n.push(`Slow response to input (${Math.round(e.worstInteractionMs)} ms)`)}if(e.layoutShift!=null&&e.layoutShift>=.1)n.push(`Layout shifts (${e.layoutShift})`);if(e.domGrowth!=null&&e.domGrowth>0){n.push(`DOM grew every run (+${e.domGrowth} nodes): check for a leak`)}return n}function domGrowthAcrossRuns(e){const n=e.filter(r=>!r.batchFailureReason&&!r.discardedWarmup).sort((r,i)=>(r.runIndex??0)-(i.runIndex??0)).map(r=>r.webRun?.domNodesStart).filter(r=>typeof r==="number");if(n.length<3)return null;for(let r=1;r<n.length;r++)if(n[r]<=n[r-1])return null;const t=n[n.length-1]-n[0];return t>=Math.max(50,n[0]*.05)?t:null}function pickBaseline(e,n){const t=e.find(i=>i.isBaseline);if(t)return t;const r=n?.[0]?.name;if(r){const i=e.filter(o=>o.caseName===r);if(i.length===1)return i[0]}return e[0]}function rankBatchFromIndex(e,n,t,r=[]){const i=e.filter(f=>f.batchId===n);const o=new Map(r.map(f=>[f.index,f.reason]));const a=Array.from(new Set(i.map(f=>f.batchIndex??0))).sort((f,v)=>f-v);const s=f=>{const v=i.filter($=>($.batchIndex??0)===f);if(v.length===0)return void 0;const y=v.filter($=>!$.batchFailureReason&&!$.discardedWarmup);const b=y.filter($=>$.webRun?.fps!=null);if(b.length>0&&b.length===y.length){const $=[...b].sort((T,_)=>T.webRun.fps-_.webRun.fps);return $[Math.floor(($.length-1)/2)]}if(y.length>0){return y.find($=>$.isMedianRun===true)??y.find($=>$.runIndex===0||$.runIndex===void 0)??y[0]}return v.find($=>$.batchFailureReason)??v[0]};const c=f=>typeof f==="number"?f:null;const l=a.map(f=>{const v=s(f);const y=i.filter(R=>(R.batchIndex??0)===f);const b=y.length;const $=y.filter(R=>!R.batchFailureReason&&!R.discardedWarmup);const T=R=>R.webRun?R.webRun.fps??R.jsFpsAvg:R.uiFpsAvg;const _=$.map(T).filter(R=>typeof R==="number");const x=v?.name??t?.[f]?.name??`case ${f+1}`;const I=i.some(R=>(R.batchIndex??0)===f&&R.isBaseline===true);const D=o.get(f)??v?.batchFailureReason;const E=y.every(R=>R.batchFailureReason||R.discardedWarmup);const S=Boolean(D)||!v||E;const k={batchIndex:f,caseName:x,params:v?.params??{},runs:b,failed:S,...v?.route?{route:v.route}:{},...I?{isBaseline:true}:{},failureReason:S?D??(E&&v?"only warmup runs were saved":"no run recorded"):void 0,uiFps:c(v?.uiFpsAvg),jsFps:c(v?.jsFpsAvg),cpu:c(v?.cpuAvg),memMb:c(v?.memMaxMb),jsJank:c(v?.jsJankFrames),uiJank:c(v?.uiJankFrames),deviceMaxRefreshRate:c(v?.deviceMaxRefreshRate),deltaUiFps:null,deltaJsFps:null,validRuns:$.length,fpsMin:_.length?round(Math.min(..._),1):null,fpsMax:_.length?round(Math.max(..._),1):null,...v?.thermalState?{thermalState:v.thermalState}:{},renderCommits:c(v?.renderCommits),renderWasted:v?.renderWasted,topRenderers:v?.topRenderers??[]};const M=v?.webRun;if(!M)return{...k,flags:S?[]:computeFlags(k)};const A=[...M.longTasksSupported?[]:["long tasks"],...M.heapSupported?[]:["JS heap"],...M.loaf===null?["long animation frames"]:[]];const O={...k,platform:"web",uiFps:null,uiJank:null,jsJank:null,cpu:null,memMb:M.heapSupported?k.memMb:null,deviceMaxRefreshRate:Math.max(k.deviceMaxRefreshRate??0,M.refreshHz??0)||null,longTaskPct:M.longTaskPct,frameGapP95Ms:M.frameGapP95Ms,frameGapMaxMs:M.frameGapMaxMs,edgeSilenceMs:M.edgeSilenceMs??null,jsFps:M.fps??k.jsFps,longFrames:M.longFrames,...A.length?{missingMetrics:A}:{},loafBlockingMs:M.loaf?.blockingMs??null,styleLayoutMs:M.loaf?.styleLayoutMs??null,forcedLayoutMs:M.loaf?.forcedLayoutMs??null,topScripts:M.loaf?.topScripts??[],worstInteractionMs:M.interactions?.worstMs??null,layoutShift:M.layoutShift??null,domNodes:M.domNodesEnd??null,domGrowth:domGrowthAcrossRuns(y),pageLoad:M.pageLoad??null,refreshCalibrated:M.refreshCalibrated??null};return{...O,flags:S?[]:computeWebFlags({...O,frames:M.frames})}}).filter(f=>f.caseName!==WARMUP_CASE_NAME).map((f,v)=>({...f,batchIndex:v}));const u=pickBaseline(l,t);if(u){u.isBaseline=true;for(const f of l){if(f===u)continue;if(f.uiFps!=null&&u.uiFps!=null)f.deltaUiFps=round(f.uiFps-u.uiFps,1);if(f.jsFps!=null&&u.jsFps!=null)f.deltaJsFps=round(f.jsFps-u.jsFps,1)}}const d=l.filter(f=>!f.failed);const h=(f,v)=>{let y;let b=NaN;for(const $ of d){const T=f($);if(T==null)continue;if(y===void 0||v(T,b)){y=$;b=T}}return y?.caseName};const w=f=>f.platform==="web"?f.longFrames??null:f.jsJank==null&&f.uiJank==null?null:(f.jsJank??0)+(f.uiJank??0);const p={uiFps:h(f=>f.uiFps,(f,v)=>f>v),jsFps:h(f=>f.jsFps,(f,v)=>f>v),lowestCpu:h(f=>f.cpu,(f,v)=>f<v),lowestMem:h(f=>f.memMb,(f,v)=>f<v),fewestJank:h(w,(f,v)=>f<v),fewestLongTasks:h(f=>f.longTaskPct??null,(f,v)=>f<v)};const g=d.filter(f=>f.flags.length>0).map(f=>({caseName:f.caseName,flags:f.flags}));const m=d.filter(f=>f.flags.length===0).sort((f,v)=>(v.uiFps??v.jsFps??0)-(f.uiFps??f.jsFps??0)||(f.cpu??f.longTaskPct??Infinity)-(v.cpu??v.longTaskPct??Infinity)||(f.memMb??Infinity)-(v.memMb??Infinity)).map(f=>f.caseName);return{batchId:n,baselineName:u?.caseName??null,deviceMaxRefreshRate:d.find(f=>f.deviceMaxRefreshRate!=null)?.deviceMaxRefreshRate??null,rows:l,leaders:p,flagged:g,balanced:m}}function pageLoadLines(e){const n=e.filter(a=>!a.failed);if(n.length===0)return[];const t=n.map(a=>a.pageLoad?.navigationId);if(t.some(a=>a==null)||new Set(t).size!==t.length)return[];if(n.some(a=>(a.pageLoad?.pageAgeMs??Infinity)>3e4))return[];const r=a=>(a??"").replace(/\/+$/,"")||"/";const i=a=>{const s=a.pageLoad;if(!s?.loadPath||r(s.loadPath)!==r(a.route))return false;const c=new URLSearchParams(s.loadSearch??"");const l=[...c.keys()];if(new Set(l).size!==l.length)return false;const u=Object.entries(a.params);return l.length===u.length&&u.every(([d,h])=>c.get(d)===h)};if(n.some(a=>!i(a)))return[];const o=a=>a==null?"\u2014":String(Math.round(a));return[`**Page load** (each case started on a fresh page load):`,"",`| Case | TTFB ms | FCP ms | LCP ms | DOM ready ms | Script KB | Total KB |`,`|------|--------:|-------:|-------:|-------------:|----------:|---------:|`,...n.map(a=>{const s=a.pageLoad;return`| ${a.caseName} | ${o(s.ttfbMs)} | ${o(s.fcpMs)} | ${o(s.lcpMs)} | ${o(s.domContentLoadedMs)} | ${o(s.scriptKb)} | ${o(s.totalKb)} |`}),"",`_KB is bytes over the network. 0 can mean the file came from cache, so compare cold loads with cold loads._`]}function closeCallNote(e){const n=o=>o.platform==="web"?o.jsFps:o.uiFps;const t=e.filter(o=>!o.failed&&n(o)!=null&&o.fpsMin!=null&&o.fpsMax!=null).sort((o,a)=>(n(a)??0)-(n(o)??0));if(t.length<2)return null;const[r,i]=t;if((r.validRuns??0)<2||(i.validRuns??0)<2){return`**Too few runs to separate the top cases.** ${r.caseName} and ${i.caseName} each need 2+ valid runs before their FPS gap means anything.`}if((i.fpsMax??0)>=(r.fpsMin??0)||(n(r)??0)-(n(i)??0)<=2){return`**Too close to call:** ${r.caseName} (${r.fpsMin}\u2013${r.fpsMax} FPS) and ${i.caseName} (${i.fpsMin}\u2013${i.fpsMax} FPS) overlap or sit within 2 FPS. No clear winner between them; more runs may separate them.`}return null}function formatRankingMarkdown(e){const n=(h,w=1)=>h==null?"\u2014":h.toFixed(w);const t=h=>h==null?"":h>0?` (+${h.toFixed(1)})`:` (${h.toFixed(1)})`;const r=[];r.push(`### Benchmark batch \`${e.batchId}\``);if(e.rows.some(h=>h.platform==="web")){formatWebTable(e,r);return r.join("\n")}r.push(`**No single winner \u2014 weigh the trade-offs.** UI-thread health matters more than raw averages: a cheap run that drops UI frames is worse than a pricier one that holds them.`);r.push("");const i=e.rows.some(h=>h.thermalState);const o=i?" Thermal |":"";const a=i?"-------|":"";r.push(`| # | Case | UI FPS | JS FPS | CPU % | Mem MB | JS jank | UI jank |${o} Flags |`);r.push(`|---|------|-------:|-------:|------:|-------:|--------:|--------:|${a}-------|`);for(const h of e.rows){const w=i?` ${THERMAL_MARK[h.thermalState??"unknown"]??"\u2014"} |`:"";if(h.failed){r.push(`| ${h.batchIndex} | ${h.caseName} | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 |${w} \u274C FAILED (${h.failureReason}) |`);continue}const p=h.flags.length?`\u26A0\uFE0F ${h.flags.join("; ")}`:"no flags";r.push(`| ${h.batchIndex} | ${h.caseName} | ${n(h.uiFps)}${t(h.deltaUiFps)} | ${n(h.jsFps)}${t(h.deltaJsFps)} | ${n(h.cpu)} | ${n(h.memMb)} | ${n(h.jsJank,0)} | ${n(h.uiJank,0)} |${w} ${p} |`)}const s=closeCallNote(e.rows);if(s){r.push("");r.push(s)}const c=e.rows.filter(h=>h.thermalState==="serious"||h.thermalState==="critical");if(c.length){r.push("");r.push(`**\u{1F525} Thermally throttled: ${c.map(h=>h.caseName).join(", ")}.** A throttled device runs SLOWER at a LOWER cpu%, so these cases can look like the cheapest in the batch while actually delivering fewer frames \u2014 check their UI FPS and jank, and re-run them on a cool device before drawing any conclusion.`)}r.push("");const l=e.leaders;const u=[l.uiFps&&`UI FPS \u2192 **${l.uiFps}**`,l.jsFps&&`JS FPS \u2192 **${l.jsFps}**`,l.lowestCpu&&`lowest CPU \u2192 **${l.lowestCpu}**`,l.lowestMem&&`lowest mem \u2192 **${l.lowestMem}**`,l.fewestJank&&`fewest jank \u2192 **${l.fewestJank}**`].filter(Boolean).join(" \xB7 ");if(u)r.push(`**Per-metric best:** ${u}`);r.push(e.balanced.length?`**No configured risk flags:** ${e.balanced.join(", ")}. Check missing metrics and workload requirements before choosing.`:`**No configured risk flags:** no candidates listed. Review failures, available metrics and flags before choosing.`);if(e.flagged.length){r.push(`**\u26A0\uFE0F At-risk:** ${e.flagged.map(h=>`${h.caseName} (${h.flags.join("; ")})`).join(" \xB7 ")}`)}const d=e.rows.filter(h=>!h.failed&&(h.renderCommits!=null||h.topRenderers.length>0)).map(h=>{const w=h.topRenderers.map(m=>`${m.name} \xD7${m.renders} (${m.totalMs}ms${m.cause?`, ${m.cause}`:""})`).join(", ");const p=h.renderCommits!=null?`${h.renderCommits} commits`:"";const g=h.renderWasted!=null?`${h.renderWasted} wasted`:"";return`- **${h.caseName}** \u2014 ${[p,g,w].filter(Boolean).join(": ")}`});if(d.length){r.push("");r.push("**Renders (median run)** \u2014 `wasted` = parent cascades + identity-only prop churn (removable). Cause per component: `propsUnstable` means a parent handed it a fresh function/object with unchanged values \u2014 fix upstream.");r.push(...d)}r.push("");r.push(`_Deltas vs baseline (\`${e.baselineName??"case #0"}\`). Don't pick on one metric \u2014 explain the trade-off (e.g. "A is cheapest but drops UI frames \u2192 jank risk; B costs more CPU but caps nothing")._`);return r.join("\n")}function compareReportStats(e,n){const t=(r,i)=>({a:{avg:round(r.avg,1),p95:round(r.p95,1)},b:{avg:round(i.avg,1),p95:round(i.p95,1)},deltaAvg:round(i.avg-r.avg,1)});return{a:e.name,b:n.name,uiFps:t(e.stats.uiFps,n.stats.uiFps),jsFps:t(e.stats.jsFps,n.stats.jsFps),cpuUsage:t(e.stats.cpuUsage,n.stats.cpuUsage),memoryUsage:t(e.stats.memoryUsage,n.stats.memoryUsage),jsJankFrames:{a:e.stats.jsJankFrames,b:n.stats.jsJankFrames,delta:n.stats.jsJankFrames-e.stats.jsJankFrames},uiJankFrames:{a:e.stats.uiJankFrames,b:n.stats.uiJankFrames,delta:n.stats.uiJankFrames-e.stats.uiJankFrames},...compareRenders(e.renders,n.renders)}}function compareWebReports(e,n){const t=(a,s,c)=>({a:a??null,b:s??null,delta:a!=null&&s!=null?round(s-a,1):null,better:c});const r=a=>a.webRun.heapSupported?round(a.stats.memoryUsage.max,1):null;const i=e.webRun;const o=n.webRun;return{a:e.name,b:n.name,platform:"web",note:"Browser runs: FPS is the main thread's whole-run requestAnimationFrame rate; long tasks % is not CPU. null = this browser couldn't measure it.",fps:t(i.fps??e.stats.jsFps.avg,o.fps??n.stats.jsFps.avg,"higher"),frameGapP95Ms:t(i.frameGapP95Ms,o.frameGapP95Ms,"lower"),frameGapMaxMs:t(i.frameGapMaxMs,o.frameGapMaxMs,"lower"),longFrames:t(i.longFrames,o.longFrames,"lower"),longTaskPct:t(i.longTaskPct,o.longTaskPct,"lower"),slowFrameBlockingMs:t(i.loaf?.blockingMs,o.loaf?.blockingMs,"lower"),styleLayoutPaintMs:t(i.loaf?.styleLayoutMs,o.loaf?.styleLayoutMs,"lower"),forcedLayoutMs:t(i.loaf?.forcedLayoutMs,o.loaf?.forcedLayoutMs,"lower"),worstInteractionMs:t(i.interactions?.worstMs,o.interactions?.worstMs,"lower"),layoutShift:t(i.layoutShift,o.layoutShift,"lower"),domNodes:t(i.domNodesEnd,o.domNodesEnd,"lower"),jsHeapMb:t(r(e),r(n),"lower"),topScripts:{a:i.loaf?.topScripts??[],b:o.loaf?.topScripts??[]},...compareRenders(e.renders,n.renders)}}function compareRenders(e,n){if(!e&&!n)return null;const t=r=>r??0;return{renders:{total:{a:t(e?.totalRenders),b:t(n?.totalRenders),delta:t(n?.totalRenders)-t(e?.totalRenders)},commits:{a:t(e?.totalCommits),b:t(n?.totalCommits),delta:t(n?.totalCommits)-t(e?.totalCommits)},wasted:{a:t(e?.wastedRenders),b:t(n?.wastedRenders),delta:t(n?.wastedRenders)-t(e?.wastedRenders)},causes:{a:e?.causes??{},b:n?.causes??{}}}}}function round(e,n){const t=Math.pow(10,n);return Math.round(e*t)/t}function formatWebTable(e,n){const t=(u,d=1)=>u==null?"\u2014":u.toFixed(d);const r=u=>u==null?"":u>0?` (+${u.toFixed(1)})`:` (${u.toFixed(1)})`;n.push(`**How to read this.** This is a browser run. FPS is the main thread's frame rate (requestAnimationFrame); it can't see frames dropped later by the GPU or compositor. Long tasks % is time the main thread was blocked by tasks over 50 ms, not CPU use. For Chrome's own dropped-frame count, use run_web_benchmark.`);n.push("");n.push(`| # | Case | FPS | p95 frame gap ms | Worst gap ms | Long frames | Long tasks % | JS heap MB | Flags |`);n.push(`|---|------|----:|-----------------:|-------------:|------------:|-------------:|--------:|-------|`);for(const u of e.rows){const d=u.isBaseline?`${u.caseName} (baseline)`:u.caseName;if(u.failed){n.push(`| ${u.batchIndex} | ${d} | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u274C FAILED (${u.failureReason}) |`);continue}const h=u.flags.length?`\u26A0\uFE0F ${u.flags.join("; ")}`:"no flags";n.push(`| ${u.batchIndex} | ${d} | ${t(u.jsFps)}${r(u.deltaJsFps)} | ${t(u.frameGapP95Ms)} | ${t(u.frameGapMaxMs)} | ${t(u.longFrames,0)} | ${t(u.longTaskPct)} | ${t(u.memMb)} | ${h} |`)}const i=e.rows.filter(u=>!u.failed).map(u=>{const d=[u.loafBlockingMs!=null&&u.loafBlockingMs>0&&`slow frames blocked input ${u.loafBlockingMs} ms`,u.styleLayoutMs!=null&&u.styleLayoutMs>0&&`style + layout ${u.styleLayoutMs} ms`,u.forcedLayoutMs!=null&&u.forcedLayoutMs>0&&`forced layout ${u.forcedLayoutMs} ms`,u.worstInteractionMs!=null&&`slowest input ${u.worstInteractionMs} ms`,u.layoutShift!=null&&u.layoutShift>0&&`layout shift ${u.layoutShift}`,u.domNodes!=null&&`${u.domNodes} DOM nodes${u.domGrowth?` (+${u.domGrowth} over the runs)`:""}`,u.topScripts&&u.topScripts.length>0&&`top scripts: ${u.topScripts.slice(0,3).map(h=>`${h.name} ${h.ms} ms`).join(", ")}`].filter(Boolean);return d.length?`- **${u.caseName}**: ${d.join(" \xB7 ")}`:null}).filter(Boolean);if(i.length){n.push("");n.push(`**Why frames were slow** (Long Animation Frames, Event Timing, DOM size; slow frames that ran past a run's end are left out):`);n.push(...i)}const o=pageLoadLines(e.rows);if(o.length){n.push("");n.push(...o)}const a=closeCallNote(e.rows);if(a){n.push("");n.push(a)}const s=Array.from(new Set(e.rows.flatMap(u=>u.missingMetrics??[])));if(s.length){n.push("");n.push(`**Not measured in this browser:** ${s.join(", ")}. These show as \u2014 and can't win or lose.`)}if(e.rows.some(u=>u.refreshCalibrated===false)){n.push("");n.push(`**Refresh rate not checked on an idle screen:** the batch couldn't reach its bounce screen first, so the screen rate (and frame budgets) may read low.`)}if(e.deviceMaxRefreshRate){n.push("");n.push(`Screen rate: ${e.deviceMaxRefreshRate} Hz. A frame gap over ${(1500/e.deviceMaxRefreshRate).toFixed(1)} ms missed at least one frame.`)}n.push("");const c=e.leaders;const l=[c.jsFps&&`FPS \u2192 **${c.jsFps}**`,c.fewestJank&&`fewest long frames \u2192 **${c.fewestJank}**`,c.fewestLongTasks&&`fewest long tasks \u2192 **${c.fewestLongTasks}**`,c.lowestMem&&`lowest heap \u2192 **${c.lowestMem}**`].filter(Boolean).join(" \xB7 ");if(l)n.push(`**Per-metric leaders:** ${l}`);if(e.flagged.length){n.push(`**\u26A0\uFE0F At-risk:** ${e.flagged.map(u=>`${u.caseName} (${u.flags.join("; ")})`).join(" \xB7 ")}`)}n.push(e.balanced.length?`**No configured risk flags:** ${e.balanced.join(", ")}. Check missing metrics and workload requirements before choosing.`:`**No configured risk flags:** no candidates listed. Review failures, available metrics and flags before choosing.`);n.push("");n.push(`_Deltas vs baseline (\`${e.baselineName??"case #0"}\`). Confirm finalists on a real phone browser: desktop numbers don't predict mobile GPU, memory or heat._`)}var POLL_INTERVAL_MS=1500;var delay2=e=>new Promise(n=>setTimeout(n,e));var json2=e=>({content:[{type:"text",text:JSON.stringify(e,null,2)}]});var caseSchema=import_zod3.z.object({name:import_zod3.z.string().describe("Display name for this variant (becomes the saved run's name)."),params:import_zod3.z.record(import_zod3.z.string()).optional().describe('Query params applied to the route for this case, e.g. { "renderer": "v2", "count": "100" }.'),route:import_zod3.z.string().optional().describe("Optional per-case route override; defaults to targetRoute.")});async function readDeviceSettings(e,n){try{const t=await e.callAction(PERF_TOOL_ID,"getAutomationConfig",{},n);if(!t)return{};const{perCaseDurationMs:r,settleMs:i,navTimeoutMs:o,runsPerCase:a,coolDownMs:s,discardWarmupRuns:c,shuffleCases:l,reloadBetweenCases:u,captureRenders:d}=t;return{perCaseDurationMs:r,settleMs:i,navTimeoutMs:o,runsPerCase:a,coolDownMs:s,discardWarmupRuns:c,shuffleCases:l,reloadBetweenCases:u,captureRenders:d}}catch{return{}}}async function readPerfSnapshot(e,n){const{payload:t}=await e.getSnapshot(PERF_TOOL_ID,n,{timeoutMs:4e3});return t}function batchIdsIn(e){const n=new Set;for(const t of e??[])if(t.batchId)n.add(t.batchId);return n}function runCountFor(e,n){return(e??[]).filter(t=>t.batchId===n).length}function newestBatchId(e){let n=null;for(const t of e??[]){if(t.batchId&&(!n||t.createdAt>n.at))n={id:t.batchId,at:t.createdAt}}return n?.id??null}function failuresFromIndex(e,n){const t=new Map;for(const r of e??[]){if(r.batchId===n&&r.batchFailureReason&&!t.has(r.batchIndex??0)){t.set(r.batchIndex??0,r.batchFailureReason)}}return[...t.entries()].map(([r,i])=>({index:r,reason:i}))}function expectedRunsFor(e){const n=e.cases.length+(e.discardWarmupCase===true?1:0);return n*(e.runsPerCase??1)}var SETTLE_WAIT_MS=1e4;function isRunnerBusy(e){return!!e&&e!=="idle"&&e!=="done"&&e!=="cancelled"}async function waitForRunnerSettled(e,n,t,r=SETTLE_WAIT_MS){const i=Date.now();while(Date.now()-i<r){const o=await readPerfSnapshot(e,n).catch(()=>null);if(o&&!isRunnerBusy(o.live?.automation?.phase))return true;await delay2(POLL_INTERVAL_MS)}t(`automation still busy after ${Math.round(r/1e3)}s`);return false}async function waitForBatchByIndex(e,n,t){const{preBatchIds:r,expectedRuns:i,maxWaitMs:o,log:a}=t;const s=t.reloadsBetweenCases?10:3;const c=Date.now();let l="";let u=false;let d=0;while(Date.now()-c<o){let p;try{p=await readPerfSnapshot(e,n)}catch{await delay2(POLL_INTERVAL_MS);continue}const g=p.index??[];const m=p.live?.automation?.phase??"idle";const f=p.live?.automationCompleted;if(f?.phase==="cancelled"&&!r.has(f.batchId)){return{batchId:f.batchId,failures:[],cancelled:true}}if(f?.phase==="done"&&!r.has(f.batchId)){return{batchId:f.batchId,failures:f.failures??failuresFromIndex(g,f.batchId)}}if(m!=="idle")u=true;if(m!==l){l=m;a(`automation phase: ${m}`)}const v=[...batchIdsIn(g)].find(y=>!r.has(y));if(v){const y=runCountFor(g,v);if(i>0&&y>=i){await waitForRunnerSettled(e,n,a);a(`batch ${v} complete (${y}/${i} runs saved)`);return{batchId:v,failures:failuresFromIndex(g,v)}}const b=(g??[]).filter(x=>x.batchId===v&&x.name!==WARMUP_CASE_NAME).length;const $=p.live?.pendingBatchId===v;const T=Boolean(p.live&&"pendingBatchId"in p.live);const _=!t.reloadsBetweenCases||T;if(m==="idle"&&u&&b>0&&!$&&_){if(++d>=s){a(`batch ${v} settled (${y} runs, automation idle)`);return{batchId:v,failures:failuresFromIndex(g,v)}}}else{d=0}}await delay2(POLL_INTERVAL_MS)}const h=await readPerfSnapshot(e,n).catch(()=>null);const w=h?[...batchIdsIn(h.index)].find(p=>!r.has(p)):void 0;if(w&&h)return{batchId:w,failures:failuresFromIndex(h.index,w),timedOut:true};throw new Error(`Batch did not start within ${Math.round(o/1e3)}s (last phase: ${l||"idle"}). Check get_automation_status \u2014 the device may not have navigated.`)}function registerPerfMonitorTools(e,n){e.registerTool("run_benchmark_batch",{description:"Run a perf-monitor benchmark batch and return per-metric leaders, risk flags and a comparison of available case results. Give it a target route and a matrix of cases (each a name + query params that select a variant on that route); it navigates, records, and benchmarks each case on the device, then ranks them. This blocks until the batch completes (can be minutes for large batches). The app must have the target route render its variants from the params.",inputSchema:{targetRoute:import_zod3.z.string().describe('The screen to benchmark, e.g. "/perf-test". Reads case params to pick a variant.'),cases:import_zod3.z.array(caseSchema).min(1).describe("The variants to compare. Case #0 is the baseline for deltas."),bounceRoute:import_zod3.z.string().optional().describe('Screen to bounce to between runs so the test screen fully remounts. Defaults to "/" (or a stub if target is "/").'),runsPerCase:import_zod3.z.number().optional().describe("Runs per case; the median becomes the canonical result. Default 3 (1\u201310)."),perCaseDurationMs:import_zod3.z.number().optional().describe("How long to record each run. Default 5000."),settleMs:import_zod3.z.number().optional().describe("Idle gap after navigation before recording. Default 600."),coolDownMs:import_zod3.z.number().optional().describe("Idle between runs/cases for thermal recovery. Default 2000."),navTimeoutMs:import_zod3.z.number().optional().describe("Max wait for navigation per run. Default 5000."),discardWarmupRuns:import_zod3.z.number().optional().describe("Discard first N runs of each case before taking the median. Default 0."),shuffleCases:import_zod3.z.boolean().optional().describe("Interleave and shuffle case order to reduce order-related bias. Default on for >3 cases."),reloadBetweenCases:import_zod3.z.boolean().optional().describe("Fully reload JS between cases (needs <AutomationResumer/> mounted). Default false."),captureRenders:import_zod3.z.boolean().optional().describe("Capture per-component render counts/durations during each run (needs @buoy-gg/highlight-updates installed; dev builds only). Adds instrumentation overhead that can vary with the workload. Default true."),deviceId:import_zod3.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."),maxWaitMs:import_zod3.z.number().optional().describe("Safety cap for how long to wait for completion. Defaults to ~3\xD7 the estimate + 60s.")}},async t=>{const r=i=>process.stderr.write(`[buoy-mcp] ${i}
7
7
  `);try{const i=n.requireProDevice(t.deviceId);const o=await readDeviceSettings(n,i);const{config:a,warnings:s}=buildAutomationConfig(t,o);const c=estimateBatchMs(a);const l=t.maxWaitMs??c*3+6e4;const u=expectedRunsFor(a);if(!await waitForRunnerSettled(n,i,r)){return fail2("Another benchmark batch is still running on this device. Wait for it to finish, or cancel it (call_action perf-monitor cancelAutomation), then retry.")}await n.callAction(PERF_TOOL_ID,"acknowledgeAutomation",{},i).catch(()=>{});await n.callAction(PERF_TOOL_ID,"setEnabled",{enabled:true},i).catch(()=>{});await n.callAction(PERF_TOOL_ID,"refreshIndex",{},i).catch(()=>{});const d=await readPerfSnapshot(n,i);const h=batchIdsIn(d.index);r(`starting batch: ${a.cases.length} cases \xD7 ${a.runsPerCase} runs (~${Math.round(c/1e3)}s estimated) on ${i}`);await n.callAction(PERF_TOOL_ID,"startAutomation",{config:a},i);const w=await waitForBatchByIndex(n,i,{preBatchIds:h,expectedRuns:u,maxWaitMs:l,log:r,reloadsBetweenCases:a.reloadBetweenCases===true});if(w.cancelled){await n.callAction(PERF_TOOL_ID,"acknowledgeAutomation",{},i).catch(()=>{});return fail2(`Batch ${w.batchId} was cancelled before completing.`)}await n.callAction(PERF_TOOL_ID,"refreshIndex",{},i).catch(()=>{});const p=await readPerfSnapshot(n,i);const g=rankBatchFromIndex(p.index??[],w.batchId,a.cases,w.failures);await n.callAction(PERF_TOOL_ID,"acknowledgeAutomation",{},i).catch(()=>{});await n.callAction(PERF_TOOL_ID,"setEnabled",{enabled:false},i).catch(()=>{});if(g.rows.length===0){const v=n.connectedDevices().some($=>$.deviceId===i);const y=p.live?.pendingBatchId===w.batchId;const b=!v?`The device disconnected during the batch (a browser tab that closes, reloads or sleeps drops off). Reconnect it and run again.`:y?`The batch reloaded the app between cases and never resumed. Check that <AutomationResumer/> is mounted (the web host mounts it), or pass reloadBetweenCases: false.`:w.timedOut?`No runs were saved before the wait cap (${Math.round(l/1e3)}s). On web, a hidden or background tab pauses the run: keep the tab in front. Check get_automation_status for the device's phase.`:`The batch finished without saving any runs. Check get_automation_status and the device console.`;return fail2(`Benchmark batch ${w.batchId||"(no id)"} saved no runs. ${b}`)}const m=formatRankingMarkdown(g);const f={batchId:w.batchId,leaders:g.leaders,balanced:g.balanced,flagged:g.flagged,rows:g.rows,failures:w.failures,warnings:s,estimateMs:c,...w.timedOut?{note:"Wait cap hit \u2014 results may be partial (some runs may still be saving)."}:{}};return text(`${m}
8
8
 
9
9
  \`\`\`json
@@ -35,8 +35,8 @@ _${e} more withheld ${e===1?"body was":"bodies were"} not fetched (cap ${MAX_BOD
35
35
  \u2514\u2500 response: ${r(e.responseData,t?.responseData,e.responseBodyOmitted)}`}function formatRow(e,n,t){const r=n.path||n.url;const i=[`${n.duration!==void 0?`${Math.round(n.duration)}ms`:"\u2014"}`,formatBytes(n.responseSize),n.host??"",n.requestClient??""].filter(Boolean);const o=n.operationName?` (${n.operationName})`:"";return`${e}. \`${n.id}\` ${statusIcon(n)} ${statusLabel(n)} ${n.method} ${r}${o}${t?` ${t}`:""}
36
36
  \u2514\u2500 ${i.join(" \xB7 ")}`}function registerNetworkTools(e,n){e.registerTool("network_conditions",{description:"Read or set the device's network conditions. Offline blocks new intercepted HTTP requests; slow adds 500 ms and verySlow adds 2000 ms before dispatch. Normal clears conditions. State resets on JS reload. Check app and server observations to verify the effect.",inputSchema:{action:import_zod5.z.enum(["get","set"]).describe("Read the effective profile or select one."),profile:import_zod5.z.enum(["normal","offline","slow","verySlow"]).optional().describe("Required for set."),deviceId:deviceIdInput}},async t=>{try{if(t.action==="set"&&!t.profile)return fail2("Set requires a profile.");const r=n.resolveDevice(t.deviceId);const i=await n.callAction(NETWORK_TOOL_ID,t.action==="get"?"getNetworkConditions":"setNetworkConditions",t.action==="set"?{profile:t.profile}:void 0,r);if(!i||typeof i!=="object"||!("profile"in i))return fail2("The device did not report its effective network conditions.");return text(JSON.stringify(i))}catch(r){return fail2(errMsg2(r))}});e.registerTool("get_network_requests",{description:"List captured HTTP requests with IDs, available status/timing/size fields and pinned or saved markers. Capture depends on supported transports, installed hooks and recording timing; requests made before capture starts may be absent. Use IDs for network actions and flagged to inspect retained records. A flag does not establish who created it or the cause of a problem. Filter by status or URL pattern. includeBodies:true requests available truncated bodies, which can be missing or withheld. Requires the network integration and Buoy Pro.",inputSchema:{limit:import_zod5.z.number().optional().describe("Most-recent N requests. Default 25."),pattern:import_zod5.z.string().optional().describe("Only requests whose URL contains this substring (case-insensitive)."),status:import_zod5.z.enum(["all","errors","success","pending"]).optional().describe("Filter by outcome. Default all."),flagged:import_zod5.z.enum(["pinned","saved","any"]).optional().describe("Read KEPT requests instead of the live list: 'pinned' (held at the top of the developer's list), 'saved' (their favorites), 'any' (either). These are separate from the live list; restart retention depends on successful persistence."),includeBodies:import_zod5.z.boolean().optional().describe("Include truncated request/response bodies. Default false (compact)."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:i,stale:o}=await n.getSnapshot(NETWORK_TOOL_ID,r);const{events:a,saved:s}=parseSnapshot(i);const c=typeof t.limit==="number"&&t.limit>0?t.limit:25;const l=t.pattern?.toLowerCase();const u=new Set;const d=new Set;for(const m of s){if(m.pinned)u.add(m.event?.id);if(m.saved)d.add(m.event?.id);if(m.pinned)u.add(m.liveId);if(m.saved)d.add(m.liveId)}if(t.flagged){const m=s.filter(b=>t.flagged==="pinned"?b.pinned:t.flagged==="saved"?b.saved:b.pinned||b.saved);const f=m.filter(b=>b.event&&matchesStatus(b.event,t.status)).filter(b=>!l||(b.event.url??"").toLowerCase().includes(l)).slice(0,c);if(f.length===0){return text(staleHeader(o)+`No ${t.flagged==="any"?"pinned or saved":t.flagged} requests on ${r}.
37
37
 
38
- The developer pins/saves a request from the Network tool (long-press a row, or the pin/bookmark buttons in the request detail header), or you can with network_action.`)}const v=t.includeBodies?await resolveBodies(n,f.map(b=>b.event),r):{bodies:new Map,skipped:0};const y=f.map((b,$)=>{const T=[b.pinned?"\u{1F4CC} pinned":"",b.saved?"\u{1F516} saved":""].filter(Boolean).join(" ");const _=b.event.id?.startsWith("saved:")?" \xB7 from an earlier app run":"";const x=b.bodyTruncated?" \xB7 body truncated":"";let A=formatRow($+1,b.event,T);A+=`
39
- \u2514\u2500 key \`${b.key}\`${_}${x}`;if(t.includeBodies)A+=bodyLines(b.event,v.bodies);return A}).join("\n");return text(staleHeader(o)+`**Kept requests on ${r}** \u2014 ${f.length} of ${m.length}
38
+ The developer pins/saves a request from the Network tool (long-press a row, or the pin/bookmark buttons in the request detail header), or you can with network_action.`)}const v=t.includeBodies?await resolveBodies(n,f.map(b=>b.event),r):{bodies:new Map,skipped:0};const y=f.map((b,$)=>{const T=[b.pinned?"\u{1F4CC} pinned":"",b.saved?"\u{1F516} saved":""].filter(Boolean).join(" ");const _=b.event.id?.startsWith("saved:")?" \xB7 from an earlier app run":"";const x=b.bodyTruncated?" \xB7 body truncated":"";let I=formatRow($+1,b.event,T);I+=`
39
+ \u2514\u2500 key \`${b.key}\`${_}${x}`;if(t.includeBodies)I+=bodyLines(b.event,v.bodies);return I}).join("\n");return text(staleHeader(o)+`**Kept requests on ${r}** \u2014 ${f.length} of ${m.length}
40
40
 
41
41
  ${y}
42
42
 
@@ -93,7 +93,7 @@ ${JSON.stringify(i.state,null,2)}
93
93
  _Compact view. Pass includeValues:true for the full state tree. Dispatch with redux_dispatch({type, payload})._${a}`)}catch(r){return fail2(errMsg2(r))}});e.registerTool("redux_dispatch",{description:"Dispatch a Redux action to the app's store (e.g. to trigger a state change while debugging). Provide the action type and optional payload \u2014 they're sent as { type, payload }.",inputSchema:{type:import_zod9.z.string().describe('The action type, e.g. "counter/increment" or "auth/logout".'),payload:import_zod9.z.unknown().optional().describe("Optional action payload (any JSON)."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i={type:t.type};if(t.payload!==void 0)i.payload=t.payload;const o=await n.callAction(REDUX_TOOL_ID,"dispatch",{action:i},r);if(!o||!o.dispatched)return fail2(noStoreMessage(o?.reason));return text(`Dispatched \`${t.type}\`${t.payload!==void 0?` with payload ${JSON.stringify(t.payload)}`:""}.`)}catch(r){return fail2(errMsg2(r))}})}var import_zod10=require("zod");var STORAGE_TOOL_ID="storage";function truncate2(e,n=200){if(e===null||e===void 0)return"(null)";const t=typeof e==="string"?e:JSON.stringify(e);return t.length>n?`${t.slice(0,n)}\u2026(+${t.length-n} chars)`:t}function registerStorageTools(e,n){e.registerTool("get_storage",{description:"Read the app's storage keys across ALL backends: AsyncStorage, MMKV (per instance), and Expo SecureStore. Data wrong or missing after an app restart \u2192 read the persisted values here FIRST \u2014 the bug is usually a stale, missing, or malformed stored value, and reading it beats hunting for it in code. Compact by DEFAULT \u2014 keys only \u2014 so it's token-cheap; pass includeValues:true for the values (truncated), or a `pattern` substring to narrow. Buoy's own internal keys are already filtered out.",inputSchema:{pattern:import_zod10.z.string().optional().describe("Only keys containing this substring (case-insensitive)."),includeValues:import_zod10.z.boolean().optional().describe("Include each key's value (truncated). Default false (keys only)."),limit:import_zod10.z.number().optional().describe("Max keys per backend section. Default 100."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=t.pattern?.toLowerCase();const o=typeof t.limit==="number"&&t.limit>0?t.limit:100;const a=p=>!i||p.toLowerCase().includes(i);const s=[];const c=await n.callAction(STORAGE_TOOL_ID,"async.getAllKeys",{},r);if(!Array.isArray(c)){return fail2("No storage result from the device. The storage tool may be inactive.")}const l=c.filter(a).slice(0,o);if(l.length>0){let p;if(t.includeValues){const g=await n.callAction(STORAGE_TOOL_ID,"async.multiGet",{keys:l},r);const m=new Map((g??[]).map(([f,v])=>[f,v]));p=l.map(f=>`- \`${f}\` = ${truncate2(m.get(f)??null)}`)}else{p=l.map(g=>`- \`${g}\``)}s.push(`**AsyncStorage (${l.length}/${c.length} keys):**
94
94
  ${p.join("\n")}`)}const u=await n.callAction(STORAGE_TOOL_ID,"mmkv.snapshot",{},r).catch(()=>null);for(const p of u??[]){const g=p.entries.filter(v=>a(v.key)).slice(0,o);if(g.length===0)continue;const m=g.map(v=>t.includeValues?`- \`${v.key}\` (${v.valueType}) = ${truncate2(v.value)}`:`- \`${v.key}\``);const f=[p.encrypted&&"encrypted",p.readOnly&&"read-only"].filter(Boolean).join(", ");s.push(`**MMKV \`${p.id}\`${f?` (${f})`:""} (${g.length}/${p.entries.length} keys):**
95
95
  ${m.join("\n")}`)}const d=await n.callAction(STORAGE_TOOL_ID,"secure.keys",{},r).catch(()=>null);const h=(d??[]).filter(p=>a(p.key)).slice(0,o);if(h.length>0){const p=await Promise.all(h.map(async g=>{if(g.requireAuthentication)return`- \`${g.key}\` \u{1F512} (biometric-protected \u2014 not read)`;if(!t.includeValues)return`- \`${g.key}\``;const m=await n.callAction(STORAGE_TOOL_ID,"secure.get",{key:g.key},r).catch(()=>null);return`- \`${g.key}\` = ${truncate2(m)}`}));s.push(`**SecureStore (${h.length} registered keys):**
96
- ${p.join("\n")}`)}if(s.length===0){return text(`No storage keys${i?` matching "${t.pattern}"`:""} in any backend.`)}const w=t.includeValues?"":"\n\n_Keys only. Pass includeValues:true for values, or a pattern to filter. Modify AsyncStorage with storage_action._";return text(`${s.join("\n\n")}${w}`)}catch(r){return fail2(errMsg2(r))}});e.registerTool("storage_action",{description:"Modify the app's AsyncStorage: set a key, remove a key, or clear supported app AsyncStorage keys (Buoy's own devtool keys are preserved). Values are stored as strings \u2014 JSON-encode objects yourself.",inputSchema:{action:import_zod10.z.enum(["set","remove","clear"]).describe("set/remove a key, or clear supported app AsyncStorage keys."),key:import_zod10.z.string().optional().describe("The key (required for set and remove)."),value:import_zod10.z.string().optional().describe("The string value to store (required for set; JSON-encode objects)."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);if(t.action==="clear"){await n.callAction(STORAGE_TOOL_ID,"clearAppStorage",{},r);return text("Requested clearing of supported app AsyncStorage keys. Read storage again to confirm.")}if(!t.key){return fail2(`'${t.action}' needs a key.`)}if(t.action==="remove"){await n.callAction(STORAGE_TOOL_ID,"async.removeItem",{key:t.key},r);return text(`Requested removal of storage key "${t.key}".`)}if(t.value===void 0){return fail2("'set' needs a value (a string).")}await n.callAction(STORAGE_TOOL_ID,"async.setItem",{key:t.key,value:t.value},r);return text(`Requested update of storage key "${t.key}".`)}catch(r){return fail2(errMsg2(r))}})}var import_zod16=require("zod");var import_zod15=require("zod");var MAX_LEAVES=4e3;var MAX_DEPTH=6;function valueKey(e){if(typeof e==="number"){if(!Number.isFinite(e)||Number.isInteger(e)&&Math.abs(e)<10)return null;return`n:${e}`}if(typeof e!=="string")return null;const n=e.trim();if(n.length<3||n.length>80)return null;const t=/^[$€£]?-?[\d,]+(\.\d+)?$/.test(n)?Number(n.replace(/[$€£,]/g,"")):NaN;if(Number.isFinite(t)&&/[\d]/.test(n))return valueKey(t);return`s:${n}`}function walk(e,n,t,r){if(r.length>=MAX_LEAVES||t>MAX_DEPTH||e==null)return;if(typeof e==="object"){const o=Array.isArray(e)?e.slice(0,50).map((a,s)=>[String(s),a]):Object.entries(e);for(const[a,s]of o)walk(s,n?`${n}.${a}`:a,t+1,r);return}const i=valueKey(e);if(i)r.push([i,n])}function indexState(e,n,t){const r=[];walk(t,"",0,r);for(const[i,o]of r){const a=o?`${n}, ${o}`:n;const s=e.get(i)??[];if(s.length<3)s.push(a);e.set(i,s)}}async function liveStateIndex(e,n){const t=new Set(e.connectedDevices().find(a=>a.deviceId===n)?.tools.map(a=>a.toolId)??[]);const r={timeoutMs:1500,silent:true};const i=[];const o=new Map;if(t.has("zustand")){i.push(e.callAction("zustand","listStores",{includeValues:true},n,r).then(a=>{for(const s of a?.stores??[])indexState(o,`${s.name} store`,s.currentState)}))}if(t.has("redux")){i.push(e.callAction("redux","getState",{includeValues:true},n,r).then(a=>{const s=a;if(s?.available)indexState(o,"redux state",s.state)}))}if(t.has("jotai")){i.push(e.callAction("jotai","listAtoms",{includeValues:true},n,r).then(a=>{for(const s of a?.atoms??[])indexState(o,`atom ${s.label}`,s.currentValue)}))}if(!i.length)return null;await Promise.all(i.map(a=>a.catch(()=>void 0)));return o.size?o:null}function stateNote(e,n){if(!e||!n)return"";const t=valueKey(n);const r=t?e.get(t):void 0;return r?.length?` = live state: ${r.join("; ")}`:""}var import_zod14=require("zod");var import_node_child_process12=require("child_process");var import_node_util11=require("util");var import_node_fs12=require("fs");var import_node_os9=__toESM(require("os"));var import_node_path13=__toESM(require("path"));var import_pngjs3=__toESM(require_png());function pixelmatch(e,n,t,r,i,o={}){const{threshold:a=.1,alpha:s=.1,aaColor:c=[255,255,0],diffColor:l=[255,0,0],checkerboard:u=true,includeAA:d,diffColorAlt:h,diffMask:w}=o;if(!isPixelData(e)||!isPixelData(n)||t&&!isPixelData(t))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(e.length!==n.length||t&&t.length!==e.length)throw new Error(`Image sizes do not match. Image 1 size: ${e.length}, image 2 size: ${n.length}`);if(e.length!==r*i*4)throw new Error(`Image data size does not match width/height. Expecting ${r*i*4}. Got ${e.length}`);const p=r*i;const g=new Uint32Array(e.buffer,e.byteOffset,p);const m=new Uint32Array(n.buffer,n.byteOffset,p);let f=true;for(let k=0;k<p;k++){if(g[k]!==m[k]){f=false;break}}if(f){if(t&&!w){for(let k=0,M=0;k<p;k++,M+=4)drawGrayPixel(e,M,s,t)}return 0}const v=35215*a*a;const[y,b,$]=c;const[T,_,x]=l;const[A,I,E]=h||l;let S=0;for(let k=0,M=0;k<p;k++,M+=4){const D=g[k]===m[k]?0:colorDelta(e,n,M,M,u);if(Math.abs(D)>v){const P=k%r;const R=k/r|0;const j=!d&&(antialiased(e,P,R,r,i,g,m,u)||antialiased(n,P,R,r,i,m,g,u));if(j){if(t&&!w)drawPixel(t,M,y,b,$)}else{if(t){if(D<0){drawPixel(t,M,A,I,E)}else{drawPixel(t,M,T,_,x)}}S++}}else if(t&&!w){drawGrayPixel(e,M,s,t)}}return S}function isPixelData(e){return ArrayBuffer.isView(e)&&e.BYTES_PER_ELEMENT===1}function antialiased(e,n,t,r,i,o,a,s){const c=Math.max(n-1,0);const l=Math.max(t-1,0);const u=Math.min(n+1,r-1);const d=Math.min(t+1,i-1);const h=(t*r+n)*4;const w=e[h];const p=e[h+1];const g=e[h+2];const m=e[h+3];let f=n===c||n===u||t===l||t===d?1:0;let v=0;let y=0;let b=0;let $=0;let T=0;let _=0;for(let x=c;x<=u;x++){for(let A=l;A<=d;A++){if(x===n&&A===t)continue;const I=brightnessDelta(e,h,(A*r+x)*4,w,p,g,m,s);if(I===0){f++;if(f>2)return false}else if(I<v){v=I;b=x;$=A}else if(I>y){y=I;T=x;_=A}}}if(v===0||y===0)return false;return hasManySiblings(o,b,$,r,i)&&hasManySiblings(a,b,$,r,i)||hasManySiblings(o,T,_,r,i)&&hasManySiblings(a,T,_,r,i)}function hasManySiblings(e,n,t,r,i){const o=Math.max(n-1,0);const a=Math.max(t-1,0);const s=Math.min(n+1,r-1);const c=Math.min(t+1,i-1);const l=e[t*r+n];let u=n===o||n===s||t===a||t===c?1:0;for(let d=o;d<=s;d++){for(let h=a;h<=c;h++){if(d===n&&h===t)continue;u+=+(l===e[h*r+d]);if(u>2)return true}}return false}function colorDelta(e,n,t,r,i){const o=e[t];const a=e[t+1];const s=e[t+2];const c=e[t+3];const l=n[r];const u=n[r+1];const d=n[r+2];const h=n[r+3];let w=o-l;let p=a-u;let g=s-d;const m=c-h;if(c<255||h<255){let $=255,T=255,_=255;if(i){$=48+159*(t%2);T=48+159*((t/1.618033988749895|0)%2);_=48+159*((t/2.618033988749895|0)%2)}w=(o*c-l*h-$*m)/255;p=(a*c-u*h-T*m)/255;g=(s*c-d*h-_*m)/255}const f=w*.29889531+p*.58662247+g*.11448223;const v=w*.59597799-p*.2741761-g*.32180189;const y=w*.21147017-p*.52261711+g*.31114694;const b=.5053*f*f+.299*v*v+.1957*y*y;return f>0?-b:b}function brightnessDelta(e,n,t,r,i,o,a,s){const c=e[t];const l=e[t+1];const u=e[t+2];const d=e[t+3];let h=r-c;let w=i-l;let p=o-u;const g=a-d;if(!h&&!w&&!p&&!g)return 0;if(a<255||d<255){let m=255,f=255,v=255;if(s){m=48+159*(n%2);f=48+159*((n/1.618033988749895|0)%2);v=48+159*((n/2.618033988749895|0)%2)}h=(r*a-c*d-m*g)/255;w=(i*a-l*d-f*g)/255;p=(o*a-u*d-v*g)/255}return h*.29889531+w*.58662247+p*.11448223}function drawPixel(e,n,t,r,i){e[n]=t;e[n+1]=r;e[n+2]=i;e[n+3]=255}function drawGrayPixel(e,n,t,r){const i=255+(e[n]*.29889531+e[n+1]*.58662247+e[n+2]*.11448223-255)*t*e[n+3]/255;drawPixel(r,n,i,i,i)}function decodePng(e){return import_pngjs3.PNG.sync.read(e)}function diffScreens(e,n,t={}){const r=decodePng(e);const i=decodePng(n);if(r.width!==i.width||r.height!==i.height){throw new Error(`The screenshots are different sizes (${r.width}\xD7${r.height} vs ${i.width}\xD7${i.height}). Compare on the same device and orientation, or save a new baseline.`)}const{width:o,height:a}=r;const s=Math.round(a*(t.ignoreTop??0));for(const w of[r,i])w.data.fill(0,0,s*o*4);for(const w of t.masks??[]){const p=Math.max(0,Math.floor(w.x*o));const g=Math.min(o,Math.ceil((w.x+w.width)*o));const m=Math.max(0,Math.floor(w.y*a));const f=Math.min(a,Math.ceil((w.y+w.height)*a));for(const v of[r,i])for(let y=m;y<f;y++)v.data.fill(0,(y*o+p)*4,(y*o+g)*4)}const c=t.threshold??.1;const l=new import_pngjs3.PNG({width:o,height:a});const u=pixelmatch(r.data,i.data,l.data,o,a,{threshold:c,includeAA:false,diffMask:true});const d=new import_pngjs3.PNG({width:o,height:a});pixelmatch(r.data,i.data,d.data,o,a,{threshold:c,includeAA:false,alpha:.25,diffColor:[230,30,40]});const h=o*(a-s);return{width:o,height:a,changedPixels:u,percent:h?u/h*100:0,boxes:changedBoxes(l.data,o,a),diffPng:import_pngjs3.PNG.sync.write(d)}}function changedBoxes(e,n,t){const r=Math.max(8,Math.round(n/48));const i=Math.ceil(n/r);const o=Math.ceil(t/r);const a=new Uint32Array(i*o);for(let u=0;u<t;u++){for(let d=0;d<n;d++){if(e[(u*n+d)*4+3]>0)a[Math.floor(u/r)*i+Math.floor(d/r)]++}}const s=1;const c=new Uint8Array(i*o);const l=[];for(let u=0;u<a.length;u++){if(c[u]||a[u]<s)continue;const d={x0:Infinity,y0:Infinity,x1:-1,y1:-1,pixels:0};const h=[u];c[u]=1;while(h.length){const w=h.pop();const p=w%i;const g=Math.floor(w/i);d.x0=Math.min(d.x0,p);d.y0=Math.min(d.y0,g);d.x1=Math.max(d.x1,p);d.y1=Math.max(d.y1,g);d.pixels+=a[w];for(let m=-2;m<=2;m++){for(let f=-2;f<=2;f++){const v=p+f;const y=g+m;if(v<0||y<0||v>=i||y>=o)continue;const b=y*i+v;if(!c[b]&&a[b]>=s){c[b]=1;h.push(b)}}}}l.push(d)}return l.sort((u,d)=>d.pixels-u.pixels).slice(0,8).map(u=>({x:u.x0*r/n,y:u.y0*r/t,width:Math.min(n,(u.x1+1)*r-u.x0*r)/n,height:Math.min(t,(u.y1+1)*r-u.y0*r)/t,pixels:u.pixels}))}function boxColors(e,n,t,r=0){const i=decodePng(e);const o=decodePng(n);if(i.width!==o.width||i.height!==o.height)return null;const{width:a,height:s}=i;const c=Math.max(0,Math.floor(t.x*a));const l=Math.min(a,Math.ceil((t.x+t.width)*a));const u=Math.max(Math.round(s*r),Math.floor(t.y*s));const d=Math.min(s,Math.ceil((t.y+t.height)*s));const h=new Map;const w=new Map;for(let v=u;v<d;v++){for(let y=c;y<l;y++){const b=(v*a+y)*4;const $=i.data[b]<<16|i.data[b+1]<<8|i.data[b+2];const T=o.data[b]<<16|o.data[b+1]<<8|o.data[b+2];if($===T)continue;h.set($,(h.get($)??0)+1);w.set(T,(w.get(T)??0)+1)}}const p=v=>[...v].sort((y,b)=>b[1]-y[1])[0]?.[0];const g=p(h);const m=p(w);if(g===void 0||m===void 0)return null;const f=v=>`#${v.toString(16).padStart(6,"0").toUpperCase()}`;return{before:f(g),after:f(m)}}function describeSpot(e){const n=e.x+e.width/2;const t=e.y+e.height/2;const r=t<.33?"top":t<.66?"middle":"bottom";const i=n<.33?" left":n<.66?"":" right";return`${r}${i}`}function cropPng(e,n){const t=decodePng(e);const r=Math.max(0,Math.floor(n.x*t.width));const i=Math.max(0,Math.floor(n.y*t.height));const o=Math.max(1,Math.min(t.width-r,Math.round(n.width*t.width)));const a=Math.max(1,Math.min(t.height-i,Math.round(n.height*t.height)));const s=new import_pngjs3.PNG({width:o,height:a});import_pngjs3.PNG.bitblt(t,s,r,i,o,a,0,0);return import_pngjs3.PNG.sync.write(s)}var import_node_child_process8=require("child_process");var import_node_util8=require("util");var execFileAsync8=(0,import_node_util8.promisify)(import_node_child_process8.execFile);var IDB_SENDER=/^ACEFADE/i;var OTHER_UNSEEN="unseen";function touchOwnerFromLog(e){let n=null;let t;const r=[];for(const i of e.split("\n")){const o=/digitizer attached \(sender ([0-9A-F]+)\)/i.exec(i);if(o){if(!r.includes(o[1]))r.push(o[1]);t=n;n=o[1];continue}if(/already have a main display digitizer/i.test(i)){if(t!==void 0)n=t??OTHER_UNSEEN;t=void 0;continue}t=void 0;const a=/digitizer detached \(sender ([0-9A-F]+)\)/i.exec(i);if(a){const s=r.indexOf(a[1]);if(s>=0)r.splice(s,1);if(n===a[1]||n===OTHER_UNSEEN&&s<0)n=r.find(c=>IDB_SENDER.test(c))??r[r.length-1]??null}}if(!n)return"unknown";return IDB_SENDER.test(n)?"idb":"other"}var TOUCH_TAKEN="Real touches can't reach this simulator right now. On Xcode 27, DeviceHub (the app that shows simulators) takes over each booted simulator's touch screen, so a touch sent from here is dropped. Use tap_element for React elements (it presses them inside the app), or run_flow. Don't quit DeviceHub to fix this: quitting it shuts down every simulator.";var cache=new Map;async function simTouchOwner(e){const n=cache.get(e);if(n&&Date.now()-n.at<6e4)return n.owner;let t="unknown";try{const{stdout:r}=await execFileAsync8("xcrun",["simctl","spawn",e,"log","show","--last","24h","--style","compact","--predicate",'process == "backboardd" AND category == "TouchEvents"'],{timeout:2e4,maxBuffer:16*1024*1024});t=touchOwnerFromLog(r.split("\n").filter(i=>/digitizer|already have a main/i.test(i)).join("\n"))}catch{t="unknown"}cache.set(e,{owner:t,at:Date.now()});return t}async function assertSimTouchable(e){if(await simTouchOwner(e)==="other")throw new Error(TOUCH_TAKEN)}var import_node_child_process10=require("child_process");var import_node_util9=require("util");var import_node_fs7=require("fs");var import_node_os7=__toESM(require("os"));var import_node_path8=__toESM(require("path"));var HID_SWIFT=`import Foundation
96
+ ${p.join("\n")}`)}if(s.length===0){return text(`No storage keys${i?` matching "${t.pattern}"`:""} in any backend.`)}const w=t.includeValues?"":"\n\n_Keys only. Pass includeValues:true for values, or a pattern to filter. Modify AsyncStorage with storage_action._";return text(`${s.join("\n\n")}${w}`)}catch(r){return fail2(errMsg2(r))}});e.registerTool("storage_action",{description:"Modify the app's AsyncStorage: set a key, remove a key, or clear supported app AsyncStorage keys (Buoy's own devtool keys are preserved). Values are stored as strings \u2014 JSON-encode objects yourself.",inputSchema:{action:import_zod10.z.enum(["set","remove","clear"]).describe("set/remove a key, or clear supported app AsyncStorage keys."),key:import_zod10.z.string().optional().describe("The key (required for set and remove)."),value:import_zod10.z.string().optional().describe("The string value to store (required for set; JSON-encode objects)."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);if(t.action==="clear"){await n.callAction(STORAGE_TOOL_ID,"clearAppStorage",{},r);return text("Requested clearing of supported app AsyncStorage keys. Read storage again to confirm.")}if(!t.key){return fail2(`'${t.action}' needs a key.`)}if(t.action==="remove"){await n.callAction(STORAGE_TOOL_ID,"async.removeItem",{key:t.key},r);return text(`Requested removal of storage key "${t.key}".`)}if(t.value===void 0){return fail2("'set' needs a value (a string).")}await n.callAction(STORAGE_TOOL_ID,"async.setItem",{key:t.key,value:t.value},r);return text(`Requested update of storage key "${t.key}".`)}catch(r){return fail2(errMsg2(r))}})}var import_zod16=require("zod");var import_zod15=require("zod");var MAX_LEAVES=4e3;var MAX_DEPTH=6;function valueKey(e){if(typeof e==="number"){if(!Number.isFinite(e)||Number.isInteger(e)&&Math.abs(e)<10)return null;return`n:${e}`}if(typeof e!=="string")return null;const n=e.trim();if(n.length<3||n.length>80)return null;const t=/^[$€£]?-?[\d,]+(\.\d+)?$/.test(n)?Number(n.replace(/[$€£,]/g,"")):NaN;if(Number.isFinite(t)&&/[\d]/.test(n))return valueKey(t);return`s:${n}`}function walk(e,n,t,r){if(r.length>=MAX_LEAVES||t>MAX_DEPTH||e==null)return;if(typeof e==="object"){const o=Array.isArray(e)?e.slice(0,50).map((a,s)=>[String(s),a]):Object.entries(e);for(const[a,s]of o)walk(s,n?`${n}.${a}`:a,t+1,r);return}const i=valueKey(e);if(i)r.push([i,n])}function indexState(e,n,t){const r=[];walk(t,"",0,r);for(const[i,o]of r){const a=o?`${n}, ${o}`:n;const s=e.get(i)??[];if(s.length<3)s.push(a);e.set(i,s)}}async function liveStateIndex(e,n){const t=new Set(e.connectedDevices().find(a=>a.deviceId===n)?.tools.map(a=>a.toolId)??[]);const r={timeoutMs:1500,silent:true};const i=[];const o=new Map;if(t.has("zustand")){i.push(e.callAction("zustand","listStores",{includeValues:true},n,r).then(a=>{for(const s of a?.stores??[])indexState(o,`${s.name} store`,s.currentState)}))}if(t.has("redux")){i.push(e.callAction("redux","getState",{includeValues:true},n,r).then(a=>{const s=a;if(s?.available)indexState(o,"redux state",s.state)}))}if(t.has("jotai")){i.push(e.callAction("jotai","listAtoms",{includeValues:true},n,r).then(a=>{for(const s of a?.atoms??[])indexState(o,`atom ${s.label}`,s.currentValue)}))}if(!i.length)return null;await Promise.all(i.map(a=>a.catch(()=>void 0)));return o.size?o:null}function stateNote(e,n){if(!e||!n)return"";const t=valueKey(n);const r=t?e.get(t):void 0;return r?.length?` = live state: ${r.join("; ")}`:""}var import_zod14=require("zod");var import_node_child_process12=require("child_process");var import_node_util11=require("util");var import_node_fs12=require("fs");var import_node_os9=__toESM(require("os"));var import_node_path13=__toESM(require("path"));var import_pngjs3=__toESM(require_png());function pixelmatch(e,n,t,r,i,o={}){const{threshold:a=.1,alpha:s=.1,aaColor:c=[255,255,0],diffColor:l=[255,0,0],checkerboard:u=true,includeAA:d,diffColorAlt:h,diffMask:w}=o;if(!isPixelData(e)||!isPixelData(n)||t&&!isPixelData(t))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(e.length!==n.length||t&&t.length!==e.length)throw new Error(`Image sizes do not match. Image 1 size: ${e.length}, image 2 size: ${n.length}`);if(e.length!==r*i*4)throw new Error(`Image data size does not match width/height. Expecting ${r*i*4}. Got ${e.length}`);const p=r*i;const g=new Uint32Array(e.buffer,e.byteOffset,p);const m=new Uint32Array(n.buffer,n.byteOffset,p);let f=true;for(let k=0;k<p;k++){if(g[k]!==m[k]){f=false;break}}if(f){if(t&&!w){for(let k=0,M=0;k<p;k++,M+=4)drawGrayPixel(e,M,s,t)}return 0}const v=35215*a*a;const[y,b,$]=c;const[T,_,x]=l;const[I,D,E]=h||l;let S=0;for(let k=0,M=0;k<p;k++,M+=4){const A=g[k]===m[k]?0:colorDelta(e,n,M,M,u);if(Math.abs(A)>v){const O=k%r;const R=k/r|0;const j=!d&&(antialiased(e,O,R,r,i,g,m,u)||antialiased(n,O,R,r,i,m,g,u));if(j){if(t&&!w)drawPixel(t,M,y,b,$)}else{if(t){if(A<0){drawPixel(t,M,I,D,E)}else{drawPixel(t,M,T,_,x)}}S++}}else if(t&&!w){drawGrayPixel(e,M,s,t)}}return S}function isPixelData(e){return ArrayBuffer.isView(e)&&e.BYTES_PER_ELEMENT===1}function antialiased(e,n,t,r,i,o,a,s){const c=Math.max(n-1,0);const l=Math.max(t-1,0);const u=Math.min(n+1,r-1);const d=Math.min(t+1,i-1);const h=(t*r+n)*4;const w=e[h];const p=e[h+1];const g=e[h+2];const m=e[h+3];let f=n===c||n===u||t===l||t===d?1:0;let v=0;let y=0;let b=0;let $=0;let T=0;let _=0;for(let x=c;x<=u;x++){for(let I=l;I<=d;I++){if(x===n&&I===t)continue;const D=brightnessDelta(e,h,(I*r+x)*4,w,p,g,m,s);if(D===0){f++;if(f>2)return false}else if(D<v){v=D;b=x;$=I}else if(D>y){y=D;T=x;_=I}}}if(v===0||y===0)return false;return hasManySiblings(o,b,$,r,i)&&hasManySiblings(a,b,$,r,i)||hasManySiblings(o,T,_,r,i)&&hasManySiblings(a,T,_,r,i)}function hasManySiblings(e,n,t,r,i){const o=Math.max(n-1,0);const a=Math.max(t-1,0);const s=Math.min(n+1,r-1);const c=Math.min(t+1,i-1);const l=e[t*r+n];let u=n===o||n===s||t===a||t===c?1:0;for(let d=o;d<=s;d++){for(let h=a;h<=c;h++){if(d===n&&h===t)continue;u+=+(l===e[h*r+d]);if(u>2)return true}}return false}function colorDelta(e,n,t,r,i){const o=e[t];const a=e[t+1];const s=e[t+2];const c=e[t+3];const l=n[r];const u=n[r+1];const d=n[r+2];const h=n[r+3];let w=o-l;let p=a-u;let g=s-d;const m=c-h;if(c<255||h<255){let $=255,T=255,_=255;if(i){$=48+159*(t%2);T=48+159*((t/1.618033988749895|0)%2);_=48+159*((t/2.618033988749895|0)%2)}w=(o*c-l*h-$*m)/255;p=(a*c-u*h-T*m)/255;g=(s*c-d*h-_*m)/255}const f=w*.29889531+p*.58662247+g*.11448223;const v=w*.59597799-p*.2741761-g*.32180189;const y=w*.21147017-p*.52261711+g*.31114694;const b=.5053*f*f+.299*v*v+.1957*y*y;return f>0?-b:b}function brightnessDelta(e,n,t,r,i,o,a,s){const c=e[t];const l=e[t+1];const u=e[t+2];const d=e[t+3];let h=r-c;let w=i-l;let p=o-u;const g=a-d;if(!h&&!w&&!p&&!g)return 0;if(a<255||d<255){let m=255,f=255,v=255;if(s){m=48+159*(n%2);f=48+159*((n/1.618033988749895|0)%2);v=48+159*((n/2.618033988749895|0)%2)}h=(r*a-c*d-m*g)/255;w=(i*a-l*d-f*g)/255;p=(o*a-u*d-v*g)/255}return h*.29889531+w*.58662247+p*.11448223}function drawPixel(e,n,t,r,i){e[n]=t;e[n+1]=r;e[n+2]=i;e[n+3]=255}function drawGrayPixel(e,n,t,r){const i=255+(e[n]*.29889531+e[n+1]*.58662247+e[n+2]*.11448223-255)*t*e[n+3]/255;drawPixel(r,n,i,i,i)}function decodePng(e){return import_pngjs3.PNG.sync.read(e)}function diffScreens(e,n,t={}){const r=decodePng(e);const i=decodePng(n);if(r.width!==i.width||r.height!==i.height){throw new Error(`The screenshots are different sizes (${r.width}\xD7${r.height} vs ${i.width}\xD7${i.height}). Compare on the same device and orientation, or save a new baseline.`)}const{width:o,height:a}=r;const s=Math.round(a*(t.ignoreTop??0));for(const w of[r,i])w.data.fill(0,0,s*o*4);for(const w of t.masks??[]){const p=Math.max(0,Math.floor(w.x*o));const g=Math.min(o,Math.ceil((w.x+w.width)*o));const m=Math.max(0,Math.floor(w.y*a));const f=Math.min(a,Math.ceil((w.y+w.height)*a));for(const v of[r,i])for(let y=m;y<f;y++)v.data.fill(0,(y*o+p)*4,(y*o+g)*4)}const c=t.threshold??.1;const l=new import_pngjs3.PNG({width:o,height:a});const u=pixelmatch(r.data,i.data,l.data,o,a,{threshold:c,includeAA:false,diffMask:true});const d=new import_pngjs3.PNG({width:o,height:a});pixelmatch(r.data,i.data,d.data,o,a,{threshold:c,includeAA:false,alpha:.25,diffColor:[230,30,40]});const h=o*(a-s);return{width:o,height:a,changedPixels:u,percent:h?u/h*100:0,boxes:changedBoxes(l.data,o,a),diffPng:import_pngjs3.PNG.sync.write(d)}}function changedBoxes(e,n,t){const r=Math.max(8,Math.round(n/48));const i=Math.ceil(n/r);const o=Math.ceil(t/r);const a=new Uint32Array(i*o);for(let u=0;u<t;u++){for(let d=0;d<n;d++){if(e[(u*n+d)*4+3]>0)a[Math.floor(u/r)*i+Math.floor(d/r)]++}}const s=1;const c=new Uint8Array(i*o);const l=[];for(let u=0;u<a.length;u++){if(c[u]||a[u]<s)continue;const d={x0:Infinity,y0:Infinity,x1:-1,y1:-1,pixels:0};const h=[u];c[u]=1;while(h.length){const w=h.pop();const p=w%i;const g=Math.floor(w/i);d.x0=Math.min(d.x0,p);d.y0=Math.min(d.y0,g);d.x1=Math.max(d.x1,p);d.y1=Math.max(d.y1,g);d.pixels+=a[w];for(let m=-2;m<=2;m++){for(let f=-2;f<=2;f++){const v=p+f;const y=g+m;if(v<0||y<0||v>=i||y>=o)continue;const b=y*i+v;if(!c[b]&&a[b]>=s){c[b]=1;h.push(b)}}}}l.push(d)}return l.sort((u,d)=>d.pixels-u.pixels).slice(0,8).map(u=>({x:u.x0*r/n,y:u.y0*r/t,width:Math.min(n,(u.x1+1)*r-u.x0*r)/n,height:Math.min(t,(u.y1+1)*r-u.y0*r)/t,pixels:u.pixels}))}function boxColors(e,n,t,r=0){const i=decodePng(e);const o=decodePng(n);if(i.width!==o.width||i.height!==o.height)return null;const{width:a,height:s}=i;const c=Math.max(0,Math.floor(t.x*a));const l=Math.min(a,Math.ceil((t.x+t.width)*a));const u=Math.max(Math.round(s*r),Math.floor(t.y*s));const d=Math.min(s,Math.ceil((t.y+t.height)*s));const h=new Map;const w=new Map;for(let v=u;v<d;v++){for(let y=c;y<l;y++){const b=(v*a+y)*4;const $=i.data[b]<<16|i.data[b+1]<<8|i.data[b+2];const T=o.data[b]<<16|o.data[b+1]<<8|o.data[b+2];if($===T)continue;h.set($,(h.get($)??0)+1);w.set(T,(w.get(T)??0)+1)}}const p=v=>[...v].sort((y,b)=>b[1]-y[1])[0]?.[0];const g=p(h);const m=p(w);if(g===void 0||m===void 0)return null;const f=v=>`#${v.toString(16).padStart(6,"0").toUpperCase()}`;return{before:f(g),after:f(m)}}function describeSpot(e){const n=e.x+e.width/2;const t=e.y+e.height/2;const r=t<.33?"top":t<.66?"middle":"bottom";const i=n<.33?" left":n<.66?"":" right";return`${r}${i}`}function cropPng(e,n){const t=decodePng(e);const r=Math.max(0,Math.floor(n.x*t.width));const i=Math.max(0,Math.floor(n.y*t.height));const o=Math.max(1,Math.min(t.width-r,Math.round(n.width*t.width)));const a=Math.max(1,Math.min(t.height-i,Math.round(n.height*t.height)));const s=new import_pngjs3.PNG({width:o,height:a});import_pngjs3.PNG.bitblt(t,s,r,i,o,a,0,0);return import_pngjs3.PNG.sync.write(s)}var import_node_child_process8=require("child_process");var import_node_util8=require("util");var execFileAsync8=(0,import_node_util8.promisify)(import_node_child_process8.execFile);var IDB_SENDER=/^ACEFADE/i;var OTHER_UNSEEN="unseen";function touchOwnerFromLog(e){let n=null;let t;const r=[];for(const i of e.split("\n")){const o=/digitizer attached \(sender ([0-9A-F]+)\)/i.exec(i);if(o){if(!r.includes(o[1]))r.push(o[1]);t=n;n=o[1];continue}if(/already have a main display digitizer/i.test(i)){if(t!==void 0)n=t??OTHER_UNSEEN;t=void 0;continue}t=void 0;const a=/digitizer detached \(sender ([0-9A-F]+)\)/i.exec(i);if(a){const s=r.indexOf(a[1]);if(s>=0)r.splice(s,1);if(n===a[1]||n===OTHER_UNSEEN&&s<0)n=r.find(c=>IDB_SENDER.test(c))??r[r.length-1]??null}}if(!n)return"unknown";return IDB_SENDER.test(n)?"idb":"other"}var TOUCH_TAKEN="Real touches can't reach this simulator right now. On Xcode 27, DeviceHub (the app that shows simulators) takes over each booted simulator's touch screen, so a touch sent from here is dropped. Use tap_element for React elements (it presses them inside the app), or run_flow. Don't quit DeviceHub to fix this: quitting it shuts down every simulator.";var cache=new Map;async function simTouchOwner(e){const n=cache.get(e);if(n&&Date.now()-n.at<6e4)return n.owner;let t="unknown";try{const{stdout:r}=await execFileAsync8("xcrun",["simctl","spawn",e,"log","show","--last","24h","--style","compact","--predicate",'process == "backboardd" AND category == "TouchEvents"'],{timeout:2e4,maxBuffer:16*1024*1024});t=touchOwnerFromLog(r.split("\n").filter(i=>/digitizer|already have a main/i.test(i)).join("\n"))}catch{t="unknown"}cache.set(e,{owner:t,at:Date.now()});return t}async function assertSimTouchable(e){if(await simTouchOwner(e)==="other")throw new Error(TOUCH_TAKEN)}var import_node_child_process10=require("child_process");var import_node_util9=require("util");var import_node_fs7=require("fs");var import_node_os7=__toESM(require("os"));var import_node_path8=__toESM(require("path"));var HID_SWIFT=`import Foundation
97
97
  import Darwin
98
98
  import CryptoKit
99
99
 
@@ -569,19 +569,19 @@ struct Command {
569
569
  `;var HID_INTERFACE="// swift-interface-format-version: 1.0\n// swift-compiler-version: Apple Swift version 6.4\n// swift-module-flags: -target arm64-apple-macosx15.0 -enable-library-evolution -module-name CoreDevice\n// Reconstructed API subset. No replacement framework code is linked.\n// Non-frozen types and protocol/class calls resolve through Apple metadata and thunks.\nimport Foundation\nimport CoreGraphics\npublic struct Capability {}\npublic protocol CoreDeviceServiceConnection {}\npublic struct CoreDeviceService {\n public static var sharedConnection: any CoreDeviceServiceConnection { get }\n}\npublic enum DeviceVisibilityClass: Swift.Hashable {\n case `default`, wirelessPairableDevices, devicesBeingProvisioned, simulators\n public static func == (lhs: DeviceVisibilityClass, rhs: DeviceVisibilityClass) -> Swift.Bool\n public func hash(into hasher: inout Swift.Hasher)\n public var hashValue: Swift.Int { get }\n}\npublic class DeviceManager {\n public static var shared: DeviceManager { get }\n public init(serviceConnection: any CoreDeviceServiceConnection, allowedDeviceVisibilityClasses: Swift.Set<DeviceVisibilityClass>)\n public func awaitFullInitialization() async\n public func waitForPostPluginLoadCheckIn() async\n public var devices: [Foundation.UUID: RemoteDevice] { get }\n public func deviceNamed(_ name: Swift.String) throws -> RemoteDevice\n}\npublic class RemoteDevice {\n public var deviceIdentifier: Foundation.UUID { get }\n public func getImplementation<C: DeviceCapability>(for capability: CapabilityStaticMember<C>) async throws -> C.ProtocolType\n}\npublic protocol DeviceCapability {\n associatedtype ProtocolType\n static var capability: Capability { get }\n}\npublic struct CapabilityStaticMember<C> {\n public init()\n}\npublic struct DigitizerHIDCapability: DeviceCapability {\n public typealias ProtocolType = any HIDDigitizer\n public static var capability: Capability { get }\n}\npublic protocol DeviceCapabilityProtocol {\n static var capability: Capability { get }\n static var identifier: Swift.String { get }\n static var identifierSuffix: Swift.String { get }\n static var priority: Swift.Int { get }\n}\npublic protocol HIDDigitizer: DeviceCapabilityProtocol {\n func send(pointOne: DigitizerPoint, pointTwo: DigitizerPoint?, eventType: DigitizerEventType, edge: DigitizerEdge, target: DigitizerTarget) throws\n func sendBarrier()\n}\npublic struct DigitizerPoint {\n public init(x: Swift.Double, y: Swift.Double)\n}\npublic enum DigitizerEventType { case start, position, end }\npublic enum DigitizerEdge { case none, top, left, bottom, right }\npublic enum DigitizerTarget { case mainScreen, display1, display2, display3, display4, display5, display6, display7, display8, display9, display10 }\npublic struct KeyboardHIDCapability: DeviceCapability {\n public typealias ProtocolType = any HIDKeyboard\n public static var capability: Capability { get }\n}\npublic protocol HIDKeyboard: DeviceCapabilityProtocol {\n func send(key: HIDKeyboardUsageCode, state: HIDButtonState) throws\n func sendBarrier()\n}\npublic struct HIDKeyboardUsageCode {\n public init(rawValue: Swift.UInt16)\n}\npublic enum HIDButtonState { case down, up }\npublic struct ButtonHIDCapability: DeviceCapability {\n public typealias ProtocolType = any HIDButton\n public static var capability: Capability { get }\n}\npublic protocol HIDButton: DeviceCapabilityProtocol {\n func sendCustomButton(usagePage: Swift.Int, usageCode: Swift.Int, state: HIDButtonState) throws\n func sendBarrier()\n}\n";var HID_HASH="718c261deb06";var import_node_child_process9=require("child_process");var workers=new Map;var queues=new Map;function stopAllHidStreamsNow(){for(const e of workers.values())e.child.kill("SIGKILL")}function runHidStream(e,n,t,r=""){const i=n;const o=(queues.get(i)??Promise.resolve()).catch(()=>void 0).then(()=>send(i,e,t,r));queues.set(i,o);void o.finally(()=>{if(queues.get(i)===o)queues.delete(i)}).catch(()=>void 0);return o}async function send(e,n,t,r){let i=workers.get(e);if(i&&i.bin!==n)i.stop(new Error("The touch helper build changed."));if(i?.stopped){await i.exited;i=void 0}if(!i){const a=(0,import_node_child_process9.spawn)(n,["--stream"],{stdio:["pipe","pipe","pipe"]});let s;const c=new Promise(d=>{s=d});i={bin:n,child:a,buffer:"",stopped:false,exited:c,stop:()=>{}};if(workers.size===0)process.once("exit",stopAllHidStreamsNow);workers.set(e,i);const l=i;const u=d=>{if(l.stopped)return;l.stopped=true;if(l.idle)clearTimeout(l.idle);const h=l.pending;l.pending=void 0;if(h)clearTimeout(h.timer);a.ref();a.kill("SIGKILL");void c.then(()=>{if(workers.get(e)===l)workers.delete(e);if(workers.size===0)process.removeListener("exit",stopAllHidStreamsNow);h?.reject(d)})};l.stop=u;a.on("error",d=>{s();u(d)});a.on("exit",()=>{s();u(new Error("The touch helper closed. Try the next touch."))});a.stdin.on("error",d=>u(d));a.stdout.on("data",d=>{l.buffer+=d;let h;while((h=l.buffer.indexOf("\n"))>=0){const w=l.buffer.slice(0,h);l.buffer=l.buffer.slice(h+1);const p=l.pending;if(!p)continue;try{const g=JSON.parse(w);if(!g||typeof g.ok!=="boolean")throw new Error("Bad reply.");if(g.ok===true){clearTimeout(p.timer);l.pending=void 0;p.resolve()}else u(new Error(g.error??"The touch failed."))}catch{u(new Error("The touch helper sent a bad reply."))}}});a.stderr.resume();a.unref();for(const d of[a.stdin,a.stdout,a.stderr])d.unref?.()}const o=i;if(o.idle)clearTimeout(o.idle);return new Promise((a,s)=>{const c=setTimeout(()=>{o.stop(new Error("The touch helper timed out."))},45e3);o.pending={resolve:a,reject:s,timer:c};o.child.stdin.write(JSON.stringify({args:t,input:r})+"\n")}).finally(()=>{if(o.stopped)return;o.idle=setTimeout(()=>{o.child.stdin.end();o.stop(new Error("The touch helper went idle."))},1e4);o.idle.unref()})}var execFileAsync9=(0,import_node_util9.promisify)(import_node_child_process10.execFile);var PRIVATE_FRAMEWORKS="/Library/Developer/PrivateFrameworks";var built=null;var buildError="";var lastUsed=0;var developerDir;var buildKey;var refreshing=null;async function xcodeBuild(){try{const{stdout:e}=await execFileAsync9("xcode-select",["-p"],{timeout:1e4});const n=import_node_path8.default.join(process.env.DEVELOPER_DIR||e.trim(),"..","Info.plist");const{stdout:t}=await execFileAsync9("plutil",["-extract","DTXcodeBuild","raw",n],{timeout:1e4});return t.trim().replace(/[^\w.-]/g,"")||"unknown"}catch{return"unknown"}}async function build(e){if(process.platform!=="darwin")return null;const n=import_node_path8.default.join(import_node_os7.default.homedir(),".buoy","hidtouch",`${e}-${HID_HASH}`);const t=import_node_path8.default.join(n,"hidtouch");try{await import_node_fs7.promises.access(t);return t}catch{}try{await import_node_fs7.promises.access(import_node_path8.default.join(PRIVATE_FRAMEWORKS,"CoreDevice.framework"))}catch{buildError="CoreDevice is not installed (it ships with Xcode 15 and later).";return null}const r=await import_node_fs7.promises.mkdtemp(import_node_path8.default.join(import_node_os7.default.tmpdir(),"buoy-hidtouch-"));try{await import_node_fs7.promises.mkdir(import_node_path8.default.join(r,"modules"));await import_node_fs7.promises.writeFile(import_node_path8.default.join(r,"hidtouch.swift"),HID_SWIFT);await import_node_fs7.promises.writeFile(import_node_path8.default.join(r,"modules","CoreDevice.swiftinterface"),HID_INTERFACE);const i=import_node_path8.default.join(r,"hidtouch");await execFileAsync9("xcrun",["swiftc","-O","-module-cache-path",import_node_path8.default.join(r,"cache"),"-I",import_node_path8.default.join(r,"modules"),"-F",PRIVATE_FRAMEWORKS,"-framework","CoreDevice","-parse-as-library",import_node_path8.default.join(r,"hidtouch.swift"),"-o",i],{timeout:18e4,maxBuffer:8*1024*1024,env:{...process.env,TMPDIR:r}});await import_node_fs7.promises.mkdir(n,{recursive:true});const o=`${t}.${process.pid}`;await import_node_fs7.promises.copyFile(i,o);await import_node_fs7.promises.chmod(o,493);await import_node_fs7.promises.rename(o,t);return t}catch(i){const o=i;buildError=(o.stderr||o.message||"").trim().split("\n").slice(-3).join(" ").slice(0,300);return null}finally{await import_node_fs7.promises.rm(r,{recursive:true,force:true}).catch(()=>void 0)}}function simHidTool(){const e=Date.now();const n=!built||e-lastUsed>=1e4||developerDir!==process.env.DEVELOPER_DIR;lastUsed=e;if(refreshing)return refreshing;if(!n)return built;developerDir=process.env.DEVELOPER_DIR;const t=developerDir;refreshing=xcodeBuild().then(r=>{const i=JSON.stringify([t,r]);if(!built||buildKey!==i){buildKey=i;buildError="";built=build(r)}return built}).finally(()=>{refreshing=null});return refreshing}async function deviceOrientation(e){try{const{stdout:n}=await execFileAsync9("xcrun",["devicectl","device","orientation","get","--device",e],{timeout:15e3});const t=/Orientation:\s*(\w+)/.exec(n)?.[1];return t==="portrait"||t==="portraitUpsideDown"||t==="landscapeLeft"||t==="landscapeRight"?t:null}catch{return null}}async function appUpsideDown(e,n){if(!n)return null;try{const{stdout:t}=await execFileAsync9("xcrun",["simctl","get_app_container",e,n,"app"],{timeout:1e4});const{stdout:r}=await execFileAsync9("plutil",["-convert","json","-o","-",import_node_path8.default.join(t.trim(),"Info.plist")],{timeout:1e4});const i=JSON.parse(r);const{stdout:o}=await execFileAsync9("xcrun",["simctl","getenv",e,"SIMULATOR_MODEL_IDENTIFIER"],{timeout:1e4});const a=o.trim().startsWith("iPad")?"ipad":"iphone";const s=i[`UISupportedInterfaceOrientations~${a}`]??i.UISupportedInterfaceOrientations;if(!Array.isArray(s)||!s.every(c=>typeof c==="string"))return null;return s.includes("UIInterfaceOrientationPortraitUpsideDown")}catch{return null}}function toDigitizer(e,n,t,r,i){if(r==="portraitUpsideDown"){if(i==null)throw new Error("Upside-down touch needs the app turn list. Turn the device upright and try again.");return i?[1-e,1-n]:[e,n]}if(!t)return[e,n];if(r==="landscapeRight")return[n,1-e];return[1-n,e]}async function run(e,n,t,r=false){try{const i=n[n.indexOf("--device")+1];await runHidStream(e,i,n,t)}catch(i){const o=i;const a=o.stderr||o.message||"";if(/HID Digitizer/i.test(a)&&/not supported/i.test(a)){console.error("[buoy:hid]",a);throw new Error(r?"Your iPhone isn't connected. Unlock it and plug it in, or put it on the same Wi-Fi. Then try again.":"Touch is not supported on this iOS Simulator.")}throw new Error(`The touch failed: ${a.replace(/^hidtouch:\s*/,"").split("\n")[0].slice(0,300)}`)}}var clamp3=e=>Math.min(1,Math.max(0,e));var frac=e=>clamp3(e).toFixed(5);async function simHidTap(e,n,t,r,i,o,a){const s=t.width>t.height;const c=a!==void 0?a:await deviceOrientation(n);const l=c==="portraitUpsideDown"?await appUpsideDown(n,t.bundleId):null;const[u,d]=toDigitizer(r/t.width,i/t.height,s,c,l);await run(e,o?["--device",n,"long-press",frac(u),frac(d),String(Math.round(o))]:["--device",n,"tap",frac(u),frac(d)],void 0,t.isPhone);return c}async function simHidSwipe(e,n,t,r,i,o,a=0,s=0,c){const l=t.width>t.height;const u=c!==void 0?c:await deviceOrientation(n);const d=u==="portraitUpsideDown"?await appUpsideDown(n,t.bundleId):null;const h=toDigitizer(r[0]/t.width,r[1]/t.height,l,u,d);const w=toDigitizer(i[0]/t.width,i[1]/t.height,l,u,d);const p=String(Math.round(Math.min(1e4,Math.max(1,o))));const g=[frac(h[0]),frac(h[1]),frac(w[0]),frac(w[1])];const m=a>0?["--device",n,"drag",...g,String(Math.round(Math.min(1e4,a))),p]:s>0?["--device",n,"scroll",...g,p,String(Math.round(Math.min(1e4,s)))]:["--device",n,"swipe",...g,p];await run(e,m,void 0,t.isPhone);return u}async function simHidTwo(e,n,t,r,i,o,a,s){const c=t.width>t.height;const l=await deviceOrientation(n);const u=l==="portraitUpsideDown"?await appUpsideDown(n,t.bundleId):null;const d=c?{w:t.height,h:t.width}:{w:t.width,h:t.height};const h=[r,i,o,a].flatMap(w=>{const[p,g]=toDigitizer(w[0]/t.width,w[1]/t.height,c,l,u);return[(clamp3(p)*d.w).toFixed(2),(clamp3(g)*d.h).toFixed(2)]});await run(e,["--device",n,"--points",String(d.w),String(d.h),"two",...h,String(Math.round(Math.min(1e4,Math.max(1,s))))],void 0,t.isPhone);return l}var SIM_TYPEABLE=/^[\x20-\x7e\n]*$/;async function simHidType(e,n,t){if(!SIM_TYPEABLE.test(t))throw new Error("The simulator keyboard types plain ASCII letters, digits, punctuation and newlines only. For other text use tap_element with text.");if(!t)return;await run(e,["--device",n,"type","-"],t)}var import_zod13=require("zod");var import_node_fs11=require("fs");var import_node_path12=__toESM(require("path"));var import_node_crypto6=require("crypto");var import_zod11=require("zod");function pickDescribeScreenMatch(e,n,t){if(t!=null){const o=e.find(a=>a.nativeTag===t);if(o)return o}const r=(n??"").trim().toLowerCase();if(!r)return void 0;let i;for(const o of e){const a=[o.testID,o.label,o.text,o.name].filter(Boolean).map(l=>l.toLowerCase());let s=0;for(const l of a){if(l===r)s=Math.max(s,100);else if(l.startsWith(r))s=Math.max(s,50);else if(l.includes(r))s=Math.max(s,25)}const c=o.tap;if(c&&c.x>=0&&c.x<=1&&c.y>=0&&c.y<=1)s+=20;else if(c)s-=40;if(s<=0)continue;if(!i||s>i.score)i={el:o,score:s}}return i?.el}function frameToRect(e,n){return{x:e.x*n.width,y:e.y*n.height,width:e.width*n.width,height:e.height*n.height}}var import_node_os8=__toESM(require("os"));var import_node_fs8=require("fs");var import_node_path9=__toESM(require("path"));var import_pngjs4=__toESM(require_png());var TOOL_ID="highlight-updates";var MARGIN_PT=12;var CAPTURE_PADDING_PT=6;var fail3=e=>({isError:true,content:[{type:"text",text:e}]});var errMsg3=e=>e instanceof Error?e.message:String(e);function reasonMessage(e,n){switch(e.reason){case"no-renders":return"No components matched via highlight tracking or the live fiber walk. Pass a testID / name from describe_screen, then retry.";case"no-match":return n?`Nothing matched "${n}".`:"No query or nativeTag given \u2014 pass one, or a testID/name to search for.";case"no-measurement":return"Found the component but couldn't measure it \u2014 it may have just unmounted. Re-navigate to it and retry.";default:return e.reason?`Locate failed: ${e.reason}`:"Couldn't locate that component."}}function candidatesText(e){if(!e||e.length===0)return"";const n=e.map(t=>{const r=t.testID||t.nativeID;return`- ${t.componentName||t.viewType}${r?` (${r})`:""} \u2014 nativeTag ${t.nativeTag}, rendered \xD7${t.renderCount}`});return`
570
570
 
571
571
  Closest matches (retry with a more precise query, or pass nativeTag directly):
572
- ${n.join("\n")}`}function registerScreenshotTools(e,n){e.registerTool("screenshot_component",{_meta:coreTool(),description:"Take a screenshot of the app. Pass compareTo with a saved PNG path to view both screens. It first says what changed, measured: where, which element, and the exact colors before and now. Then the saved file, then the live screen. Leave query and nativeTag out for the whole screen. To crop a React Native view on an iOS Sim, pass query or nativeTag. The tool may scroll that view into sight. Use describe_screen to read text or find controls. Pictures use more tokens. Run the MCP on the device host.",inputSchema:{compareTo:import_zod11.z.string().min(1).optional().describe("A saved PNG file to view next to this screen. Use a full path or a path from the project root. The file stays as it is."),query:import_zod11.z.string().optional().describe('Fuzzy match against testID, nativeID, accessibilityLabel, component name, or view type \u2014 e.g. "submit-button".'),nativeTag:import_zod11.z.number().optional().describe("An exact nativeTag (from a previous call's candidates) to skip fuzzy matching."),scrollIntoView:import_zod11.z.boolean().optional().describe("Attempt to scroll an off-screen component into view before capture. Default true; inspect the result."),serial:import_zod11.z.string().optional().describe("Android: the adb serial, when several devices are connected."),baseline:import_zod11.z.string().optional().describe('Whole screen only: a name like "home". The first call saves the screen as that baseline (in .buoy/baselines); later calls compare against it and report what changed, with a diff picture.'),updateBaseline:import_zod11.z.boolean().optional().describe("With baseline: save the current screen as the new baseline instead of comparing."),steady:import_zod11.z.boolean().optional().describe("With baseline: freeze the app's clock at the baseline's moment while capturing, so countdowns and times match (needs @buoy-gg/clock). Default true when the app has the clock tool."),threshold:import_zod11.z.number().min(0).max(1).optional().describe("With baseline: per-pixel color tolerance, 0 to 1. Default 0.1."),ignore:import_zod11.z.array(import_zod11.z.string()).optional().describe('With baseline: leave these out of the comparison, by testID (e.g. ["live-map", "ad-banner"]), for parts that change on their own.'),ignoreAreas:import_zod11.z.array(import_zod11.z.object({x:import_zod11.z.number(),y:import_zod11.z.number(),width:import_zod11.z.number(),height:import_zod11.z.number()})).optional().describe("With baseline: areas to leave out, as fractions of the screen (0 to 1)."),deviceId:deviceIdInput}},async t=>{try{if(t.compareTo){if(t.query||t.nativeTag!=null)return fail3("compareTo uses the whole screen. Leave query and nativeTag out.");if(t.baseline||t.updateBaseline!=null||t.steady!=null||t.threshold!=null||t.ignore!=null||t.ignoreAreas!=null)return fail3("compareTo shows both pictures. Use baseline for diff options.");return await compareFileShot(n,t.compareTo,t.deviceId,t.serial)}if(t.baseline){if(t.query||t.nativeTag!=null)return fail3("baseline works on the whole screen: leave query and nativeTag out.");return await baselineShot(n,t.baseline,{deviceId:t.deviceId,serial:t.serial,update:t.updateBaseline,threshold:t.threshold,steady:t.steady,ignore:t.ignore,ignoreAreas:t.ignoreAreas})}if(!t.query&&t.nativeTag==null){const{id:b,host:$,online:T}=await hostTarget(n,t.deviceId,{serial:t.serial},{allowOffline:true});let _=Buffer.alloc(0);const x=await maskSecrets(n,b,T,async()=>_=await hostPng($));const A={length:x.covered};const I=await toSmallImage(x.png);const E=$.platform==="ios-device"&&isAllBlack(_)?` ${BLACK_PHONE_NOTE}`:"";return{content:[{type:"image",data:I.data,mimeType:I.mimeType},{type:"text",text:`Whole screen of ${hostLabel($)}, ${I.width}\xD7${I.height}px.${A.length?` ${A.length} element(s) showing a secret were blacked out.`:""}${E}`}]}}const r=n.requireProDevice(t.deviceId);await n.callAction(TOOL_ID,"setSilentTracking",{enabled:true},r).catch(()=>{});let i=t.nativeTag;const o=i==null&&t.query?await exactTag(n,r,t.query):null;if(o)i=o.tag;const a=await n.callAction(TOOL_ID,"locateComponent",{query:i==null?t.query:void 0,nativeTag:i,scrollIntoView:t.scrollIntoView??true,margin:MARGIN_PT},r);let s=a;if(!s.matched&&(s.reason==="no-renders"||s.reason==="no-match")){const b=await n.callAction(TOOL_ID,"describeScreen",{},r).catch(()=>null);const $=b?.elements?pickDescribeScreenMatch(b.elements,t.query,i):void 0;if($?.frame&&b?.screen){s={matched:true,live:true,rect:frameToRect($.frame,b.screen),screen:b.screen,nativeTag:$.nativeTag??void 0,componentName:$.name,testID:$.testID}}else if(s.reason==="no-renders"){s={matched:false,reason:"no-match",candidates:s.candidates}}}if(!s.matched||!s.rect||!s.screen){return fail3(reasonMessage(s,t.query)+candidatesText(s.candidates))}if(i==null&&t.query){const b=t.query.toLowerCase();const $=s.candidates?.find(I=>I.nativeTag===s.nativeTag);const T=await n.callAction(TOOL_ID,"describeScreen",{},r,{timeoutMs:4e3}).catch(()=>null);const _=T?.elements?.find(I=>I.nativeTag===s.nativeTag);const x=[s.testID,s.nativeID,s.componentName,$?.testID,$?.nativeID,$?.componentName,_?.testID,_?.nativeID,_?.text,_?.label].filter(Boolean).map(I=>String(I).toLowerCase());const A=x.some(I=>I.includes(b)||I.length>3&&b.includes(I));if(!A){return fail3(`"${t.query}" is not on the current screen (the closest component was ${s.componentName??"unknown"}${s.testID?` [${s.testID}]`:""}). Navigate to it first, or pass a testID from describe_screen.`+candidatesText(s.candidates))}}const{host:c}=await hostTarget(n,r);if(c.platform!=="ios")return fail3("Cropping one component works on the iOS Simulator. Leave query out for a whole-screen picture.");let l={ok:false};const u=await maskSecrets(n,r,true,async()=>{l=await captureIosFramebuffer(c.udid);return l.ok&&l.srcPath?import_node_fs8.promises.readFile(l.srcPath):Buffer.alloc(0)});if(u.covered&&l.ok&&l.srcPath)await import_node_fs8.promises.writeFile(l.srcPath,u.png);if(!l.ok||!l.srcPath||!l.width||!l.height){return fail3(l.error??"Screenshot capture failed.")}const d=l.width/s.screen.width;const h=s.rect;const w=CAPTURE_PADDING_PT;const p=await cropToBuffer(l.srcPath,{width:l.width,height:l.height},{x:(h.x-w)*d,y:(h.y-w)*d,width:(h.width+w*2)*d,height:(h.height+w*2)*d});if(!p.ok||!p.buffer){return fail3(p.error??"Crop failed.")}const g=s.componentName||o?.name||"component";const m=s.testID??o?.testID;const f=m?` (testID: "${m}")`:"";const v=s.inView===false?"\n\nNote: the component is partly off-screen even after scrolling, so the crop is clamped to the screen edge.":"";const y=`Captured "${g}"${f} \u2014 ${p.width}\xD7${p.height}px.${v}`;return{content:[{type:"image",data:p.buffer.toString("base64"),mimeType:"image/png"},{type:"text",text:y}]}}catch(r){return fail3(errMsg3(r))}})}async function maskSecrets(e,n,t,r){const i=typeof r==="function"?r:async()=>r;const o=secretValues();if(!o.length)return{png:await i(),covered:0};const a=t?await secretBoxes(e,n,o):null;const s=await i();const c=t?await secretBoxes(e,n,o):null;if(a===null||c===null){if(t||typedSecretValues().length){throw new Error("Buoy can't read the app's screen to hide secrets right now, so no picture was taken. Try again in a moment.")}return{png:s,covered:0}}const l=[...a,...c];if(!s.length)return{png:s,covered:0};return{png:l.length?blackOut(s,l):s,covered:Math.max(a.length,c.length)}}async function secretBoxes(e,n,t){const r=await e.callAction(TOOL_ID,"describeScreen",{includeHidden:false,includeBuoy:true,fullText:true},n,{timeoutMs:4e3}).catch(()=>null);if(!r?.screen)return null;const i=typedSecretValues().length>0;const o=[];for(const a of r.elements??[]){const s=a.value;const c=[a.text,a.label,s].filter(h=>h!=null&&h!=="").map(String);const l=c.some(h=>t.some(w=>showsSecret(h,w)));const u=i&&a.control==="text"&&s===void 0;if(!l&&!u)continue;const d=a.frame?.width&&a.frame.height?fractionFrame(a,r.screen):void 0;if(!d)return null;o.push({...d,pixels:0})}return o}function showsSecret(e,n){const t=e.replace(/\s+/g," ");const r=n.replace(/\s+/g," ").trim();if(t.includes(r))return true;const i=t.replace(/(…|\.\.\.)$/,"");for(let o=r.length-1;o>=MIN_SECRET_LENGTH;o--)if(i.endsWith(r.slice(0,o)))return true;return false}function blackOut(e,n){const t=import_pngjs4.PNG.sync.read(e);for(const r of n){const i=Math.max(0,Math.floor((r.x-.01)*t.width));const o=Math.min(t.width,Math.ceil((r.x+r.width+.01)*t.width));const a=Math.max(0,Math.floor((r.y-.005)*t.height));const s=Math.min(t.height,Math.ceil((r.y+r.height+.005)*t.height));for(let c=a;c<s;c++){for(let l=i;l<o;l++){const u=(c*t.width+l)*4;t.data[u]=t.data[u+1]=t.data[u+2]=0;t.data[u+3]=255}}}return import_pngjs4.PNG.sync.write(t)}async function exactTag(e,n,t){const r=await e.callAction(TOOL_ID,"describeScreen",{},n,{timeoutMs:4e3}).catch(()=>null);const i=r?.elements??[];const o=l=>({tag:l.nativeTag,name:l.name,testID:l.testID});const a=i.filter(l=>l.testID===t&&l.nativeTag!=null);if(a.length===1)return o(a[0]);const s=t.trim().toLowerCase();const c=i.filter(l=>(l.text??l.label??"").trim().toLowerCase()===s&&l.nativeTag!=null);return c.length===1?o(c[0]):null}async function readComparisonPng(e){const n=32*1024*1024;const t=i=>{if(!i.isFile()||i.size>n)throw new Error("Use a PNG file under 32 MB.")};t(await import_node_fs8.promises.stat(e));const r=await import_node_fs8.promises.open(e,import_node_fs8.constants.O_RDONLY|import_node_fs8.constants.O_NONBLOCK);try{t(await r.stat());const i=[];let o=0;while(o<=n){const l=Buffer.alloc(Math.min(64*1024,n+1-o));const{bytesRead:u}=await r.read(l,0,l.length,null);if(!u)break;o+=u;if(o>n)throw new Error("Use a PNG file under 32 MB.");i.push(l.subarray(0,u))}const a=Buffer.concat(i,o);if(a.length<24||a.subarray(0,8).toString("hex")!=="89504e470d0a1a0a")throw new Error("The saved file must be a PNG.");const s=a.readUInt32BE(16),c=a.readUInt32BE(20);if(!s||!c||s*c>32e6)throw new Error("Use a PNG with at most 32 million pixels.");return a}finally{await r.close()}}async function compareFileShot(e,n,t,r){const i=n==="~"?import_node_os8.default.homedir():n.startsWith("~/")?import_node_path9.default.join(import_node_os8.default.homedir(),n.slice(2)):n;const o=await readComparisonPng(import_node_path9.default.resolve(process.env.BUOY_PROJECT_ROOT||process.cwd(),i));const{id:a,host:s,online:c}=await hostTarget(e,t,{serial:r},{allowOffline:true});const l=await maskSecrets(e,a,c,()=>hostPng(s));const u=await toSmallImage(o);const d=await toSmallImage(l.png);const h=await measureChange(e,a,c,o,l.png);return{content:[...h?[{type:"text",text:h}]:[],{type:"text",text:`Saved file: ${n} (${u.width}x${u.height}).`},{type:"image",data:u.data,mimeType:u.mimeType},{type:"text",text:`Current screen (${d.width}x${d.height}). Compare it with the saved file above.${l.covered?" Fields with secrets are hidden in this screen.":""}`},{type:"image",data:d.data,mimeType:d.mimeType}]}}async function measureChange(e,n,t,r,i){const o=.06;let a;try{a=diffScreens(r,i,{ignoreTop:o})}catch{return null}if(!a.boxes.length)return"Measured: no change outside the status bar.";let s=[];if(t){try{const l=await e.callAction("highlight-updates","describeScreen",{},n,{timeoutMs:3e3,silent:true});const u=l?.screen??{width:1,height:1};s=(l?.elements??[]).map(d=>({name:d.name,words:d.text??d.label,testID:d.testID,frame:fractionFrame(d,u)}))}catch{}}const c=a.boxes.slice(0,3).map(l=>{const u=elementsIn(l,s)[0];const d=boxColors(r,i,l,o);return`- ${describeSpot(l)}${u?`, ${u}`:""}${d?`: main color ${d.before} before, ${d.after} now`:""}.`});return[`Measured: ${a.percent.toFixed(1)}% of the screen changed, in ${a.boxes.length} area${a.boxes.length===1?"":"s"}.`,...c].join("\n")}function baselinePath(e){const n=e.trim().replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"")||"screen";return import_node_path9.default.join(process.env.BUOY_PROJECT_ROOT||process.cwd(),".buoy","baselines",`${n}.png`)}function fractionFrame(e,n){if(e.frame&&e.frame.width&&e.frame.height){const t=e.frame.x+e.frame.width>1.5||e.frame.y+e.frame.height>1.5;return t?{x:e.frame.x/n.width,y:e.frame.y/n.height,width:e.frame.width/n.width,height:e.frame.height/n.height}:{...e.frame}}if(e.tap)return{x:e.tap.x-.01,y:e.tap.y-.01,width:.02,height:.02};return void 0}var labelOf=e=>`${e.name??"View"}${e.words?` "${e.words.length>40?`${e.words.slice(0,40)}\u2026`:e.words}"`:""}${e.testID?` [${e.testID}]`:""}`;function elementsIn(e,n){const t=[];for(const r of n){const i=r.frame;if(!i)continue;const o=Math.max(0,Math.min(e.x+e.width,i.x+i.width)-Math.max(e.x,i.x));const a=Math.max(0,Math.min(e.y+e.height,i.y+i.height)-Math.max(e.y,i.y));const s=i.width*i.height;if(!s||o*a/s<.5)continue;t.push({label:labelOf(r),area:s,words:!!r.words})}return[...new Set(t.sort((r,i)=>Number(i.words)-Number(r.words)||r.area-i.area).map(r=>r.label))].slice(0,3)}function textChanges(e,n){const t=d=>d.testID?`id:${d.testID}`:`${d.name??""}@${d.frame?`${Math.round(d.frame.x*40)},${Math.round(d.frame.y*40)}`:"?"}`;const r=new Map(e.filter(d=>d.words).map(d=>[t(d),d]));const i=new Map(n.filter(d=>d.words).map(d=>[t(d),d]));const o=new Set([...r.values()].map(d=>d.words));const a=new Set([...i.values()].map(d=>d.words));const s=[];for(const[d,h]of i){const w=r.get(d);if(w){if(w.words!==h.words)s.push(`changed: ${labelOf({...h,words:void 0})} "${w.words}" \u2192 "${h.words}"`)}else if(!o.has(h.words))s.push(`appeared: ${labelOf(h)}`)}for(const[d,h]of r)if(!i.has(d)&&!a.has(h.words))s.push(`gone: ${labelOf(h)}`);const c=[...r.entries()].filter(([d,h])=>!i.has(d)&&!a.has(h.words)).map(([,d])=>d);const l=[...i.entries()].filter(([d,h])=>!r.has(d)&&!o.has(h.words)).map(([,d])=>d);const u=(d,h)=>!!d&&!!h&&d.x<h.x+h.width&&h.x<d.x+d.width&&d.y<h.y+h.height&&h.y<d.y+d.height;for(const d of l){const h=c.find(p=>p.name===d.name&&u(p.frame,d.frame));if(!h)continue;c.splice(c.indexOf(h),1);const w=new Set([`appeared: ${labelOf(d)}`,`gone: ${labelOf(h)}`]);for(let p=s.length-1;p>=0;p--)if(w.has(s[p]))s.splice(p,1);s.push(`changed: ${labelOf({...d,words:void 0})} "${h.words}" \u2192 "${d.words}"`)}return s.slice(0,12)}async function readScreen(e,n){try{const[t,r,i]=await Promise.all([e.callAction("highlight-updates","describeScreen",{includeBuoy:true},n,{timeoutMs:4e3}),e.callAction("highlight-updates","describeScreen",{},n,{timeoutMs:4e3}),e.callAction("route-events","getCurrentRoute",{},n,{timeoutMs:2e3}).catch(()=>null)]);const o=r?.screen??t?.screen;if(!o)return null;const a=new Set((r?.elements??[]).map(u=>u.nativeTag));const s=[];for(const u of t?.elements??[]){if(a.has(u.nativeTag))continue;const d=fractionFrame(u,o);if(d)s.push({x:d.x-.01,y:d.y-.01,width:d.width+.02,height:d.height+.02,pixels:0})}const c=(r?.elements??[]).map(u=>{const d=scrubSecrets((u.text??u.label??"").replace(/[\s\u200b\u00a0]+/g," ").trim());return{name:u.name,words:d||void 0,testID:u.testID?scrubSecrets(u.testID):void 0,frame:fractionFrame(u,o)}});const l=i?.path??i?.pathname;return{elements:c,masks:s,route:l?scrubSecrets(l):void 0}}catch{return null}}async function withFrozenClock(e,n,t,r){let i;let o;let a;try{await e.callAction("clock","freeze",{time:t},n);await new Promise(c=>setTimeout(c,1300));i=await r()}catch(c){o=c}finally{try{await e.callAction("clock","reset",{},n)}catch(c){a=c}}const s=a?` WARNING: putting the app's clock back failed (${errMsg3(a)}); run clock_action reset.`:"";if(o)throw new Error(`${errMsg3(o)}${s}`);return{result:i,note:` The app's clock was frozen at ${new Date(t).toISOString()} for the capture.${s}`}}async function baselineShot(...e){return(await runBaseline(...e)).result}async function runBaseline(e,n,t){const{id:r,host:i}=await hostTarget(e,t.deviceId,{serial:t.serial});const o=baselinePath(n);const a=o.replace(/\.png$/,".json");const s=import_node_path9.default.relative(process.env.BUOY_PROJECT_ROOT||process.cwd(),o);let c=null;try{c=await import_node_fs8.promises.readFile(o)}catch{}const l=!c||!!t.update;const u=l?{}:JSON.parse(await import_node_fs8.promises.readFile(a,"utf8").catch(()=>"{}"));const d=hostLabel(i);const h=e.connectedDevices().find(z=>z.deviceId===r)?.tools.some(z=>z.toolId==="clock")??false;const w=t.steady??h;let p="";const g=async()=>{const{result:z,steadied:F}=await withSteadyStatusBar(i,async()=>({png:(await maskSecrets(e,r,true,()=>hostPng(i))).png,screen:await readScreen(e,r)}));return{...z,steadied:F}};let m;if(w&&h){const z=await e.callAction("clock","getState",{},r).catch(()=>null);if(z?.mode==="real"){const F=l||!u.steadyTime?Math.floor(Date.now()/6e4)*6e4:u.steadyTime;u.steadyTime=F;const B=await withFrozenClock(e,r,F,g);m=B.result;p+=B.note}else{m=await g();p+=" The app's clock was already overridden, so it was left as it was."}}else{m=await g();if(w&&!h)p+=" (steady needs the Clock tool in the app; times on screen may differ.)"}const f={width:m.png.readUInt32BE(16),height:m.png.readUInt32BE(20)};if(l){await import_node_fs8.promises.mkdir(import_node_path9.default.dirname(o),{recursive:true});await import_node_fs8.promises.writeFile(o,m.png);const z={...u,device:d,size:f,route:m.screen?.route,elements:m.screen?.elements};await import_node_fs8.promises.writeFile(a,JSON.stringify(z,null,1));const F=await toSmallImage(m.png);const B=`${c?"Replaced":"Saved"} baseline "${n}"`;return{outcome:{saved:true,changed:false,percent:0,texts:0,summary:`${B} (first run)`},result:{content:[{type:"image",data:F.data,mimeType:F.mimeType},{type:"text",text:`${c?"Replaced":"Saved"} baseline "${n}" (${s}) from ${d}${m.screen?.route?` on ${m.screen.route}`:""}. Call again with the same baseline to compare.${p}`}]}}}const v=[];if(u.device&&u.device!==d)v.push(`The baseline was saved on ${u.device}; this is ${d}.`);if(u.route&&m.screen?.route&&u.route!==m.screen.route)v.push(`The baseline was on ${u.route}; the app is now on ${m.screen.route}.`);const y=[...t.ignoreAreas??[]];const b=new Set(t.ignore??[]);const $=new Set(b);for(const z of[...u.elements??[],...m.screen?.elements??[]]){if(!z.testID||!b.has(z.testID)||!z.frame)continue;$.delete(z.testID);y.push({x:z.frame.x-.005,y:z.frame.y-.005,width:z.frame.width+.01,height:z.frame.height+.01})}if($.size)v.push(`Not on screen, so not left out: ${[...$].join(", ")}.`);const T=i.platform==="android"?[]:[{x:.28,y:0,width:.44,height:.055}];const _=diffScreens(c,m.png,{threshold:t.threshold,masks:[...m.screen?.masks??[],...y,...T],ignoreTop:m.steadied?0:.065});const x=z=>!!z&&y.some(F=>z.x+z.width/2>=F.x&&z.x+z.width/2<=F.x+F.width&&z.y+z.height/2>=F.y&&z.y+z.height/2<=F.y+F.height);const A=z=>(!z.testID||!b.has(z.testID))&&!x(z.frame);const I=u.elements&&m.screen?textChanges(u.elements.filter(A),m.screen.elements.filter(A)):[];const E=[m.steadied?"":"status bar",m.screen?.masks.length?"Buoy's overlay":"",y.length?"the parts you asked to ignore":""].filter(Boolean);const S=E.join(" and ");const k=S?`; ${S} left out`:"";const M=v.length?`
572
+ ${n.join("\n")}`}function registerScreenshotTools(e,n){e.registerTool("screenshot_component",{_meta:coreTool(),description:"Take a screenshot of the app. Pass compareTo with a saved PNG path to view both screens. It first says what changed, measured: where, which element, and the exact colors before and now. Then the saved file, then the live screen. Leave query and nativeTag out for the whole screen. To crop a React Native view on an iOS Sim, pass query or nativeTag. The tool may scroll that view into sight. Use describe_screen to read text or find controls. Pictures use more tokens. Run the MCP on the device host.",inputSchema:{compareTo:import_zod11.z.string().min(1).optional().describe("A saved PNG file to view next to this screen. Use a full path or a path from the project root. The file stays as it is."),query:import_zod11.z.string().optional().describe('Fuzzy match against testID, nativeID, accessibilityLabel, component name, or view type \u2014 e.g. "submit-button".'),nativeTag:import_zod11.z.number().optional().describe("An exact nativeTag (from a previous call's candidates) to skip fuzzy matching."),scrollIntoView:import_zod11.z.boolean().optional().describe("Attempt to scroll an off-screen component into view before capture. Default true; inspect the result."),serial:import_zod11.z.string().optional().describe("Android: the adb serial, when several devices are connected."),baseline:import_zod11.z.string().optional().describe('Whole screen only: a name like "home". The first call saves the screen as that baseline (in .buoy/baselines); later calls compare against it and report what changed, with a diff picture.'),updateBaseline:import_zod11.z.boolean().optional().describe("With baseline: save the current screen as the new baseline instead of comparing."),steady:import_zod11.z.boolean().optional().describe("With baseline: freeze the app's clock at the baseline's moment while capturing, so countdowns and times match (needs @buoy-gg/clock). Default true when the app has the clock tool."),threshold:import_zod11.z.number().min(0).max(1).optional().describe("With baseline: per-pixel color tolerance, 0 to 1. Default 0.1."),ignore:import_zod11.z.array(import_zod11.z.string()).optional().describe('With baseline: leave these out of the comparison, by testID (e.g. ["live-map", "ad-banner"]), for parts that change on their own.'),ignoreAreas:import_zod11.z.array(import_zod11.z.object({x:import_zod11.z.number(),y:import_zod11.z.number(),width:import_zod11.z.number(),height:import_zod11.z.number()})).optional().describe("With baseline: areas to leave out, as fractions of the screen (0 to 1)."),deviceId:deviceIdInput}},async t=>{try{if(t.compareTo){if(t.query||t.nativeTag!=null)return fail3("compareTo uses the whole screen. Leave query and nativeTag out.");if(t.baseline||t.updateBaseline!=null||t.steady!=null||t.threshold!=null||t.ignore!=null||t.ignoreAreas!=null)return fail3("compareTo shows both pictures. Use baseline for diff options.");return await compareFileShot(n,t.compareTo,t.deviceId,t.serial)}if(t.baseline){if(t.query||t.nativeTag!=null)return fail3("baseline works on the whole screen: leave query and nativeTag out.");return await baselineShot(n,t.baseline,{deviceId:t.deviceId,serial:t.serial,update:t.updateBaseline,threshold:t.threshold,steady:t.steady,ignore:t.ignore,ignoreAreas:t.ignoreAreas})}if(!t.query&&t.nativeTag==null){const{id:b,host:$,online:T}=await hostTarget(n,t.deviceId,{serial:t.serial},{allowOffline:true});let _=Buffer.alloc(0);const x=await maskSecrets(n,b,T,async()=>_=await hostPng($));const I={length:x.covered};const D=await toSmallImage(x.png);const E=$.platform==="ios-device"&&isAllBlack(_)?` ${BLACK_PHONE_NOTE}`:"";return{content:[{type:"image",data:D.data,mimeType:D.mimeType},{type:"text",text:`Whole screen of ${hostLabel($)}, ${D.width}\xD7${D.height}px.${I.length?` ${I.length} element(s) showing a secret were blacked out.`:""}${E}`}]}}const r=n.requireProDevice(t.deviceId);await n.callAction(TOOL_ID,"setSilentTracking",{enabled:true},r).catch(()=>{});let i=t.nativeTag;const o=i==null&&t.query?await exactTag(n,r,t.query):null;if(o)i=o.tag;const a=await n.callAction(TOOL_ID,"locateComponent",{query:i==null?t.query:void 0,nativeTag:i,scrollIntoView:t.scrollIntoView??true,margin:MARGIN_PT},r);let s=a;if(!s.matched&&(s.reason==="no-renders"||s.reason==="no-match")){const b=await n.callAction(TOOL_ID,"describeScreen",{},r).catch(()=>null);const $=b?.elements?pickDescribeScreenMatch(b.elements,t.query,i):void 0;if($?.frame&&b?.screen){s={matched:true,live:true,rect:frameToRect($.frame,b.screen),screen:b.screen,nativeTag:$.nativeTag??void 0,componentName:$.name,testID:$.testID}}else if(s.reason==="no-renders"){s={matched:false,reason:"no-match",candidates:s.candidates}}}if(!s.matched||!s.rect||!s.screen){return fail3(reasonMessage(s,t.query)+candidatesText(s.candidates))}if(i==null&&t.query){const b=t.query.toLowerCase();const $=s.candidates?.find(D=>D.nativeTag===s.nativeTag);const T=await n.callAction(TOOL_ID,"describeScreen",{},r,{timeoutMs:4e3}).catch(()=>null);const _=T?.elements?.find(D=>D.nativeTag===s.nativeTag);const x=[s.testID,s.nativeID,s.componentName,$?.testID,$?.nativeID,$?.componentName,_?.testID,_?.nativeID,_?.text,_?.label].filter(Boolean).map(D=>String(D).toLowerCase());const I=x.some(D=>D.includes(b)||D.length>3&&b.includes(D));if(!I){return fail3(`"${t.query}" is not on the current screen (the closest component was ${s.componentName??"unknown"}${s.testID?` [${s.testID}]`:""}). Navigate to it first, or pass a testID from describe_screen.`+candidatesText(s.candidates))}}const{host:c}=await hostTarget(n,r);if(c.platform!=="ios")return fail3("Cropping one component works on the iOS Simulator. Leave query out for a whole-screen picture.");let l={ok:false};const u=await maskSecrets(n,r,true,async()=>{l=await captureIosFramebuffer(c.udid);return l.ok&&l.srcPath?import_node_fs8.promises.readFile(l.srcPath):Buffer.alloc(0)});if(u.covered&&l.ok&&l.srcPath)await import_node_fs8.promises.writeFile(l.srcPath,u.png);if(!l.ok||!l.srcPath||!l.width||!l.height){return fail3(l.error??"Screenshot capture failed.")}const d=l.width/s.screen.width;const h=s.rect;const w=CAPTURE_PADDING_PT;const p=await cropToBuffer(l.srcPath,{width:l.width,height:l.height},{x:(h.x-w)*d,y:(h.y-w)*d,width:(h.width+w*2)*d,height:(h.height+w*2)*d});if(!p.ok||!p.buffer){return fail3(p.error??"Crop failed.")}const g=s.componentName||o?.name||"component";const m=s.testID??o?.testID;const f=m?` (testID: "${m}")`:"";const v=s.inView===false?"\n\nNote: the component is partly off-screen even after scrolling, so the crop is clamped to the screen edge.":"";const y=`Captured "${g}"${f} \u2014 ${p.width}\xD7${p.height}px.${v}`;return{content:[{type:"image",data:p.buffer.toString("base64"),mimeType:"image/png"},{type:"text",text:y}]}}catch(r){return fail3(errMsg3(r))}})}async function maskSecrets(e,n,t,r){const i=typeof r==="function"?r:async()=>r;const o=secretValues();if(!o.length)return{png:await i(),covered:0};const a=t?await secretBoxes(e,n,o):null;const s=await i();const c=t?await secretBoxes(e,n,o):null;if(a===null||c===null){if(t||typedSecretValues().length){throw new Error("Buoy can't read the app's screen to hide secrets right now, so no picture was taken. Try again in a moment.")}return{png:s,covered:0}}const l=[...a,...c];if(!s.length)return{png:s,covered:0};return{png:l.length?blackOut(s,l):s,covered:Math.max(a.length,c.length)}}async function secretBoxes(e,n,t){const r=await e.callAction(TOOL_ID,"describeScreen",{includeHidden:false,includeBuoy:true,fullText:true},n,{timeoutMs:4e3}).catch(()=>null);if(!r?.screen)return null;const i=typedSecretValues().length>0;const o=[];for(const a of r.elements??[]){const s=a.value;const c=[a.text,a.label,s].filter(h=>h!=null&&h!=="").map(String);const l=c.some(h=>t.some(w=>showsSecret(h,w)));const u=i&&a.control==="text"&&s===void 0;if(!l&&!u)continue;const d=a.frame?.width&&a.frame.height?fractionFrame(a,r.screen):void 0;if(!d)return null;o.push({...d,pixels:0})}return o}function showsSecret(e,n){const t=e.replace(/\s+/g," ");const r=n.replace(/\s+/g," ").trim();if(t.includes(r))return true;const i=t.replace(/(…|\.\.\.)$/,"");for(let o=r.length-1;o>=MIN_SECRET_LENGTH;o--)if(i.endsWith(r.slice(0,o)))return true;return false}function blackOut(e,n){const t=import_pngjs4.PNG.sync.read(e);for(const r of n){const i=Math.max(0,Math.floor((r.x-.01)*t.width));const o=Math.min(t.width,Math.ceil((r.x+r.width+.01)*t.width));const a=Math.max(0,Math.floor((r.y-.005)*t.height));const s=Math.min(t.height,Math.ceil((r.y+r.height+.005)*t.height));for(let c=a;c<s;c++){for(let l=i;l<o;l++){const u=(c*t.width+l)*4;t.data[u]=t.data[u+1]=t.data[u+2]=0;t.data[u+3]=255}}}return import_pngjs4.PNG.sync.write(t)}async function exactTag(e,n,t){const r=await e.callAction(TOOL_ID,"describeScreen",{},n,{timeoutMs:4e3}).catch(()=>null);const i=r?.elements??[];const o=l=>({tag:l.nativeTag,name:l.name,testID:l.testID});const a=i.filter(l=>l.testID===t&&l.nativeTag!=null);if(a.length===1)return o(a[0]);const s=t.trim().toLowerCase();const c=i.filter(l=>(l.text??l.label??"").trim().toLowerCase()===s&&l.nativeTag!=null);return c.length===1?o(c[0]):null}async function readComparisonPng(e){const n=32*1024*1024;const t=i=>{if(!i.isFile()||i.size>n)throw new Error("Use a PNG file under 32 MB.")};t(await import_node_fs8.promises.stat(e));const r=await import_node_fs8.promises.open(e,import_node_fs8.constants.O_RDONLY|import_node_fs8.constants.O_NONBLOCK);try{t(await r.stat());const i=[];let o=0;while(o<=n){const l=Buffer.alloc(Math.min(64*1024,n+1-o));const{bytesRead:u}=await r.read(l,0,l.length,null);if(!u)break;o+=u;if(o>n)throw new Error("Use a PNG file under 32 MB.");i.push(l.subarray(0,u))}const a=Buffer.concat(i,o);if(a.length<24||a.subarray(0,8).toString("hex")!=="89504e470d0a1a0a")throw new Error("The saved file must be a PNG.");const s=a.readUInt32BE(16),c=a.readUInt32BE(20);if(!s||!c||s*c>32e6)throw new Error("Use a PNG with at most 32 million pixels.");return a}finally{await r.close()}}async function compareFileShot(e,n,t,r){const i=n==="~"?import_node_os8.default.homedir():n.startsWith("~/")?import_node_path9.default.join(import_node_os8.default.homedir(),n.slice(2)):n;const o=await readComparisonPng(import_node_path9.default.resolve(process.env.BUOY_PROJECT_ROOT||process.cwd(),i));const{id:a,host:s,online:c}=await hostTarget(e,t,{serial:r},{allowOffline:true});const l=await maskSecrets(e,a,c,()=>hostPng(s));const u=await toSmallImage(o);const d=await toSmallImage(l.png);const h=await measureChange(e,a,c,o,l.png);return{content:[...h?[{type:"text",text:h}]:[],{type:"text",text:`Saved file: ${n} (${u.width}x${u.height}).`},{type:"image",data:u.data,mimeType:u.mimeType},{type:"text",text:`Current screen (${d.width}x${d.height}). Compare it with the saved file above.${l.covered?" Fields with secrets are hidden in this screen.":""}`},{type:"image",data:d.data,mimeType:d.mimeType}]}}async function measureChange(e,n,t,r,i){const o=.06;let a;try{a=diffScreens(r,i,{ignoreTop:o})}catch{return null}if(!a.boxes.length)return"Measured: no change outside the status bar.";let s=[];if(t){try{const l=await e.callAction("highlight-updates","describeScreen",{},n,{timeoutMs:3e3,silent:true});const u=l?.screen??{width:1,height:1};s=(l?.elements??[]).map(d=>({name:d.name,words:d.text??d.label,testID:d.testID,frame:fractionFrame(d,u)}))}catch{}}const c=a.boxes.slice(0,3).map(l=>{const u=elementsIn(l,s)[0];const d=boxColors(r,i,l,o);return`- ${describeSpot(l)}${u?`, ${u}`:""}${d?`: main color ${d.before} before, ${d.after} now`:""}.`});return[`Measured: ${a.percent.toFixed(1)}% of the screen changed, in ${a.boxes.length} area${a.boxes.length===1?"":"s"}.`,...c].join("\n")}function baselinePath(e){const n=e.trim().replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"")||"screen";return import_node_path9.default.join(process.env.BUOY_PROJECT_ROOT||process.cwd(),".buoy","baselines",`${n}.png`)}function fractionFrame(e,n){if(e.frame&&e.frame.width&&e.frame.height){const t=e.frame.x+e.frame.width>1.5||e.frame.y+e.frame.height>1.5;return t?{x:e.frame.x/n.width,y:e.frame.y/n.height,width:e.frame.width/n.width,height:e.frame.height/n.height}:{...e.frame}}if(e.tap)return{x:e.tap.x-.01,y:e.tap.y-.01,width:.02,height:.02};return void 0}var labelOf=e=>`${e.name??"View"}${e.words?` "${e.words.length>40?`${e.words.slice(0,40)}\u2026`:e.words}"`:""}${e.testID?` [${e.testID}]`:""}`;function elementsIn(e,n){const t=[];for(const r of n){const i=r.frame;if(!i)continue;const o=Math.max(0,Math.min(e.x+e.width,i.x+i.width)-Math.max(e.x,i.x));const a=Math.max(0,Math.min(e.y+e.height,i.y+i.height)-Math.max(e.y,i.y));const s=i.width*i.height;if(!s||o*a/s<.5)continue;t.push({label:labelOf(r),area:s,words:!!r.words})}return[...new Set(t.sort((r,i)=>Number(i.words)-Number(r.words)||r.area-i.area).map(r=>r.label))].slice(0,3)}function textChanges(e,n){const t=d=>d.testID?`id:${d.testID}`:`${d.name??""}@${d.frame?`${Math.round(d.frame.x*40)},${Math.round(d.frame.y*40)}`:"?"}`;const r=new Map(e.filter(d=>d.words).map(d=>[t(d),d]));const i=new Map(n.filter(d=>d.words).map(d=>[t(d),d]));const o=new Set([...r.values()].map(d=>d.words));const a=new Set([...i.values()].map(d=>d.words));const s=[];for(const[d,h]of i){const w=r.get(d);if(w){if(w.words!==h.words)s.push(`changed: ${labelOf({...h,words:void 0})} "${w.words}" \u2192 "${h.words}"`)}else if(!o.has(h.words))s.push(`appeared: ${labelOf(h)}`)}for(const[d,h]of r)if(!i.has(d)&&!a.has(h.words))s.push(`gone: ${labelOf(h)}`);const c=[...r.entries()].filter(([d,h])=>!i.has(d)&&!a.has(h.words)).map(([,d])=>d);const l=[...i.entries()].filter(([d,h])=>!r.has(d)&&!o.has(h.words)).map(([,d])=>d);const u=(d,h)=>!!d&&!!h&&d.x<h.x+h.width&&h.x<d.x+d.width&&d.y<h.y+h.height&&h.y<d.y+d.height;for(const d of l){const h=c.find(p=>p.name===d.name&&u(p.frame,d.frame));if(!h)continue;c.splice(c.indexOf(h),1);const w=new Set([`appeared: ${labelOf(d)}`,`gone: ${labelOf(h)}`]);for(let p=s.length-1;p>=0;p--)if(w.has(s[p]))s.splice(p,1);s.push(`changed: ${labelOf({...d,words:void 0})} "${h.words}" \u2192 "${d.words}"`)}return s.slice(0,12)}async function readScreen(e,n){try{const[t,r,i]=await Promise.all([e.callAction("highlight-updates","describeScreen",{includeBuoy:true},n,{timeoutMs:4e3}),e.callAction("highlight-updates","describeScreen",{},n,{timeoutMs:4e3}),e.callAction("route-events","getCurrentRoute",{},n,{timeoutMs:2e3}).catch(()=>null)]);const o=r?.screen??t?.screen;if(!o)return null;const a=new Set((r?.elements??[]).map(u=>u.nativeTag));const s=[];for(const u of t?.elements??[]){if(a.has(u.nativeTag))continue;const d=fractionFrame(u,o);if(d)s.push({x:d.x-.01,y:d.y-.01,width:d.width+.02,height:d.height+.02,pixels:0})}const c=(r?.elements??[]).map(u=>{const d=scrubSecrets((u.text??u.label??"").replace(/[\s\u200b\u00a0]+/g," ").trim());return{name:u.name,words:d||void 0,testID:u.testID?scrubSecrets(u.testID):void 0,frame:fractionFrame(u,o)}});const l=i?.path??i?.pathname;return{elements:c,masks:s,route:l?scrubSecrets(l):void 0}}catch{return null}}async function withFrozenClock(e,n,t,r){let i;let o;let a;try{await e.callAction("clock","freeze",{time:t},n);await new Promise(c=>setTimeout(c,1300));i=await r()}catch(c){o=c}finally{try{await e.callAction("clock","reset",{},n)}catch(c){a=c}}const s=a?` WARNING: putting the app's clock back failed (${errMsg3(a)}); run clock_action reset.`:"";if(o)throw new Error(`${errMsg3(o)}${s}`);return{result:i,note:` The app's clock was frozen at ${new Date(t).toISOString()} for the capture.${s}`}}async function baselineShot(...e){return(await runBaseline(...e)).result}async function runBaseline(e,n,t){const{id:r,host:i}=await hostTarget(e,t.deviceId,{serial:t.serial});const o=baselinePath(n);const a=o.replace(/\.png$/,".json");const s=import_node_path9.default.relative(process.env.BUOY_PROJECT_ROOT||process.cwd(),o);let c=null;try{c=await import_node_fs8.promises.readFile(o)}catch{}const l=!c||!!t.update;const u=l?{}:JSON.parse(await import_node_fs8.promises.readFile(a,"utf8").catch(()=>"{}"));const d=hostLabel(i);const h=e.connectedDevices().find(z=>z.deviceId===r)?.tools.some(z=>z.toolId==="clock")??false;const w=t.steady??h;let p="";const g=async()=>{const{result:z,steadied:F}=await withSteadyStatusBar(i,async()=>({png:(await maskSecrets(e,r,true,()=>hostPng(i))).png,screen:await readScreen(e,r)}));return{...z,steadied:F}};let m;if(w&&h){const z=await e.callAction("clock","getState",{},r).catch(()=>null);if(z?.mode==="real"){const F=l||!u.steadyTime?Math.floor(Date.now()/6e4)*6e4:u.steadyTime;u.steadyTime=F;const B=await withFrozenClock(e,r,F,g);m=B.result;p+=B.note}else{m=await g();p+=" The app's clock was already overridden, so it was left as it was."}}else{m=await g();if(w&&!h)p+=" (steady needs the Clock tool in the app; times on screen may differ.)"}const f={width:m.png.readUInt32BE(16),height:m.png.readUInt32BE(20)};if(l){await import_node_fs8.promises.mkdir(import_node_path9.default.dirname(o),{recursive:true});await import_node_fs8.promises.writeFile(o,m.png);const z={...u,device:d,size:f,route:m.screen?.route,elements:m.screen?.elements};await import_node_fs8.promises.writeFile(a,JSON.stringify(z,null,1));const F=await toSmallImage(m.png);const B=`${c?"Replaced":"Saved"} baseline "${n}"`;return{outcome:{saved:true,changed:false,percent:0,texts:0,summary:`${B} (first run)`},result:{content:[{type:"image",data:F.data,mimeType:F.mimeType},{type:"text",text:`${c?"Replaced":"Saved"} baseline "${n}" (${s}) from ${d}${m.screen?.route?` on ${m.screen.route}`:""}. Call again with the same baseline to compare.${p}`}]}}}const v=[];if(u.device&&u.device!==d)v.push(`The baseline was saved on ${u.device}; this is ${d}.`);if(u.route&&m.screen?.route&&u.route!==m.screen.route)v.push(`The baseline was on ${u.route}; the app is now on ${m.screen.route}.`);const y=[...t.ignoreAreas??[]];const b=new Set(t.ignore??[]);const $=new Set(b);for(const z of[...u.elements??[],...m.screen?.elements??[]]){if(!z.testID||!b.has(z.testID)||!z.frame)continue;$.delete(z.testID);y.push({x:z.frame.x-.005,y:z.frame.y-.005,width:z.frame.width+.01,height:z.frame.height+.01})}if($.size)v.push(`Not on screen, so not left out: ${[...$].join(", ")}.`);const T=i.platform==="android"?[]:[{x:.28,y:0,width:.44,height:.055}];const _=diffScreens(c,m.png,{threshold:t.threshold,masks:[...m.screen?.masks??[],...y,...T],ignoreTop:m.steadied?0:.065});const x=z=>!!z&&y.some(F=>z.x+z.width/2>=F.x&&z.x+z.width/2<=F.x+F.width&&z.y+z.height/2>=F.y&&z.y+z.height/2<=F.y+F.height);const I=z=>(!z.testID||!b.has(z.testID))&&!x(z.frame);const D=u.elements&&m.screen?textChanges(u.elements.filter(I),m.screen.elements.filter(I)):[];const E=[m.steadied?"":"status bar",m.screen?.masks.length?"Buoy's overlay":"",y.length?"the parts you asked to ignore":""].filter(Boolean);const S=E.join(" and ");const k=S?`; ${S} left out`:"";const M=v.length?`
573
573
 
574
- \u26A0\uFE0F ${v.join(" ")}`:"";if(_.changedPixels===0&&I.length===0){return{outcome:{saved:false,changed:false,percent:0,texts:0,summary:`no change from baseline "${n}"`},result:text(`No change from baseline "${n}" (${s}${k}).${p}${M}`)}}const D=_.boxes.map((z,F)=>{const B=m.screen?elementsIn(z,m.screen.elements):[];const U=`${describeSpot(z)} (x ${z.x.toFixed(2)}, y ${z.y.toFixed(2)}, ${z.width.toFixed(2)}\xD7${z.height.toFixed(2)})`;return`${F+1}. ${U}${B.length?`: ${B.join(", ")}`:""}`});const P=await toSmallImage(_.diffPng);const R=_.percent<.01&&_.changedPixels>0?"<0.01":_.percent.toFixed(2);const j=D[0]?`; ${D[0].replace(/^1\. /,"")}`:"";const C=I[0]?`; ${I[0]}`:"";const O=_.changedPixels===0?`no pixel change from baseline "${n}", but text changed`:`${R}% changed from baseline "${n}"`;const N={saved:false,changed:true,percent:_.percent,texts:I.length,summary:`${O}${j}${C}`};return{outcome:N,result:{content:[{type:"image",data:P.data,mimeType:P.mimeType},{type:"text",text:`**Changed from baseline "${n}": ${_.percent<.01&&_.changedPixels>0?"<0.01":_.percent.toFixed(2)}% of the screen** (${_.changedPixels} px${k}). Changes are red in the picture.${p}`+(D.length?`
574
+ \u26A0\uFE0F ${v.join(" ")}`:"";if(_.changedPixels===0&&D.length===0){return{outcome:{saved:false,changed:false,percent:0,texts:0,summary:`no change from baseline "${n}"`},result:text(`No change from baseline "${n}" (${s}${k}).${p}${M}`)}}const A=_.boxes.map((z,F)=>{const B=m.screen?elementsIn(z,m.screen.elements):[];const U=`${describeSpot(z)} (x ${z.x.toFixed(2)}, y ${z.y.toFixed(2)}, ${z.width.toFixed(2)}\xD7${z.height.toFixed(2)})`;return`${F+1}. ${U}${B.length?`: ${B.join(", ")}`:""}`});const O=await toSmallImage(_.diffPng);const R=_.percent<.01&&_.changedPixels>0?"<0.01":_.percent.toFixed(2);const j=A[0]?`; ${A[0].replace(/^1\. /,"")}`:"";const C=D[0]?`; ${D[0]}`:"";const P=_.changedPixels===0?`no pixel change from baseline "${n}", but text changed`:`${R}% changed from baseline "${n}"`;const N={saved:false,changed:true,percent:_.percent,texts:D.length,summary:`${P}${j}${C}`};return{outcome:N,result:{content:[{type:"image",data:O.data,mimeType:O.mimeType},{type:"text",text:`**Changed from baseline "${n}": ${_.percent<.01&&_.changedPixels>0?"<0.01":_.percent.toFixed(2)}% of the screen** (${_.changedPixels} px${k}). Changes are red in the picture.${p}`+(A.length?`
575
575
 
576
576
  Where:
577
- ${D.join("\n")}`:"")+(I.length?`
577
+ ${A.join("\n")}`:"")+(D.length?`
578
578
 
579
579
  Text:
580
- ${I.map(z=>`- ${z}`).join("\n")}`:"")+`${M}
580
+ ${D.map(z=>`- ${z}`).join("\n")}`:"")+`${M}
581
581
 
582
- If this change is expected, save it with updateBaseline: true.`}]}}}var import_zod12=require("zod");var import_node_fs9=require("fs");var import_node_path10=__toESM(require("path"));var FLOW_DIR=()=>import_node_path10.default.join(process.cwd(),".buoy","flows");var FLOW_NAME=/^[A-Za-z0-9_-]{1,64}$/;async function listSavedFlows(){try{return(await import_node_fs9.promises.readdir(FLOW_DIR())).filter(e=>e.endsWith(".json")).map(e=>e.slice(0,-5))}catch{return[]}}var UI_TOOL_ID="highlight-updates";var APP_TOOL_ID="app";var text2=e=>({content:[{type:"text",text:e}]});var fail4=e=>({isError:true,content:[{type:"text",text:e}]});var errMsg4=e=>e instanceof Error?e.message:String(e);var delay3=e=>new Promise(n=>setTimeout(n,e));var POLL_MS=250;var TAP_SETTLE_MS=2e3;var DEFAULT_WAIT_MS=5e3;var ASSERT_SETTLE_MS=2e3;var TEARDOWN_GRACE_MS=1200;var REALM_PROBE_MS=1500;var MAX_FLOW_MS=12e4;function matches(e,n){if(e.testID&&e.testID===n)return true;const t=n.toLowerCase();return[e.testID,e.text,e.label,e.name].filter(Boolean).some(r=>String(r).toLowerCase().includes(t))}var STEP_KINDS=["tap","waitFor","waitGone","expect","expectGone","reload","wait","swipe"];function normalizeStep(e){if(!e||typeof e!=="object"||Array.isArray(e))return e;const n={...e};const t=a=>{if(!a||typeof a!=="object"||Array.isArray(a))return a;const s=a;return[s.testID,s.text,s.query,s.label,s.name].find(c=>typeof c==="string")??a};for(const a of["tap","into","waitFor","waitGone","expect","expectGone"])n[a]=t(n[a]);for(const a of Object.keys(n))if(n[a]===void 0)delete n[a];if(typeof n.into==="string")return n;const r=typeof n.type==="string"&&STEP_KINDS.includes(n.type)?"type":typeof n.action==="string"&&STEP_KINDS.includes(n.action)?"action":null;if(!r)return n;const i=n[r];delete n[r];const o=[n.query,n.text,n.target,n.selector,n.element,n.testID].map(t).find(a=>typeof a==="string");for(const a of["query","text","target","selector","element","testID"])delete n[a];if(i==="reload")n.reload=true;else if(i==="swipe"){n.swipe=n.direction??o??"up";delete n.direction}else if(i==="wait")n.waitMs=n.waitMs??n.ms??n.durationMs??n.timeoutMs;else if(o!==void 0&&n[i]===void 0)n[i]=o;delete n.ms;delete n.durationMs;return n}var stepSchema=import_zod12.z.preprocess(normalizeStep,import_zod12.z.object({tap:import_zod12.z.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),longPress:import_zod12.z.boolean().optional().describe("Make `tap` a long-press instead."),type:import_zod12.z.string().optional().describe("Text to type (needs `into`)."),into:import_zod12.z.string().optional().describe("Target text input for `type`: testID or fuzzy text."),set:import_zod12.z.union([import_zod12.z.number(),import_zod12.z.boolean()]).optional().describe("Set a toggle (true/false) or slider (number) \u2014 pair with `tap` as the target."),swipe:import_zod12.z.enum(["up","down","left","right"]).optional().describe('A real swipe, the way the finger moves: "up" scrolls down the list.'),untilEnd:import_zod12.z.boolean().optional().describe("With swipe: keep swiping until the screen stops moving (the end of the list)."),real:import_zod12.z.boolean().optional().describe("Make this step's tap a real touch. Default: the flow's `real`."),reload:import_zod12.z.boolean().optional().describe("Reload the JS bundle before this step's action."),waitMs:import_zod12.z.number().min(0).max(3e4).optional().describe("Fixed pause after the action, in ms (max 30000). To wait for a result (a slow request, a new screen), use waitFor with timeoutMs instead: it stops as soon as the element shows."),waitFor:import_zod12.z.string().optional().describe("Wait until an element matching this appears (default 5s)."),waitGone:import_zod12.z.string().optional().describe("Wait until no element matches this (default 5s)."),expect:import_zod12.z.string().optional().describe("Assert an element matching this IS on screen (waits up to 2s for it); fails the flow if not."),expectGone:import_zod12.z.string().optional().describe("Assert nothing matches this (waits up to 2s for it to go); fails the flow if something does."),snapshot:import_zod12.z.string().optional().describe("Compare the whole screen to the baseline with this name (saved on the first run, like screenshot_component baseline). Fails the step on a text change or a change bigger than maxChange."),maxChange:import_zod12.z.number().min(0).max(100).optional().describe("snapshot: allowed changed share of the screen, in percent. Default 0.05."),timeoutMs:import_zod12.z.number().min(0).max(6e4).optional().describe("Budget for this step's waitFor/waitGone/expect, max 60000. Default 5000 (2000 for expect).")}).describe("One flow step. Order within a step: reload \u2192 tap/type/set/swipe \u2192 waitMs \u2192 waitFor/waitGone \u2192 expect."));var flowInput={steps:import_zod12.z.array(stepSchema).min(1).optional().describe("Steps to run, in order. Leave out when replaying a saved flow."),flow:import_zod12.z.string().optional().describe("Replay a saved flow by name (from .buoy/flows in the project) instead of passing steps."),save:import_zod12.z.string().optional().describe('Save these steps under this name when the flow passes, so it can be replayed with flow:"name".'),include:import_zod12.z.enum(["all","screen","none"]).optional().describe("What to report after the flow: 'all' (default) = available final element tree + newly observed captured network/console entries; 'screen' = available final element tree only; 'none' = step results only."),updateSnapshots:import_zod12.z.boolean().optional().describe("Save every snapshot step's screen as its new baseline instead of comparing."),continueOnFailure:import_zod12.z.boolean().optional().describe("Keep going after a failed step instead of stopping. Default false."),real:import_zod12.z.boolean().optional().describe("Make every tap a real OS touch (iOS Simulator, Android), found by testID, text or native label. Default false."),deviceId:deviceIdInput};var runFlow=async()=>fail4("run_flow is not ready.");function registerFlowTools(e,n){e.registerTool("run_flow",{_meta:coreTool(),description:"Run supported UI actions and element checks in sequence, with per-step results. Stops on the first failed step unless continueOnFailure is true. Depending on include, attempts to return the final element tree and newly observed captured network/console entries. Background activity can appear in that output; it does not establish causation. Taps use exposed app handlers by default; a tap with no handler match (a native tab bar) falls back to a real touch on that native label. Pass real: true to make every tap a real touch. A tap waits up to 2 s for its target to show, so steps rarely need waitMs between them. A swipe step is a real swipe; add untilEnd: true to scroll to the end of a list. Review failures and check the expected behavior. To wait for something slow, use waitFor or waitGone with a timeoutMs, not a long waitMs. Requires Buoy Pro and the app interaction integration.",inputSchema:flowInput},async t=>runFlow(t));runFlow=async t=>{const r=Date.now();try{let i=t.steps;if(t.flow){if(!FLOW_NAME.test(t.flow))return fail4(`Flow names use letters, numbers, - and _ (got "${t.flow}").`);try{i=JSON.parse(await import_node_fs9.promises.readFile(import_node_path10.default.join(FLOW_DIR(),`${t.flow}.json`),"utf8")).steps}catch{const S=await listSavedFlows();return fail4(`No saved flow "${t.flow}". ${S.length?`Saved flows: ${S.join(", ")}.`:'No flows are saved yet; run one with save:"name" first.'}`)}}if(!i||i.length===0)return fail4('Pass steps, or flow:"name" to replay a saved flow.');if(t.save&&!FLOW_NAME.test(t.save))return fail4(`Flow names use letters, numbers, - and _ (got "${t.save}").`);const o=n.requireProDevice(t.deviceId);const a=t.include??"all";const s=nativeKit(n);let c=null;const l=()=>c??=hostTarget(n,o).then(async S=>{await s.primeScreen(o,S.host,S.online);return S});let u;const d=async(S,k,M,D)=>{const P=k?await s.buoyCover(o,S,M):null;if(P)throw new Error(P);const R=D?600:void 0;const j=await s.touch(S,M,R,u);if(j!==void 0)u=j;await s.mark(o,S,R?"hold":"tap",[[M.x,M.y]],void 0,R??150,j);await delay3(120);return`${D?"long-pressed":"tapped"} ${M.what} (real touch)`};const h=async(S,k,M)=>{const{host:D,online:P}=await l();const R=Date.now();let j=false;for(;;){let C=await s.findSpot(o,D,S,P,"app");if("miss"in C&&!C.tie&&(j||!P||Date.now()-R>=600)){if(!j){j=true;C=await s.findSpot(o,D,S,P,"native")}if("miss"in C&&!C.tie)C=await s.findSpot(o,D,S,P,"loose")}if(!("miss"in C))return d(D,P,C,k);if(C.tie||Date.now()-R>=M)throw new Error(C.miss);await delay3(POLL_MS)}};const w=async(S,k,M)=>{let D;try{D=await l()}catch{return null}if(D.host.platform==="ios-device")return null;const P=await s.findSpot(o,D.host,S,D.online,M?"nativeExact":"native").catch(()=>null);if(!P||"miss"in P)return null;return d(D.host,D.online,P,k)};const p=async()=>{const S=await n.callAction(UI_TOOL_ID,"describeScreen",{},o);return S?.elements??[]};const g=async()=>{try{const S=await n.callAction(APP_TOOL_ID,"ping",{},o,{timeoutMs:REALM_PROBE_MS,silent:true});return typeof S?.startedAt==="number"?S.startedAt:null}catch{return null}};const m=async(S,k)=>{const M=Date.now();while(Date.now()-M<k){const D=await g();if(D!==null&&D!==S)return Date.now()-M;await delay3(POLL_MS)}return null};const f=new Set;const v=new Set;const y=new Set((n.connectedDevices().find(S=>S.deviceId===o)?.tools??[]).map(S=>S.toolId));if(a==="all"){if(y.has("console")){const{payload:S}=await n.getSnapshot("console",o).catch(()=>({payload:null}));const k=S?.entries??[];for(const M of k)f.add(M.id)}if(y.has("network")){const{payload:S}=await n.getSnapshot("network",o).catch(()=>({payload:null}));const k=Array.isArray(S)?S:S?.events??[];for(const M of k)v.add(M.id)}}const b=async(S,k)=>{const M=Date.now();let D=false;for(;;){if(Date.now()-M>=k||Date.now()-r>MAX_FLOW_MS){return{ok:false,ms:Date.now()-M,unread:!D}}let P;try{P=await p();D=true}catch{await delay3(POLL_MS);continue}if(S(P))return{ok:true,ms:Date.now()-M,unread:false};await delay3(POLL_MS)}};const $=S=>`could not read the screen within ${S}ms, so this step is unknown`;const T=[];let _=null;let x=0;for(let S=0;S<i.length;S++){const k=i[S];const M=`${S+1}`;const D=k.timeoutMs??DEFAULT_WAIT_MS;if(Date.now()-r>MAX_FLOW_MS){T.push(`${M} \u2717 flow exceeded ${MAX_FLOW_MS/1e3}s \u2014 stopped here`);_=S;break}const P=[];const R=[];const j=k.reload||k.tap||k.swipe||k.type!==void 0||k.waitMs||k.waitFor||k.waitGone||k.expect||k.expectGone||k.snapshot;if(!j){T.push(`${S+1} \u2717 step does nothing \u2014 give it a tap/type/wait/expect${k.set!==void 0?" (`set` needs `tap` naming the control)":""}`);_=_??S;if(!t.continueOnFailure)break;continue}try{if(k.reload){const C=await g();await n.callAction(APP_TOOL_ID,"reloadApp",{strategy:"auto"},o);await delay3(TEARDOWN_GRACE_MS);const O=await m(C,Math.max(D,2e4));if(O==null){P.push("app did not come back after reload")}else{R.push(`reloaded (${O}ms)`);await b(N=>N.length>0,1e4)}}if(k.type!==void 0){const C=k.into??k.tap;if(!C){P.push("`type` needs `into` (which input to type into)")}else{const O=await n.callAction(UI_TOOL_ID,"tapElement",{...selector(C),text:fillSecrets(k.type)},o);if(!O?.tapped){P.push(O?.reason??`could not type into "${C}"`)}else if(O.matched?.via&&O.matched.via!=="onChangeText"){P.push(`"${C}" is not a text input \u2014 it ran ${O.matched.via} instead, and the text was not entered`)}else{R.push(`typed ${JSON.stringify(k.type)} into "${C}"`)}}}else if(k.tap&&(k.real??t.real)&&k.set===void 0){R.push(await h(k.tap,k.longPress,k.timeoutMs??3e3))}else if(k.tap){const C={...selector(k.tap)};if(k.longPress)C.longPress=true;if(k.set!==void 0)C.value=k.set;let O=await n.callAction(UI_TOOL_ID,"tapElement",C,o);for(let B=0;!O?.tapped&&/No element matched/.test(O?.reason??"")&&B<TAP_SETTLE_MS;B+=POLL_MS){await delay3(POLL_MS);O=await n.callAction(UI_TOOL_ID,"tapElement",C,o)}const N=/isn't showing|No element matched|no JS press handler|can't be driven in JS/;const z=/equally well/.test(O?.reason??"");const F=!O?.tapped&&k.set===void 0&&(z||N.test(O?.reason??""))?await w(k.tap,k.longPress,z):null;if(F){R.push(F)}else if(!O?.tapped){P.push(O?.reason??`no element matched "${k.tap}"`)}else{const B=O.matched;const U=B?.text??B?.label??B?.name??k.tap;if(k.set!==void 0&&B?.via&&B.via!=="onValueChange"){P.push(`"${U}" is not a toggle/slider \u2014 it ran ${B.via} instead, so it was not set to ${JSON.stringify(k.set)}`)}else{R.push(k.set!==void 0?`set "${U}" \u2192 ${JSON.stringify(B?.value??k.set)}`:`${k.longPress?"long-pressed":"tapped"} "${U}"`)}}}if(!P.length&&k.swipe){const{host:C,online:O}=await l();const N=await s.screenOf(C);const z=k.swipe;const{from:F,to:B}=swipePoints(z,!!k.untilEnd);const U=[F[0]*N.width,F[1]*N.height];const L=[B[0]*N.width,B[1]*N.height];const H=O?await s.buoyCover(o,C,{x:U[0],y:U[1]}):null;if(H)throw new Error(H);if(k.untilEnd){const{swipes:W,atEnd:J,lastRow:V}=await s.scrollToEnd(o,C,U,L,250);if(J)R.push(`swiped ${z} to the end (${W} swipes)${V?`; the last row is "${V}"`:""}`);else P.push(`swiped ${z} ${W} times and the screen was still moving`)}else{const W=await s.swipe(C,U,L,300);await s.mark(o,C,"swipe",[U],[L],300,W);await delay3(400);R.push(`swiped ${z}`)}}if(!P.length&&k.waitMs){await delay3(k.waitMs);R.push(`waited ${k.waitMs}ms`)}if(!P.length&&k.waitFor){const C=await b(O=>O.some(N=>matches(N,k.waitFor)),D);if(C.ok)R.push(`"${k.waitFor}" appeared (${C.ms}ms)`);else P.push(C.unread?$(D):`"${k.waitFor}" never appeared within ${D}ms`)}if(!P.length&&k.waitGone){const C=await b(O=>!O.some(N=>matches(N,k.waitGone)),D);if(C.ok)R.push(`"${k.waitGone}" gone (${C.ms}ms)`);else P.push(C.unread?$(D):`"${k.waitGone}" was still there after ${D}ms`)}if(!P.length&&k.expect){const C=await b(O=>O.some(N=>matches(N,k.expect)),k.timeoutMs??ASSERT_SETTLE_MS);if(C.ok)R.push(`"${k.expect}" is on screen`);else P.push(C.unread?$(k.timeoutMs??ASSERT_SETTLE_MS):`expected "${k.expect}" on screen \u2014 not found`)}if(!P.length&&k.expectGone){const C=await b(O=>!O.some(N=>matches(N,k.expectGone)),k.timeoutMs??ASSERT_SETTLE_MS);if(C.ok)R.push(`"${k.expectGone}" is gone`);else P.push(C.unread?$(k.timeoutMs??ASSERT_SETTLE_MS):`expected "${k.expectGone}" to be gone \u2014 still on screen`)}if(!P.length&&k.snapshot){const{outcome:C}=await runBaseline(n,k.snapshot,{deviceId:o,update:t.updateSnapshots});const O=k.maxChange??.05;if(C.changed&&(C.texts>0||C.percent>O)){P.push(`${C.summary}${C.texts>0?"":` (more than ${O}%)`}. Run screenshot_component with baseline "${k.snapshot}" to see the diff, or updateSnapshots: true if it is expected.`)}else R.push(C.summary)}}catch(C){P.push(errMsg4(C))}if(P.length){T.push(`${M} \u2717 ${describeStep(k)} \u2014 ${P.join("; ")}`);_=_??S;if(!t.continueOnFailure)break}else{x++;T.push(`${M} \u2713 ${R.join(", ")||describeStep(k)}`)}}const A=((Date.now()-r)/1e3).toFixed(1);const I=_===null?`**Flow: ${x}/${i.length} steps OK (${A}s)**`:`**Flow FAILED at step ${_+1} \u2014 ${x}/${i.length} steps OK (${A}s)**`;const E=[I,T.join("\n")];if(a!=="none"){E.push(`**Screen now:**${await observeAfterAction(n,o,void 0,0)}`)}if(a==="all"){if(y.has("network")){const{payload:S}=await n.getSnapshot("network",o).catch(()=>({payload:null}));const k=Array.isArray(S)?S:S?.events??[];const M=k.filter(D=>!v.has(D.id)).slice(-15);if(M.length){E.push(`**Network during this flow (${M.length}):**
583
- `+M.map(D=>`${D.error||(D.status??0)>=400?"\u274C":"\u2705"} ${D.method??"GET"} ${D.path??D.url??"?"} \u2192 ${D.error??D.status??"pending"}`).join("\n"))}}if(y.has("console")){const{payload:S}=await n.getSnapshot("console",o).catch(()=>({payload:null}));const k=S?.entries??[];const M=k.filter(D=>!f.has(D.id)&&(D.level==="error"||D.level==="warning")).slice(-10);if(M.length){E.push(`**Console during this flow (${M.length}):**
584
- `+M.map(D=>`[${D.level==="error"?"ERR":"warn"}] ${cap(firstLines(scrubSecrets(D.message??"")),220)}`).join("\n"))}}}if(t.save&&_===null){await import_node_fs9.promises.mkdir(FLOW_DIR(),{recursive:true});const S=import_node_path10.default.join(FLOW_DIR(),`${t.save}.json`);await import_node_fs9.promises.writeFile(S,JSON.stringify({steps:i},null,2)+"\n");E.push(`Saved as flow "${t.save}" (${import_node_path10.default.relative(process.cwd(),S)}). Replay with run_flow({flow:"${t.save}"}).`)}else if(t.save){E.push(`Not saved: the flow failed. Fix it, then run it again with save:"${t.save}".`)}return _===null?text2(E.join("\n\n")):{...text2(E.join("\n\n")),isError:true}}catch(i){return fail4(errMsg4(i))}}}function selector(e){return/\s/.test(e)?{query:e}:{testID:e,query:e}}function describeStep(e){if(e.tap)return`tap "${e.tap}"`;if(e.type!==void 0)return`type into "${e.into??"?"}"`;if(e.reload)return"reload";if(e.swipe)return`swipe ${e.swipe}${e.untilEnd?" to the end":""}`;if(e.waitFor)return`waitFor "${e.waitFor}"`;if(e.waitGone)return`waitGone "${e.waitGone}"`;if(e.expect)return`expect "${e.expect}"`;if(e.expectGone)return`expectGone "${e.expectGone}"`;if(e.snapshot)return`snapshot "${e.snapshot}"`;return"step"}var cap=(e,n=160)=>{const t=scrubSecrets(e);return t.length>n?`${t.slice(0,n)}\u2026`:t};var firstLines=(e,n=3)=>e.split("\n").map(t=>t.trim()).filter(Boolean).slice(0,n).join(" \u23CE ");var import_node_child_process11=require("child_process");var import_node_util10=require("util");var import_node_fs10=require("fs");var import_node_path11=__toESM(require("path"));var MAX_RECORDING_MS=3*6e4;var live=new Set;async function startRecording(e,n){await import_node_fs10.promises.mkdir(import_node_path11.default.dirname(n),{recursive:true});const t=Date.now();let r;let i;if(e.platform==="ios"){r=(0,import_node_child_process11.spawn)("xcrun",["simctl","io",e.udid,"recordVideo","--codec=h264","--force",n],{stdio:["ignore","ignore","pipe"]})}else if(e.platform==="ios-device"){r=(0,import_node_child_process11.spawn)("xcrun",phoneRecordArgs(e.udid,n,MAX_RECORDING_MS/1e3),{stdio:["ignore","ignore","pipe"]})}else{i=`/sdcard/buoy-recording-${t}-${Math.random().toString(36).slice(2,8)}.mp4`;r=(0,import_node_child_process11.spawn)("adb",["-s",e.serial,"shell",`echo $$; exec screenrecord --time-limit ${MAX_RECORDING_MS/1e3} ${q(i)}`],{stdio:["ignore","pipe","pipe"]})}const o={host:e,file:n,startedAt:t,proc:r,remote:i};live.add(o);let a="";let s=t;let c;r.stderr?.on("data",d=>{a+=String(d);if(/Recording started/i.test(String(d)))s=Date.now()});r.stdout?.on("data",d=>{const h=/^(\d+)/m.exec(String(d));if(h&&c===void 0)c=Number(h[1])});const l=await new Promise(d=>{const h=setTimeout(()=>d(null),e.platform==="ios"?3e3:e.platform==="ios-device"?4e3:1200);const w=setInterval(()=>{if(e.platform==="ios"&&s!==t||e.platform==="android"&&c!==void 0){clearTimeout(h);clearInterval(w);d(null)}},50);r.once("exit",p=>{clearTimeout(h);clearInterval(w);d(p??-1)});r.once("error",()=>{clearTimeout(h);clearInterval(w);d(-1)})});live.delete(o);if(l!==null){if(/not supported by this device/i.test(a)){throw new Error("This iPhone can't record its screen through Xcode (devicectl says the device doesn't support it). Record on a simulator, or use the iPhone's own Screen Recording in Control Center.")}throw new Error(`The screen recorder stopped right away: ${a.trim().slice(0,300)||`exit ${l}`}`)}if(e.platform==="ios"&&r.pid){const d=r.pid;const h=(0,import_node_child_process11.spawn)("sh",["-c",`sleep ${MAX_RECORDING_MS/1e3+15}; ps -p ${d} -o command= | grep -q 'simctl io .* recordVideo' && kill -INT ${d}`],{detached:true,stdio:"ignore"});h.on("error",()=>void 0);h.unref();r.once("exit",()=>{try{if(h.pid)process.kill(-h.pid,"SIGTERM")}catch{h.kill("SIGTERM")}})}const u={host:e,file:n,startedAt:s,proc:r,remote:i,remotePid:c};live.add(u);return u}async function stopRecording(e){if(e.stopTimer)clearTimeout(e.stopTimer);const n=Date.now();const t=new Promise(o=>{if(e.proc.exitCode!==null||e.proc.signalCode!==null)return o();e.proc.once("exit",()=>o())});if(e.host.platform==="ios"||e.host.platform==="ios-device"){e.proc.kill("SIGINT")}else if(e.remotePid){await adbShell(e.host.serial,`kill -INT ${e.remotePid}`).catch(()=>void 0)}await Promise.race([t,new Promise(o=>setTimeout(o,e.host.platform==="ios-device"?6e4:1e4))]);if(e.proc.exitCode===null&&e.proc.signalCode===null)e.proc.kill("SIGKILL");live.delete(e);if(e.host.platform==="android"&&e.remote){await new Promise(o=>setTimeout(o,800));await adb(e.host.serial,["pull",e.remote,e.file],6e4);await adbShell(e.host.serial,`rm -f ${q(e.remote)}`).catch(()=>void 0)}const r=await import_node_fs10.promises.stat(e.file).catch(()=>null);if(!r||r.size<1e3)throw new Error("The recording file is missing or empty. Was the screen showing anything?");const i=n-e.startedAt;if(e.host.platform==="ios"||e.host.platform==="ios-device")await padToWallTime(e.file,i).catch(()=>void 0);return i}async function padToWallTime(e,n){const t=(await execFileAsync10("ffprobe",["-v","error","-show_entries","format=duration","-of","csv=p=0",e],{timeout:2e4})).stdout;const r=Number(t.trim());const i=n/1e3-.3-r;if(!Number.isFinite(r)||i<.25)return;const o=e.replace(/\.mp4$/,".pad.mp4");const a=s=>execFileAsync10("ffmpeg",["-y","-v","error","-i",e,"-vf",`tpad=stop_mode=clone:stop_duration=${i.toFixed(2)},fps=30`,"-an",...s,"-pix_fmt","yuv420p","-movflags","+faststart",o],{timeout:24e4,maxBuffer:4*1024*1024});try{await a(["-c:v","h264_videotoolbox","-b:v","6M"])}catch{await a(["-c:v","libx264","-preset","veryfast","-crf","22"])}await import_node_fs10.promises.rename(o,e)}function markPoint(e,n,t,r){const i=n.width!==n.height&&t.width!==t.height&&n.width>n.height!==t.width>t.height;if(!i)return e;const o=r==="landscapeRight";const a=n.width>n.height?!o:o;return a?[1-e[1],e[0]]:[e[1],1-e[0]]}function pinchPath(e){if(e.kind!=="pinch"||e.from.length!==2||e.to?.length!==2)return null;const{width:n,height:t}=e.screen;const r=h=>[h[0]*n,h[1]*t];const[i,o,a,s]=[r(e.from[0]),r(e.from[1]),r(e.to[0]),r(e.to[1])];const c=[(i[0]+o[0])/2,(i[1]+o[1])/2];const l=[(a[0]+s[0])/2,(a[1]+s[1])/2];const u=Math.atan2(i[1]-c[1],i[0]-c[0]);let d=Math.atan2(a[1]-l[1],a[0]-l[0])-u;if(d>Math.PI)d-=2*Math.PI;if(d<-Math.PI)d+=2*Math.PI;return{c0:c,c1:l,r0:Math.hypot(i[0]-c[0],i[1]-c[1]),r1:Math.hypot(a[0]-l[0],a[1]-l[1]),a0:u,turn:d}}var MAX_BURN_DOTS=300;function touchDotNote(e){const n=Math.max(0,e.reduce((t,r)=>t+r.from.length,0)-MAX_BURN_DOTS);return n?`${n} touch dots were left out of the MP4. The viewer keeps all dots.`:null}var execFileAsync10=(0,import_node_util10.promisify)(import_node_child_process11.execFile);async function burnTouchMarks(e,n,t){let r;try{r=(await execFileAsync10("ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e],{timeout:2e4})).stdout}catch(g){if(g.code==="ENOENT")return null;throw g}const[i,o]=r.trim().split("x").map(Number);if(!i||!o)throw new Error("could not read the video's size");const a={width:i,height:o};const s=Math.max(8,Math.round(Math.min(i,o)*.045));const c=s*2;const l=Math.max(2,Math.round(s*.18));const u=g=>g.toFixed(3);const d=[];for(const g of n){const m=g.t/1e3;const f=Math.max(g.ms,1)/1e3;const v=`clip((t-${u(m)})/${u(f)},0,1)`;const y=`enable='between(t,${u(m)},${u(m+f+.35)})':eval=frame:shortest=1`;const b=pinchPath(g);if(b){const{width:$,height:T}=g.screen;const _=markPoint([0,0],g.screen,a,g.orientation);const x=markPoint([1,0],g.screen,a,g.orientation);const A=markPoint([0,1],g.screen,a,g.orientation);[1,-1].forEach(I=>{const E=`(${u(b.r0)}+(${u(b.r1-b.r0)})*${v})`;const S=`(${u(b.a0)}+(${u(b.turn)})*${v})`;const k=`clip((${u(b.c0[0])}+(${u(b.c1[0]-b.c0[0])})*${v}+${I}*${E}*cos(${S}))/${u($)},0,1)`;const M=`clip((${u(b.c0[1])}+(${u(b.c1[1]-b.c0[1])})*${v}+${I}*${E}*sin(${S}))/${u(T)},0,1)`;const[D,P]=[0,1].map(R=>`(${_[R]}+(${x[R]-_[R]})*${k}+(${A[R]-_[R]})*${M})`);d.push(`overlay=x='${D}*${i}-${s}':y='${P}*${o}-${s}':${y}`)});continue}g.from.forEach(($,T)=>{const[_,x]=markPoint($,g.screen,a,g.orientation);const[A,I]=markPoint(g.to?.[T]??$,g.screen,a,g.orientation);d.push(`overlay=x='${u(_*i-s)}+(${u((A-_)*i)})*${v}':y='${u(x*o-s)}+(${u((I-x)*o)})*${v}':${y}`)})}const h=d.slice(0,MAX_BURN_DOTS);const w=["[0:v]fps=30[base]",`[1:v]split=${h.length}${h.map((g,m)=>`[c${m}]`).join("")}`,...h.map((g,m)=>`${m===0?"[base]":`[v${m-1}]`}[c${m}]${g}[v${m}]`)].join(";");const p=`color=c=white@0:s=${c}x${c},format=rgba,geq=r='255':g='255':b='255':a='if(lte(hypot(X-${s},Y-${s}),${s}),if(gte(hypot(X-${s},Y-${s}),${s-l}),235,105),0)'`;await execFileAsync10("ffmpeg",["-y","-v","error","-i",e,"-f","lavfi","-i",p,"-filter_complex",w,"-map",`[v${h.length-1}]`,"-an","-c:v","libx264","-preset","veryfast","-crf","22","-pix_fmt","yuv420p","-movflags","+faststart",t],{timeout:24e4,maxBuffer:4*1024*1024});return t}function redact(e){return e.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi,"$1 [redacted]").replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}/g,"[redacted jwt]").replace(/((?:api[_-]?key|token|secret|password|passwd|authorization|cookie|session)["']?\s*[:=]\s*["']?)([^\s"'&,;}]{4,})/gi,"$1[redacted]")}function viewerHtml(e){const n=(e.marks??[]).map(r=>({...r,arc:pinchPath(r)??void 0}));const t=JSON.stringify({...e,marks:n}).replace(/</g,"\\u003c");return`<!doctype html>
582
+ If this change is expected, save it with updateBaseline: true.`}]}}}var import_zod12=require("zod");var import_node_fs9=require("fs");var import_node_path10=__toESM(require("path"));var FLOW_DIR=()=>import_node_path10.default.join(process.cwd(),".buoy","flows");var FLOW_NAME=/^[A-Za-z0-9_-]{1,64}$/;async function listSavedFlows(){try{return(await import_node_fs9.promises.readdir(FLOW_DIR())).filter(e=>e.endsWith(".json")).map(e=>e.slice(0,-5))}catch{return[]}}var UI_TOOL_ID="highlight-updates";var APP_TOOL_ID="app";var text2=e=>({content:[{type:"text",text:e}]});var fail4=e=>({isError:true,content:[{type:"text",text:e}]});var errMsg4=e=>e instanceof Error?e.message:String(e);var delay3=e=>new Promise(n=>setTimeout(n,e));var POLL_MS=250;var TAP_SETTLE_MS=2e3;var DEFAULT_WAIT_MS=5e3;var ASSERT_SETTLE_MS=2e3;var TEARDOWN_GRACE_MS=1200;var REALM_PROBE_MS=1500;var MAX_FLOW_MS=12e4;function matches(e,n){if(e.testID&&e.testID===n)return true;const t=n.toLowerCase();return[e.testID,e.text,e.label,e.name].filter(Boolean).some(r=>String(r).toLowerCase().includes(t))}var STEP_KINDS=["tap","waitFor","waitGone","expect","expectGone","reload","wait","swipe"];function normalizeStep(e){if(!e||typeof e!=="object"||Array.isArray(e))return e;const n={...e};const t=a=>{if(!a||typeof a!=="object"||Array.isArray(a))return a;const s=a;return[s.testID,s.text,s.query,s.label,s.name].find(c=>typeof c==="string")??a};for(const a of["tap","into","waitFor","waitGone","expect","expectGone"])n[a]=t(n[a]);for(const a of Object.keys(n))if(n[a]===void 0)delete n[a];if(typeof n.into==="string")return n;const r=typeof n.type==="string"&&STEP_KINDS.includes(n.type)?"type":typeof n.action==="string"&&STEP_KINDS.includes(n.action)?"action":null;if(!r)return n;const i=n[r];delete n[r];const o=[n.query,n.text,n.target,n.selector,n.element,n.testID].map(t).find(a=>typeof a==="string");for(const a of["query","text","target","selector","element","testID"])delete n[a];if(i==="reload")n.reload=true;else if(i==="swipe"){n.swipe=n.direction??o??"up";delete n.direction}else if(i==="wait")n.waitMs=n.waitMs??n.ms??n.durationMs??n.timeoutMs;else if(o!==void 0&&n[i]===void 0)n[i]=o;delete n.ms;delete n.durationMs;return n}var stepSchema=import_zod12.z.preprocess(normalizeStep,import_zod12.z.object({tap:import_zod12.z.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),longPress:import_zod12.z.boolean().optional().describe("Make `tap` a long-press instead."),type:import_zod12.z.string().optional().describe("Text to type (needs `into`)."),into:import_zod12.z.string().optional().describe("Target text input for `type`: testID or fuzzy text."),set:import_zod12.z.union([import_zod12.z.number(),import_zod12.z.boolean()]).optional().describe("Set a toggle (true/false) or slider (number) \u2014 pair with `tap` as the target."),swipe:import_zod12.z.enum(["up","down","left","right"]).optional().describe('A real swipe, the way the finger moves: "up" scrolls down the list.'),untilEnd:import_zod12.z.boolean().optional().describe("With swipe: keep swiping until the screen stops moving (the end of the list)."),real:import_zod12.z.boolean().optional().describe("Make this step's tap a real touch. Default: the flow's `real`."),reload:import_zod12.z.boolean().optional().describe("Reload the JS bundle before this step's action."),waitMs:import_zod12.z.number().min(0).max(3e4).optional().describe("Fixed pause after the action, in ms (max 30000). To wait for a result (a slow request, a new screen), use waitFor with timeoutMs instead: it stops as soon as the element shows."),waitFor:import_zod12.z.string().optional().describe("Wait until an element matching this appears (default 5s)."),waitGone:import_zod12.z.string().optional().describe("Wait until no element matches this (default 5s)."),expect:import_zod12.z.string().optional().describe("Assert an element matching this IS on screen (waits up to 2s for it); fails the flow if not."),expectGone:import_zod12.z.string().optional().describe("Assert nothing matches this (waits up to 2s for it to go); fails the flow if something does."),snapshot:import_zod12.z.string().optional().describe("Compare the whole screen to the baseline with this name (saved on the first run, like screenshot_component baseline). Fails the step on a text change or a change bigger than maxChange."),maxChange:import_zod12.z.number().min(0).max(100).optional().describe("snapshot: allowed changed share of the screen, in percent. Default 0.05."),timeoutMs:import_zod12.z.number().min(0).max(6e4).optional().describe("Budget for this step's waitFor/waitGone/expect, max 60000. Default 5000 (2000 for expect).")}).describe("One flow step. Order within a step: reload \u2192 tap/type/set/swipe \u2192 waitMs \u2192 waitFor/waitGone \u2192 expect."));var flowInput={steps:import_zod12.z.array(stepSchema).min(1).optional().describe("Steps to run, in order. Leave out when replaying a saved flow."),flow:import_zod12.z.string().optional().describe("Replay a saved flow by name (from .buoy/flows in the project) instead of passing steps."),save:import_zod12.z.string().optional().describe('Save these steps under this name when the flow passes, so it can be replayed with flow:"name".'),include:import_zod12.z.enum(["all","screen","none"]).optional().describe("What to report after the flow: 'all' (default) = available final element tree + newly observed captured network/console entries; 'screen' = available final element tree only; 'none' = step results only."),updateSnapshots:import_zod12.z.boolean().optional().describe("Save every snapshot step's screen as its new baseline instead of comparing."),continueOnFailure:import_zod12.z.boolean().optional().describe("Keep going after a failed step instead of stopping. Default false."),real:import_zod12.z.boolean().optional().describe("Make every tap a real OS touch (iOS Simulator, Android), found by testID, text or native label. Default false."),deviceId:deviceIdInput};var runFlow=async()=>fail4("run_flow is not ready.");function registerFlowTools(e,n){e.registerTool("run_flow",{_meta:coreTool(),description:"Run supported UI actions and element checks in sequence, with per-step results. Stops on the first failed step unless continueOnFailure is true. Depending on include, attempts to return the final element tree and newly observed captured network/console entries. Background activity can appear in that output; it does not establish causation. Taps use exposed app handlers by default; a tap with no handler match (a native tab bar) falls back to a real touch on that native label. Pass real: true to make every tap a real touch. A tap waits up to 2 s for its target to show, so steps rarely need waitMs between them. A swipe step is a real swipe; add untilEnd: true to scroll to the end of a list. Review failures and check the expected behavior. To wait for something slow, use waitFor or waitGone with a timeoutMs, not a long waitMs. Requires Buoy Pro and the app interaction integration.",inputSchema:flowInput},async t=>runFlow(t));runFlow=async t=>{const r=Date.now();try{let i=t.steps;if(t.flow){if(!FLOW_NAME.test(t.flow))return fail4(`Flow names use letters, numbers, - and _ (got "${t.flow}").`);try{i=JSON.parse(await import_node_fs9.promises.readFile(import_node_path10.default.join(FLOW_DIR(),`${t.flow}.json`),"utf8")).steps}catch{const S=await listSavedFlows();return fail4(`No saved flow "${t.flow}". ${S.length?`Saved flows: ${S.join(", ")}.`:'No flows are saved yet; run one with save:"name" first.'}`)}}if(!i||i.length===0)return fail4('Pass steps, or flow:"name" to replay a saved flow.');if(t.save&&!FLOW_NAME.test(t.save))return fail4(`Flow names use letters, numbers, - and _ (got "${t.save}").`);const o=n.requireProDevice(t.deviceId);const a=t.include??"all";const s=nativeKit(n);let c=null;const l=()=>c??=hostTarget(n,o).then(async S=>{await s.primeScreen(o,S.host,S.online);return S});let u;const d=async(S,k,M,A)=>{const O=k?await s.buoyCover(o,S,M):null;if(O)throw new Error(O);const R=A?600:void 0;const j=await s.touch(S,M,R,u);if(j!==void 0)u=j;await s.mark(o,S,R?"hold":"tap",[[M.x,M.y]],void 0,R??150,j);await delay3(120);return`${A?"long-pressed":"tapped"} ${M.what} (real touch)`};const h=async(S,k,M)=>{const{host:A,online:O}=await l();const R=Date.now();let j=false;for(;;){let C=await s.findSpot(o,A,S,O,"app");if("miss"in C&&!C.tie&&(j||!O||Date.now()-R>=600)){if(!j){j=true;C=await s.findSpot(o,A,S,O,"native")}if("miss"in C&&!C.tie)C=await s.findSpot(o,A,S,O,"loose")}if(!("miss"in C))return d(A,O,C,k);if(C.tie||Date.now()-R>=M)throw new Error(C.miss);await delay3(POLL_MS)}};const w=async(S,k,M)=>{let A;try{A=await l()}catch{return null}if(A.host.platform==="ios-device")return null;const O=await s.findSpot(o,A.host,S,A.online,M?"nativeExact":"native").catch(()=>null);if(!O||"miss"in O)return null;return d(A.host,A.online,O,k)};const p=async()=>{const S=await n.callAction(UI_TOOL_ID,"describeScreen",{},o);return S?.elements??[]};const g=async()=>{try{const S=await n.callAction(APP_TOOL_ID,"ping",{},o,{timeoutMs:REALM_PROBE_MS,silent:true});return typeof S?.startedAt==="number"?S.startedAt:null}catch{return null}};const m=async(S,k)=>{const M=Date.now();while(Date.now()-M<k){const A=await g();if(A!==null&&A!==S)return Date.now()-M;await delay3(POLL_MS)}return null};const f=new Set;const v=new Set;const y=new Set((n.connectedDevices().find(S=>S.deviceId===o)?.tools??[]).map(S=>S.toolId));if(a==="all"){if(y.has("console")){const{payload:S}=await n.getSnapshot("console",o).catch(()=>({payload:null}));const k=S?.entries??[];for(const M of k)f.add(M.id)}if(y.has("network")){const{payload:S}=await n.getSnapshot("network",o).catch(()=>({payload:null}));const k=Array.isArray(S)?S:S?.events??[];for(const M of k)v.add(M.id)}}const b=async(S,k)=>{const M=Date.now();let A=false;for(;;){if(Date.now()-M>=k||Date.now()-r>MAX_FLOW_MS){return{ok:false,ms:Date.now()-M,unread:!A}}let O;try{O=await p();A=true}catch{await delay3(POLL_MS);continue}if(S(O))return{ok:true,ms:Date.now()-M,unread:false};await delay3(POLL_MS)}};const $=S=>`could not read the screen within ${S}ms, so this step is unknown`;const T=[];let _=null;let x=0;for(let S=0;S<i.length;S++){const k=i[S];const M=`${S+1}`;const A=k.timeoutMs??DEFAULT_WAIT_MS;if(Date.now()-r>MAX_FLOW_MS){T.push(`${M} \u2717 flow exceeded ${MAX_FLOW_MS/1e3}s \u2014 stopped here`);_=S;break}const O=[];const R=[];const j=k.reload||k.tap||k.swipe||k.type!==void 0||k.waitMs||k.waitFor||k.waitGone||k.expect||k.expectGone||k.snapshot;if(!j){T.push(`${S+1} \u2717 step does nothing \u2014 give it a tap/type/wait/expect${k.set!==void 0?" (`set` needs `tap` naming the control)":""}`);_=_??S;if(!t.continueOnFailure)break;continue}try{if(k.reload){const C=await g();await n.callAction(APP_TOOL_ID,"reloadApp",{strategy:"auto"},o);await delay3(TEARDOWN_GRACE_MS);const P=await m(C,Math.max(A,2e4));if(P==null){O.push("app did not come back after reload")}else{R.push(`reloaded (${P}ms)`);await b(N=>N.length>0,1e4)}}if(k.type!==void 0){const C=k.into??k.tap;if(!C){O.push("`type` needs `into` (which input to type into)")}else{const P=await n.callAction(UI_TOOL_ID,"tapElement",{...selector(C),text:fillSecrets(k.type)},o);if(!P?.tapped){O.push(P?.reason??`could not type into "${C}"`)}else if(P.matched?.via&&P.matched.via!=="onChangeText"){O.push(`"${C}" is not a text input \u2014 it ran ${P.matched.via} instead, and the text was not entered`)}else{R.push(`typed ${JSON.stringify(k.type)} into "${C}"`)}}}else if(k.tap&&(k.real??t.real)&&k.set===void 0){R.push(await h(k.tap,k.longPress,k.timeoutMs??3e3))}else if(k.tap){const C={...selector(k.tap)};if(k.longPress)C.longPress=true;if(k.set!==void 0)C.value=k.set;let P=await n.callAction(UI_TOOL_ID,"tapElement",C,o);for(let B=0;!P?.tapped&&/No element matched/.test(P?.reason??"")&&B<TAP_SETTLE_MS;B+=POLL_MS){await delay3(POLL_MS);P=await n.callAction(UI_TOOL_ID,"tapElement",C,o)}const N=/isn't showing|No element matched|no JS press handler|can't be driven in JS/;const z=/equally well/.test(P?.reason??"");const F=!P?.tapped&&k.set===void 0&&(z||N.test(P?.reason??""))?await w(k.tap,k.longPress,z):null;if(F){R.push(F)}else if(!P?.tapped){O.push(P?.reason??`no element matched "${k.tap}"`)}else{const B=P.matched;const U=B?.text??B?.label??B?.name??k.tap;if(k.set!==void 0&&B?.via&&B.via!=="onValueChange"){O.push(`"${U}" is not a toggle/slider \u2014 it ran ${B.via} instead, so it was not set to ${JSON.stringify(k.set)}`)}else{R.push(k.set!==void 0?`set "${U}" \u2192 ${JSON.stringify(B?.value??k.set)}`:`${k.longPress?"long-pressed":"tapped"} "${U}"`)}}}if(!O.length&&k.swipe){const{host:C,online:P}=await l();const N=await s.screenOf(C);const z=k.swipe;const{from:F,to:B}=swipePoints(z,!!k.untilEnd);const U=[F[0]*N.width,F[1]*N.height];const L=[B[0]*N.width,B[1]*N.height];const H=P?await s.buoyCover(o,C,{x:U[0],y:U[1]}):null;if(H)throw new Error(H);if(k.untilEnd){const{swipes:W,atEnd:J,lastRow:V}=await s.scrollToEnd(o,C,U,L,250);if(J)R.push(`swiped ${z} to the end (${W} swipes)${V?`; the last row is "${V}"`:""}`);else O.push(`swiped ${z} ${W} times and the screen was still moving`)}else{const W=await s.swipe(C,U,L,300);await s.mark(o,C,"swipe",[U],[L],300,W);await delay3(400);R.push(`swiped ${z}`)}}if(!O.length&&k.waitMs){await delay3(k.waitMs);R.push(`waited ${k.waitMs}ms`)}if(!O.length&&k.waitFor){const C=await b(P=>P.some(N=>matches(N,k.waitFor)),A);if(C.ok)R.push(`"${k.waitFor}" appeared (${C.ms}ms)`);else O.push(C.unread?$(A):`"${k.waitFor}" never appeared within ${A}ms`)}if(!O.length&&k.waitGone){const C=await b(P=>!P.some(N=>matches(N,k.waitGone)),A);if(C.ok)R.push(`"${k.waitGone}" gone (${C.ms}ms)`);else O.push(C.unread?$(A):`"${k.waitGone}" was still there after ${A}ms`)}if(!O.length&&k.expect){const C=await b(P=>P.some(N=>matches(N,k.expect)),k.timeoutMs??ASSERT_SETTLE_MS);if(C.ok)R.push(`"${k.expect}" is on screen`);else O.push(C.unread?$(k.timeoutMs??ASSERT_SETTLE_MS):`expected "${k.expect}" on screen \u2014 not found`)}if(!O.length&&k.expectGone){const C=await b(P=>!P.some(N=>matches(N,k.expectGone)),k.timeoutMs??ASSERT_SETTLE_MS);if(C.ok)R.push(`"${k.expectGone}" is gone`);else O.push(C.unread?$(k.timeoutMs??ASSERT_SETTLE_MS):`expected "${k.expectGone}" to be gone \u2014 still on screen`)}if(!O.length&&k.snapshot){const{outcome:C}=await runBaseline(n,k.snapshot,{deviceId:o,update:t.updateSnapshots});const P=k.maxChange??.05;if(C.changed&&(C.texts>0||C.percent>P)){O.push(`${C.summary}${C.texts>0?"":` (more than ${P}%)`}. Run screenshot_component with baseline "${k.snapshot}" to see the diff, or updateSnapshots: true if it is expected.`)}else R.push(C.summary)}}catch(C){O.push(errMsg4(C))}if(O.length){T.push(`${M} \u2717 ${describeStep(k)} \u2014 ${O.join("; ")}`);_=_??S;if(!t.continueOnFailure)break}else{x++;T.push(`${M} \u2713 ${R.join(", ")||describeStep(k)}`)}}const I=((Date.now()-r)/1e3).toFixed(1);const D=_===null?`**Flow: ${x}/${i.length} steps OK (${I}s)**`:`**Flow FAILED at step ${_+1} \u2014 ${x}/${i.length} steps OK (${I}s)**`;const E=[D,T.join("\n")];if(a!=="none"){E.push(`**Screen now:**${await observeAfterAction(n,o,void 0,0)}`)}if(a==="all"){if(y.has("network")){const{payload:S}=await n.getSnapshot("network",o).catch(()=>({payload:null}));const k=Array.isArray(S)?S:S?.events??[];const M=k.filter(A=>!v.has(A.id)).slice(-15);if(M.length){E.push(`**Network during this flow (${M.length}):**
583
+ `+M.map(A=>`${A.error||(A.status??0)>=400?"\u274C":"\u2705"} ${A.method??"GET"} ${A.path??A.url??"?"} \u2192 ${A.error??A.status??"pending"}`).join("\n"))}}if(y.has("console")){const{payload:S}=await n.getSnapshot("console",o).catch(()=>({payload:null}));const k=S?.entries??[];const M=k.filter(A=>!f.has(A.id)&&(A.level==="error"||A.level==="warning")).slice(-10);if(M.length){E.push(`**Console during this flow (${M.length}):**
584
+ `+M.map(A=>`[${A.level==="error"?"ERR":"warn"}] ${cap(firstLines(scrubSecrets(A.message??"")),220)}`).join("\n"))}}}if(t.save&&_===null){await import_node_fs9.promises.mkdir(FLOW_DIR(),{recursive:true});const S=import_node_path10.default.join(FLOW_DIR(),`${t.save}.json`);await import_node_fs9.promises.writeFile(S,JSON.stringify({steps:i},null,2)+"\n");E.push(`Saved as flow "${t.save}" (${import_node_path10.default.relative(process.cwd(),S)}). Replay with run_flow({flow:"${t.save}"}).`)}else if(t.save){E.push(`Not saved: the flow failed. Fix it, then run it again with save:"${t.save}".`)}return _===null?text2(E.join("\n\n")):{...text2(E.join("\n\n")),isError:true}}catch(i){return fail4(errMsg4(i))}}}function selector(e){return/\s/.test(e)?{query:e}:{testID:e,query:e}}function describeStep(e){if(e.tap)return`tap "${e.tap}"`;if(e.type!==void 0)return`type into "${e.into??"?"}"`;if(e.reload)return"reload";if(e.swipe)return`swipe ${e.swipe}${e.untilEnd?" to the end":""}`;if(e.waitFor)return`waitFor "${e.waitFor}"`;if(e.waitGone)return`waitGone "${e.waitGone}"`;if(e.expect)return`expect "${e.expect}"`;if(e.expectGone)return`expectGone "${e.expectGone}"`;if(e.snapshot)return`snapshot "${e.snapshot}"`;return"step"}var cap=(e,n=160)=>{const t=scrubSecrets(e);return t.length>n?`${t.slice(0,n)}\u2026`:t};var firstLines=(e,n=3)=>e.split("\n").map(t=>t.trim()).filter(Boolean).slice(0,n).join(" \u23CE ");var import_node_child_process11=require("child_process");var import_node_util10=require("util");var import_node_fs10=require("fs");var import_node_path11=__toESM(require("path"));var MAX_RECORDING_MS=3*6e4;var live=new Set;async function startRecording(e,n){await import_node_fs10.promises.mkdir(import_node_path11.default.dirname(n),{recursive:true});const t=Date.now();let r;let i;if(e.platform==="ios"){r=(0,import_node_child_process11.spawn)("xcrun",["simctl","io",e.udid,"recordVideo","--codec=h264","--force",n],{stdio:["ignore","ignore","pipe"]})}else if(e.platform==="ios-device"){r=(0,import_node_child_process11.spawn)("xcrun",phoneRecordArgs(e.udid,n,MAX_RECORDING_MS/1e3),{stdio:["ignore","ignore","pipe"]})}else{i=`/sdcard/buoy-recording-${t}-${Math.random().toString(36).slice(2,8)}.mp4`;r=(0,import_node_child_process11.spawn)("adb",["-s",e.serial,"shell",`echo $$; exec screenrecord --time-limit ${MAX_RECORDING_MS/1e3} ${q(i)}`],{stdio:["ignore","pipe","pipe"]})}const o={host:e,file:n,startedAt:t,proc:r,remote:i};live.add(o);let a="";let s=t;let c;r.stderr?.on("data",d=>{a+=String(d);if(/Recording started/i.test(String(d)))s=Date.now()});r.stdout?.on("data",d=>{const h=/^(\d+)/m.exec(String(d));if(h&&c===void 0)c=Number(h[1])});const l=await new Promise(d=>{const h=setTimeout(()=>d(null),e.platform==="ios"?3e3:e.platform==="ios-device"?4e3:1200);const w=setInterval(()=>{if(e.platform==="ios"&&s!==t||e.platform==="android"&&c!==void 0){clearTimeout(h);clearInterval(w);d(null)}},50);r.once("exit",p=>{clearTimeout(h);clearInterval(w);d(p??-1)});r.once("error",()=>{clearTimeout(h);clearInterval(w);d(-1)})});live.delete(o);if(l!==null){if(/not supported by this device/i.test(a)){throw new Error("This iPhone can't record its screen through Xcode (devicectl says the device doesn't support it). Record on a simulator, or use the iPhone's own Screen Recording in Control Center.")}throw new Error(`The screen recorder stopped right away: ${a.trim().slice(0,300)||`exit ${l}`}`)}if(e.platform==="ios"&&r.pid){const d=r.pid;const h=(0,import_node_child_process11.spawn)("sh",["-c",`sleep ${MAX_RECORDING_MS/1e3+15}; ps -p ${d} -o command= | grep -q 'simctl io .* recordVideo' && kill -INT ${d}`],{detached:true,stdio:"ignore"});h.on("error",()=>void 0);h.unref();r.once("exit",()=>{try{if(h.pid)process.kill(-h.pid,"SIGTERM")}catch{h.kill("SIGTERM")}})}const u={host:e,file:n,startedAt:s,proc:r,remote:i,remotePid:c};live.add(u);return u}async function stopRecording(e){if(e.stopTimer)clearTimeout(e.stopTimer);const n=Date.now();const t=new Promise(o=>{if(e.proc.exitCode!==null||e.proc.signalCode!==null)return o();e.proc.once("exit",()=>o())});if(e.host.platform==="ios"||e.host.platform==="ios-device"){e.proc.kill("SIGINT")}else if(e.remotePid){await adbShell(e.host.serial,`kill -INT ${e.remotePid}`).catch(()=>void 0)}await Promise.race([t,new Promise(o=>setTimeout(o,e.host.platform==="ios-device"?6e4:1e4))]);if(e.proc.exitCode===null&&e.proc.signalCode===null)e.proc.kill("SIGKILL");live.delete(e);if(e.host.platform==="android"&&e.remote){await new Promise(o=>setTimeout(o,800));await adb(e.host.serial,["pull",e.remote,e.file],6e4);await adbShell(e.host.serial,`rm -f ${q(e.remote)}`).catch(()=>void 0)}const r=await import_node_fs10.promises.stat(e.file).catch(()=>null);if(!r||r.size<1e3)throw new Error("The recording file is missing or empty. Was the screen showing anything?");const i=n-e.startedAt;if(e.host.platform==="ios"||e.host.platform==="ios-device")await padToWallTime(e.file,i).catch(()=>void 0);return i}async function padToWallTime(e,n){const t=(await execFileAsync10("ffprobe",["-v","error","-show_entries","format=duration","-of","csv=p=0",e],{timeout:2e4})).stdout;const r=Number(t.trim());const i=n/1e3-.3-r;if(!Number.isFinite(r)||i<.25)return;const o=e.replace(/\.mp4$/,".pad.mp4");const a=s=>execFileAsync10("ffmpeg",["-y","-v","error","-i",e,"-vf",`tpad=stop_mode=clone:stop_duration=${i.toFixed(2)},fps=30`,"-an",...s,"-pix_fmt","yuv420p","-movflags","+faststart",o],{timeout:24e4,maxBuffer:4*1024*1024});try{await a(["-c:v","h264_videotoolbox","-b:v","6M"])}catch{await a(["-c:v","libx264","-preset","veryfast","-crf","22"])}await import_node_fs10.promises.rename(o,e)}function markPoint(e,n,t,r){const i=n.width!==n.height&&t.width!==t.height&&n.width>n.height!==t.width>t.height;if(!i)return e;const o=r==="landscapeRight";const a=n.width>n.height?!o:o;return a?[1-e[1],e[0]]:[e[1],1-e[0]]}function pinchPath(e){if(e.kind!=="pinch"||e.from.length!==2||e.to?.length!==2)return null;const{width:n,height:t}=e.screen;const r=h=>[h[0]*n,h[1]*t];const[i,o,a,s]=[r(e.from[0]),r(e.from[1]),r(e.to[0]),r(e.to[1])];const c=[(i[0]+o[0])/2,(i[1]+o[1])/2];const l=[(a[0]+s[0])/2,(a[1]+s[1])/2];const u=Math.atan2(i[1]-c[1],i[0]-c[0]);let d=Math.atan2(a[1]-l[1],a[0]-l[0])-u;if(d>Math.PI)d-=2*Math.PI;if(d<-Math.PI)d+=2*Math.PI;return{c0:c,c1:l,r0:Math.hypot(i[0]-c[0],i[1]-c[1]),r1:Math.hypot(a[0]-l[0],a[1]-l[1]),a0:u,turn:d}}var MAX_BURN_DOTS=300;function touchDotNote(e){const n=Math.max(0,e.reduce((t,r)=>t+r.from.length,0)-MAX_BURN_DOTS);return n?`${n} touch dots were left out of the MP4. The viewer keeps all dots.`:null}var execFileAsync10=(0,import_node_util10.promisify)(import_node_child_process11.execFile);async function burnTouchMarks(e,n,t){let r;try{r=(await execFileAsync10("ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e],{timeout:2e4})).stdout}catch(g){if(g.code==="ENOENT")return null;throw g}const[i,o]=r.trim().split("x").map(Number);if(!i||!o)throw new Error("could not read the video's size");const a={width:i,height:o};const s=Math.max(8,Math.round(Math.min(i,o)*.045));const c=s*2;const l=Math.max(2,Math.round(s*.18));const u=g=>g.toFixed(3);const d=[];for(const g of n){const m=g.t/1e3;const f=Math.max(g.ms,1)/1e3;const v=`clip((t-${u(m)})/${u(f)},0,1)`;const y=`enable='between(t,${u(m)},${u(m+f+.35)})':eval=frame:shortest=1`;const b=pinchPath(g);if(b){const{width:$,height:T}=g.screen;const _=markPoint([0,0],g.screen,a,g.orientation);const x=markPoint([1,0],g.screen,a,g.orientation);const I=markPoint([0,1],g.screen,a,g.orientation);[1,-1].forEach(D=>{const E=`(${u(b.r0)}+(${u(b.r1-b.r0)})*${v})`;const S=`(${u(b.a0)}+(${u(b.turn)})*${v})`;const k=`clip((${u(b.c0[0])}+(${u(b.c1[0]-b.c0[0])})*${v}+${D}*${E}*cos(${S}))/${u($)},0,1)`;const M=`clip((${u(b.c0[1])}+(${u(b.c1[1]-b.c0[1])})*${v}+${D}*${E}*sin(${S}))/${u(T)},0,1)`;const[A,O]=[0,1].map(R=>`(${_[R]}+(${x[R]-_[R]})*${k}+(${I[R]-_[R]})*${M})`);d.push(`overlay=x='${A}*${i}-${s}':y='${O}*${o}-${s}':${y}`)});continue}g.from.forEach(($,T)=>{const[_,x]=markPoint($,g.screen,a,g.orientation);const[I,D]=markPoint(g.to?.[T]??$,g.screen,a,g.orientation);d.push(`overlay=x='${u(_*i-s)}+(${u((I-_)*i)})*${v}':y='${u(x*o-s)}+(${u((D-x)*o)})*${v}':${y}`)})}const h=d.slice(0,MAX_BURN_DOTS);const w=["[0:v]fps=30[base]",`[1:v]split=${h.length}${h.map((g,m)=>`[c${m}]`).join("")}`,...h.map((g,m)=>`${m===0?"[base]":`[v${m-1}]`}[c${m}]${g}[v${m}]`)].join(";");const p=`color=c=white@0:s=${c}x${c},format=rgba,geq=r='255':g='255':b='255':a='if(lte(hypot(X-${s},Y-${s}),${s}),if(gte(hypot(X-${s},Y-${s}),${s-l}),235,105),0)'`;await execFileAsync10("ffmpeg",["-y","-v","error","-i",e,"-f","lavfi","-i",p,"-filter_complex",w,"-map",`[v${h.length-1}]`,"-an","-c:v","libx264","-preset","veryfast","-crf","22","-pix_fmt","yuv420p","-movflags","+faststart",t],{timeout:24e4,maxBuffer:4*1024*1024});return t}function redact(e){return e.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi,"$1 [redacted]").replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}/g,"[redacted jwt]").replace(/((?:api[_-]?key|token|secret|password|passwd|authorization|cookie|session)["']?\s*[:=]\s*["']?)([^\s"'&,;}]{4,})/gi,"$1[redacted]")}function viewerHtml(e){const n=(e.marks??[]).map(r=>({...r,arc:pinchPath(r)??void 0}));const t=JSON.stringify({...e,marks:n}).replace(/</g,"\\u003c");return`<!doctype html>
585
585
  <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
586
586
  <title>${escapeHtml(e.title)}</title>
587
587
  <style>
@@ -638,7 +638,7 @@ ${d}`),d=>finished.set(o,`The recording hit the time limit and could not be save
638
638
 
639
639
  Could not save the recording: ${errMsg2(f)}. Call screen_recording with action "stop" to retry.`)}const m=text(`${h.content.map(f=>f.text).join("\n")}
640
640
 
641
- ${g}${p}`);return h.isError?{...m,isError:true}:m}const u=typedSecretValues().length?" Note: a secret was typed earlier this session; if it is still on screen, the video will show it. Typing secrets is blocked until the recording stops.":" Typing secrets ({{secret:NAME}}) is blocked until the recording stops, because a video can't hide them.";return text(`Recording ${hostLabel(a)}. Do the steps, then call screen_recording with action "stop". It stops by itself after ${MAX_RECORDING_MS/6e4} minutes.${u}`)}let r=t.deviceId;if(!r){try{r=n.requireProDevice()}catch{r=void 0}}if(!r||!sessions.has(r)){if(r&&finished.has(r)){const o=finished.get(r);finished.delete(r);return text(o)}if(sessions.size===1)r=[...sessions.keys()][0];else return fail2(sessions.size?"Several recordings are running. Pass deviceId.":'No recording is running. Start one with action "start".')}const i=sessions.get(r);await i.starting;if(!i.rec)return fail2("The recording did not start.");i.finishing??=finish(n,i);try{return text(await i.finishing)}catch(o){i.finishing=void 0;return fail2(`Could not save the recording: ${errMsg2(o)}. Call stop again to retry.`)}}catch(r){return fail2(errMsg2(r))}})}var execFileAsync11=(0,import_node_util11.promisify)(import_node_child_process12.execFile);var UI_TOOL_ID2="highlight-updates";var delay5=e=>new Promise(n=>setTimeout(n,e));var IDB_MISSING="Native touch on the iOS Simulator needs idb on this Mac (brew install facebook/fb/idb-companion && pipx install fb-idb).";var PHONE_TOUCH="Real touches on a physical iPhone need Xcode's CoreDevice touch support, and Buoy couldn't set it up on this Mac. Use tap_element (it calls the element's handler) or run_flow; screenshots, recording and app control work on the iPhone.";var phoneScreens=new Map;async function phoneScreenSize(e){const n=phoneScreens.get(e);if(n&&Date.now()-n.at<SCREEN_TTL_MS)return n.size;const t=await phoneScreenshot(e);const r={width:t.readUInt32BE(16),height:t.readUInt32BE(20)};phoneScreens.set(e,{size:r,at:Date.now()});return r}var simScreens=new Map;function swipePoints(e,n){if(n){if(e==="up")return{from:[.5,.88],to:[.5,.06]};if(e==="down")return{from:[.5,.3],to:[.5,.94]};if(e==="left")return{from:[.9,.5],to:[.1,.5]};return{from:[.1,.5],to:[.9,.5]}}const t=e==="left"?-.35:e==="right"?.35:0;const r=e==="up"?-.3:e==="down"?.3:0;return{from:[.5-t/2,.5-r/2],to:[.5+t/2,.5+r/2]}}var SCROLL_REST_MS=60;var SCREEN_TTL_MS=3e3;function forgetScreenSize(e){barCache.delete(e);simScreens.delete(e);phoneScreens.delete(e)}function freshScreen(e){if(e.platform==="android")return;simScreens.delete(e.udid);phoneScreens.delete(e.udid)}var IDB_SETUP=/idb on this Mac|SimulatorKit|not booted|connection refused|Failed to connect to companion/i;async function xcodeShimDir(){const e=(await execFileAsync11("xcode-select",["-p"],{timeout:5e3}).catch(()=>({stdout:""}))).stdout.trim();if(!e.endsWith("/Contents/Developer"))return null;const n=import_node_path13.default.dirname(e);const t=import_node_path13.default.join(e,"Library","PrivateFrameworks","SimulatorKit.framework");const r=import_node_path13.default.join(n,"SharedFrameworks","SimulatorKit.framework");const i=l=>import_node_fs12.promises.access(l).then(()=>true,()=>false);if(await i(t)||!await i(r))return null;const o=(await execFileAsync11("plutil",["-extract","DTXcodeBuild","raw","-o","-",import_node_path13.default.join(n,"Info.plist")]).catch(()=>({stdout:"x"}))).stdout.trim();const a=import_node_path13.default.join(import_node_os9.default.homedir(),".buoy","xcode-shim",o.replace(/[^\w.-]/g,"_"),"Contents");const s=import_node_path13.default.join(a,"Developer");if(await i(import_node_path13.default.join(s,"Library","PrivateFrameworks","SimulatorKit.framework")))return s;await import_node_fs12.promises.mkdir(import_node_path13.default.join(s,"Library","PrivateFrameworks"),{recursive:true});const c=async(l,u,d)=>{for(const h of await import_node_fs12.promises.readdir(l)){if(h===d)continue;await import_node_fs12.promises.symlink(import_node_path13.default.join(l,h),import_node_path13.default.join(u,h)).catch(()=>void 0)}};await c(n,a,"Developer");await c(e,s,"Library");await c(import_node_path13.default.join(e,"Library"),import_node_path13.default.join(s,"Library"),"PrivateFrameworks");await c(import_node_path13.default.join(e,"Library","PrivateFrameworks"),import_node_path13.default.join(s,"Library","PrivateFrameworks"),"").catch(()=>void 0);await import_node_fs12.promises.symlink(r,import_node_path13.default.join(s,"Library","PrivateFrameworks","SimulatorKit.framework")).catch(()=>void 0);return s}async function restartCompanion(e){const n=`/tmp/idb/${e}.buoy-restart`;await import_node_fs12.promises.mkdir("/tmp/idb",{recursive:true}).catch(()=>void 0);const t=async()=>{try{await(await import_node_fs12.promises.open(n,"wx")).close();return true}catch{const r=await import_node_fs12.promises.stat(n).then(i=>Date.now()-i.mtimeMs,()=>0);if(r>15e3){const i=`${n}.stale-${process.pid}-${Date.now()}`;await import_node_fs12.promises.rename(n,i).then(()=>import_node_fs12.promises.unlink(i).catch(()=>void 0),()=>void 0);return t()}return false}};if(!await t()){for(let r=0;r<60;r++){await delay5(250);if(!await import_node_fs12.promises.stat(n).then(()=>true,()=>false))return}return}try{await execFileAsync11("pkill",["-f",`idb_companion --udid ${e}`],{timeout:5e3}).catch(()=>void 0);await delay5(300);const r=await xcodeShimDir().catch(()=>null);const i=(0,import_node_child_process12.spawn)("idb_companion",["--udid",e,"--grpc-domain-sock",`/tmp/idb/${e}_companion.sock`,"--only","simulator"],{detached:true,stdio:"ignore",env:r?{...process.env,DEVELOPER_DIR:r}:process.env});i.on("error",()=>void 0);i.unref();await delay5(1800)}finally{await import_node_fs12.promises.unlink(n).catch(()=>void 0)}}async function idb(e,n=15e3,t=false){try{const{stdout:r}=await execFileAsync11("idb",e,{timeout:n});return r}catch(r){const i=r;if(i.code==="ENOENT")throw new Error(IDB_MISSING);const o=(i.stderr||i.message||"").slice(0,300);const a=e.includes("--udid")?e[e.indexOf("--udid")+1]:void 0;if(!t&&a&&/not booted|connection refused|Failed to connect to companion/i.test(o)){await restartCompanion(a);return idb(e,n,true)}if(/SimulatorKit is required/i.test(o)){if(!t&&a&&await xcodeShimDir().catch(()=>null)){await restartCompanion(a);return idb(e,n,true)}throw new Error("idb can't send touches with this Xcode: it can't load SimulatorKit, and Buoy could not work around it. Use tap_element (it calls the element's handler) for now. Reading the screen (describe_screen, screenshot_component) still works.")}throw new Error(`idb ${e[0]} ${e[1]??""} failed: ${o}`)}}async function iosTree(e){const n=JSON.parse(await idb(["ui","describe-all","--udid",e,"--json","--nested"]));const t=[];const r=o=>{t.push(o);for(const a of o.children??[])r(a)};n.forEach(r);const i=t.find(o=>o.type==="Application"&&o.frame);return{all:t,screen:i?.frame?{width:i.frame.width,height:i.frame.height}:{width:0,height:0}}}var barCache=new Map;var BAR_FILE=import_node_path13.default.join(import_node_os9.default.homedir(),".buoy","cache","native-bars.json");var barFileRead=false;async function loadBars(){if(barFileRead||process.env.VITEST)return;barFileRead=true;try{const e=JSON.parse(await import_node_fs12.promises.readFile(BAR_FILE,"utf8"));for(const[n,t]of Object.entries(e))if(!barCache.has(n)&&t?.screen&&Array.isArray(t.els))barCache.set(n,t)}catch{}}function saveBars(){if(process.env.VITEST)return;const e=Object.fromEntries([...barCache].map(([t,r])=>[t,{screen:r.screen,els:r.els.map(i=>({AXLabel:i.AXLabel,type:i.type,frame:i.frame}))}]));const n=`${BAR_FILE}.${process.pid}`;void import_node_fs12.promises.mkdir(import_node_path13.default.dirname(BAR_FILE),{recursive:true}).then(()=>import_node_fs12.promises.writeFile(n,JSON.stringify(e))).then(()=>import_node_fs12.promises.rename(n,BAR_FILE)).catch(()=>void 0)}async function cachedBarControl(e,n){await loadBars();const t=barCache.get(e);const r=n.trim().toLowerCase();const i=t?.els.find(o=>(o.AXLabel??"").trim().toLowerCase()===r&&o.frame);if(!t||!i?.frame)return null;try{const o=Math.round(i.frame.x+i.frame.width/2);const a=Math.round(i.frame.y+i.frame.height/2);const s=JSON.parse(await idb(["ui","describe-point","--udid",e,String(o),String(a),"--json"],3e3));if((s.AXLabel??"").trim().toLowerCase()===r&&s.frame)return{el:s,screen:t.screen}}catch{}barCache.delete(e);saveBars();return null}async function findByLabel(e,n,t,r=false,i=[.95,.97,.09,.06]){const o=n.trim().toLowerCase();const a=Date.now()+8e3;const s=p=>{const g=(p.AXLabel??"").trim().toLowerCase();if(!g)return 0;if(g===o)return 3;if(g.startsWith(o))return 2;if(g.includes(o))return 1;return 0};const{width:c,height:l}=t.screen;const u=p=>{if(!c||!p.frame)return true;const g=p.frame.x+p.frame.width/2;const m=p.frame.y+p.frame.height/2;return g>=0&&g<=c&&m>=0&&m<=l};let d=t.all.filter(p=>s(p)>0&&p.frame&&p.type!=="Application"&&u(p));if(!d.some(p=>s(p)===3)&&t.screen.width){const p=i.map(g=>{const m=[];for(let f=20;f<t.screen.width;f+=40)m.push([f,Math.round(t.screen.height*g)]);return m});for(const g of p){if(Date.now()>=a)break;const m=await Promise.allSettled(g.map(async([v,y])=>JSON.parse(await idb(["ui","describe-point","--udid",e,String(v),String(y),"--json"],3e3))));const f=[];for(const v of m){if(v.status==="rejected"){if(IDB_SETUP.test(String(v.reason)))throw v.reason;continue}const y=v.value;if(y?.frame&&y.AXLabel&&y.type&&y.type!=="Application")f.push(y);if(s(y)>0&&y.frame)d.push(y)}if(f.length){const v=barCache.get(e);const y=v&&v.screen.width===t.screen.width&&v.screen.height===t.screen.height;const b=[...y?v.els:[],...f].filter(($,T,_)=>_.findIndex(x=>x.AXLabel===$.AXLabel&&JSON.stringify(x.frame)===JSON.stringify($.frame))===T);barCache.set(e,{screen:t.screen,els:b});saveBars()}if(d.some(v=>s(v)===3))break}}const h=Math.max(0,...d.map(s));if(r&&h<3)return[];d=d.filter(p=>s(p)===h);let w=d.filter((p,g)=>d.findIndex(m=>JSON.stringify(m.frame)===JSON.stringify(p.frame))===g);if(w.length>1){const p=w.filter(g=>(g.AXLabel??"").trim()===n.trim());if(p.length)w=p}if(w.length>1){const p=w.filter(g=>g.type&&!/StaticText|Text$|Other|Image/.test(g.type));if(p.length)w=p}return w}async function iosNativeElements(e){const n=await iosTree(e);const t=n.all.filter(s=>s.frame&&s.frame.width>0&&s.type!=="Application");const r=s=>`${s.AXLabel??""}|${JSON.stringify(s.frame)}`;const i=new Set(t.map(r));const{width:o,height:a}=n.screen;if(o){const s=t.filter(d=>!!d.type&&!/StaticText|Text$|Other|Image|Group|Heading/.test(d.type));const c=(d,h)=>s.some(w=>d>=w.frame.x&&d<=w.frame.x+w.frame.width&&h>=w.frame.y&&h<=w.frame.y+w.frame.height);const l=[];for(const d of[.95,.97,.09,.06])for(let h=20;h<o;h+=40){const w=Math.round(a*d);if(!c(h,w))l.push([h,w])}const u=Date.now()+6e3;for(let d=0;d<l.length&&Date.now()<u;d+=8){const h=await Promise.all(l.slice(d,d+8).map(([w,p])=>idb(["ui","describe-point","--udid",e,String(w),String(p),"--json"],3e3).then(g=>JSON.parse(g),g=>{if(IDB_SETUP.test(String(g)))throw g;return null})));for(const w of h){if(!w?.type||!w.frame?.width||w.type==="Application"||i.has(r(w)))continue;i.add(r(w));t.push(w)}}}t.sort((s,c)=>s.frame.y-c.frame.y||s.frame.x-c.frame.x);return{elements:t,screen:n.screen}}function axLine(e){const n=e.frame;const t=[e.type??"Element",e.AXLabel?JSON.stringify(e.AXLabel.slice(0,80)):"",e.AXUniqueId?`id=${e.AXUniqueId}`:"",e.AXValue?`value=${JSON.stringify(String(e.AXValue).slice(0,40))}`:"",e.enabled===false?"(disabled)":""].filter(Boolean);return`${t.join(" ")} at (${Math.round(n.x)}, ${Math.round(n.y)}) ${Math.round(n.width)}x${Math.round(n.height)}`}function nativeKit(e){async function n(v,y,b){if(y.platform!=="ios"||!b)return;try{const $=await e.callAction(UI_TOOL_ID2,"describeScreen",{},v,{timeoutMs:2e3,silent:true});const T=$?.screen?.width??0;const _=$?.screen?.height??0;const x=Math.max(T,_)/Math.max(1,Math.min(T,_));if(T>0&&_>0&&x>1.7)simScreens.set(y.udid,{size:{width:T,height:_},at:Date.now()})}catch{}}async function t(v,y){if(v.platform==="android")return adbScreenSize(v.serial);if(v.platform==="ios-device")return{...await phoneScreenSize(v.udid),isPhone:true};const b=simScreens.get(v.udid);if(!y&&b&&Date.now()-b.at<SCREEN_TTL_MS)return b.size;try{const $=(y??await iosTree(v.udid)).screen;if(!$.width)throw new Error("Could not read the simulator's screen size from idb.");simScreens.set(v.udid,{size:$,at:Date.now()});return $}catch($){if(y||!await simHidTool())throw $;const T=import_node_path13.default.join(import_node_os9.default.tmpdir(),`buoy-size-${process.pid}-${Date.now()}.png`);try{await execFileAsync11("xcrun",["simctl","io",v.udid,"screenshot","--type=png",T],{timeout:2e4});const _=await import_node_fs12.promises.readFile(T);return{width:_.readUInt32BE(16),height:_.readUInt32BE(20)}}finally{await import_node_fs12.promises.rm(T,{force:true}).catch(()=>void 0)}}}async function r(v,y,b,$){if(v.platform==="android")await adbTap(v.serial,y.x,y.y,b);else if(v.platform==="ios-device"){const T=await simHidTool();if(!T)throw new Error(PHONE_TOUCH);return simHidTap(T,await coreDeviceId(v.udid),await t(v),y.x,y.y,b,$)}else if(await simHidTool()){return simHidTap(await simHidTool(),v.udid,{...await t(v),bundleId:v.bundleId},y.x,y.y,b,$)}else{await assertSimTouchable(v.udid);await idb(["ui","tap","--udid",v.udid,...b?["--duration",(b/1e3).toFixed(2)]:[],String(Math.round(y.x)),String(Math.round(y.y))])}}async function i(v,y){if(v.platform==="android"){const $=await adbAppFrame(v.serial,v.packageName);const T=$??{x:0,y:0,...await adbScreenSize(v.serial)};return[(y.x-T.x)/T.width,(y.y-T.y)/T.height]}const b=await t(v);return[y.x/b.width,y.y/b.height]}async function o(v,y,b){try{const[$,T]=await i(y,b);if(!($>=0&&$<=1&&T>=0&&T<=1))return null;return await e.callAction(UI_TOOL_ID2,"hitTest",{x:$,y:T},v,{timeoutMs:2500,silent:true})}catch{return null}}async function a(v,y,b){const $=await o(v,y,b);if(!$?.found||!$.buoy)return null;const T=$.path?.length?` (${$.path.slice(0,3).join(" in ")})`:"";return`Buoy's own overlay${T} is on top at that spot, so a real touch would land on Buoy, not the app. Nothing was touched. Close or minimize the Buoy panel first, or pass allowBuoy: true to touch Buoy on purpose.`}async function s(v,y,b,$,T,_,x){if(!isRecording(v))return;try{const A=await t(y);const I=k=>[k[0]/A.width,k[1]/A.height];const E=Date.now()-_-(y.platform==="android"?50:80);const S=x!==void 0?x:y.platform==="android"?null:await deviceOrientation(y.udid);noteTouch(v,{at:E,kind:b,ms:_,from:$.map(I),to:T?.map(I),screen:A,orientation:S})}catch{}}async function c(v,y,b){const $=await e.callAction(UI_TOOL_ID2,"describeScreen",{},v);const T=(b.query??"").toLowerCase();const _=($.elements??[]).filter(S=>b.nativeTag!=null?S.nativeTag===b.nativeTag:b.testID?S.testID===b.testID:(S.text??S.label??"").toLowerCase()===T);const x=_.filter(S=>S.tap);if(x.length===0)return"No element on screen matches that. Call describe_screen, or use label for native controls.";if(x.length>1&&b.nativeTag==null)return`${x.length} elements match equally well, so nothing was tapped. Use nativeTag: ${x.map(S=>`#${S.nativeTag}`).join(", ")}.`;const A=x[0].tap;const I=`"${x[0].text??x[0].label??x[0].name}"`;if(y.platform==="android"){const S=await adbAppFrame(y.serial,y.packageName);const k=S??{x:0,y:0,...await adbScreenSize(y.serial)};return{x:k.x+A.x*k.width,y:k.y+A.y*k.height,what:I}}const E=await t(y);return{x:A.x*E.width,y:A.y*E.height,what:I}}async function l(v,y,b=false){if(v.platform==="android"){const A=findUiNodes(await adbUiNodes(v.serial),y).filter(E=>!b||[E.desc,E.text].some(S=>(S??"").trim().toLowerCase()===y.trim().toLowerCase()));if(A.length===0)return`No native element labeled "${y}" was found on screen.`;if(A.length>1)return`${A.length} native elements match "${y}" equally well, so nothing was tapped: ${A.map(E=>`"${E.desc||E.text||E.id}" at (${E.bounds.x}, ${E.bounds.y})`).join(", ")}. Tap one by x/y.`;const I=A[0].bounds;return{x:I.x+I.width/2,y:I.y+I.height/2,what:`"${A[0].desc||A[0].text||A[0].id}" (${A[0].cls.split(".").pop()})`}}const $=await cachedBarControl(v.udid,y);if($){simScreens.set(v.udid,{size:$.screen,at:Date.now()});const A=$.el.frame;return{x:A.x+A.width/2,y:A.y+A.height/2,what:`"${$.el.AXLabel}" (${$.el.type})`}}const T=await iosTree(v.udid);await t(v,T);const _=await findByLabel(v.udid,y,T,b);if(_.length===0)return`No native element labeled "${y}" was found on screen.`;if(_.length>1)return`${_.length} native elements match "${y}" equally well, so nothing was tapped: ${_.map(A=>`"${A.AXLabel}" at (${Math.round(A.frame.x)}, ${Math.round(A.frame.y)})`).join(", ")}. Tap one by x/y.`;const x=_[0].frame;return{x:x.x+x.width/2,y:x.y+x.height/2,what:`"${_[0].AXLabel}" (${_[0].type})`}}async function u(v,y,b,$,T=false,_=0,x){const A=[...y,...b].map(E=>String(Math.round(E)));const I=v.platform==="android"?null:await simHidTool();if(v.platform!=="android"&&!I)await assertSimTouchable(v.udid);if(v.platform==="android"){if(T)await adbShell(v.serial,`input draganddrop ${A.join(" ")} ${Math.round($)}`);else await adbSwipe(v.serial,y,b,$);return void 0}if(I){const E=v.platform==="ios-device"?await coreDeviceId(v.udid):v.udid;const S=x?.screen??await t(v);return simHidSwipe(I,E,{...S,bundleId:v.platform==="ios"?v.bundleId:null},y,b,$,T?700:0,T?0:_,x?.orientation)}if(T)await idb(["ui","swipe","--udid",v.udid,...A,"--duration",($/1e3).toFixed(2),"--delta","4"]);else await idb(["ui","swipe","--udid",v.udid,...A,"--duration",($/1e3).toFixed(2)]);return void 0}async function d(v){try{const y=await e.callAction(UI_TOOL_ID2,"describeScreen",{},v,{timeoutMs:3e3,silent:true});const b=new Map;for(const $ of y?.elements??[]){if(!$.tap)continue;const T=`${$.name??""}|${$.text??$.label??""}|${$.nativeTag??""}`;if(b.has(T))b.set(T,{x:NaN,y:NaN});else b.set(T,$.tap)}return b}catch{return null}}function h(v,y,b,$,T=true){let _=0;let x=0;for(const[A,I]of y){const E=v.get(A);if(!E)x++;else if(Number.isFinite(E[b])&&Number.isFinite(I[b])&&Math.abs(I[b]-E[b])>$)_++}return _+(T&&x>=2?x:0)}function w(v,y,b){const $=[];for(const[T,_]of y){const x=v.get(T);if(x&&Number.isFinite(x[b])&&Number.isFinite(_[b])&&Math.abs(_[b]-x[b])>.002)$.push(_[b]-x[b])}if($.length<2)return 0;$.sort((T,_)=>T-_);return $[Math.floor($.length/2)]}async function p(v,y){await delay5(120);let b=await d(v);const $=Date.now()+2500;while(b&&Date.now()<$){await delay5(100);const T=await d(v);if(!T)break;const _=h(b,T,y,.002,false)===0;b=T;if(_)break}return b}async function g(v,y,b,$,T,_=15){const x=Math.abs($[1]-b[1])>=Math.abs($[0]-b[0])?"y":"x";let A=await d(v);if(A===null)throw new Error("Scrolling to the end needs the app connected, to see when the list stops moving.");let I=0;let E=false;const S={screen:await t(y)};const k=x==="y"?1:0;const M=x==="y"?S.screen.height:S.screen.width;const D=Math.sign($[k]-b[k]);const P=Math.abs($[k]-b[k])/M;const R=new Set;const j=(F,B)=>{for(const[U,L]of B){const H=F.get(U);if(H&&Number.isFinite(H[x])&&Number.isFinite(L[x])&&Math.abs(L[x]-H[x])>.01)R.add(U)}};let C=A;while(I<_){const F=await u(y,b,$,T,false,SCROLL_REST_MS,S);if(F!==void 0)S.orientation=F;I++;await s(v,y,"swipe",[b],[$],T,F);await delay5(90);const B=await d(v);await delay5(70);const U=await d(v);if(!B||!U)throw new Error("The app stopped answering while scrolling.");const L=w(B,U,x)*D;j(A,U);C=U;if(L>.004||L>=-.004&&h(B,U,x,.002,false)===0&&h(A,U,x,.01)>0){A=U;continue}const H=await p(v,x);if(!H)throw new Error("The app stopped answering while scrolling.");j(A,H);C=H;if(h(A,H,x,.01)===0){E=true;break}const W=w(A,H,x)*D;if(W>.01&&W<P*.85){E=true;break}A=H}const O=[...C].filter(([F,B])=>R.has(F)&&B[x]>=0&&B[x]<=1&&F.split("|")[1]);const N=F=>F.sort((B,U)=>(U[1][x]-B[1][x])*-D)[0];const z=N(O.filter(([F])=>!F.startsWith("Text|")))??N(O);return{swipes:I,atEnd:E,lastRow:z?z[0].split("|")[1]:void 0}}async function m(v,y){if(v.platform==="android"){const $=await adbAppFrame(v.serial,v.packageName);const T=$??{x:0,y:0,...await adbScreenSize(v.serial)};return{x:T.x+y.x*T.width,y:T.y+y.y*T.height}}const b=await t(v);return{x:y.x*b.width,y:y.y*b.height}}async function f(v,y,b,$,T){if($&&(T==="app"||T==="loose")){const _=await e.callAction(UI_TOOL_ID2,"describeScreen",{},v,{timeoutMs:4e3,silent:true}).catch(()=>null);const x=(_?.elements??[]).filter(S=>S.tap&&S.tap.x>=0&&S.tap.x<=1&&S.tap.y>=0&&S.tap.y<=1);const A=b.trim().toLowerCase();const I=S=>(S.text??S.label??"").trim().toLowerCase();const E=T==="app"?[x.filter(S=>S.testID===b),x.filter(S=>I(S)===A)]:[x.filter(S=>!!A&&I(S).includes(A))];for(const S of E){if(!S.length)continue;const k=S.filter(R=>R.interactive);const M=k.length?k:S;const D=M.filter((R,j)=>M.findIndex(C=>Math.abs(C.tap.x-R.tap.x)<.02&&Math.abs(C.tap.y-R.tap.y)<.02)===j);if(D.length>1){return{tie:true,miss:`${D.length} elements match "${b}", so nothing was touched: ${D.slice(0,5).map(R=>R.testID?`testID ${R.testID}`:JSON.stringify(R.text??R.label??R.name)).join(", ")}. Use an exact testID.`}}const P=D[0];return{...await m(y,P.tap),what:`"${P.text??P.label??P.name}"${P.testID?` [testID=${P.testID}]`:""}`}}}if((T==="native"||T==="nativeExact")&&y.platform!=="ios-device"){const _=await l(y,b,T==="nativeExact");if(typeof _!=="string")return _;if(/equally well/.test(_))return{miss:_,tie:true}}return{miss:`Nothing on screen matches "${b}".`}}return{primeScreen:n,screenOf:t,touch:r,hitAt:o,buoyCover:a,mark:s,reactSpot:c,labelSpot:l,swipe:u,scrollToEnd:g,findSpot:f}}async function nativeLabelTap(e,n,t,r,i=false){const o=nativeKit(e);const{id:a,host:s,online:c}=await hostTarget(e,n);if(s.platform==="ios-device")return null;freshScreen(s);await o.primeScreen(a,s,c);const l=await o.findSpot(a,s,t,c,i?"nativeExact":"native");if("miss"in l)return null;if(c&&await o.buoyCover(a,s,l))return null;const u=r?600:void 0;const d=await o.touch(s,l,u);await o.mark(a,s,u?"hold":"tap",[[l.x,l.y]],void 0,u??150,d);return`${u?"Long-pressed":"Tapped"} ${l.what} with a real touch at (${Math.round(l.x)}, ${Math.round(l.y)}).`}function warmNativeTouch(e){if(process.platform!=="darwin"||process.env.BUOY_WARM_TOUCH==="0")return;const n=Date.now();const t=async()=>{try{const r=e.peekProjectDevice();const i=r?e.listDevices().find(o=>o.deviceId===r)?.platform:void 0;if(r&&i==="ios"){const{host:o}=await hostTarget(e,r);if(o.platform!=="ios")return;const a=await simHidTool();if(a)await runHidStream(a,o.udid,["--device",o.udid,"ping"]);await deviceOrientation(o.udid);await loadBars();if(!barCache.has(o.udid)){const s=await iosTree(o.udid).catch(()=>null);if(s?.screen.width)await findByLabel(o.udid,"\0no such label",s,false,[.95]).catch(()=>void 0)}return}if(r&&i)return}catch{}if(Date.now()-n<3e4)setTimeout(()=>void t(),500).unref()};setTimeout(()=>void t(),300).unref()}function registerNativeTools(e,n){warmNativeTouch(n);const{primeScreen:t,screenOf:r,touch:i,hitAt:o,buoyCover:a,mark:s,reactSpot:c,labelSpot:l,swipe:u,scrollToEnd:d}=nativeKit(n);const h=import_zod14.z.string().optional().describe("Android: the adb serial, when several devices are connected.");const w=p=>p.platform==="ios"?"pt":"px";e.registerTool("native_tap",{_meta:coreTool(),description:"Tap the screen for real (an OS touch: CoreDevice on the iOS Simulator, the way Xcode sends it, or idb on older Xcode; adb on Android), for native-only controls like a native tab bar or a system dialog, or when tap_element finds no handler. Pass holdMs for a long press. label and x/y work even when the app's JS is stuck.",inputSchema:{label:import_zod14.z.string().optional().describe('Native accessibility label, e.g. "Rewards" for a native tab.'),query:import_zod14.z.string().optional().describe("Text of an element from describe_screen."),testID:import_zod14.z.string().optional(),nativeTag:import_zod14.z.number().optional(),x:import_zod14.z.number().min(0).max(1).optional().describe("Horizontal position, 0 to 1."),y:import_zod14.z.number().min(0).max(1).optional().describe("Vertical position, 0 to 1."),holdMs:import_zod14.z.number().min(100).max(1e4).optional().describe("Hold the touch this long: a long press (context menus, Paste, reorder handles). 600 is a typical long press."),allowBuoy:import_zod14.z.boolean().optional().describe("Touch even if Buoy's own panel covers the spot. By default the tap stops there, because it would hit Buoy instead of the app."),serial:h,deviceId:deviceIdInput}},async p=>{try{const g=p.nativeTag!=null||!!p.testID||!!p.query;const{id:m,host:f,online:v}=await hostTarget(n,p.deviceId,{serial:p.serial},{allowOffline:!g});freshScreen(f);await t(m,f,v);if(f.platform==="ios-device"&&!await simHidTool())return fail2(PHONE_TOUCH);let y;if(p.x!=null&&p.y!=null){const T=await r(f);y={x:p.x*T.width,y:p.y*T.height,what:`(${p.x.toFixed(2)}, ${p.y.toFixed(2)})`}}else if(g){y=await c(m,f,p)}else if(p.label){if(f.platform==="ios-device")return fail2("label works on simulators and Android. On a physical iPhone, tap by query, testID or nativeTag (from describe_screen), or by x and y.");y=await l(f,p.label)}else{return fail2("Give label, query, testID, nativeTag, or x and y.")}if(typeof y==="string")return fail2(y);if(v&&!p.allowBuoy){const T=await a(m,f,y);if(T)return fail2(T)}const b=await i(f,y,p.holdMs);await s(m,f,p.holdMs?"hold":"tap",[[y.x,y.y]],void 0,p.holdMs??150,b);const $=v?await observeAfterAction(n,m):" (The app is not connected, so its screen was not read back.)";return text(`${p.holdMs?`Long-pressed (${p.holdMs}ms)`:"Tapped"} ${y.what} with a real touch at (${Math.round(y.x)}, ${Math.round(y.y)}) ${w(f)}.${$}`)}catch(g){return fail2(errMsg2(g))}});e.registerTool("native_type",{description:"Type text on the real keyboard into the focused field (CoreDevice or idb on the iOS Simulator, adb on Android). Tap the field first (tap_element or native_tap). Unlike tap_element's text, this goes through the keyboard like a person typing. It types plain ASCII only (letters, digits, punctuation, newlines).",inputSchema:{text:import_zod14.z.string().describe("The text to type. Write {{secret:NAME}} for a password: Buoy types BUOY_SECRET_NAME from its environment and hides it in what it returns. Prefer real password fields (shown as dots)."),serial:h,deviceId:deviceIdInput}},async p=>{try{const{id:g,host:m,online:f}=await hostTarget(n,p.deviceId,{serial:p.serial},{allowOffline:true});if(m.platform==="ios-device"&&!await simHidTool())return fail2(PHONE_TOUCH);const v=fillSecrets(p.text);let y=false;if(m.platform==="android")await adbText(m.serial,v);else if(m.platform==="ios-device")await simHidType(await simHidTool(),await coreDeviceId(m.udid),v);else{const $=await simHidTool();if($){await simHidType($,m.udid,v);y=true}else{await assertSimTouchable(m.udid);await idb(["ui","text","--udid",m.udid,v])}}if(!y)await delay5(300);const b=f?await observeAfterAction(n,g):"";return text(`Typed ${JSON.stringify(p.text)} on the keyboard.${b}`)}catch(g){return fail2(errMsg2(g))}});e.registerTool("native_swipe",{_meta:coreTool(),description:"Swipe the screen for real (CoreDevice or idb on the iOS Simulator, adb on Android): scroll a list, dismiss a sheet, change a page. Give a direction (the way your finger moves) or from/to points as fractions of the screen. To reach the bottom of a list, pass untilEnd: true. It swipes again until the screen stops moving, in one call.",inputSchema:{direction:import_zod14.z.enum(["up","down","left","right"]).optional().describe('"up" scrolls content down the list (finger moves up).'),fromX:import_zod14.z.number().min(0).max(1).optional(),fromY:import_zod14.z.number().min(0).max(1).optional(),toX:import_zod14.z.number().min(0).max(1).optional(),toY:import_zod14.z.number().min(0).max(1).optional(),durationMs:import_zod14.z.number().min(50).max(5e3).optional().describe("Default 300 (1200 with drag)."),drag:import_zod14.z.boolean().optional().describe("Drag instead of flick: press, hold, then move (reorder handles, drag and drop, sliders). On the iOS Simulator with older Xcode (idb) it is a slow swipe only."),untilEnd:import_zod14.z.boolean().optional().describe("Keep swiping until the screen stops moving (the end of the list), up to 15 swipes. Returns the last screen."),allowBuoy:import_zod14.z.boolean().optional().describe("Swipe even if Buoy's own panel covers the starting point."),serial:h,deviceId:deviceIdInput}},async p=>{try{const{id:g,host:m,online:f}=await hostTarget(n,p.deviceId,{serial:p.serial},{allowOffline:true});freshScreen(m);await t(g,m,f);if(m.platform==="ios-device"&&!await simHidTool())return fail2(PHONE_TOUCH);const v=await r(m);let y;let b;if(p.fromX!=null&&p.fromY!=null&&p.toX!=null&&p.toY!=null){y=[p.fromX,p.fromY];b=[p.toX,p.toY]}else{({from:y,to:b}=swipePoints(p.direction??"up",!!p.untilEnd))}const $=[y[0]*v.width,y[1]*v.height];const T=[b[0]*v.width,b[1]*v.height];let _=0;if(p.drag&&m.platform==="android"){const S=Number((await adbShell(m.serial,"settings get secure long_press_timeout").catch(()=>"")).trim())||500;_=S*1.5+600}const x=Math.max(p.durationMs??(p.drag?1200:300),_);if(f&&!p.allowBuoy){const S=await a(g,m,{x:$[0],y:$[1]});if(S)return fail2(S)}if(p.untilEnd){if(p.drag)return fail2("untilEnd scrolls with flicks. Leave out drag.");if(!f)return fail2("untilEnd needs the app connected, to see when the list stops moving.");const S=await d(g,m,$,T,p.durationMs??250);const{swipes:k,atEnd:M}=S;const D=await observeAfterAction(n,g,void 0,0);const{lastRow:P}=S;return text(`${M?`Reached the end of the list after ${k} swipe(s)${P?`. The last row is "${P}"`:""}`:`Swiped ${k} times and the screen was still moving`}.${D}`)}const A=m.platform==="android"?null:await simHidTool();const I=await u(m,$,T,x,p.drag);await s(g,m,p.drag?"drag":"swipe",[$],[T],x+(p.drag&&A?700:0),I);await delay5(400);const E=f?await observeAfterAction(n,g):"";return text(`${p.drag?"Dragged":"Swiped"} from (${$.map(Math.round).join(", ")}) to (${T.map(Math.round).join(", ")}) ${w(m)}.${E}`)}catch(g){return fail2(errMsg2(g))}});e.registerTool("native_inspect",{description:"Read native controls on the screen. Pass pointX and pointY for points on iOS Sims, pixels elsewhere. Use x and y for screen fractions (0 to 1). Leave all points out to list controls, with types, labels, IDs, and frames. This includes tabs, alerts, and sheets. A point read also checks the app view and Buoy's cover. iOS Sims use idb; Android uses uiautomator. Real iPhones show just the app view.",inputSchema:{pointX:import_zod14.z.number().finite().min(0).optional().describe("From the left. iOS Sims use points. Other hosts use pixels."),pointY:import_zod14.z.number().finite().min(0).optional().describe("From the top. iOS Sims use points. Other hosts use pixels."),x:import_zod14.z.number().min(0).max(1).optional().describe("Horizontal position, 0 to 1."),y:import_zod14.z.number().min(0).max(1).optional().describe("Vertical position, 0 to 1."),serial:h,deviceId:deviceIdInput}},async p=>{try{const g=p.pointX!=null||p.pointY!=null;if(g&&(p.pointX==null||p.pointY==null))return fail2("Use pointX and pointY together.");if(g&&(p.x!=null||p.y!=null))return fail2("Use pointX/pointY or x/y, not both.");if(!g&&p.x==null!==(p.y==null))return fail2("Use x and y together.");const{id:m,host:f,online:v}=await hostTarget(n,p.deviceId,{serial:p.serial},{allowOffline:true});freshScreen(f);await t(m,f,v);const y=w(f);if(!g&&(p.x==null||p.y==null)){if(f.platform==="ios-device")return fail2("A physical iPhone doesn't share its native element tree with this Mac. Use describe_screen for the app's elements, or native_inspect with x and y to see what is at a point.");let _;let x=0;if(f.platform==="android"){const I=await adbUiNodes(f.serial);_=I.filter(E=>E.text||E.desc||E.id||E.clickable).map(E=>{const S=E.bounds;const k=[E.cls.split(".").pop(),E.text?JSON.stringify(E.text.slice(0,80)):"",E.desc?`desc=${JSON.stringify(E.desc.slice(0,60))}`:"",E.id?`id=${E.id.split("/").pop()}`:"",E.clickable?"(clickable)":""];return`${k.filter(Boolean).join(" ")} at (${S.x}, ${S.y}) ${S.width}x${S.height}`})}else{const{elements:I,screen:E}=await iosNativeElements(f.udid);const S=I.filter(k=>!E.width||k.frame.y<E.height&&k.frame.y+k.frame.height>0&&k.frame.x<E.width&&k.frame.x+k.frame.width>0);x=I.length-S.length;_=S.map(axLine)}const A=_.slice(0,150);return text([`${_.length} native element(s) on screen, top to bottom (${y}; frames are x, y, width x height)${x?`. ${x} more are scrolled out of view`:""}:`,...A.map(I=>`- ${I}`),..._.length>A.length?[`(${_.length-A.length} more not shown.)`]:[],"Tap one with native_tap label or x/y. For the app's React elements (testID, handlers), use describe_screen."].join("\n"))}let b;if(g){const _=await r(f);b={x:p.pointX,y:p.pointY};if(b.x>=_.width||b.y>=_.height){return fail2(`That point is outside the screen (${_.width} x ${_.height} ${y}).`)}}else{const _=await r(f);b={x:p.x*_.width,y:p.y*_.height}}const $=[g?`At (${Math.round(b.x)}, ${Math.round(b.y)}) ${y}:`:`At (${p.x.toFixed(2)}, ${p.y.toFixed(2)}) = (${Math.round(b.x)}, ${Math.round(b.y)}) ${y}:`];const T=v?o(m,f,b):Promise.resolve(null);if(f.platform==="android"){const _=(await adbUiNodes(f.serial)).filter(A=>{const I=A.bounds;return b.x>=I.x&&b.x<=I.x+I.width&&b.y>=I.y&&b.y<=I.y+I.height});const x=_.sort((A,I)=>A.bounds.width*A.bounds.height-I.bounds.width*I.bounds.height)[0];$.push(x?`- Native: ${x.cls.split(".").pop()}${x.text?` ${JSON.stringify(x.text.slice(0,80))}`:""}${x.desc?` desc=${JSON.stringify(x.desc.slice(0,60))}`:""}${x.id?` id=${x.id.split("/").pop()}`:""} at (${x.bounds.x}, ${x.bounds.y}) ${x.bounds.width}x${x.bounds.height}`:"- Native: nothing with a label or id here.")}else if(f.platform==="ios"){const _=JSON.parse(await idb(["ui","describe-point","--udid",f.udid,String(Math.round(b.x)),String(Math.round(b.y)),"--json"],5e3));$.push(_?.type&&_.frame?.width?`- Native: ${axLine(_)}`:"- Native: no accessible element here (plain views and canvases often have none).")}else{$.push("- Native: not available on a physical iPhone.")}if(!v)$.push("- App: not connected, so its views can't be read.");else{const _=await T;if(!_)$.push("- App: no answer (an older Buoy without hitTest, or the JS thread is busy).");else if(!_.found)$.push(`- App: ${_.reason??"no React view here (native UI, or outside the app's views)."}`);else{const x=_.view;const A=[x.name,x.testID?`testID=${x.testID}`:"",x.label?`label=${JSON.stringify(x.label)}`:"",x.text?JSON.stringify(x.text.slice(0,60)):""].filter(Boolean).join(" ");$.push(`- App: ${A}${_.path?.length?` in ${_.path.join(" < ")}`:""}.`);if(_.buoy)$.push("- This spot is Buoy's own overlay. A real touch here hits Buoy, not the app; close or minimize the panel first.");else if(_.target){const I=_.target;$.push(`- A tap here presses ${I.testID?`testID ${I.testID}`:JSON.stringify(I.text??I.label??I.name)} (${I.name}${I.nativeTag!=null?`, nativeTag ${I.nativeTag}`:""}).`)}else $.push("- Nothing tappable in the app here.")}}return text($.join("\n"))}catch(g){return fail2(errMsg2(g))}});e.registerTool("native_pinch",{description:"Pinch, spread or turn with two real fingers (CoreDevice on the iOS Simulator and a physical iPhone): zoom a map or photo, or rotate, in one call. scale above 1 zooms in (fingers spread), below 1 zooms out. The reply says how far a map turned and zoomed, read from the map itself. For other views it says how much of the area changed and shows it. No screenshot is needed. Not on Android or older Xcode, which can't send two fingers.",_meta:coreTool(),inputSchema:{x:import_zod14.z.number().min(0).max(1).optional().describe("Center between the fingers, 0 to 1. Default 0.5."),y:import_zod14.z.number().min(0).max(1).optional().describe("Center between the fingers, 0 to 1. Default 0.5."),scale:import_zod14.z.number().min(.1).max(10).optional().describe("How far the fingers spread: 2 doubles the gap (zoom in), 0.5 halves it (zoom out). Default 2."),rotate:import_zod14.z.number().min(-180).max(180).optional().describe("Turn the fingers this many degrees while pinching, clockwise. Default 0."),durationMs:import_zod14.z.number().min(100).max(5e3).optional().describe("Default 500."),allowBuoy:import_zod14.z.boolean().optional().describe("Pinch even if a finger starts on Buoy."),deviceId:deviceIdInput}},async p=>{try{const{id:g,host:m,online:f}=await hostTarget(n,p.deviceId,{},{allowOffline:true});freshScreen(m);await t(g,m,f);if(m.platform==="android")return fail2("Android's input command sends one finger only, so Buoy can't pinch there yet. Use the app's zoom buttons, or native_swipe for one-finger moves.");const v=await simHidTool();if(!v)return fail2(m.platform==="ios-device"?PHONE_TOUCH:"Pinching needs Xcode's CoreDevice touch support (Xcode 26 or later); idb sends one finger only.");const y=await r(m);const b=[(p.x??.5)*y.width,(p.y??.5)*y.height];const $=p.scale??2;const T=Math.min(y.width,y.height);const _=T*.4;const x=$>=1?Math.max(T*.04,_/$):_;const A=$>=1?_:Math.max(T*.04,_*$);const I=(p.rotate??0)*Math.PI/180;const E=G=>[Math.min(y.width-1,Math.max(1,G[0])),Math.min(y.height-1,Math.max(1,G[1]))];const S=(G,K)=>[E([b[0]-G*Math.cos(K),b[1]-G*Math.sin(K)]),E([b[0]+G*Math.cos(K),b[1]+G*Math.sin(K)])];const[k,M]=S(x,0);const[D,P]=S(A,I);if(f&&!p.allowBuoy){for(const[G,K]of[k,M]){const ie=await a(g,m,{x:G,y:K});if(ie)return fail2(ie)}}const R=p.durationMs??500;const j={x:Math.max(0,(b[0]-_)/y.width),y:Math.max(0,(b[1]-_)/y.height),width:Math.min(1,2*_/y.width),height:Math.min(1,2*_/y.height)};const C=f?await readMaps(n,g):[];const O=G=>G.find(K=>!K.frame||(p.x??.5)>=K.frame.x&&(p.x??.5)<=K.frame.x+K.frame.width&&(p.y??.5)>=K.frame.y&&(p.y??.5)<=K.frame.y+K.frame.height);const N=O(C);const z=N?null:await hostPng(m).catch(()=>null);const F=m.platform==="ios-device"?await coreDeviceId(m.udid):m.udid;const B=await simHidTwo(v,F,{...y,bundleId:m.platform==="ios"?m.bundleId:null},k,M,D,P,R);await s(g,m,"pinch",[k,M],[D,P],R,B);await delay5(400);const[U,L,H]=await Promise.all([f?observeAfterAction(n,g,void 0,0):Promise.resolve(""),z?hostPng(m).catch(()=>null):Promise.resolve(null),N?readMaps(n,g):Promise.resolve([])]);const W=A/x;const J=W>1.01?`Spread (zoom in, x${W.toFixed(2)})`:W<.99?`Pinched (zoom out, x${W.toFixed(2)})`:"Turned";const V=`${J}${p.rotate?`, turning ${p.rotate} degrees,`:""} around (${Math.round(b[0])}, ${Math.round(b[1])}) ${w(m)} with two real fingers.`;const ae=N?H.find(G=>G.name===N.name&&G.testID===N.testID):void 0;const re=N&&ae?mapChange(N,ae):null;if(re)return text(`${V}
641
+ ${g}${p}`);return h.isError?{...m,isError:true}:m}const u=typedSecretValues().length?" Note: a secret was typed earlier this session; if it is still on screen, the video will show it. Typing secrets is blocked until the recording stops.":" Typing secrets ({{secret:NAME}}) is blocked until the recording stops, because a video can't hide them.";return text(`Recording ${hostLabel(a)}. Do the steps, then call screen_recording with action "stop". It stops by itself after ${MAX_RECORDING_MS/6e4} minutes.${u}`)}let r=t.deviceId;if(!r){try{r=n.requireProDevice()}catch{r=void 0}}if(!r||!sessions.has(r)){if(r&&finished.has(r)){const o=finished.get(r);finished.delete(r);return text(o)}if(sessions.size===1)r=[...sessions.keys()][0];else return fail2(sessions.size?"Several recordings are running. Pass deviceId.":'No recording is running. Start one with action "start".')}const i=sessions.get(r);await i.starting;if(!i.rec)return fail2("The recording did not start.");i.finishing??=finish(n,i);try{return text(await i.finishing)}catch(o){i.finishing=void 0;return fail2(`Could not save the recording: ${errMsg2(o)}. Call stop again to retry.`)}}catch(r){return fail2(errMsg2(r))}})}var execFileAsync11=(0,import_node_util11.promisify)(import_node_child_process12.execFile);var UI_TOOL_ID2="highlight-updates";var delay5=e=>new Promise(n=>setTimeout(n,e));var IDB_MISSING="Native touch on the iOS Simulator needs idb on this Mac (brew install facebook/fb/idb-companion && pipx install fb-idb).";var PHONE_TOUCH="Real touches on a physical iPhone need Xcode's CoreDevice touch support, and Buoy couldn't set it up on this Mac. Use tap_element (it calls the element's handler) or run_flow; screenshots, recording and app control work on the iPhone.";var phoneScreens=new Map;async function phoneScreenSize(e){const n=phoneScreens.get(e);if(n&&Date.now()-n.at<SCREEN_TTL_MS)return n.size;const t=await phoneScreenshot(e);const r={width:t.readUInt32BE(16),height:t.readUInt32BE(20)};phoneScreens.set(e,{size:r,at:Date.now()});return r}var simScreens=new Map;function swipePoints(e,n){if(n){if(e==="up")return{from:[.5,.88],to:[.5,.06]};if(e==="down")return{from:[.5,.3],to:[.5,.94]};if(e==="left")return{from:[.9,.5],to:[.1,.5]};return{from:[.1,.5],to:[.9,.5]}}const t=e==="left"?-.35:e==="right"?.35:0;const r=e==="up"?-.3:e==="down"?.3:0;return{from:[.5-t/2,.5-r/2],to:[.5+t/2,.5+r/2]}}var SCROLL_REST_MS=60;var SCREEN_TTL_MS=3e3;function forgetScreenSize(e){barCache.delete(e);simScreens.delete(e);phoneScreens.delete(e)}function freshScreen(e){if(e.platform==="android")return;simScreens.delete(e.udid);phoneScreens.delete(e.udid)}var IDB_SETUP=/idb on this Mac|SimulatorKit|not booted|connection refused|Failed to connect to companion/i;async function xcodeShimDir(){const e=(await execFileAsync11("xcode-select",["-p"],{timeout:5e3}).catch(()=>({stdout:""}))).stdout.trim();if(!e.endsWith("/Contents/Developer"))return null;const n=import_node_path13.default.dirname(e);const t=import_node_path13.default.join(e,"Library","PrivateFrameworks","SimulatorKit.framework");const r=import_node_path13.default.join(n,"SharedFrameworks","SimulatorKit.framework");const i=l=>import_node_fs12.promises.access(l).then(()=>true,()=>false);if(await i(t)||!await i(r))return null;const o=(await execFileAsync11("plutil",["-extract","DTXcodeBuild","raw","-o","-",import_node_path13.default.join(n,"Info.plist")]).catch(()=>({stdout:"x"}))).stdout.trim();const a=import_node_path13.default.join(import_node_os9.default.homedir(),".buoy","xcode-shim",o.replace(/[^\w.-]/g,"_"),"Contents");const s=import_node_path13.default.join(a,"Developer");if(await i(import_node_path13.default.join(s,"Library","PrivateFrameworks","SimulatorKit.framework")))return s;await import_node_fs12.promises.mkdir(import_node_path13.default.join(s,"Library","PrivateFrameworks"),{recursive:true});const c=async(l,u,d)=>{for(const h of await import_node_fs12.promises.readdir(l)){if(h===d)continue;await import_node_fs12.promises.symlink(import_node_path13.default.join(l,h),import_node_path13.default.join(u,h)).catch(()=>void 0)}};await c(n,a,"Developer");await c(e,s,"Library");await c(import_node_path13.default.join(e,"Library"),import_node_path13.default.join(s,"Library"),"PrivateFrameworks");await c(import_node_path13.default.join(e,"Library","PrivateFrameworks"),import_node_path13.default.join(s,"Library","PrivateFrameworks"),"").catch(()=>void 0);await import_node_fs12.promises.symlink(r,import_node_path13.default.join(s,"Library","PrivateFrameworks","SimulatorKit.framework")).catch(()=>void 0);return s}async function restartCompanion(e){const n=`/tmp/idb/${e}.buoy-restart`;await import_node_fs12.promises.mkdir("/tmp/idb",{recursive:true}).catch(()=>void 0);const t=async()=>{try{await(await import_node_fs12.promises.open(n,"wx")).close();return true}catch{const r=await import_node_fs12.promises.stat(n).then(i=>Date.now()-i.mtimeMs,()=>0);if(r>15e3){const i=`${n}.stale-${process.pid}-${Date.now()}`;await import_node_fs12.promises.rename(n,i).then(()=>import_node_fs12.promises.unlink(i).catch(()=>void 0),()=>void 0);return t()}return false}};if(!await t()){for(let r=0;r<60;r++){await delay5(250);if(!await import_node_fs12.promises.stat(n).then(()=>true,()=>false))return}return}try{await execFileAsync11("pkill",["-f",`idb_companion --udid ${e}`],{timeout:5e3}).catch(()=>void 0);await delay5(300);const r=await xcodeShimDir().catch(()=>null);const i=(0,import_node_child_process12.spawn)("idb_companion",["--udid",e,"--grpc-domain-sock",`/tmp/idb/${e}_companion.sock`,"--only","simulator"],{detached:true,stdio:"ignore",env:r?{...process.env,DEVELOPER_DIR:r}:process.env});i.on("error",()=>void 0);i.unref();await delay5(1800)}finally{await import_node_fs12.promises.unlink(n).catch(()=>void 0)}}async function idb(e,n=15e3,t=false){try{const{stdout:r}=await execFileAsync11("idb",e,{timeout:n});return r}catch(r){const i=r;if(i.code==="ENOENT")throw new Error(IDB_MISSING);const o=(i.stderr||i.message||"").slice(0,300);const a=e.includes("--udid")?e[e.indexOf("--udid")+1]:void 0;if(!t&&a&&/not booted|connection refused|Failed to connect to companion/i.test(o)){await restartCompanion(a);return idb(e,n,true)}if(/SimulatorKit is required/i.test(o)){if(!t&&a&&await xcodeShimDir().catch(()=>null)){await restartCompanion(a);return idb(e,n,true)}throw new Error("idb can't send touches with this Xcode: it can't load SimulatorKit, and Buoy could not work around it. Use tap_element (it calls the element's handler) for now. Reading the screen (describe_screen, screenshot_component) still works.")}throw new Error(`idb ${e[0]} ${e[1]??""} failed: ${o}`)}}async function iosTree(e){const n=JSON.parse(await idb(["ui","describe-all","--udid",e,"--json","--nested"]));const t=[];const r=o=>{t.push(o);for(const a of o.children??[])r(a)};n.forEach(r);const i=t.find(o=>o.type==="Application"&&o.frame);return{all:t,screen:i?.frame?{width:i.frame.width,height:i.frame.height}:{width:0,height:0}}}var barCache=new Map;var BAR_FILE=import_node_path13.default.join(import_node_os9.default.homedir(),".buoy","cache","native-bars.json");var barFileRead=false;async function loadBars(){if(barFileRead||process.env.VITEST)return;barFileRead=true;try{const e=JSON.parse(await import_node_fs12.promises.readFile(BAR_FILE,"utf8"));for(const[n,t]of Object.entries(e))if(!barCache.has(n)&&t?.screen&&Array.isArray(t.els))barCache.set(n,t)}catch{}}function saveBars(){if(process.env.VITEST)return;const e=Object.fromEntries([...barCache].map(([t,r])=>[t,{screen:r.screen,els:r.els.map(i=>({AXLabel:i.AXLabel,type:i.type,frame:i.frame}))}]));const n=`${BAR_FILE}.${process.pid}`;void import_node_fs12.promises.mkdir(import_node_path13.default.dirname(BAR_FILE),{recursive:true}).then(()=>import_node_fs12.promises.writeFile(n,JSON.stringify(e))).then(()=>import_node_fs12.promises.rename(n,BAR_FILE)).catch(()=>void 0)}async function cachedBarControl(e,n){await loadBars();const t=barCache.get(e);const r=n.trim().toLowerCase();const i=t?.els.find(o=>(o.AXLabel??"").trim().toLowerCase()===r&&o.frame);if(!t||!i?.frame)return null;try{const o=Math.round(i.frame.x+i.frame.width/2);const a=Math.round(i.frame.y+i.frame.height/2);const s=JSON.parse(await idb(["ui","describe-point","--udid",e,String(o),String(a),"--json"],3e3));if((s.AXLabel??"").trim().toLowerCase()===r&&s.frame)return{el:s,screen:t.screen}}catch{}barCache.delete(e);saveBars();return null}async function findByLabel(e,n,t,r=false,i=[.95,.97,.09,.06]){const o=n.trim().toLowerCase();const a=Date.now()+8e3;const s=p=>{const g=(p.AXLabel??"").trim().toLowerCase();if(!g)return 0;if(g===o)return 3;if(g.startsWith(o))return 2;if(g.includes(o))return 1;return 0};const{width:c,height:l}=t.screen;const u=p=>{if(!c||!p.frame)return true;const g=p.frame.x+p.frame.width/2;const m=p.frame.y+p.frame.height/2;return g>=0&&g<=c&&m>=0&&m<=l};let d=t.all.filter(p=>s(p)>0&&p.frame&&p.type!=="Application"&&u(p));if(!d.some(p=>s(p)===3)&&t.screen.width){const p=i.map(g=>{const m=[];for(let f=20;f<t.screen.width;f+=40)m.push([f,Math.round(t.screen.height*g)]);return m});for(const g of p){if(Date.now()>=a)break;const m=await Promise.allSettled(g.map(async([v,y])=>JSON.parse(await idb(["ui","describe-point","--udid",e,String(v),String(y),"--json"],3e3))));const f=[];for(const v of m){if(v.status==="rejected"){if(IDB_SETUP.test(String(v.reason)))throw v.reason;continue}const y=v.value;if(y?.frame&&y.AXLabel&&y.type&&y.type!=="Application")f.push(y);if(s(y)>0&&y.frame)d.push(y)}if(f.length){const v=barCache.get(e);const y=v&&v.screen.width===t.screen.width&&v.screen.height===t.screen.height;const b=[...y?v.els:[],...f].filter(($,T,_)=>_.findIndex(x=>x.AXLabel===$.AXLabel&&JSON.stringify(x.frame)===JSON.stringify($.frame))===T);barCache.set(e,{screen:t.screen,els:b});saveBars()}if(d.some(v=>s(v)===3))break}}const h=Math.max(0,...d.map(s));if(r&&h<3)return[];d=d.filter(p=>s(p)===h);let w=d.filter((p,g)=>d.findIndex(m=>JSON.stringify(m.frame)===JSON.stringify(p.frame))===g);if(w.length>1){const p=w.filter(g=>(g.AXLabel??"").trim()===n.trim());if(p.length)w=p}if(w.length>1){const p=w.filter(g=>g.type&&!/StaticText|Text$|Other|Image/.test(g.type));if(p.length)w=p}return w}async function iosNativeElements(e){const n=await iosTree(e);const t=n.all.filter(s=>s.frame&&s.frame.width>0&&s.type!=="Application");const r=s=>`${s.AXLabel??""}|${JSON.stringify(s.frame)}`;const i=new Set(t.map(r));const{width:o,height:a}=n.screen;if(o){const s=t.filter(d=>!!d.type&&!/StaticText|Text$|Other|Image|Group|Heading/.test(d.type));const c=(d,h)=>s.some(w=>d>=w.frame.x&&d<=w.frame.x+w.frame.width&&h>=w.frame.y&&h<=w.frame.y+w.frame.height);const l=[];for(const d of[.95,.97,.09,.06])for(let h=20;h<o;h+=40){const w=Math.round(a*d);if(!c(h,w))l.push([h,w])}const u=Date.now()+6e3;for(let d=0;d<l.length&&Date.now()<u;d+=8){const h=await Promise.all(l.slice(d,d+8).map(([w,p])=>idb(["ui","describe-point","--udid",e,String(w),String(p),"--json"],3e3).then(g=>JSON.parse(g),g=>{if(IDB_SETUP.test(String(g)))throw g;return null})));for(const w of h){if(!w?.type||!w.frame?.width||w.type==="Application"||i.has(r(w)))continue;i.add(r(w));t.push(w)}}}t.sort((s,c)=>s.frame.y-c.frame.y||s.frame.x-c.frame.x);return{elements:t,screen:n.screen}}function axLine(e){const n=e.frame;const t=[e.type??"Element",e.AXLabel?JSON.stringify(e.AXLabel.slice(0,80)):"",e.AXUniqueId?`id=${e.AXUniqueId}`:"",e.AXValue?`value=${JSON.stringify(String(e.AXValue).slice(0,40))}`:"",e.enabled===false?"(disabled)":""].filter(Boolean);return`${t.join(" ")} at (${Math.round(n.x)}, ${Math.round(n.y)}) ${Math.round(n.width)}x${Math.round(n.height)}`}function nativeKit(e){async function n(v,y,b){if(y.platform!=="ios"||!b)return;try{const $=await e.callAction(UI_TOOL_ID2,"describeScreen",{},v,{timeoutMs:2e3,silent:true});const T=$?.screen?.width??0;const _=$?.screen?.height??0;const x=Math.max(T,_)/Math.max(1,Math.min(T,_));if(T>0&&_>0&&x>1.7)simScreens.set(y.udid,{size:{width:T,height:_},at:Date.now()})}catch{}}async function t(v,y){if(v.platform==="android")return adbScreenSize(v.serial);if(v.platform==="ios-device")return{...await phoneScreenSize(v.udid),isPhone:true};const b=simScreens.get(v.udid);if(!y&&b&&Date.now()-b.at<SCREEN_TTL_MS)return b.size;try{const $=(y??await iosTree(v.udid)).screen;if(!$.width)throw new Error("Could not read the simulator's screen size from idb.");simScreens.set(v.udid,{size:$,at:Date.now()});return $}catch($){if(y||!await simHidTool())throw $;const T=import_node_path13.default.join(import_node_os9.default.tmpdir(),`buoy-size-${process.pid}-${Date.now()}.png`);try{await execFileAsync11("xcrun",["simctl","io",v.udid,"screenshot","--type=png",T],{timeout:2e4});const _=await import_node_fs12.promises.readFile(T);return{width:_.readUInt32BE(16),height:_.readUInt32BE(20)}}finally{await import_node_fs12.promises.rm(T,{force:true}).catch(()=>void 0)}}}async function r(v,y,b,$){if(v.platform==="android")await adbTap(v.serial,y.x,y.y,b);else if(v.platform==="ios-device"){const T=await simHidTool();if(!T)throw new Error(PHONE_TOUCH);return simHidTap(T,await coreDeviceId(v.udid),await t(v),y.x,y.y,b,$)}else if(await simHidTool()){return simHidTap(await simHidTool(),v.udid,{...await t(v),bundleId:v.bundleId},y.x,y.y,b,$)}else{await assertSimTouchable(v.udid);await idb(["ui","tap","--udid",v.udid,...b?["--duration",(b/1e3).toFixed(2)]:[],String(Math.round(y.x)),String(Math.round(y.y))])}}async function i(v,y){if(v.platform==="android"){const $=await adbAppFrame(v.serial,v.packageName);const T=$??{x:0,y:0,...await adbScreenSize(v.serial)};return[(y.x-T.x)/T.width,(y.y-T.y)/T.height]}const b=await t(v);return[y.x/b.width,y.y/b.height]}async function o(v,y,b){try{const[$,T]=await i(y,b);if(!($>=0&&$<=1&&T>=0&&T<=1))return null;return await e.callAction(UI_TOOL_ID2,"hitTest",{x:$,y:T},v,{timeoutMs:2500,silent:true})}catch{return null}}async function a(v,y,b){const $=await o(v,y,b);if(!$?.found||!$.buoy)return null;const T=$.path?.length?` (${$.path.slice(0,3).join(" in ")})`:"";return`Buoy's own overlay${T} is on top at that spot, so a real touch would land on Buoy, not the app. Nothing was touched. Close or minimize the Buoy panel first, or pass allowBuoy: true to touch Buoy on purpose.`}async function s(v,y,b,$,T,_,x){if(!isRecording(v))return;try{const I=await t(y);const D=k=>[k[0]/I.width,k[1]/I.height];const E=Date.now()-_-(y.platform==="android"?50:80);const S=x!==void 0?x:y.platform==="android"?null:await deviceOrientation(y.udid);noteTouch(v,{at:E,kind:b,ms:_,from:$.map(D),to:T?.map(D),screen:I,orientation:S})}catch{}}async function c(v,y,b){const $=await e.callAction(UI_TOOL_ID2,"describeScreen",{},v);const T=(b.query??"").toLowerCase();const _=($.elements??[]).filter(S=>b.nativeTag!=null?S.nativeTag===b.nativeTag:b.testID?S.testID===b.testID:(S.text??S.label??"").toLowerCase()===T);const x=_.filter(S=>S.tap);if(x.length===0)return"No element on screen matches that. Call describe_screen, or use label for native controls.";if(x.length>1&&b.nativeTag==null)return`${x.length} elements match equally well, so nothing was tapped. Use nativeTag: ${x.map(S=>`#${S.nativeTag}`).join(", ")}.`;const I=x[0].tap;const D=`"${x[0].text??x[0].label??x[0].name}"`;if(y.platform==="android"){const S=await adbAppFrame(y.serial,y.packageName);const k=S??{x:0,y:0,...await adbScreenSize(y.serial)};return{x:k.x+I.x*k.width,y:k.y+I.y*k.height,what:D}}const E=await t(y);return{x:I.x*E.width,y:I.y*E.height,what:D}}async function l(v,y,b=false){if(v.platform==="android"){const I=findUiNodes(await adbUiNodes(v.serial),y).filter(E=>!b||[E.desc,E.text].some(S=>(S??"").trim().toLowerCase()===y.trim().toLowerCase()));if(I.length===0)return`No native element labeled "${y}" was found on screen.`;if(I.length>1)return`${I.length} native elements match "${y}" equally well, so nothing was tapped: ${I.map(E=>`"${E.desc||E.text||E.id}" at (${E.bounds.x}, ${E.bounds.y})`).join(", ")}. Tap one by x/y.`;const D=I[0].bounds;return{x:D.x+D.width/2,y:D.y+D.height/2,what:`"${I[0].desc||I[0].text||I[0].id}" (${I[0].cls.split(".").pop()})`}}const $=await cachedBarControl(v.udid,y);if($){simScreens.set(v.udid,{size:$.screen,at:Date.now()});const I=$.el.frame;return{x:I.x+I.width/2,y:I.y+I.height/2,what:`"${$.el.AXLabel}" (${$.el.type})`}}const T=await iosTree(v.udid);await t(v,T);const _=await findByLabel(v.udid,y,T,b);if(_.length===0)return`No native element labeled "${y}" was found on screen.`;if(_.length>1)return`${_.length} native elements match "${y}" equally well, so nothing was tapped: ${_.map(I=>`"${I.AXLabel}" at (${Math.round(I.frame.x)}, ${Math.round(I.frame.y)})`).join(", ")}. Tap one by x/y.`;const x=_[0].frame;return{x:x.x+x.width/2,y:x.y+x.height/2,what:`"${_[0].AXLabel}" (${_[0].type})`}}async function u(v,y,b,$,T=false,_=0,x){const I=[...y,...b].map(E=>String(Math.round(E)));const D=v.platform==="android"?null:await simHidTool();if(v.platform!=="android"&&!D)await assertSimTouchable(v.udid);if(v.platform==="android"){if(T)await adbShell(v.serial,`input draganddrop ${I.join(" ")} ${Math.round($)}`);else await adbSwipe(v.serial,y,b,$);return void 0}if(D){const E=v.platform==="ios-device"?await coreDeviceId(v.udid):v.udid;const S=x?.screen??await t(v);return simHidSwipe(D,E,{...S,bundleId:v.platform==="ios"?v.bundleId:null},y,b,$,T?700:0,T?0:_,x?.orientation)}if(T)await idb(["ui","swipe","--udid",v.udid,...I,"--duration",($/1e3).toFixed(2),"--delta","4"]);else await idb(["ui","swipe","--udid",v.udid,...I,"--duration",($/1e3).toFixed(2)]);return void 0}async function d(v){try{const y=await e.callAction(UI_TOOL_ID2,"describeScreen",{},v,{timeoutMs:3e3,silent:true});const b=new Map;for(const $ of y?.elements??[]){if(!$.tap)continue;const T=`${$.name??""}|${$.text??$.label??""}|${$.nativeTag??""}`;if(b.has(T))b.set(T,{x:NaN,y:NaN});else b.set(T,$.tap)}return b}catch{return null}}function h(v,y,b,$,T=true){let _=0;let x=0;for(const[I,D]of y){const E=v.get(I);if(!E)x++;else if(Number.isFinite(E[b])&&Number.isFinite(D[b])&&Math.abs(D[b]-E[b])>$)_++}return _+(T&&x>=2?x:0)}function w(v,y,b){const $=[];for(const[T,_]of y){const x=v.get(T);if(x&&Number.isFinite(x[b])&&Number.isFinite(_[b])&&Math.abs(_[b]-x[b])>.002)$.push(_[b]-x[b])}if($.length<2)return 0;$.sort((T,_)=>T-_);return $[Math.floor($.length/2)]}async function p(v,y){await delay5(120);let b=await d(v);const $=Date.now()+2500;while(b&&Date.now()<$){await delay5(100);const T=await d(v);if(!T)break;const _=h(b,T,y,.002,false)===0;b=T;if(_)break}return b}async function g(v,y,b,$,T,_=15){const x=Math.abs($[1]-b[1])>=Math.abs($[0]-b[0])?"y":"x";let I=await d(v);if(I===null)throw new Error("Scrolling to the end needs the app connected, to see when the list stops moving.");let D=0;let E=false;const S={screen:await t(y)};const k=x==="y"?1:0;const M=x==="y"?S.screen.height:S.screen.width;const A=Math.sign($[k]-b[k]);const O=Math.abs($[k]-b[k])/M;const R=new Set;const j=(F,B)=>{for(const[U,L]of B){const H=F.get(U);if(H&&Number.isFinite(H[x])&&Number.isFinite(L[x])&&Math.abs(L[x]-H[x])>.01)R.add(U)}};let C=I;while(D<_){const F=await u(y,b,$,T,false,SCROLL_REST_MS,S);if(F!==void 0)S.orientation=F;D++;await s(v,y,"swipe",[b],[$],T,F);await delay5(90);const B=await d(v);await delay5(70);const U=await d(v);if(!B||!U)throw new Error("The app stopped answering while scrolling.");const L=w(B,U,x)*A;j(I,U);C=U;if(L>.004||L>=-.004&&h(B,U,x,.002,false)===0&&h(I,U,x,.01)>0){I=U;continue}const H=await p(v,x);if(!H)throw new Error("The app stopped answering while scrolling.");j(I,H);C=H;if(h(I,H,x,.01)===0){E=true;break}const W=w(I,H,x)*A;if(W>.01&&W<O*.85){E=true;break}I=H}const P=[...C].filter(([F,B])=>R.has(F)&&B[x]>=0&&B[x]<=1&&F.split("|")[1]);const N=F=>F.sort((B,U)=>(U[1][x]-B[1][x])*-A)[0];const z=N(P.filter(([F])=>!F.startsWith("Text|")))??N(P);return{swipes:D,atEnd:E,lastRow:z?z[0].split("|")[1]:void 0}}async function m(v,y){if(v.platform==="android"){const $=await adbAppFrame(v.serial,v.packageName);const T=$??{x:0,y:0,...await adbScreenSize(v.serial)};return{x:T.x+y.x*T.width,y:T.y+y.y*T.height}}const b=await t(v);return{x:y.x*b.width,y:y.y*b.height}}async function f(v,y,b,$,T){if($&&(T==="app"||T==="loose")){const _=await e.callAction(UI_TOOL_ID2,"describeScreen",{},v,{timeoutMs:4e3,silent:true}).catch(()=>null);const x=(_?.elements??[]).filter(S=>S.tap&&S.tap.x>=0&&S.tap.x<=1&&S.tap.y>=0&&S.tap.y<=1);const I=b.trim().toLowerCase();const D=S=>(S.text??S.label??"").trim().toLowerCase();const E=T==="app"?[x.filter(S=>S.testID===b),x.filter(S=>D(S)===I)]:[x.filter(S=>!!I&&D(S).includes(I))];for(const S of E){if(!S.length)continue;const k=S.filter(R=>R.interactive);const M=k.length?k:S;const A=M.filter((R,j)=>M.findIndex(C=>Math.abs(C.tap.x-R.tap.x)<.02&&Math.abs(C.tap.y-R.tap.y)<.02)===j);if(A.length>1){return{tie:true,miss:`${A.length} elements match "${b}", so nothing was touched: ${A.slice(0,5).map(R=>R.testID?`testID ${R.testID}`:JSON.stringify(R.text??R.label??R.name)).join(", ")}. Use an exact testID.`}}const O=A[0];return{...await m(y,O.tap),what:`"${O.text??O.label??O.name}"${O.testID?` [testID=${O.testID}]`:""}`}}}if((T==="native"||T==="nativeExact")&&y.platform!=="ios-device"){const _=await l(y,b,T==="nativeExact");if(typeof _!=="string")return _;if(/equally well/.test(_))return{miss:_,tie:true}}return{miss:`Nothing on screen matches "${b}".`}}return{primeScreen:n,screenOf:t,touch:r,hitAt:o,buoyCover:a,mark:s,reactSpot:c,labelSpot:l,swipe:u,scrollToEnd:g,findSpot:f}}async function nativeLabelTap(e,n,t,r,i=false){const o=nativeKit(e);const{id:a,host:s,online:c}=await hostTarget(e,n);if(s.platform==="ios-device")return null;freshScreen(s);await o.primeScreen(a,s,c);const l=await o.findSpot(a,s,t,c,i?"nativeExact":"native");if("miss"in l)return null;if(c&&await o.buoyCover(a,s,l))return null;const u=r?600:void 0;const d=await o.touch(s,l,u);await o.mark(a,s,u?"hold":"tap",[[l.x,l.y]],void 0,u??150,d);return`${u?"Long-pressed":"Tapped"} ${l.what} with a real touch at (${Math.round(l.x)}, ${Math.round(l.y)}).`}function warmNativeTouch(e){if(process.platform!=="darwin"||process.env.BUOY_WARM_TOUCH==="0")return;const n=Date.now();const t=async()=>{try{const r=e.peekProjectDevice();const i=r?e.listDevices().find(o=>o.deviceId===r)?.platform:void 0;if(r&&i==="ios"){const{host:o}=await hostTarget(e,r);if(o.platform!=="ios")return;const a=await simHidTool();if(a)await runHidStream(a,o.udid,["--device",o.udid,"ping"]);await deviceOrientation(o.udid);await loadBars();if(!barCache.has(o.udid)){const s=await iosTree(o.udid).catch(()=>null);if(s?.screen.width)await findByLabel(o.udid,"\0no such label",s,false,[.95]).catch(()=>void 0)}return}if(r&&i)return}catch{}if(Date.now()-n<3e4)setTimeout(()=>void t(),500).unref()};setTimeout(()=>void t(),300).unref()}function registerNativeTools(e,n){warmNativeTouch(n);const{primeScreen:t,screenOf:r,touch:i,hitAt:o,buoyCover:a,mark:s,reactSpot:c,labelSpot:l,swipe:u,scrollToEnd:d}=nativeKit(n);const h=import_zod14.z.string().optional().describe("Android: the adb serial, when several devices are connected.");const w=p=>p.platform==="ios"?"pt":"px";e.registerTool("native_tap",{_meta:coreTool(),description:"Tap the screen for real (an OS touch: CoreDevice on the iOS Simulator, the way Xcode sends it, or idb on older Xcode; adb on Android), for native-only controls like a native tab bar or a system dialog, or when tap_element finds no handler. Pass holdMs for a long press. label and x/y work even when the app's JS is stuck.",inputSchema:{label:import_zod14.z.string().optional().describe('Native accessibility label, e.g. "Rewards" for a native tab.'),query:import_zod14.z.string().optional().describe("Text of an element from describe_screen."),testID:import_zod14.z.string().optional(),nativeTag:import_zod14.z.number().optional(),x:import_zod14.z.number().min(0).max(1).optional().describe("Horizontal position, 0 to 1."),y:import_zod14.z.number().min(0).max(1).optional().describe("Vertical position, 0 to 1."),holdMs:import_zod14.z.number().min(100).max(1e4).optional().describe("Hold the touch this long: a long press (context menus, Paste, reorder handles). 600 is a typical long press."),allowBuoy:import_zod14.z.boolean().optional().describe("Touch even if Buoy's own panel covers the spot. By default the tap stops there, because it would hit Buoy instead of the app."),serial:h,deviceId:deviceIdInput}},async p=>{try{const g=p.nativeTag!=null||!!p.testID||!!p.query;const{id:m,host:f,online:v}=await hostTarget(n,p.deviceId,{serial:p.serial},{allowOffline:!g});freshScreen(f);await t(m,f,v);if(f.platform==="ios-device"&&!await simHidTool())return fail2(PHONE_TOUCH);let y;if(p.x!=null&&p.y!=null){const T=await r(f);y={x:p.x*T.width,y:p.y*T.height,what:`(${p.x.toFixed(2)}, ${p.y.toFixed(2)})`}}else if(g){y=await c(m,f,p)}else if(p.label){if(f.platform==="ios-device")return fail2("label works on simulators and Android. On a physical iPhone, tap by query, testID or nativeTag (from describe_screen), or by x and y.");y=await l(f,p.label)}else{return fail2("Give label, query, testID, nativeTag, or x and y.")}if(typeof y==="string")return fail2(y);if(v&&!p.allowBuoy){const T=await a(m,f,y);if(T)return fail2(T)}const b=await i(f,y,p.holdMs);await s(m,f,p.holdMs?"hold":"tap",[[y.x,y.y]],void 0,p.holdMs??150,b);const $=v?await observeAfterAction(n,m):" (The app is not connected, so its screen was not read back.)";return text(`${p.holdMs?`Long-pressed (${p.holdMs}ms)`:"Tapped"} ${y.what} with a real touch at (${Math.round(y.x)}, ${Math.round(y.y)}) ${w(f)}.${$}`)}catch(g){return fail2(errMsg2(g))}});e.registerTool("native_type",{description:"Type text on the real keyboard into the focused field (CoreDevice or idb on the iOS Simulator, adb on Android). Tap the field first (tap_element or native_tap). Unlike tap_element's text, this goes through the keyboard like a person typing. It types plain ASCII only (letters, digits, punctuation, newlines).",inputSchema:{text:import_zod14.z.string().describe("The text to type. Write {{secret:NAME}} for a password: Buoy types BUOY_SECRET_NAME from its environment and hides it in what it returns. Prefer real password fields (shown as dots)."),serial:h,deviceId:deviceIdInput}},async p=>{try{const{id:g,host:m,online:f}=await hostTarget(n,p.deviceId,{serial:p.serial},{allowOffline:true});if(m.platform==="ios-device"&&!await simHidTool())return fail2(PHONE_TOUCH);const v=fillSecrets(p.text);let y=false;if(m.platform==="android")await adbText(m.serial,v);else if(m.platform==="ios-device")await simHidType(await simHidTool(),await coreDeviceId(m.udid),v);else{const $=await simHidTool();if($){await simHidType($,m.udid,v);y=true}else{await assertSimTouchable(m.udid);await idb(["ui","text","--udid",m.udid,v])}}if(!y)await delay5(300);const b=f?await observeAfterAction(n,g):"";return text(`Typed ${JSON.stringify(p.text)} on the keyboard.${b}`)}catch(g){return fail2(errMsg2(g))}});e.registerTool("native_swipe",{_meta:coreTool(),description:"Swipe the screen for real (CoreDevice or idb on the iOS Simulator, adb on Android): scroll a list, dismiss a sheet, change a page. Give a direction (the way your finger moves) or from/to points as fractions of the screen. To reach the bottom of a list, pass untilEnd: true. It swipes again until the screen stops moving, in one call.",inputSchema:{direction:import_zod14.z.enum(["up","down","left","right"]).optional().describe('"up" scrolls content down the list (finger moves up).'),fromX:import_zod14.z.number().min(0).max(1).optional(),fromY:import_zod14.z.number().min(0).max(1).optional(),toX:import_zod14.z.number().min(0).max(1).optional(),toY:import_zod14.z.number().min(0).max(1).optional(),durationMs:import_zod14.z.number().min(50).max(5e3).optional().describe("Default 300 (1200 with drag)."),drag:import_zod14.z.boolean().optional().describe("Drag instead of flick: press, hold, then move (reorder handles, drag and drop, sliders). On the iOS Simulator with older Xcode (idb) it is a slow swipe only."),untilEnd:import_zod14.z.boolean().optional().describe("Keep swiping until the screen stops moving (the end of the list), up to 15 swipes. Returns the last screen."),allowBuoy:import_zod14.z.boolean().optional().describe("Swipe even if Buoy's own panel covers the starting point."),serial:h,deviceId:deviceIdInput}},async p=>{try{const{id:g,host:m,online:f}=await hostTarget(n,p.deviceId,{serial:p.serial},{allowOffline:true});freshScreen(m);await t(g,m,f);if(m.platform==="ios-device"&&!await simHidTool())return fail2(PHONE_TOUCH);const v=await r(m);let y;let b;if(p.fromX!=null&&p.fromY!=null&&p.toX!=null&&p.toY!=null){y=[p.fromX,p.fromY];b=[p.toX,p.toY]}else{({from:y,to:b}=swipePoints(p.direction??"up",!!p.untilEnd))}const $=[y[0]*v.width,y[1]*v.height];const T=[b[0]*v.width,b[1]*v.height];let _=0;if(p.drag&&m.platform==="android"){const S=Number((await adbShell(m.serial,"settings get secure long_press_timeout").catch(()=>"")).trim())||500;_=S*1.5+600}const x=Math.max(p.durationMs??(p.drag?1200:300),_);if(f&&!p.allowBuoy){const S=await a(g,m,{x:$[0],y:$[1]});if(S)return fail2(S)}if(p.untilEnd){if(p.drag)return fail2("untilEnd scrolls with flicks. Leave out drag.");if(!f)return fail2("untilEnd needs the app connected, to see when the list stops moving.");const S=await d(g,m,$,T,p.durationMs??250);const{swipes:k,atEnd:M}=S;const A=await observeAfterAction(n,g,void 0,0);const{lastRow:O}=S;return text(`${M?`Reached the end of the list after ${k} swipe(s)${O?`. The last row is "${O}"`:""}`:`Swiped ${k} times and the screen was still moving`}.${A}`)}const I=m.platform==="android"?null:await simHidTool();const D=await u(m,$,T,x,p.drag);await s(g,m,p.drag?"drag":"swipe",[$],[T],x+(p.drag&&I?700:0),D);await delay5(400);const E=f?await observeAfterAction(n,g):"";return text(`${p.drag?"Dragged":"Swiped"} from (${$.map(Math.round).join(", ")}) to (${T.map(Math.round).join(", ")}) ${w(m)}.${E}`)}catch(g){return fail2(errMsg2(g))}});e.registerTool("native_inspect",{description:"Read native controls on the screen. Pass pointX and pointY for points on iOS Sims, pixels elsewhere. Use x and y for screen fractions (0 to 1). Leave all points out to list controls, with types, labels, IDs, and frames. This includes tabs, alerts, and sheets. A point read also checks the app view and Buoy's cover. iOS Sims use idb; Android uses uiautomator. Real iPhones show just the app view.",inputSchema:{pointX:import_zod14.z.number().finite().min(0).optional().describe("From the left. iOS Sims use points. Other hosts use pixels."),pointY:import_zod14.z.number().finite().min(0).optional().describe("From the top. iOS Sims use points. Other hosts use pixels."),x:import_zod14.z.number().min(0).max(1).optional().describe("Horizontal position, 0 to 1."),y:import_zod14.z.number().min(0).max(1).optional().describe("Vertical position, 0 to 1."),serial:h,deviceId:deviceIdInput}},async p=>{try{const g=p.pointX!=null||p.pointY!=null;if(g&&(p.pointX==null||p.pointY==null))return fail2("Use pointX and pointY together.");if(g&&(p.x!=null||p.y!=null))return fail2("Use pointX/pointY or x/y, not both.");if(!g&&p.x==null!==(p.y==null))return fail2("Use x and y together.");const{id:m,host:f,online:v}=await hostTarget(n,p.deviceId,{serial:p.serial},{allowOffline:true});freshScreen(f);await t(m,f,v);const y=w(f);if(!g&&(p.x==null||p.y==null)){if(f.platform==="ios-device")return fail2("A physical iPhone doesn't share its native element tree with this Mac. Use describe_screen for the app's elements, or native_inspect with x and y to see what is at a point.");let _;let x=0;if(f.platform==="android"){const D=await adbUiNodes(f.serial);_=D.filter(E=>E.text||E.desc||E.id||E.clickable).map(E=>{const S=E.bounds;const k=[E.cls.split(".").pop(),E.text?JSON.stringify(E.text.slice(0,80)):"",E.desc?`desc=${JSON.stringify(E.desc.slice(0,60))}`:"",E.id?`id=${E.id.split("/").pop()}`:"",E.clickable?"(clickable)":""];return`${k.filter(Boolean).join(" ")} at (${S.x}, ${S.y}) ${S.width}x${S.height}`})}else{const{elements:D,screen:E}=await iosNativeElements(f.udid);const S=D.filter(k=>!E.width||k.frame.y<E.height&&k.frame.y+k.frame.height>0&&k.frame.x<E.width&&k.frame.x+k.frame.width>0);x=D.length-S.length;_=S.map(axLine)}const I=_.slice(0,150);return text([`${_.length} native element(s) on screen, top to bottom (${y}; frames are x, y, width x height)${x?`. ${x} more are scrolled out of view`:""}:`,...I.map(D=>`- ${D}`),..._.length>I.length?[`(${_.length-I.length} more not shown.)`]:[],"Tap one with native_tap label or x/y. For the app's React elements (testID, handlers), use describe_screen."].join("\n"))}let b;if(g){const _=await r(f);b={x:p.pointX,y:p.pointY};if(b.x>=_.width||b.y>=_.height){return fail2(`That point is outside the screen (${_.width} x ${_.height} ${y}).`)}}else{const _=await r(f);b={x:p.x*_.width,y:p.y*_.height}}const $=[g?`At (${Math.round(b.x)}, ${Math.round(b.y)}) ${y}:`:`At (${p.x.toFixed(2)}, ${p.y.toFixed(2)}) = (${Math.round(b.x)}, ${Math.round(b.y)}) ${y}:`];const T=v?o(m,f,b):Promise.resolve(null);if(f.platform==="android"){const _=(await adbUiNodes(f.serial)).filter(I=>{const D=I.bounds;return b.x>=D.x&&b.x<=D.x+D.width&&b.y>=D.y&&b.y<=D.y+D.height});const x=_.sort((I,D)=>I.bounds.width*I.bounds.height-D.bounds.width*D.bounds.height)[0];$.push(x?`- Native: ${x.cls.split(".").pop()}${x.text?` ${JSON.stringify(x.text.slice(0,80))}`:""}${x.desc?` desc=${JSON.stringify(x.desc.slice(0,60))}`:""}${x.id?` id=${x.id.split("/").pop()}`:""} at (${x.bounds.x}, ${x.bounds.y}) ${x.bounds.width}x${x.bounds.height}`:"- Native: nothing with a label or id here.")}else if(f.platform==="ios"){const _=JSON.parse(await idb(["ui","describe-point","--udid",f.udid,String(Math.round(b.x)),String(Math.round(b.y)),"--json"],5e3));$.push(_?.type&&_.frame?.width?`- Native: ${axLine(_)}`:"- Native: no accessible element here (plain views and canvases often have none).")}else{$.push("- Native: not available on a physical iPhone.")}if(!v)$.push("- App: not connected, so its views can't be read.");else{const _=await T;if(!_)$.push("- App: no answer (an older Buoy without hitTest, or the JS thread is busy).");else if(!_.found)$.push(`- App: ${_.reason??"no React view here (native UI, or outside the app's views)."}`);else{const x=_.view;const I=[x.name,x.testID?`testID=${x.testID}`:"",x.label?`label=${JSON.stringify(x.label)}`:"",x.text?JSON.stringify(x.text.slice(0,60)):""].filter(Boolean).join(" ");$.push(`- App: ${I}${_.path?.length?` in ${_.path.join(" < ")}`:""}.`);if(_.buoy)$.push("- This spot is Buoy's own overlay. A real touch here hits Buoy, not the app; close or minimize the panel first.");else if(_.target){const D=_.target;$.push(`- A tap here presses ${D.testID?`testID ${D.testID}`:JSON.stringify(D.text??D.label??D.name)} (${D.name}${D.nativeTag!=null?`, nativeTag ${D.nativeTag}`:""}).`)}else $.push("- Nothing tappable in the app here.")}}return text($.join("\n"))}catch(g){return fail2(errMsg2(g))}});e.registerTool("native_pinch",{description:"Pinch, spread or turn with two real fingers (CoreDevice on the iOS Simulator and a physical iPhone): zoom a map or photo, or rotate, in one call. scale above 1 zooms in (fingers spread), below 1 zooms out. The reply says how far a map turned and zoomed, read from the map itself. For other views it says how much of the area changed and shows it. No screenshot is needed. Not on Android or older Xcode, which can't send two fingers.",_meta:coreTool(),inputSchema:{x:import_zod14.z.number().min(0).max(1).optional().describe("Center between the fingers, 0 to 1. Default 0.5."),y:import_zod14.z.number().min(0).max(1).optional().describe("Center between the fingers, 0 to 1. Default 0.5."),scale:import_zod14.z.number().min(.1).max(10).optional().describe("How far the fingers spread: 2 doubles the gap (zoom in), 0.5 halves it (zoom out). Default 2."),rotate:import_zod14.z.number().min(-180).max(180).optional().describe("Turn the fingers this many degrees while pinching, clockwise. Default 0."),durationMs:import_zod14.z.number().min(100).max(5e3).optional().describe("Default 500."),allowBuoy:import_zod14.z.boolean().optional().describe("Pinch even if a finger starts on Buoy."),deviceId:deviceIdInput}},async p=>{try{const{id:g,host:m,online:f}=await hostTarget(n,p.deviceId,{},{allowOffline:true});freshScreen(m);await t(g,m,f);if(m.platform==="android")return fail2("Android's input command sends one finger only, so Buoy can't pinch there yet. Use the app's zoom buttons, or native_swipe for one-finger moves.");const v=await simHidTool();if(!v)return fail2(m.platform==="ios-device"?PHONE_TOUCH:"Pinching needs Xcode's CoreDevice touch support (Xcode 26 or later); idb sends one finger only.");const y=await r(m);const b=[(p.x??.5)*y.width,(p.y??.5)*y.height];const $=p.scale??2;const T=Math.min(y.width,y.height);const _=T*.4;const x=$>=1?Math.max(T*.04,_/$):_;const I=$>=1?_:Math.max(T*.04,_*$);const D=(p.rotate??0)*Math.PI/180;const E=G=>[Math.min(y.width-1,Math.max(1,G[0])),Math.min(y.height-1,Math.max(1,G[1]))];const S=(G,K)=>[E([b[0]-G*Math.cos(K),b[1]-G*Math.sin(K)]),E([b[0]+G*Math.cos(K),b[1]+G*Math.sin(K)])];const[k,M]=S(x,0);const[A,O]=S(I,D);if(f&&!p.allowBuoy){for(const[G,K]of[k,M]){const ie=await a(g,m,{x:G,y:K});if(ie)return fail2(ie)}}const R=p.durationMs??500;const j={x:Math.max(0,(b[0]-_)/y.width),y:Math.max(0,(b[1]-_)/y.height),width:Math.min(1,2*_/y.width),height:Math.min(1,2*_/y.height)};const C=f?await readMaps(n,g):[];const P=G=>G.find(K=>!K.frame||(p.x??.5)>=K.frame.x&&(p.x??.5)<=K.frame.x+K.frame.width&&(p.y??.5)>=K.frame.y&&(p.y??.5)<=K.frame.y+K.frame.height);const N=P(C);const z=N?null:await hostPng(m).catch(()=>null);const F=m.platform==="ios-device"?await coreDeviceId(m.udid):m.udid;const B=await simHidTwo(v,F,{...y,bundleId:m.platform==="ios"?m.bundleId:null},k,M,A,O,R);await s(g,m,"pinch",[k,M],[A,O],R,B);await delay5(400);const[U,L,H]=await Promise.all([f?observeAfterAction(n,g,void 0,0):Promise.resolve(""),z?hostPng(m).catch(()=>null):Promise.resolve(null),N?readMaps(n,g):Promise.resolve([])]);const W=I/x;const J=W>1.01?`Spread (zoom in, x${W.toFixed(2)})`:W<.99?`Pinched (zoom out, x${W.toFixed(2)})`:"Turned";const V=`${J}${p.rotate?`, turning ${p.rotate} degrees,`:""} around (${Math.round(b[0])}, ${Math.round(b[1])}) ${w(m)} with two real fingers.`;const ae=N?H.find(G=>G.name===N.name&&G.testID===N.testID):void 0;const re=N&&ae?mapChange(N,ae):null;if(re)return text(`${V}
642
642
  ${re}${U}`);const ee=z&&L?await pinchProof(z,L,j):null;if(!ee)return text(`${V}${U}`);return{content:[{type:"text",text:`${V}
643
643
  ${ee.line}${U}`},{type:"image",data:ee.image.data,mimeType:ee.image.mimeType}]}}catch(g){return fail2(errMsg2(g))}})}async function pinchProof(e,n,t){try{const r=cropPng(e,t);const i=cropPng(n,t);const{percent:o}=diffScreens(r,i);const a=o<2?`Checked: the area under the fingers looks the same as before (${o.toFixed(1)}% changed). The pinch did not move anything there.`:`Checked: ${o.toFixed(0)}% of the area under the fingers changed, so it moved. It looks like this now:`;return{line:a,image:await toSmallImage(i,480)}}catch{return null}}async function readMaps(e,n){try{const t=await e.callAction(UI_TOOL_ID2,"readMaps",{},n,{timeoutMs:2e3,silent:true});return t?.maps??[]}catch{return[]}}function mapChange(e,n){const t=`The map${e.testID?` [${e.testID}]`:""}`;const r=[];const i=e.camera.heading,o=n.camera.heading;if(typeof i==="number"&&typeof o==="number"){const d=p=>(p%360+360)%360;const h=p=>Math.round(Math.min(d(p),360-d(p)));const w=Math.round(Math.abs((d(o)-d(i)+540)%360-180));r.push(`heading ${Math.round(d(i))}\xB0 before, ${Math.round(d(o))}\xB0 now (turned ${w}\xB0, now ${h(o)}\xB0 from north)`)}const a=e.camera.altitude,s=n.camera.altitude;const c=e.camera.zoom,l=n.camera.zoom;const u=typeof a==="number"&&typeof s==="number"&&a>0&&s>0?a/s:typeof c==="number"&&typeof l==="number"?Math.pow(2,l-c):null;if(u!=null&&Number.isFinite(u)){const d=u*u;const h=u>1.01?`zoomed in x${u.toFixed(2)}, so it shows about 1/${d.toFixed(1)} of the area it did`:u<.99?`zoomed out x${(1/u).toFixed(2)}, so it shows about ${d>0?(1/d).toFixed(1):"?"} times the area`:"same zoom";const w=typeof a==="number"&&typeof s==="number"?` (altitude ${Math.round(a).toLocaleString("en-US")} m to ${Math.round(s).toLocaleString("en-US")} m)`:typeof c==="number"&&typeof l==="number"?` (zoom ${c.toFixed(1)} to ${l.toFixed(1)})`:"";r.push(`${h}${w}`)}return r.length?`Checked in the app: ${t} ${r.join("; ")}.`:null}var TOOL_ID2="highlight-updates";var text3=e=>({content:[{type:"text",text:e}]});var fail5=e=>({isError:true,content:[{type:"text",text:e}]});var errMsg5=e=>e instanceof Error?e.message:String(e);var delay6=e=>new Promise(n=>setTimeout(n,e));var OBSERVE_MAX=40;async function observeAfterAction(e,n,t,r=300){let i="";for(let a=0;a<(t?6:1);a++){await delay6(a===0?r:250);try{const s=await e.callAction("route-events","getCurrentRoute",{},n,{timeoutMs:3e3,silent:true});i=String(s?.pathname??s?.path??"")}catch{break}if(!t||i.replace(/\(.*?\)\//g,"").replace(/\/$/,"")===t.replace(/\/$/,"")||i.endsWith(t))break}let o="";try{const a=await e.callAction(TOOL_ID2,"describeScreen",{},n,{timeoutMs:5e3,silent:true});const s=a?.elements??[];const c=new Set(s.filter(g=>g.name!=="Text").map(g=>g.text??g.label).filter(Boolean));const l=s.filter(g=>g.name!=="Text"&&g.tap&&(g.text??g.label));const u=(g,m)=>!!g.tap&&l.some(f=>Math.abs(f.tap.y-g.tap.y)<.06&&(f.text??f.label).includes(m));const d=s.filter(g=>{const m=g.text??g.label;if(g.name==="Text"&&(!m||/^[\s\uE000-\uF8FF]*$/.test(m)))return false;if(g.name==="Text"&&c.has(m))return false;if(g.name==="Text"&&m&&u(g,m))return false;return true});const h=g=>!g.tap||g.tap.x>=0&&g.tap.x<=1&&g.tap.y>=0&&g.tap.y<=1;const w=[...d.filter(h),...d.filter(g=>!h(g))];const p=w.slice(0,OBSERVE_MAX);o=p.map(formatElement).join("\n");if(w.length>p.length)o+=`
644
644
  \u2026 ${w.length-p.length} more (describe_screen lists everything)`}catch{o="(could not read the screen)"}return`
@@ -739,7 +739,8 @@ The simulator camera itself is free \u2014 the Mac camera, image, video, test-pa
739
739
 
740
740
  _Tell the user to enter a licence in Buoy Desktop, or see https://buoy.gg/pricing. Don't try to work around it \u2014 use the desktop panel by hand instead._`}var text6=e=>({content:[{type:"text",text:e}]});var gate=e=>readEntitlement().isPro?null:fail8(proRequired(e));var fail8=e=>({isError:true,content:[{type:"text",text:e}]});function registerCameraTools(e){e.registerTool("camera_source",{description:"Give the iOS Simulator a camera, and choose what it shows. Use this before testing anything that opens a camera \u2014 a QR or barcode scanner, document capture, an avatar picker. `barcode` generates the code from text, so testing a scanner needs no printed code and no second device; pdf417 is the barcode on a driver's licence. `screen` points the phone's camera at this Mac's screen. Needs no Buoy integration in the app under test.",inputSchema:{kind:import_zod25.z.enum(["barcode","image","video","camera","screen","pattern"]).describe("What the camera should show."),value:import_zod25.z.string().optional().describe("Text for `barcode`, a file path for `image`/`video`, a camera uniqueId for `camera` (see `camera_inputs`), or one of `behind` / `display` / `window:<id>` / `region:<id>[:<gutter>]` for `screen`."),format:import_zod25.z.enum(["qr","pdf417","aztec","code128"]).optional().describe("Barcode symbology; defaults to qr.")}},async n=>{const t=gate("camera_source");if(t)return t;const r=["source",n.kind];if(n.value)r.push(n.value);if(n.format)r.push("--format",n.format);const i=await run3(r);if(!i.ok){return fail8(i.error??i.data?.error??"could not set the camera source")}const o=n.kind==="barcode"?`a ${n.format??"qr"} code reading "${n.value}"`:n.kind==="screen"?`this Mac's screen (${n.value??"behind the simulator window"})`:n.value??n.kind;return text6(`The simulator camera is now showing ${o}, at ${i.data?.fps??0} fps.
741
741
 
742
- _Apps already running do not pick up a camera they started without \u2014 use \`camera_launch\` to relaunch one, or \`camera_zero_setup\` so that anything the simulator launches gets it._`)});e.registerTool("camera_status",{description:"Check what the simulator camera is doing and what it is currently decoding. Use this to confirm a scanner test is actually seeing a code before concluding the app is broken.",inputSchema:{}},async()=>{const n=gate("camera_status");if(n)return n;const t=await run3(["status"]);if(!t.ok||!t.data){return fail8(t.error??"could not read the simulator camera status")}const{publishing:r,fps:i,codes:o}=t.data;if(!r){return text6("The simulator camera is not publishing anything.\n\n_Set a source with `camera_source` first._")}return text6([`Publishing at ${i} fps.`,o.length?`Currently decoding: ${o.map(a=>`\`${a}\``).join(", ")}`:"No barcode in the current frame.","","_A code shown here is what the app receives. If the app is not reacting to it, the problem is in the app, not the camera \u2014 `camera_diagnose` will say whether the app is even reading the feed._"].join("\n"))});e.registerTool("camera_launch",{description:"Relaunch a simulator app with the camera attached. A camera can only be attached when a process starts, so an app that is already running cannot be given one \u2014 this terminates and relaunches it.",inputSchema:{bundleId:import_zod25.z.string().describe("The app's bundle identifier."),udid:import_zod25.z.string().optional().describe("Simulator udid, if more than one is booted.")}},async n=>{const t=gate("camera_launch");if(t)return t;const r=["launch",n.bundleId];if(n.udid)r.push("--udid",n.udid);const i=await run3(r);if(!i.ok){return fail8(i.error??i.data?.error??"could not launch the app")}return text6(`Relaunched \`${n.bundleId}\` with the camera attached${i.data?.pid?` (pid ${i.data.pid})`:""}.`)});e.registerTool("camera_diagnose",{description:"Work out why the simulator camera is not working. Checks that the pieces are present, a simulator is booted, something is publishing, SOMETHING IS READING IT, the library is loaded in the target app, no other tool owns the injection, and no camera library in the project disables simulator cameras at compile time.",inputSchema:{bundleId:import_zod25.z.string().optional().describe("Check a specific app \u2014 whether the library is actually loaded in it.")}},async n=>{const t=["diagnose"];if(n.bundleId)t.push(n.bundleId);const r=await run3(t);if(!r.data?.checks){return fail8(r.error??"could not run the simulator camera diagnosis")}const i=readEntitlement();const o=i.isPro?"":"\n\n_This install is on the **free** tier, so the other `camera_*` tools are blocked. The camera still works by hand in the Buoy desktop panel._";return text6(describeDiagnosis(r.data.checks)+o)});e.registerTool("camera_stop",{description:"Turn the simulator camera off and stop publishing frames. The camera stays on until stopped \u2014 across app relaunches and after a test finishes \u2014 so call this when done, or the next thing that opens a camera will still see the last source.",inputSchema:{}},async()=>{const n=gate("camera_stop");if(n)return n;const t=await run3(["stop"]);if(!t.ok){return fail8(t.error??t.data?.error??"could not stop the camera")}return text6("The simulator camera is off.")});e.registerTool("camera_devices",{description:"List booted simulators and the apps installed on one. Use this to find the bundle id `camera_launch` needs, or the udid to pass when more than one simulator is booted. Lists every app on the simulator, not just Buoy-integrated ones \u2014 the camera works on any of them.",inputSchema:{udid:import_zod25.z.string().optional().describe("Which simulator's apps to list. Only needed when several are booted.")}},async n=>{const t=gate("camera_devices");if(t)return t;const r=await run3(["devices"]);if(!r.ok||!r.data){return fail8(r.error??"could not list booted simulators")}const i=r.data.devices??[];let o=null;if(i.length===1||n.udid){const a=await run3(["apps",...n.udid?["--udid",n.udid]:[]]);o=a.ok?a.data?.apps??[]:null}return text6(describeDevices(i,o))});e.registerTool("camera_inputs",{description:"List what this Mac can point the simulator camera at: its webcams (the uniqueId for `camera_source` with kind `camera`) and the windows the screen source can film (the id for `window:<id>`). Call this before choosing a `camera` or windowed `screen` source \u2014 those ids cannot be guessed.",inputSchema:{}},async()=>{const n=gate("camera_inputs");if(n)return n;const[t,r]=await Promise.all([run3(["cameras"]),run3(["windows"])]);if(!t.ok&&!r.ok){return fail8(t.error??r.error??"could not list the Mac's cameras or windows")}return text6(describeInputs(t.data?.cameras??[],r.data?.windows??[]))});e.registerTool("camera_zero_setup",{description:"Make every app the simulator launches get a camera, however it was launched \u2014 `expo start`, `react-native run-ios`, Xcode, a test runner. Use this when you are not the one starting the app, so `camera_launch` is not an option. It loads Buoy's library into every process in that simulator, SpringBoard included, so turn it off when finished.",inputSchema:{action:import_zod25.z.enum(["on","off","status"]).describe("Turn it on, off, or report the current state."),udid:import_zod25.z.string().optional().describe("Which simulator. Only needed when several are booted.")}},async n=>{const t=gate("camera_zero_setup");if(t)return t;const r=await run3(["zero-setup",n.action,...n.udid?["--udid",n.udid]:[]]);if(!r.ok){return fail8(r.error??r.data?.error??"could not change zero-setup mode")}const i=r.data??{};if(n.action==="status"){if(!i.enabled)return text6("Zero-setup mode is **off**.");return text6(i.foreign?`Zero-setup is on, but **another tool owns it** (\`${i.path}\`). Quit that tool before turning Buoy's on.`:"Zero-setup mode is **on** \u2014 anything this simulator launches gets the camera.")}if(n.action==="on"){return text6("Zero-setup mode is **on**. Anything this simulator launches from now on gets the camera \u2014 start your app however you normally would.\n\n_This loads the library into every process in the simulator. Turn it off with `camera_zero_setup` action `off` when you are done._")}return text6("Zero-setup mode is **off**.")})}var import_zod26=require("zod");var import_node_module=require("module");var import_node_child_process17=require("child_process");var import_node_path15=require("path");var import_node_fs14=require("fs");var import_node_os11=require("os");var import_node_url=require("url");var START_PROBE_JS=`(() => {
742
+ _Apps already running do not pick up a camera they started without \u2014 use \`camera_launch\` to relaunch one, or \`camera_zero_setup\` so that anything the simulator launches gets it._`)});e.registerTool("camera_status",{description:"Check what the simulator camera is doing and what it is currently decoding. Use this to confirm a scanner test is actually seeing a code before concluding the app is broken.",inputSchema:{}},async()=>{const n=gate("camera_status");if(n)return n;const t=await run3(["status"]);if(!t.ok||!t.data){return fail8(t.error??"could not read the simulator camera status")}const{publishing:r,fps:i,codes:o}=t.data;if(!r){return text6("The simulator camera is not publishing anything.\n\n_Set a source with `camera_source` first._")}return text6([`Publishing at ${i} fps.`,o.length?`Currently decoding: ${o.map(a=>`\`${a}\``).join(", ")}`:"No barcode in the current frame.","","_A code shown here is what the app receives. If the app is not reacting to it, the problem is in the app, not the camera \u2014 `camera_diagnose` will say whether the app is even reading the feed._"].join("\n"))});e.registerTool("camera_launch",{description:"Relaunch a simulator app with the camera attached. A camera can only be attached when a process starts, so an app that is already running cannot be given one \u2014 this terminates and relaunches it.",inputSchema:{bundleId:import_zod25.z.string().describe("The app's bundle identifier."),udid:import_zod25.z.string().optional().describe("Simulator udid, if more than one is booted.")}},async n=>{const t=gate("camera_launch");if(t)return t;const r=["launch",n.bundleId];if(n.udid)r.push("--udid",n.udid);const i=await run3(r);if(!i.ok){return fail8(i.error??i.data?.error??"could not launch the app")}return text6(`Relaunched \`${n.bundleId}\` with the camera attached${i.data?.pid?` (pid ${i.data.pid})`:""}.`)});e.registerTool("camera_diagnose",{description:"Work out why the simulator camera is not working. Checks that the pieces are present, a simulator is booted, something is publishing, SOMETHING IS READING IT, the library is loaded in the target app, no other tool owns the injection, and no camera library in the project disables simulator cameras at compile time.",inputSchema:{bundleId:import_zod25.z.string().optional().describe("Check a specific app \u2014 whether the library is actually loaded in it.")}},async n=>{const t=["diagnose"];if(n.bundleId)t.push(n.bundleId);const r=await run3(t);if(!r.data?.checks){return fail8(r.error??"could not run the simulator camera diagnosis")}const i=readEntitlement();const o=i.isPro?"":"\n\n_This install is on the **free** tier, so the other `camera_*` tools are blocked. The camera still works by hand in the Buoy desktop panel._";return text6(describeDiagnosis(r.data.checks)+o)});e.registerTool("camera_stop",{description:"Turn the simulator camera off and stop publishing frames. The camera stays on until stopped \u2014 across app relaunches and after a test finishes \u2014 so call this when done, or the next thing that opens a camera will still see the last source.",inputSchema:{}},async()=>{const n=gate("camera_stop");if(n)return n;const t=await run3(["stop"]);if(!t.ok){return fail8(t.error??t.data?.error??"could not stop the camera")}return text6("The simulator camera is off.")});e.registerTool("camera_devices",{description:"List booted simulators and the apps installed on one. Use this to find the bundle id `camera_launch` needs, or the udid to pass when more than one simulator is booted. Lists every app on the simulator, not just Buoy-integrated ones \u2014 the camera works on any of them.",inputSchema:{udid:import_zod25.z.string().optional().describe("Which simulator's apps to list. Only needed when several are booted.")}},async n=>{const t=gate("camera_devices");if(t)return t;const r=await run3(["devices"]);if(!r.ok||!r.data){return fail8(r.error??"could not list booted simulators")}const i=r.data.devices??[];let o=null;if(i.length===1||n.udid){const a=await run3(["apps",...n.udid?["--udid",n.udid]:[]]);o=a.ok?a.data?.apps??[]:null}return text6(describeDevices(i,o))});e.registerTool("camera_inputs",{description:"List what this Mac can point the simulator camera at: its webcams (the uniqueId for `camera_source` with kind `camera`) and the windows the screen source can film (the id for `window:<id>`). Call this before choosing a `camera` or windowed `screen` source \u2014 those ids cannot be guessed.",inputSchema:{}},async()=>{const n=gate("camera_inputs");if(n)return n;const[t,r]=await Promise.all([run3(["cameras"]),run3(["windows"])]);if(!t.ok&&!r.ok){return fail8(t.error??r.error??"could not list the Mac's cameras or windows")}return text6(describeInputs(t.data?.cameras??[],r.data?.windows??[]))});e.registerTool("camera_zero_setup",{description:"Make every app the simulator launches get a camera, however it was launched \u2014 `expo start`, `react-native run-ios`, Xcode, a test runner. Use this when you are not the one starting the app, so `camera_launch` is not an option. It loads Buoy's library into every process in that simulator, SpringBoard included, so turn it off when finished.",inputSchema:{action:import_zod25.z.enum(["on","off","status"]).describe("Turn it on, off, or report the current state."),udid:import_zod25.z.string().optional().describe("Which simulator. Only needed when several are booted.")}},async n=>{const t=gate("camera_zero_setup");if(t)return t;const r=await run3(["zero-setup",n.action,...n.udid?["--udid",n.udid]:[]]);if(!r.ok){return fail8(r.error??r.data?.error??"could not change zero-setup mode")}const i=r.data??{};if(n.action==="status"){if(!i.enabled)return text6("Zero-setup mode is **off**.");return text6(i.foreign?`Zero-setup is on, but **another tool owns it** (\`${i.path}\`). Quit that tool before turning Buoy's on.`:"Zero-setup mode is **on** \u2014 anything this simulator launches gets the camera.")}if(n.action==="on"){return text6("Zero-setup mode is **on**. Anything this simulator launches from now on gets the camera \u2014 start your app however you normally would.\n\n_This loads the library into every process in the simulator. Turn it off with `camera_zero_setup` action `off` when you are done._")}return text6("Zero-setup mode is **off**.")})}var import_zod26=require("zod");init_src();var text7=e=>({content:[{type:"text",text:e}]});var fail9=e=>({isError:true,content:[{type:"text",text:e}]});var json3=e=>text7(JSON.stringify(e,null,2));var gate2=e=>readEntitlement().isPro?null:fail9(proRequired(e));var client=null;function farm(){if(!client){client=connectFarm({label:process.env.BUOY_AGENT_LABEL||"Buoy MCP",launcher:nodeLauncher(process.argv[1],["farmd"])}).catch(e=>{client=null;throw e})}return client}async function call(e,n,t,r){return(await farm()).call(e,n,{timeoutMs:t,requestId:r})}function explain(e){if(e instanceof FarmError)return fail9(`${e.code}: ${e.message}${e.next?`
743
+ Next: ${e.next}`:""}`);return fail9(`Sim Farm error: ${e?.message??e}`)}var leaseFields={leaseId:import_zod26.z.string().describe("The lease id from sim_farm_acquire."),epoch:import_zod26.z.number().int().describe("The epoch from sim_farm_acquire. A stale epoch is refused.")};var requestId=import_zod26.z.string().optional().describe("Any unique string for this call. Repeating the same call with the same requestId returns the first result instead of acting twice.");function registerSimFarmTools(e){e.registerTool("sim_farm_status",{description:"Show the Sim Farm: how many farm simulators exist, which are awake or in use and by whom, free memory and disk, how many more sims fit, templates, leases, and recent events. Farm sims are slim iOS simulators (about 1.5 GB each instead of 5) that the farm makes from a template. Start here before sim_farm_acquire. Set `outside` to also list this Mac's other simulators, which the farm never touches.",inputSchema:{outside:import_zod26.z.boolean().optional().describe("Also list simulators the farm does not own.")}},async({outside:n})=>{try{return json3(await call("status",{outside:!!n}))}catch(t){return explain(t)}});e.registerTool("sim_farm_setup",{description:"Create or resize the Sim Farm. `create` makes a template sim from an app build and a seed folder (signed-in app data); clones are made from it in about 4 s each. `grow` / `shrink` change how many sims exist. Use `dryRun` first: it returns the plan, what slim mode turns off (push, StoreKit, app links, widgets, Spotlight\u2026) and whether the Mac has room.",inputSchema:{mode:import_zod26.z.enum(["create","grow","shrink"]).describe("create = new template; grow/shrink = pool size."),templateId:import_zod26.z.string().optional().describe("For grow/shrink. Defaults to the newest usable template."),count:import_zod26.z.number().int().min(1).max(40).optional().describe("For grow/shrink: how many sims to add or remove."),appPath:import_zod26.z.string().optional().describe("For create: path to a simulator .app build."),seedDir:import_zod26.z.string().optional().describe("For create: seed folder (Documents/, AsyncStorage/, seed.json)."),deviceType:import_zod26.z.string().optional().describe("For create: a simctl device type id. Default iPhone 17 Pro."),runtime:import_zod26.z.string().optional().describe("For create: a simctl runtime id. Default iOS 26.3."),profile:import_zod26.z.enum(["slim","stock"]).optional().describe("For create: slim (default) or stock."),metroPort:import_zod26.z.number().int().optional().describe("For create: the Metro port the app loads from. Default 8802."),dryRun:import_zod26.z.boolean().optional().describe("Return the plan and its cost without changing anything."),requestId}},async n=>{const t=gate2("sim_farm_setup");if(t)return t;try{if(n.mode==="create"){const o={appPath:n.appPath,seedDir:n.seedDir,deviceType:n.deviceType??"com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",runtime:n.runtime??"com.apple.CoreSimulator.SimRuntime.iOS-26-3",profile:n.profile??"slim",metroPort:n.metroPort??8802};if(!o.appPath||!o.seedDir)return fail9("create needs appPath and seedDir.");if(n.dryRun)return json3({wouldCreateTemplate:o,budget:await call("budget",{ramGB:6,diskGB:4})});return json3(await call("setup",o,15*6e4,n.requestId))}let r=n.templateId;if(!r){const o=await call("status");r=o.templates.filter(a=>a.usable).pop()?.id;if(!r)return fail9("No usable template yet. Run sim_farm_setup with mode create first.")}const i=n.count??1;if(n.dryRun){const o=await call("budget",{ramGB:0,diskGB:n.mode==="grow"?2*i:0});return json3({mode:n.mode,templateId:r,count:i,roomForMoreSims:o.roomFor,ok:o.ok,reason:o.reason})}return json3(await call(n.mode,{templateId:r,count:i},30*6e4,n.requestId))}catch(r){return explain(r)}});e.registerTool("sim_farm_acquire",{description:"Take farm simulators for your work. Returns a lease (leaseId + epoch) and exact sims (UDID, name, and buoyDeviceId once the app ran: the 8-character tail that its list_devices id ends with). Parked sims are booted and new ones cloned as needed, within the Mac's memory and disk limits. This MCP keeps the lease alive while it runs; release it with sim_farm_release when done. Only ever target the returned UDIDs: never `booted`, which picks a random simulator when many run.",inputSchema:{count:import_zod26.z.number().int().min(1).max(40).describe("How many sims."),purpose:import_zod26.z.string().describe("Shown to the person in Buoy Desktop, e.g. 'optimize: list variants'."),templateId:import_zod26.z.string().optional().describe("Defaults to the newest usable template."),launch:import_zod26.z.boolean().optional().describe("Launch the app on each sim and wait for its Buoy id."),allowPartial:import_zod26.z.boolean().optional().describe("Return fewer sims than asked instead of failing."),waitSeconds:import_zod26.z.number().int().min(0).max(1800).optional().describe("Wait this long for sims to free up."),ttlMinutes:import_zod26.z.number().int().min(1).max(1440).optional().describe("Hard limit on the lease's life. Default 15."),requestId}},async n=>{const t=gate2("sim_farm_acquire");if(t)return t;try{let r=n.templateId;if(!r){const a=await call("status");r=a.templates.filter(s=>s.usable).pop()?.id;if(!r)return fail9("No usable template yet. Run sim_farm_setup with mode create first.")}const i=await farm();const o=await i.acquire({templateId:r,count:n.count,purpose:n.purpose,launch:n.launch,allowPartial:n.allowPartial,waitMs:(n.waitSeconds??0)*1e3,ttlMs:(n.ttlMinutes??15)*6e4,requestId:n.requestId});return json3(o)}catch(r){return explain(r)}});e.registerTool("sim_farm_release",{description:"Give farm sims back. `fast` (default) stops the app and restores its seeded data in about 2 s; `full` rebuilds each sim from the template. Use `full` after anything changed OS settings (permissions, keychain, location) or after a crash.",inputSchema:{...leaseFields,reset:import_zod26.z.enum(["fast","full"]).optional()}},async n=>{try{const t=await farm();return json3(await t.release(n.leaseId,n.epoch,n.reset??"fast"))}catch(t){return explain(t)}});e.registerTool("sim_farm_action",{description:"Act on sims in your lease: `screenshot` (returns file paths), `open-url` (deep link, pass `url`), `launch` the app, `reset` (restore seeded app data), or `rebuild` (fresh clone; the UDID changes, the result maps old to new).",inputSchema:{...leaseFields,udids:import_zod26.z.array(import_zod26.z.string()).min(1).describe("UDIDs from your lease."),action:import_zod26.z.enum(["screenshot","open-url","launch","reset","rebuild"]),url:import_zod26.z.string().optional().describe("For open-url."),requestId}},async n=>{const t=gate2("sim_farm_action");if(t)return t;try{return json3(await call("action",{leaseId:n.leaseId,epoch:n.epoch,udids:n.udids,action:n.action,arg:n.url},10*6e4,n.requestId))}catch(r){return explain(r)}});e.registerTool("sim_farm_lock",{description:"Hold or free a Mac-wide lock tied to your lease. `perf-slot` is for fair speed tests: while you hold it the farm boots, clones and screenshots nothing else, so measure only then. Other names guard shared test fixtures (e.g. `ask-buoy-gateway`, `shop`). Locks end with the lease.",inputSchema:{...leaseFields,name:import_zod26.z.string().regex(/^[a-z0-9-]{1,40}$/).describe("Lock name, e.g. perf-slot."),hold:import_zod26.z.boolean().describe("true = take it, false = free it."),waitSeconds:import_zod26.z.number().int().min(0).max(1800).optional()}},async n=>{const t=gate2("sim_farm_lock");if(t)return t;try{const r={leaseId:n.leaseId,epoch:n.epoch,name:n.name,waitMs:(n.waitSeconds??0)*1e3};return json3(await call(n.hold?"lock":"unlock",r,(n.waitSeconds??0)*1e3+3e4))}catch(r){return explain(r)}})}var import_zod27=require("zod");var import_node_module=require("module");var import_node_child_process19=require("child_process");var import_node_path21=require("path");var import_node_fs22=require("fs");var import_node_os14=require("os");var import_node_url=require("url");var START_PROBE_JS=`(() => {
743
744
  const supported = (t) => {
744
745
  try { return (PerformanceObserver.supportedEntryTypes || []).includes(t); } catch { return false; }
745
746
  };
@@ -883,8 +884,8 @@ _Apps already running do not pick up a camera they started without \u2014 use \`
883
884
  const ext = gl.getExtension("WEBGL_debug_renderer_info");
884
885
  return String(gl.getParameter(ext ? ext.UNMASKED_RENDERER_WEBGL : gl.RENDERER));
885
886
  } catch { return null; }
886
- })()`;function isSoftwareGpu(e){return/swiftshader|llvmpipe|softpipe|software|microsoft basic render/i.test(e)}function percentile(e,n){if(e.length===0)return null;const t=[...e].sort((i,o)=>i-o);const r=Math.ceil(n/100*t.length)-1;return t[Math.min(t.length-1,Math.max(0,r))]}var COMMON_RATES=[30,60,75,90,120,144,165,240];function snapRefreshRate(e){for(const n of COMMON_RATES)if(Math.abs(e-n)/n<=.08)return n;return Math.max(1,Math.round(e))}function shuffled(e,n){let t=n>>>0;const r=()=>{t=t+1831565813>>>0;let o=t;o=Math.imul(o^o>>>15,o|1);o^=o+Math.imul(o^o>>>7,o|61);return((o^o>>>14)>>>0)/4294967296};const i=[...e];for(let o=i.length-1;o>0;o--){const a=Math.floor(r()*(o+1));[i[o],i[a]]=[i[a],i[o]]}return i}function caseUrl(e,n,t){const r=new URL(e);const i=n.path??t;if(i)r.pathname=i.startsWith("/")?i:`${r.pathname.replace(/\/$/,"")}/${i}`;for(const[o,a]of Object.entries(n.params??{}))r.searchParams.set(o,a);return r.toString()}var FRAME_STATES=["STATE_PRESENTED_ALL","STATE_PRESENTED_PARTIAL","STATE_DROPPED"];function summarizeFrameTrace(e){const n=w=>e.find(p=>p.name===w&&p.ts!=null);const t=n("__buoy_bench_start");const r=n("__buoy_bench_end");if(!t||!r||r.ts<=t.ts)return null;if(t.pid!==r.pid)return null;const i=t.pid;const o={STATE_PRESENTED_ALL:0,STATE_PRESENTED_PARTIAL:1,STATE_DROPPED:2};const a=new Map;for(const w of e){if(w.name!=="PipelineReporter"||w.ph!=="b")continue;if(i!=null&&w.pid!==i)continue;if(w.ts==null||w.ts<t.ts||w.ts>r.ts)continue;const p=w.args?.frame_reporter;if(!p||p.frame_sequence==null)continue;const g=p.state;if(!FRAME_STATES.includes(g))continue;const m=`${p.layer_tree_host_id??""}:${p.frame_source??""}:${p.frame_sequence}`;const f=Boolean(p.affects_smoothness)&&g!=="STATE_PRESENTED_ALL";const v=a.get(m);if(!v)a.set(m,{state:g,fault:f});else{if(o[g]>o[v.state])v.state=g;v.fault=v.fault||f}}let s=0;let c=0;let l=0;let u=0;for(const w of a.values()){if(w.state==="STATE_PRESENTED_ALL")s++;else if(w.state==="STATE_PRESENTED_PARTIAL")c++;else l++;if(w.fault)u++}const d=s+c+l;if(d===0)return null;const h=(r.ts-t.ts)/1e6;return{full:s,partial:c,dropped:l,faults:u,shownFps:r1((s+c)/h),droppedPct:r1(u/d*100)}}function keyMatches(e,n){const t=e.split("+");const r=t[t.length-1];const i=new Set(t.slice(0,-1).map(s=>s.toLowerCase()));if(n.key!==r)return false;const o=r.toLowerCase();const a={ctrl:i.has("control")||o==="control",alt:i.has("alt")||o==="alt",meta:i.has("meta")||i.has("command")||o==="meta",shift:i.has("shift")||o==="shift"};if(Boolean(n.ctrl)!==a.ctrl||Boolean(n.alt)!==a.alt||Boolean(n.meta)!==a.meta)return false;if(!a.shift&&n.shift&&r.length!==1)return false;if(a.shift&&!n.shift)return false;return true}function mergeInteractions(e){const n=[];for(const t of e){const r=t.startTime+t.duration;const i=n.find(a=>a.interactionId===t.interactionId&&Math.abs(a.startTime+a.duration-r)<=8);if(!i){n.push({...t});continue}const o=i.startTime+i.duration;i.startTime=Math.min(i.startTime,t.startTime);i.processingStart=Math.min(i.processingStart,t.processingStart);i.processingEnd=Math.max(i.processingEnd,t.processingEnd);i.duration=Math.max(o,r)-i.startTime;if(t.processingEnd-t.processingStart>0)i.name=t.name}return n}function summarizeProbe(e,n){const{start:t,end:r}=e;const i=Math.max(1,r-t);const o=[];for(let _=1;_<e.frames.length;_++)o.push(e.frames[_]-e.frames[_-1]);const a=1e3/n;const s=percentile(o,95);let c=null;if(e.longTasks){let _=0;for(const x of e.longTasks){const A=Math.min(x.end,r)-Math.max(x.start,t);if(A>0)_+=A}c=r1(Math.min(100,_/i*100))}let l=null;let u=null;let d=null;let h=[];let w=0;if(e.loaf){let _=0;let x=0;let A=0;const I=new Map;for(const E of e.loaf){if(E.startTime>=t&&E.startTime<=r&&E.startTime+E.duration>r)w++;if(E.startTime<t||E.startTime+E.duration>r)continue;_+=E.blockingDuration;if(E.styleAndLayoutStart>E.startTime)x+=Math.max(0,E.startTime+E.duration-E.styleAndLayoutStart);for(const S of E.scripts){A+=S.forced;const k=I.get(S.name)??{ms:0,count:0};k.ms+=S.duration;k.count++;I.set(S.name,k)}}l=r1(_);u=r1(x);d=r1(A);h=[...I.entries()].map(([E,S])=>({name:E,ms:r1(S.ms),count:S.count})).sort((E,S)=>S.ms-E.ms).slice(0,5)}let p=null;if(e.shifts){let _=0;for(const x of e.shifts)if(!x.hadRecentInput&&x.startTime>=t&&x.startTime<=r)_+=x.value;p=Math.round(_*1e3)/1e3}let g=null;let m=null;if(e.events){const _=mergeInteractions(e.events.filter(x=>x.startTime>=t&&x.startTime<=r));g=new Set(_.map(x=>x.interactionId)).size;for(const x of _)if(!m||x.duration>m.duration)m=x}const f=m;const v=e.frames;const y=[...(e.clicks??[]).map(_=>_.t),...(e.keys??[]).map(_=>_.t)];const b=y.length?Math.max(...y):null;const $=b==null||v.filter(_=>_>b).length>=2;const T=v.length===0?i:Math.max(0,v[0]-t,r-v[v.length-1]);return{edgeSilenceMs:r1(T),frameGapCount:o.length,inputCaptureComplete:$,resized:Boolean(e.resized),interactions:g,worstInteractionMs:f?r1(f.duration):null,worstInputDelayMs:f?r1(Math.max(0,f.processingStart-f.startTime)):null,worstProcessingMs:f?r1(Math.max(0,f.processingEnd-f.processingStart)):null,worstPresentationMs:f?r1(Math.max(0,f.startTime+f.duration-f.processingEnd)):null,fps:r1(e.frames.length/i*1e3),frameGapP95Ms:s==null?null:r1(s),frameGapMaxMs:o.length?r1(Math.max(...o)):null,longFrames:o.filter(_=>_>a*1.5).length,longTaskPct:c,loafBlockingMs:l,styleLayoutMs:u,forcedLayoutMs:d,topScripts:h,loafCutOff:w,layoutShift:p,domNodesStart:e.domStart,domNodesEnd:e.domEnd}}function cdpDeltas(e,n,t){const r=s=>s in e&&s in n?n[s]-e[s]:null;const i=s=>{const c=r(s);return c==null?null:r1(c*1e3)};const o=i("TaskDuration");const a=i("Timestamp")??t;return{mainThreadPct:o==null?null:r1(o/Math.max(1,a)*100),scriptMs:i("ScriptDuration"),styleMs:i("RecalcStyleDuration"),layoutMs:i("LayoutDuration"),layoutCount:r("LayoutCount"),styleCount:r("RecalcStyleCount"),heapMb:"JSHeapUsedSize"in n?r1(n.JSHeapUsedSize/(1024*1024)):null}}function webBenchFlags(e,n){const t=[];if(e.droppedPct!=null&&e.droppedPct>=5)t.push(`${e.droppedPct}% of frames dropped or partial`);if(e.fps!=null&&e.fps<n*.95)t.push("Low main-thread frame rate");if(e.frameGapCount&&e.longFrames/e.frameGapCount>=.02)t.push("Frequent long frames");const r=Math.max(e.frameGapMaxMs??0,e.edgeSilenceMs??0);if(r>=100)t.push(`Freeze of ${Math.round(r)} ms`);if(e.mainThreadPct!=null&&e.mainThreadPct>=80)t.push("Main thread near full");if(e.longTaskPct!=null&&e.longTaskPct>=20)t.push("Long tasks block the main thread");if(e.forcedLayoutMs!=null&&e.forcedLayoutMs>=50)t.push(`Forced layout in scripts (${Math.round(e.forcedLayoutMs)} ms)`);if(e.layoutShift!=null&&e.layoutShift>=.1)t.push(`Layout shifts (${e.layoutShift})`);if(e.worstInteractionMs!=null&&e.worstInteractionMs>=200){t.push(`Slow response to input (${Math.round(e.worstInteractionMs)} ms)`)}return t}function aggregateCase(e,n){const t=e.filter(c=>!c.failed&&c.fps!=null);const r=[...t].sort((c,l)=>(c.fps??0)-(l.fps??0));const i=t.filter(c=>c.droppedPct!=null).length;const o=t.length>0&&i===t.length;const a=o?[...t].sort((c,l)=>c.droppedPct-l.droppedPct):r;const s=a.length?a[Math.floor((a.length-1)/2)]:null;return{caseName:e[0]?.caseName??"",cpu:e[0]?.cpu??1,validRuns:t.length,plannedRuns:e.length,isBaseline:false,deltaDroppedPct:null,tracedRuns:i,...(()=>{const c=o?t.map(u=>u.droppedPct):[];const l=t.map(u=>u.worstInteractionMs).filter(u=>u!=null);return{droppedMin:c.length?Math.min(...c):null,droppedMax:c.length?Math.max(...c):null,inputMin:l.length?Math.min(...l):null,inputMax:l.length?Math.max(...l):null}})(),runs:e,median:s,fpsMin:r.length?r[0].fps:null,fpsMax:r.length?r[r.length-1].fps:null,flags:s?webBenchFlags(o?s:{...s,droppedPct:null},n):[]}}var PLAYWRIGHT_MISSING="Playwright isn't installed in this project. Install it, then run again:\n npm i -D playwright && npx playwright install chromium";async function loadChromium(e){const n=(0,import_node_module.createRequire)((0,import_node_path15.join)(e,"noop.js"));for(const t of["playwright","playwright-core"]){let r;try{r=n.resolve(t)}catch{continue}const i=await import((0,import_node_url.pathToFileURL)(r).href);const o=i.chromium??i.default?.chromium;if(o)return o}throw new Error(`${PLAYWRIGHT_MISSING}
887
- (Searched from ${e}. Pass projectRoot to look elsewhere.)`)}async function withDeadline(e,n,t){let r;const i=new Promise(o=>{r=setTimeout(()=>o("timeout"),n)});try{const o=await Promise.race([e,i]);if(o==="timeout"){e.catch(()=>{});return await t()}return o}finally{clearTimeout(r)}}function gitCommit(e){try{return(0,import_node_child_process17.execFileSync)("git",["rev-parse","HEAD"],{cwd:e,stdio:["ignore","pipe","ignore"],timeout:3e3}).toString().trim()}catch{return null}}function gitDirty(e){try{const n=(0,import_node_child_process17.execFileSync)("git",["status","--porcelain"],{cwd:e,stdio:["ignore","pipe","ignore"],timeout:5e3});return n.toString().trim().length>0}catch{return null}}async function closeWithin(e,n){if(!e)return true;return withDeadline(e.close().then(()=>true,()=>false),n,async()=>false)}function validateWebBenchOptions(e){if(!e.cases?.length)throw new Error("Give at least one case.");const n=new Set;for(const a of e.cases){if(!a.name?.trim())throw new Error("Every case needs a name.");if(n.has(a.name))throw new Error(`Two cases are named "${a.name}". Give each case its own name.`);n.add(a.name)}const t=(a,s,c,l)=>{if(a==null)return;if(!Number.isInteger(a)||a<c||a>l)throw new Error(`${s} must be a whole number from ${c} to ${l}.`)};const r=(a,s,c)=>{if(a==null)return;if(!Number.isFinite(a)||a<c)throw new Error(`${s} must be a number of at least ${c}.`)};const i=(a,s,c,l)=>{if(a==null)return;if(!Number.isFinite(a)||a<c||a>l)throw new Error(`${s} must be from ${c} to ${l}.`)};t(e.runsPerCase,"runsPerCase",1,10);i(e.durationMs,"durationMs",500,12e4);i(e.settleMs,"settleMs",0,6e4);i(e.refreshHz,"refreshHz",1,500);const o=e.cpuSlowdown??[];for(const a of o)i(a,"each cpuSlowdown rate",1,20);if(new Set(o).size!==o.length)throw new Error("cpuSlowdown has the same rate twice.");if(e.viewport){t(e.viewport.width,"viewport.width",200,8e3);t(e.viewport.height,"viewport.height",200,8e3);i(e.viewport.deviceScaleFactor,"viewport.deviceScaleFactor",.5,4)}t(e.extraRoundsWhenClose,"extraRoundsWhenClose",0,10);i(e.maxBatchMs,"maxBatchMs",1e4,6*60*6e4);for(const[a,s]of Object.entries(e.budgets??{}))i(s,`budgets.${a}`,0,1e9);for(const a of e.steps??[]){if("wait"in a)i(a.wait,"a wait step",0,6e4);if("scroll"in a)i(a.scroll,"a scroll step",-1e5,1e5)}new URL(e.url)}function oneLine(e){return e.replace(/\u001b\[[0-9;]*m/g,"").split("\n")[0].trim().slice(0,160)}var FRAME_TRACE_CATEGORIES=["disabled-by-default-devtools.timeline.frame","blink.user_timing"];var FULL_TRACE_CATEGORIES=["devtools.timeline","disabled-by-default-devtools.timeline","disabled-by-default-devtools.timeline.frame","blink.user_timing","loading","latencyInfo","v8.execute"];var MAX_TRACE_CHARS=15e7;var sleep2=e=>new Promise(n=>setTimeout(n,e));async function locateStepTargets(e,n){const t=new Map;for(const r of n){if("expect"in r)continue;const i="click"in r?r.click:"type"in r?r.type.selector:null;if(!i||t.has(i))continue;const o=await e.$(i);const a=o?await o.boundingBox():null;if(!a)throw new Error(`step target ${i} isn't on the page (or isn't visible)`);t.set(i,{x:a.x+a.width/2,y:a.y+a.height/2})}return t}async function runSteps(e,n,t){for(const r of n){if("click"in r){const i=t.get(r.click);await e.mouse.click(i.x,i.y)}else if("press"in r)await e.keyboard.press(r.press);else if("type"in r){const i=t.get(r.type.selector);await e.mouse.click(i.x,i.y);await e.keyboard.type(r.type.text)}else if("scroll"in r)await e.mouse.wheel(0,r.scroll);else if("wait"in r)await sleep2(r.wait)}}function missedInput(e,n,t=[]){const r=[...n].sort((u,d)=>u.t-d.t);const i=[...t].sort((u,d)=>u.t-d.t);let o=0;let a=0;let s=-Infinity;const c=u=>{while(o<r.length){const d=r[o++];if(d.t>=s&&d.hit.includes(u)){s=d.t;return true}}return false};const l=u=>{while(a<i.length){const d=i[a++];if(d.t>=s&&keyMatches(u,d)){s=d.t;return true}}return false};for(const[u,d]of e.entries()){if("click"in d&&!c(d.click)){return`step ${u+1} (click ${d.click}) has no real click on its target, in order (moved, covered, or ignored)`}if("type"in d){if(!c(d.type.selector))return`step ${u+1} (type into ${d.type.selector}) has no real click on its target`;for(const h of d.type.text){if(!l(h))return`step ${u+1} (type "${d.type.text}") didn't deliver the key "${h}"`}}if("press"in d&&!l(d.press))return`step ${u+1} (press ${d.press}) didn't deliver that key`}return null}async function expectsAlreadyTrue(e,n){for(const t of n){if(!("expect"in t))continue;const{selector:r,text:i}=t.expect;const o=await e.evaluate(`(() => { const n = document.querySelector(${JSON.stringify(r)}); if (!n) return false; ${i==null?"return true;":`return (n.textContent || "").includes(${JSON.stringify(i)});`} })()`);if(o)return i==null?r:`${r} contains "${i}"`}return null}async function checkTargetsStill(e,n){for(const[t,r]of n){const i=await e.$(t);const o=i?await i.boundingBox():null;if(!o)return`step target ${t} was gone after the run`;const a=o.x+o.width/2;const s=o.y+o.height/2;if(Math.abs(a-r.x)>4||Math.abs(s-r.y)>4){return`step target ${t} moved during the run, so a click may have missed it`}}return null}function expectFailureFrom(e){for(const n of e){if(!n.found)return`expected ${n.selector} at the end of the run, but it isn't there`;const t=n.matched??(n.text==null||(n.content??"").includes(n.text));if(!t){return`expected ${n.selector} to contain "${n.text}" at the end of the run, got "${(n.content??"").slice(0,60)}"`}}return null}async function readMetrics(e){const{metrics:n}=await e.send("Performance.getMetrics");return Object.fromEntries(n.map(t=>[t.name,t.value]))}async function runWebBench(e,n=()=>{}){validateWebBenchOptions(e);const t=await waitForHostLock(e.lockWaitMs??20*6e4,n);const r={browserLeftRunning:false};try{return await runWebBenchLocked(e,n,r)}finally{t(r.browserLeftRunning)}}async function waitForHostLock(e,n=()=>{},t=2e3){const r=Date.now()+Math.max(0,e);let i=false;for(;;){try{return takeHostLock()}catch(o){const a=o?.message??String(o);const s=/Another web benchmark|already running/.test(a);if(!s||Date.now()+t>r)throw o;if(!i){n("another web benchmark is running; waiting for it to finish");i=true}await new Promise(c=>setTimeout(c,t))}}}var LOCK_FILE=(0,import_node_path15.join)((0,import_node_os11.tmpdir)(),"buoy-web-bench.lock");var lockedHere=false;function takeHostLock(){if(lockedHere){throw new Error("A web benchmark is already running in this process (or left a stuck browser). Wait, or restart the MCP server.")}const e=`${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;const n=JSON.stringify({pid:process.pid,token:e,startedAt:new Date().toISOString()});const t=()=>{const o=`${LOCK_FILE}.${e.replace(/[^\w]/g,"")}.tmp`;try{(0,import_node_fs14.writeFileSync)(o,n);(0,import_node_fs14.linkSync)(o,LOCK_FILE);return true}catch{return false}finally{try{(0,import_node_fs14.unlinkSync)(o)}catch{}}};const r=()=>{try{return JSON.parse((0,import_node_fs14.readFileSync)(LOCK_FILE,"utf8"))}catch{return null}};const i=o=>{if(!o)return false;try{process.kill(o,0);return true}catch{return false}};if(!t()){const o=r();if(!o)throw new Error("Another web benchmark is starting. Wait for it to finish.");if(i(o.pid)){throw new Error(`Another web benchmark is running (pid ${o.pid}, since ${o.startedAt}). Two at once would skew both; wait for it to finish.`)}const a=`${LOCK_FILE}.cleanup`;let s=null;try{if(Date.now()-(0,import_node_fs14.statSync)(a).mtimeMs>3e4){const c=`${a}.${e.replace(/[^\w]/g,"")}.old`;(0,import_node_fs14.renameSync)(a,c);if(Date.now()-(0,import_node_fs14.statSync)(c).mtimeMs>3e4)(0,import_node_fs14.unlinkSync)(c);else{try{(0,import_node_fs14.linkSync)(c,a)}catch{}(0,import_node_fs14.unlinkSync)(c)}}}catch{}try{s=(0,import_node_fs14.openSync)(a,"wx")}catch{throw new Error("Another web benchmark is clearing an old lock. Try again in a moment.")}try{const c=r();if(c?.token===o.token)(0,import_node_fs14.unlinkSync)(LOCK_FILE);if(!t())throw new Error("Another web benchmark just started. Wait for it to finish.")}finally{(0,import_node_fs14.closeSync)(s);try{(0,import_node_fs14.unlinkSync)(a)}catch{}}}lockedHere=true;return(o=false)=>{if(o)return;lockedHere=false;if(r()?.token===e){try{(0,import_node_fs14.unlinkSync)(LOCK_FILE)}catch{}}}}async function runWebBenchLocked(e,n,t){const r=e.runsPerCase??3;const i=Math.max(500,e.durationMs??5e3);const o=Math.max(0,e.settleMs??1e3);const a=e.frameTrace!==false;const s=(e.cpuSlowdown?.length?e.cpuSlowdown:[1]).map(k=>Math.max(1,k));let c=e.refreshHz??60;const l={width:e.viewport?.width??1280,height:e.viewport?.height??800,deviceScaleFactor:e.viewport?.deviceScaleFactor??1};const u=[];const d=[];let h=null;if(r<2)u.push("runsPerCase=1 gives no spread; use 3 or more before choosing.");const w=await loadChromium(e.projectRoot??process.cwd());const p=await w.launch({headless:!e.headed,args:["--enable-gpu"]});const g=[];const m=[];const f=Date.now();const v=new Date(f).toISOString();const y=e.maxBatchMs??30*6e4;let b=false;let $=false;const T={commit:gitCommit(e.projectRoot??process.cwd()),dirty:gitDirty(e.projectRoot??process.cwd())};try{const k={viewport:{width:l.width,height:l.height},deviceScaleFactor:l.deviceScaleFactor};const M=await withDeadline(p.newContext(k),3e4,async()=>{t.browserLeftRunning=true;throw new Error("Chromium didn't open a page in 30 s. Restart the MCP server and try again.")});const D=3e4+15e3+o+i+6e4;const P=async(O,N,z,F)=>{const B={};return withDeadline(j(B,O,N,z,F),D,async()=>{B.cancelled=true;if(!B.ctx)b=true;else if(!await closeWithin(B.ctx,1e4))b=true;return{...R(O.name,N,z),failed:`run took over ${Math.round(D/1e3)} s (the page may be stuck in a loop)`}})};const R=(O,N,z)=>({caseName:O,cpu:N,round:z,fps:null,frameGapP95Ms:null,frameGapMaxMs:null,longFrames:0,longTaskPct:null,loafBlockingMs:null,styleLayoutMs:null,forcedLayoutMs:null,topScripts:[],layoutShift:null,domNodesStart:null,domNodesEnd:null,mainThreadPct:null,scriptMs:null,styleMs:null,layoutMs:null,layoutCount:null,styleCount:null,heapMb:null,pageErrors:[]});const j=async(O,N,z,F,B)=>{const U=await p.newContext(k);O.ctx=U;if(O.cancelled){await closeWithin(U,1e4);throw new Error("run was cancelled during setup")}const L=await U.newPage();const H=[];L.on("pageerror",J=>H.push(String(J?.message??J)));const W={...R(N.name,z,F),pageErrors:H};try{const J=await U.newCDPSession(L);await J.send("Performance.enable",{timeDomain:"timeTicks"});if(z>1)await J.send("Emulation.setCPUThrottlingRate",{rate:z});const V=await L.goto(caseUrl(e.url,N,e.path),{waitUntil:"load",timeout:3e4});if(V&&V.status()>=400)return{...W,failed:`HTTP ${V.status()}`};if(e.readySelector)await L.waitForSelector(e.readySelector,{state:"attached",timeout:15e3});await sleep2(o);const ae=B||a;if(ae){await J.send("Tracing.start",{transferMode:"ReturnAsStream",categories:(B?FULL_TRACE_CATEGORIES:FRAME_TRACE_CATEGORIES).join(",")})}const re=e.steps?.length?await locateStepTargets(L,e.steps):new Map;if(e.steps?.length){const te=await expectsAlreadyTrue(L,e.steps);if(te)return{...W,failed:`expect ${te} already held before the steps, so it can't prove they worked`};const ne=[...re.keys()];const Z=e.steps.flatMap(oe=>"expect"in oe?[oe.expect]:[]);await L.evaluate(`window.__buoyBenchClickTargets = ${JSON.stringify(ne)}; window.__buoyBenchExpects = ${JSON.stringify(Z)}; true`)}const ee=await readMetrics(J);await L.evaluate(START_PROBE_JS);const G=Date.now();if(e.steps?.length)await runSteps(L,e.steps,re);const K=i-(Date.now()-G);if(K>0)await sleep2(K);await L.evaluate(END_PROBE_JS);const ie=await readMetrics(J);const le=Date.now()-G;const Q=await L.evaluate(COLLECT_PROBE_JS);let Y=null;if(ae){const te=new Promise(X=>J.on("Tracing.tracingComplete",se=>X(se.stream)));await J.send("Tracing.end");const ne=await te;const Z=B?(0,import_node_fs14.openSync)(B,"w"):null;const oe=[];let ce=0;try{for(;;){const X=await J.send("IO.read",{handle:ne});const se=X.base64Encoded?Buffer.from(X.data,"base64").toString("utf8"):X.data;ce+=se.length;if(Z!=null)(0,import_node_fs14.writeSync)(Z,se);if(ce<=MAX_TRACE_CHARS)oe.push(se);else oe.length=0;if(X.eof)break}}finally{await J.send("IO.close",{handle:ne}).catch(()=>{});if(Z!=null)(0,import_node_fs14.closeSync)(Z)}if(B)d.push(B);if(ce>MAX_TRACE_CHARS){u.push(`Trace for ${N.name} was over ${Math.round(MAX_TRACE_CHARS/1e6)} MB, so its frames weren't counted. A page that busy shows its problem in the table already.`)}else{try{const X=JSON.parse(oe.join(""));Y=summarizeFrameTrace(Array.isArray(X)?X:X.traceEvents??[])}catch{Y=null}}}if(!Q)return{...W,failed:"probe returned nothing (page navigated away?)"};if(Q.hidden)return{...W,failed:"page was hidden during the run"};if(Q.resized)return{...W,failed:"the window size or zoom changed during the run"};if(H.length&&!e.allowPageErrors){return{...W,failed:`page error: ${oneLine(H[0])}`}}if(e.steps?.length){const te=missedInput(e.steps,Q.clicks??[],Q.keys??[]);if(te)return{...W,failed:te};const ne=expectFailureFrom(Q.expectResults??[]);if(ne)return{...W,failed:ne};const Z=await checkTargetsStill(L,re);if(Z)return{...W,failed:Z}}const ue="Timestamp"in ee&&"Timestamp"in ie?r1((ie.Timestamp-ee.Timestamp)*1e3):null;return{...W,...summarizeProbe(Q,c),...cdpDeltas(ee,ie,le),probeSpanMs:r1(Q.end-Q.start),cdpSpanMs:ue,shownFps:Y?.shownFps??null,droppedFrames:Y?.faults??null,frameCounts:Y?{full:Y.full,partial:Y.partial,dropped:Y.dropped,faults:Y.faults}:null,droppedPct:Y?.droppedPct??null}}catch(J){return{...W,failed:oneLine(J?.message??String(J))}}finally{await closeWithin(L,5e3);if(!await closeWithin(U,1e4))b=true}};{const O=await withDeadline(M.newPage(),15e3,async()=>{throw new Error("Chromium didn't open the GPU check page in 15 s.")});try{h=await withDeadline(O.evaluate(GPU_RENDERER_JS),5e3,async()=>null)??null}catch{h=null}finally{await closeWithin(O,5e3)}if(h)n(`GPU ${h}`);if(h&&isSoftwareGpu(h)){u.push(`Chrome is drawing with a software GPU (${h}). Canvas, WebGL and Skia pages run several times slower than on a real screen, so their numbers mean little. Try headed: true, or a machine with a GPU.`)}}if(e.refreshHz==null){const O=await withDeadline(M.newPage(),15e3,async()=>{throw new Error("Chromium didn't open the calibration page in 15 s.")});try{await withDeadline(O.goto("about:blank"),15e3,async()=>null);const N=await withDeadline(O.evaluate(MEASURE_REFRESH_JS),5e3,async()=>{throw new Error("idle rate check timed out")});c=snapRefreshRate(N);n(`idle frame rate ${N.toFixed(1)} \u2192 ${c} Hz`)}catch{u.push("Couldn't measure the idle frame rate; frame budgets assume 60 Hz.")}finally{await closeWithin(O,5e3)}}n("warmup load");await P(e.cases[0],1,-1);const C=async(O,N,z,F)=>{if(b){g.push({...R(O.name,N,z),failed:"an earlier run left the browser stuck; batch stopped"});return}if(Date.now()-f>y){g.push({...R(O.name,N,z),failed:"batch time limit reached; run skipped"});return}n(F);m.push({cpu:N,round:z,caseName:O.name});g.push(await P(O,N,z))};for(const O of s){for(let N=0;N<r;N++){const z=shuffled(e.cases,2654435769^N*7919+O);for(const F of z)await C(F,O,N,`cpu ${O}x \xB7 round ${N+1}/${r} \xB7 ${F.name}`)}for(let N=0;N<(e.extraRoundsWhenClose??0);N++){const z=e.cases.map(L=>aggregateCase(g.filter(H=>H.cpu===O&&H.caseName===L.name),c));for(const L of z)L.control=e.cases.find(H=>H.name===L.caseName)?.control===true;const F=new Set([...tiedPairs(z).flat(),...z.filter(L=>!L.control&&L.validRuns<2&&L.plannedRuns>0).map(L=>L.caseName)]);if(F.size===0)break;const B=r+N;const U=shuffled(e.cases.filter(L=>F.has(L.name)),20973^B*7919+O);for(const L of U)await C(L,O,B,`cpu ${O}x \xB7 extra round ${N+1} (close call) \xB7 ${L.name}`)}}if(e.traceDir){(0,import_node_fs14.mkdirSync)(e.traceDir,{recursive:true});for(const[O,N]of e.cases.entries()){const z=(0,import_node_path15.join)(e.traceDir,`${String(O+1).padStart(2,"0")}-${N.name.replace(/[^\w.-]+/g,"_")}.json`);if(b||Date.now()-f>y){u.push(`Trace run for ${N.name} skipped (batch time limit or a stuck browser).`);continue}n(`trace \xB7 ${N.name}`);const F=await P(N,s[0],-1,z);if(F.failed)u.push(`Trace run for ${N.name} failed: ${F.failed}`)}}await closeWithin(M,1e4)}finally{const k=await closeWithin(p,15e3);t.browserLeftRunning=!k;if(!k){$=true;u.push("Chromium didn't close in 15 s and may still be running. The benchmark lock stays held; restart the MCP server before the next batch.")}}const _=[];for(const k of s){for(const M of e.cases){_.push(aggregateCase(g.filter(D=>D.cpu===k&&D.caseName===M.name),c))}}for(const k of _)k.control=e.cases.find(M=>M.name===k.caseName)?.control===true;for(const k of s){const M=_.filter(j=>j.cpu===k);const D=M.find(j=>!j.control);if(!D)continue;D.isBaseline=true;const P=j=>j.droppedMin!=null?j.median?.droppedPct??null:null;const R=P(D);for(const j of M.filter(C=>C!==D&&!C.control)){const C=P(j);j.deltaDroppedPct=R!=null&&C!=null?r1(C-R):null}}if(e.allowPageErrors&&g.some(k=>k.pageErrors.length)){u.push("Some runs threw page errors (kept because allowPageErrors is on).")}if(b)u.push("A browser context wouldn't close, so the batch stopped early. Restart and run again.");if(e.budgets)for(const k of _)k.budget=checkBudgets(k,e.budgets,e.steps??[]);const x=_.filter(k=>k.median).length;const A=_.every(k=>k.validRuns===k.plannedRuns);const I=x===0?"failed":x<_.length||!A?"partial":"ok";const E=_.filter(k=>k.median&&k.validRuns>0&&k.validRuns<k.plannedRuns);for(const k of E){const M=Array.from(new Set(k.runs.filter(D=>D.failed).map(D=>D.failed)));u.push(`${k.caseName} (CPU ${k.cpu}x): ${k.plannedRuns-k.validRuns} of ${k.plannedRuns} runs failed: ${M.join("; ")}`)}for(const k of _){const M=k.median;if(M?.probeSpanMs&&M.cdpSpanMs&&Math.abs(M.cdpSpanMs-M.probeSpanMs)/M.probeSpanMs>.15){u.push(`${k.caseName} (CPU ${k.cpu}x): Chrome's counters cover ${Math.round(M.cdpSpanMs)} ms but frames cover ${Math.round(M.probeSpanMs)} ms, so its cost columns include extra time.`)}if(M?.probeSpanMs!=null&&M.probeSpanMs<i*.8){u.push(`${k.caseName} (CPU ${k.cpu}x) recorded ${Math.round(M.probeSpanMs)} ms, not the ${i} ms asked for.`)}}const S={status:I,hasSteps:Boolean(e.steps?.length),browserLeftRunning:$,replay:{startedAt:v,...T,runOrder:m},url:e.url,browser:`Chromium ${p.version()}${e.headed?"":" (headless)"}`,gpu:h,viewport:l,refreshHz:c,durationMs:i,runsPerCase:r,results:_,traces:d,warnings:u};if(e.outFile){try{(0,import_node_fs14.writeFileSync)(e.outFile,JSON.stringify({options:e,result:S},null,2))}catch(k){S.warnings.push(`Couldn't write outFile ${e.outFile}: ${oneLine(k?.message??String(k))}`)}}return S}var MIN_DROPPED_GAP_PP=1.5;var MIN_FPS_GAP=2;function tiedPairs(e){const n=e.filter(o=>!o.control&&o.median&&o.validRuns>1);const t=n.filter(o=>o.droppedMin!=null);const r=[];if(t.length>=2&&t.length===n.length){const o=[...t].sort((a,s)=>a.median.droppedPct-s.median.droppedPct);for(let a=1;a<o.length;a++){const[s,c]=[o[a-1],o[a]];const l=c.median.droppedPct-s.median.droppedPct<=MIN_DROPPED_GAP_PP;if(c.droppedMin<=s.droppedMax||l)r.push([s.caseName,c.caseName])}return r}if(t.length>0)return r;const i=n.filter(o=>o.median.fps!=null).sort((o,a)=>a.median.fps-o.median.fps);for(let o=1;o<i.length;o++){const[a,s]=[i[o-1],i[o]];const c=a.median.fps-s.median.fps<=MIN_FPS_GAP;if((s.fpsMax??0)>=(a.fpsMin??0)||c)r.push([a.caseName,s.caseName])}return r}function closeCall(e){const n=e.filter(s=>!s.control&&s.median);const t=[];const r=n.filter(s=>s.validRuns<2);if(r.length)t.push(`**Too few runs to rank:** ${r.map(s=>s.caseName).join(", ")} (need 2 or more valid runs).`);const i=n.filter(s=>s.validRuns>1);const o=i.filter(s=>s.droppedMin!=null);if(o.length>0&&o.length<i.length){t.push(`**Not enough traced runs to compare smoothness:** ${i.filter(s=>!o.includes(s)).map(s=>`${s.caseName} (${s.tracedRuns}/${s.validRuns} traced)`).join(", ")}.`);return t.join("\n")}const a=new Map(i.map(s=>[s.caseName,s]));for(const[s,c]of tiedPairs(e)){const l=a.get(s);const u=a.get(c);t.push(o.length?`**Too close to call:** ${s} (${l.droppedMin}\u2013${l.droppedMax}% dropped) and ${c} (${u.droppedMin}\u2013${u.droppedMax}%) overlap or sit within ${MIN_DROPPED_GAP_PP} pp. No clear winner between them; more runs may separate them.`:`**Too close to call:** ${s} and ${c} overlap or sit within ${MIN_FPS_GAP} FPS. No clear winner between them; more runs may separate them.`)}return t.length?t.join("\n"):null}function formatWebBenchMarkdown(e){const n=(s,c=1)=>s==null?"\u2014":s.toFixed(c);const t=[];t.push(`### Web benchmark \xB7 ${e.url}`);t.push(`${e.browser}${e.gpu?` \xB7 GPU: ${e.gpu}${isSoftwareGpu(e.gpu)?" \u26A0\uFE0F software":""}`:""} \xB7 ${e.viewport.width}\xD7${e.viewport.height} @${e.viewport.deviceScaleFactor}x \xB7 ${e.runsPerCase} runs${e.results.some(s=>s.plannedRuns>e.runsPerCase)?" (more for close calls)":""} \xD7 ${e.durationMs/1e3}s per case, fresh browser context each run, case order shuffled each round.`);const r=e.results.map(s=>s.median?.probeSpanMs).filter(s=>s!=null);const i=e.results.map(s=>s.median?.cdpSpanMs).filter(s=>s!=null);const o=s=>`${(Math.min(...s)/1e3).toFixed(2)}\u2013${(Math.max(...s)/1e3).toFixed(2)} s`;if(r.length){t.push(`Recorded: frames over ${o(r)}${i.length?`; cost columns (Chrome's counters) over ${o(i)}`:""}, not the requested time.`)}if(e.replay?.dirty)t.push(`Note: the project had uncommitted changes, so commit ${e.replay.commit?.slice(0,10)??"?"} alone doesn't describe the code that ran.`);t.push("");t.push(`**How to read this.** Dropped % is the smoothness number: frames Chrome dropped or only partly produced that it says hurt smoothness, as a share of the frames it wanted, from its own verdicts in a trace. Rank on it first, and only across variants doing the same work. Shown FPS counts frames Chrome produced (headless Chrome displays nothing), so an animation that changes less often needs fewer; don't compare it across variants that update at different rates. Main-thread FPS and frame gaps come from requestAnimationFrame. Main thread % is Chrome's task time for the run. Desktop numbers, even with CPU slowdown, don't stand in for a real phone's GPU, memory or heat.`);const a=Array.from(new Set(e.results.map(s=>s.cpu)));for(const s of a){t.push("");t.push(s===1?`#### No CPU slowdown`:`#### CPU slowed ${s}x`);t.push("");t.push(`| Case | Runs | Shown FPS | Dropped % | Main-thread FPS (range) | p95 gap ms | Worst gap ms | Main thread % | Script ms | Style ms | Layout ms | Layouts | DOM nodes | JS heap MB | Flags |`);t.push(`|------|-----:|----------:|----------:|------------------------:|-----------:|-------------:|--------------:|----------:|---------:|----------:|--------:|----------:|--------:|-------|`);for(const h of e.results.filter(w=>w.cpu===s)){const w=h.median;if(!w){const m=h.runs.find(f=>f.failed)?.failed??"no valid runs";t.push(`| ${h.caseName} | 0/${h.plannedRuns} | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u274C FAILED (${m}) |`);continue}const p=h.fpsMin!=null&&h.fpsMax!=null&&h.validRuns>1?` (${n(h.fpsMin)}\u2013${n(h.fpsMax)})`:"";const g=h.flags.length?`\u26A0\uFE0F ${h.flags.join("; ")}`:"no flags";t.push(`| ${h.isBaseline?`${h.caseName} (baseline)`:h.control?`${h.caseName} (control)`:h.caseName} | ${h.validRuns}/${h.plannedRuns} | ${n(w.shownFps)} | ${h.droppedMin==null&&h.tracedRuns>0?`\u2014 (${h.tracedRuns}/${h.validRuns} traced)`:n(h.droppedMin==null?null:w.droppedPct)}${h.droppedMin!=null&&h.validRuns>1?` [${h.droppedMin}\u2013${h.droppedMax}]`:""}${h.deltaDroppedPct!=null?` (${h.deltaDroppedPct>0?"+":""}${h.deltaDroppedPct} pp)`:""} | ${n(w.fps)}${p} | ${n(w.frameGapP95Ms)} | ${n(w.frameGapMaxMs)} | ${n(w.mainThreadPct)} | ${n(w.scriptMs,0)} | ${n(w.styleMs,0)} | ${n(w.layoutMs,0)} | ${n(w.layoutCount,0)} | ${n(w.domNodesEnd,0)} | ${n(w.heapMb)} | ${g} |`)}const c=closeCall(e.results.filter(h=>h.cpu===s));if(c){t.push("");t.push(c)}const l=e.results.filter(h=>h.cpu===s&&h.budget);if(l.length){t.push("");t.push(`Budget:`);for(const h of l){const w=h.budget;const p=[...w.over,...w.unknown.map(m=>`${m} not measured`)].join("; ");const g=h.control?`${h.caseName} (control)`:h.caseName;t.push(`- **${g}**: ${w.meets?"meets every limit":`misses (${p||"no result"})`}`)}}const u=e.results.filter(h=>h.cpu===s&&h.median?.interactions!=null&&(e.hasSteps||h.median.interactions>0)).map(h=>{const w=h.median;const p=h.inputMin!=null&&h.inputMax!=null?` \xB7 slowest across all runs ${h.inputMax} ms (range ${h.inputMin}\u2013${h.inputMax})`:"";const g=h.runs.filter(f=>!f.failed&&f.fps!=null&&f.inputCaptureComplete===false).length;const m=g?` \xB7 \u26A0\uFE0F timing incomplete in ${g} run(s): the last input's paint came after the run ended, so its time is unknown (leave more time after the last step)`:"";if(!w.interactions)return`- **${h.caseName}**: middle run had no input entry (inputs under 16 ms aren't reported)${p}${m}`;return`- **${h.caseName}**: middle run: ${w.interactions} reported (16 ms or more), slowest ${w.worstInteractionMs} ms (waiting ${w.worstInputDelayMs} \xB7 handlers ${w.worstProcessingMs} \xB7 to paint ${w.worstPresentationMs})${p}${m}`});if(u.length){t.push("");t.push(`Input response (scripted steps, Event Timing). Inputs under 16 ms aren't reported. Under 200 ms is good.`);t.push(...u)}const d=e.results.filter(h=>h.cpu===s&&h.median&&h.median.topScripts.length).map(h=>`- **${h.caseName}**: ${h.median.topScripts.slice(0,3).map(w=>`${w.name} ${w.ms} ms`).join(", ")}`);if(d.length){t.push("");t.push(`Scripts in slow frames (Long Animation Frames; frames that ran past the end of a run are left out):`);t.push(...d)}}if(e.traces.length){t.push("");t.push(`Chrome traces (open in DevTools \u2192 Performance \u2192 Load profile): ${e.traces.join(", ")}`)}if(e.warnings.length){t.push("");t.push(...e.warnings.map(s=>`\u26A0\uFE0F ${s}`))}return t.join("\n")}function nextLoad(e,n){const t=Math.max(e+1,e*n);const r=Math.pow(10,Math.max(0,Math.floor(Math.log10(t))-1));return Math.ceil(t/r)*r}function median(e){if(!e.length)return null;const n=[...e].sort((r,i)=>r-i);const t=Math.floor(n.length/2);return n.length%2?n[t]:Math.round((n[t-1]+n[t])/2)}function bracketResolved(e,n,t){if(n-e<=1)return true;if(e<=0)return false;return(n-e)/e<=t/100}var measureFramesJs=(e,n)=>`new Promise((resolve) => {
887
+ })()`;function isSoftwareGpu(e){return/swiftshader|llvmpipe|softpipe|software|microsoft basic render/i.test(e)}function percentile(e,n){if(e.length===0)return null;const t=[...e].sort((i,o)=>i-o);const r=Math.ceil(n/100*t.length)-1;return t[Math.min(t.length-1,Math.max(0,r))]}var COMMON_RATES=[30,60,75,90,120,144,165,240];function snapRefreshRate(e){for(const n of COMMON_RATES)if(Math.abs(e-n)/n<=.08)return n;return Math.max(1,Math.round(e))}function shuffled(e,n){let t=n>>>0;const r=()=>{t=t+1831565813>>>0;let o=t;o=Math.imul(o^o>>>15,o|1);o^=o+Math.imul(o^o>>>7,o|61);return((o^o>>>14)>>>0)/4294967296};const i=[...e];for(let o=i.length-1;o>0;o--){const a=Math.floor(r()*(o+1));[i[o],i[a]]=[i[a],i[o]]}return i}function caseUrl(e,n,t){const r=new URL(e);const i=n.path??t;if(i)r.pathname=i.startsWith("/")?i:`${r.pathname.replace(/\/$/,"")}/${i}`;for(const[o,a]of Object.entries(n.params??{}))r.searchParams.set(o,a);return r.toString()}var FRAME_STATES=["STATE_PRESENTED_ALL","STATE_PRESENTED_PARTIAL","STATE_DROPPED"];function summarizeFrameTrace(e){const n=w=>e.find(p=>p.name===w&&p.ts!=null);const t=n("__buoy_bench_start");const r=n("__buoy_bench_end");if(!t||!r||r.ts<=t.ts)return null;if(t.pid!==r.pid)return null;const i=t.pid;const o={STATE_PRESENTED_ALL:0,STATE_PRESENTED_PARTIAL:1,STATE_DROPPED:2};const a=new Map;for(const w of e){if(w.name!=="PipelineReporter"||w.ph!=="b")continue;if(i!=null&&w.pid!==i)continue;if(w.ts==null||w.ts<t.ts||w.ts>r.ts)continue;const p=w.args?.frame_reporter;if(!p||p.frame_sequence==null)continue;const g=p.state;if(!FRAME_STATES.includes(g))continue;const m=`${p.layer_tree_host_id??""}:${p.frame_source??""}:${p.frame_sequence}`;const f=Boolean(p.affects_smoothness)&&g!=="STATE_PRESENTED_ALL";const v=a.get(m);if(!v)a.set(m,{state:g,fault:f});else{if(o[g]>o[v.state])v.state=g;v.fault=v.fault||f}}let s=0;let c=0;let l=0;let u=0;for(const w of a.values()){if(w.state==="STATE_PRESENTED_ALL")s++;else if(w.state==="STATE_PRESENTED_PARTIAL")c++;else l++;if(w.fault)u++}const d=s+c+l;if(d===0)return null;const h=(r.ts-t.ts)/1e6;return{full:s,partial:c,dropped:l,faults:u,shownFps:r1((s+c)/h),droppedPct:r1(u/d*100)}}function keyMatches(e,n){const t=e.split("+");const r=t[t.length-1];const i=new Set(t.slice(0,-1).map(s=>s.toLowerCase()));if(n.key!==r)return false;const o=r.toLowerCase();const a={ctrl:i.has("control")||o==="control",alt:i.has("alt")||o==="alt",meta:i.has("meta")||i.has("command")||o==="meta",shift:i.has("shift")||o==="shift"};if(Boolean(n.ctrl)!==a.ctrl||Boolean(n.alt)!==a.alt||Boolean(n.meta)!==a.meta)return false;if(!a.shift&&n.shift&&r.length!==1)return false;if(a.shift&&!n.shift)return false;return true}function mergeInteractions(e){const n=[];for(const t of e){const r=t.startTime+t.duration;const i=n.find(a=>a.interactionId===t.interactionId&&Math.abs(a.startTime+a.duration-r)<=8);if(!i){n.push({...t});continue}const o=i.startTime+i.duration;i.startTime=Math.min(i.startTime,t.startTime);i.processingStart=Math.min(i.processingStart,t.processingStart);i.processingEnd=Math.max(i.processingEnd,t.processingEnd);i.duration=Math.max(o,r)-i.startTime;if(t.processingEnd-t.processingStart>0)i.name=t.name}return n}function summarizeProbe(e,n){const{start:t,end:r}=e;const i=Math.max(1,r-t);const o=[];for(let _=1;_<e.frames.length;_++)o.push(e.frames[_]-e.frames[_-1]);const a=1e3/n;const s=percentile(o,95);let c=null;if(e.longTasks){let _=0;for(const x of e.longTasks){const I=Math.min(x.end,r)-Math.max(x.start,t);if(I>0)_+=I}c=r1(Math.min(100,_/i*100))}let l=null;let u=null;let d=null;let h=[];let w=0;if(e.loaf){let _=0;let x=0;let I=0;const D=new Map;for(const E of e.loaf){if(E.startTime>=t&&E.startTime<=r&&E.startTime+E.duration>r)w++;if(E.startTime<t||E.startTime+E.duration>r)continue;_+=E.blockingDuration;if(E.styleAndLayoutStart>E.startTime)x+=Math.max(0,E.startTime+E.duration-E.styleAndLayoutStart);for(const S of E.scripts){I+=S.forced;const k=D.get(S.name)??{ms:0,count:0};k.ms+=S.duration;k.count++;D.set(S.name,k)}}l=r1(_);u=r1(x);d=r1(I);h=[...D.entries()].map(([E,S])=>({name:E,ms:r1(S.ms),count:S.count})).sort((E,S)=>S.ms-E.ms).slice(0,5)}let p=null;if(e.shifts){let _=0;for(const x of e.shifts)if(!x.hadRecentInput&&x.startTime>=t&&x.startTime<=r)_+=x.value;p=Math.round(_*1e3)/1e3}let g=null;let m=null;if(e.events){const _=mergeInteractions(e.events.filter(x=>x.startTime>=t&&x.startTime<=r));g=new Set(_.map(x=>x.interactionId)).size;for(const x of _)if(!m||x.duration>m.duration)m=x}const f=m;const v=e.frames;const y=[...(e.clicks??[]).map(_=>_.t),...(e.keys??[]).map(_=>_.t)];const b=y.length?Math.max(...y):null;const $=b==null||v.filter(_=>_>b).length>=2;const T=v.length===0?i:Math.max(0,v[0]-t,r-v[v.length-1]);return{edgeSilenceMs:r1(T),frameGapCount:o.length,inputCaptureComplete:$,resized:Boolean(e.resized),interactions:g,worstInteractionMs:f?r1(f.duration):null,worstInputDelayMs:f?r1(Math.max(0,f.processingStart-f.startTime)):null,worstProcessingMs:f?r1(Math.max(0,f.processingEnd-f.processingStart)):null,worstPresentationMs:f?r1(Math.max(0,f.startTime+f.duration-f.processingEnd)):null,fps:r1(e.frames.length/i*1e3),frameGapP95Ms:s==null?null:r1(s),frameGapMaxMs:o.length?r1(Math.max(...o)):null,longFrames:o.filter(_=>_>a*1.5).length,longTaskPct:c,loafBlockingMs:l,styleLayoutMs:u,forcedLayoutMs:d,topScripts:h,loafCutOff:w,layoutShift:p,domNodesStart:e.domStart,domNodesEnd:e.domEnd}}function cdpDeltas(e,n,t){const r=s=>s in e&&s in n?n[s]-e[s]:null;const i=s=>{const c=r(s);return c==null?null:r1(c*1e3)};const o=i("TaskDuration");const a=i("Timestamp")??t;return{mainThreadPct:o==null?null:r1(o/Math.max(1,a)*100),scriptMs:i("ScriptDuration"),styleMs:i("RecalcStyleDuration"),layoutMs:i("LayoutDuration"),layoutCount:r("LayoutCount"),styleCount:r("RecalcStyleCount"),heapMb:"JSHeapUsedSize"in n?r1(n.JSHeapUsedSize/(1024*1024)):null}}function webBenchFlags(e,n){const t=[];if(e.droppedPct!=null&&e.droppedPct>=5)t.push(`${e.droppedPct}% of frames dropped or partial`);if(e.fps!=null&&e.fps<n*.95)t.push("Low main-thread frame rate");if(e.frameGapCount&&e.longFrames/e.frameGapCount>=.02)t.push("Frequent long frames");const r=Math.max(e.frameGapMaxMs??0,e.edgeSilenceMs??0);if(r>=100)t.push(`Freeze of ${Math.round(r)} ms`);if(e.mainThreadPct!=null&&e.mainThreadPct>=80)t.push("Main thread near full");if(e.longTaskPct!=null&&e.longTaskPct>=20)t.push("Long tasks block the main thread");if(e.forcedLayoutMs!=null&&e.forcedLayoutMs>=50)t.push(`Forced layout in scripts (${Math.round(e.forcedLayoutMs)} ms)`);if(e.layoutShift!=null&&e.layoutShift>=.1)t.push(`Layout shifts (${e.layoutShift})`);if(e.worstInteractionMs!=null&&e.worstInteractionMs>=200){t.push(`Slow response to input (${Math.round(e.worstInteractionMs)} ms)`)}return t}function aggregateCase(e,n){const t=e.filter(c=>!c.failed&&c.fps!=null);const r=[...t].sort((c,l)=>(c.fps??0)-(l.fps??0));const i=t.filter(c=>c.droppedPct!=null).length;const o=t.length>0&&i===t.length;const a=o?[...t].sort((c,l)=>c.droppedPct-l.droppedPct):r;const s=a.length?a[Math.floor((a.length-1)/2)]:null;return{caseName:e[0]?.caseName??"",cpu:e[0]?.cpu??1,validRuns:t.length,plannedRuns:e.length,isBaseline:false,deltaDroppedPct:null,tracedRuns:i,...(()=>{const c=o?t.map(u=>u.droppedPct):[];const l=t.map(u=>u.worstInteractionMs).filter(u=>u!=null);return{droppedMin:c.length?Math.min(...c):null,droppedMax:c.length?Math.max(...c):null,inputMin:l.length?Math.min(...l):null,inputMax:l.length?Math.max(...l):null}})(),runs:e,median:s,fpsMin:r.length?r[0].fps:null,fpsMax:r.length?r[r.length-1].fps:null,flags:s?webBenchFlags(o?s:{...s,droppedPct:null},n):[]}}var PLAYWRIGHT_MISSING="Playwright isn't installed in this project. Install it, then run again:\n npm i -D playwright && npx playwright install chromium";async function loadChromium(e){const n=(0,import_node_module.createRequire)((0,import_node_path21.join)(e,"noop.js"));for(const t of["playwright","playwright-core"]){let r;try{r=n.resolve(t)}catch{continue}const i=await import((0,import_node_url.pathToFileURL)(r).href);const o=i.chromium??i.default?.chromium;if(o)return o}throw new Error(`${PLAYWRIGHT_MISSING}
888
+ (Searched from ${e}. Pass projectRoot to look elsewhere.)`)}async function withDeadline(e,n,t){let r;const i=new Promise(o=>{r=setTimeout(()=>o("timeout"),n)});try{const o=await Promise.race([e,i]);if(o==="timeout"){e.catch(()=>{});return await t()}return o}finally{clearTimeout(r)}}function gitCommit(e){try{return(0,import_node_child_process19.execFileSync)("git",["rev-parse","HEAD"],{cwd:e,stdio:["ignore","pipe","ignore"],timeout:3e3}).toString().trim()}catch{return null}}function gitDirty(e){try{const n=(0,import_node_child_process19.execFileSync)("git",["status","--porcelain"],{cwd:e,stdio:["ignore","pipe","ignore"],timeout:5e3});return n.toString().trim().length>0}catch{return null}}async function closeWithin(e,n){if(!e)return true;return withDeadline(e.close().then(()=>true,()=>false),n,async()=>false)}function validateWebBenchOptions(e){if(!e.cases?.length)throw new Error("Give at least one case.");const n=new Set;for(const a of e.cases){if(!a.name?.trim())throw new Error("Every case needs a name.");if(n.has(a.name))throw new Error(`Two cases are named "${a.name}". Give each case its own name.`);n.add(a.name)}const t=(a,s,c,l)=>{if(a==null)return;if(!Number.isInteger(a)||a<c||a>l)throw new Error(`${s} must be a whole number from ${c} to ${l}.`)};const r=(a,s,c)=>{if(a==null)return;if(!Number.isFinite(a)||a<c)throw new Error(`${s} must be a number of at least ${c}.`)};const i=(a,s,c,l)=>{if(a==null)return;if(!Number.isFinite(a)||a<c||a>l)throw new Error(`${s} must be from ${c} to ${l}.`)};t(e.runsPerCase,"runsPerCase",1,10);i(e.durationMs,"durationMs",500,12e4);i(e.settleMs,"settleMs",0,6e4);i(e.refreshHz,"refreshHz",1,500);const o=e.cpuSlowdown??[];for(const a of o)i(a,"each cpuSlowdown rate",1,20);if(new Set(o).size!==o.length)throw new Error("cpuSlowdown has the same rate twice.");if(e.viewport){t(e.viewport.width,"viewport.width",200,8e3);t(e.viewport.height,"viewport.height",200,8e3);i(e.viewport.deviceScaleFactor,"viewport.deviceScaleFactor",.5,4)}t(e.extraRoundsWhenClose,"extraRoundsWhenClose",0,10);i(e.maxBatchMs,"maxBatchMs",1e4,6*60*6e4);for(const[a,s]of Object.entries(e.budgets??{}))i(s,`budgets.${a}`,0,1e9);for(const a of e.steps??[]){if("wait"in a)i(a.wait,"a wait step",0,6e4);if("scroll"in a)i(a.scroll,"a scroll step",-1e5,1e5)}new URL(e.url)}function oneLine(e){return e.replace(/\u001b\[[0-9;]*m/g,"").split("\n")[0].trim().slice(0,160)}var FRAME_TRACE_CATEGORIES=["disabled-by-default-devtools.timeline.frame","blink.user_timing"];var FULL_TRACE_CATEGORIES=["devtools.timeline","disabled-by-default-devtools.timeline","disabled-by-default-devtools.timeline.frame","blink.user_timing","loading","latencyInfo","v8.execute"];var MAX_TRACE_CHARS=15e7;var sleep3=e=>new Promise(n=>setTimeout(n,e));async function locateStepTargets(e,n){const t=new Map;for(const r of n){if("expect"in r)continue;const i="click"in r?r.click:"type"in r?r.type.selector:null;if(!i||t.has(i))continue;const o=await e.$(i);const a=o?await o.boundingBox():null;if(!a)throw new Error(`step target ${i} isn't on the page (or isn't visible)`);t.set(i,{x:a.x+a.width/2,y:a.y+a.height/2})}return t}async function runSteps(e,n,t){for(const r of n){if("click"in r){const i=t.get(r.click);await e.mouse.click(i.x,i.y)}else if("press"in r)await e.keyboard.press(r.press);else if("type"in r){const i=t.get(r.type.selector);await e.mouse.click(i.x,i.y);await e.keyboard.type(r.type.text)}else if("scroll"in r)await e.mouse.wheel(0,r.scroll);else if("wait"in r)await sleep3(r.wait)}}function missedInput(e,n,t=[]){const r=[...n].sort((u,d)=>u.t-d.t);const i=[...t].sort((u,d)=>u.t-d.t);let o=0;let a=0;let s=-Infinity;const c=u=>{while(o<r.length){const d=r[o++];if(d.t>=s&&d.hit.includes(u)){s=d.t;return true}}return false};const l=u=>{while(a<i.length){const d=i[a++];if(d.t>=s&&keyMatches(u,d)){s=d.t;return true}}return false};for(const[u,d]of e.entries()){if("click"in d&&!c(d.click)){return`step ${u+1} (click ${d.click}) has no real click on its target, in order (moved, covered, or ignored)`}if("type"in d){if(!c(d.type.selector))return`step ${u+1} (type into ${d.type.selector}) has no real click on its target`;for(const h of d.type.text){if(!l(h))return`step ${u+1} (type "${d.type.text}") didn't deliver the key "${h}"`}}if("press"in d&&!l(d.press))return`step ${u+1} (press ${d.press}) didn't deliver that key`}return null}async function expectsAlreadyTrue(e,n){for(const t of n){if(!("expect"in t))continue;const{selector:r,text:i}=t.expect;const o=await e.evaluate(`(() => { const n = document.querySelector(${JSON.stringify(r)}); if (!n) return false; ${i==null?"return true;":`return (n.textContent || "").includes(${JSON.stringify(i)});`} })()`);if(o)return i==null?r:`${r} contains "${i}"`}return null}async function checkTargetsStill(e,n){for(const[t,r]of n){const i=await e.$(t);const o=i?await i.boundingBox():null;if(!o)return`step target ${t} was gone after the run`;const a=o.x+o.width/2;const s=o.y+o.height/2;if(Math.abs(a-r.x)>4||Math.abs(s-r.y)>4){return`step target ${t} moved during the run, so a click may have missed it`}}return null}function expectFailureFrom(e){for(const n of e){if(!n.found)return`expected ${n.selector} at the end of the run, but it isn't there`;const t=n.matched??(n.text==null||(n.content??"").includes(n.text));if(!t){return`expected ${n.selector} to contain "${n.text}" at the end of the run, got "${(n.content??"").slice(0,60)}"`}}return null}async function readMetrics(e){const{metrics:n}=await e.send("Performance.getMetrics");return Object.fromEntries(n.map(t=>[t.name,t.value]))}async function runWebBench(e,n=()=>{}){validateWebBenchOptions(e);const t=await waitForHostLock(e.lockWaitMs??20*6e4,n);const r={browserLeftRunning:false};try{return await runWebBenchLocked(e,n,r)}finally{t(r.browserLeftRunning)}}async function waitForHostLock(e,n=()=>{},t=2e3){const r=Date.now()+Math.max(0,e);let i=false;for(;;){try{return takeHostLock()}catch(o){const a=o?.message??String(o);const s=/Another web benchmark|already running/.test(a);if(!s||Date.now()+t>r)throw o;if(!i){n("another web benchmark is running; waiting for it to finish");i=true}await new Promise(c=>setTimeout(c,t))}}}var LOCK_FILE=(0,import_node_path21.join)((0,import_node_os14.tmpdir)(),"buoy-web-bench.lock");var lockedHere=false;function takeHostLock(){if(lockedHere){throw new Error("A web benchmark is already running in this process (or left a stuck browser). Wait, or restart the MCP server.")}const e=`${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;const n=JSON.stringify({pid:process.pid,token:e,startedAt:new Date().toISOString()});const t=()=>{const o=`${LOCK_FILE}.${e.replace(/[^\w]/g,"")}.tmp`;try{(0,import_node_fs22.writeFileSync)(o,n);(0,import_node_fs22.linkSync)(o,LOCK_FILE);return true}catch{return false}finally{try{(0,import_node_fs22.unlinkSync)(o)}catch{}}};const r=()=>{try{return JSON.parse((0,import_node_fs22.readFileSync)(LOCK_FILE,"utf8"))}catch{return null}};const i=o=>{if(!o)return false;try{process.kill(o,0);return true}catch{return false}};if(!t()){const o=r();if(!o)throw new Error("Another web benchmark is starting. Wait for it to finish.");if(i(o.pid)){throw new Error(`Another web benchmark is running (pid ${o.pid}, since ${o.startedAt}). Two at once would skew both; wait for it to finish.`)}const a=`${LOCK_FILE}.cleanup`;let s=null;try{if(Date.now()-(0,import_node_fs22.statSync)(a).mtimeMs>3e4){const c=`${a}.${e.replace(/[^\w]/g,"")}.old`;(0,import_node_fs22.renameSync)(a,c);if(Date.now()-(0,import_node_fs22.statSync)(c).mtimeMs>3e4)(0,import_node_fs22.unlinkSync)(c);else{try{(0,import_node_fs22.linkSync)(c,a)}catch{}(0,import_node_fs22.unlinkSync)(c)}}}catch{}try{s=(0,import_node_fs22.openSync)(a,"wx")}catch{throw new Error("Another web benchmark is clearing an old lock. Try again in a moment.")}try{const c=r();if(c?.token===o.token)(0,import_node_fs22.unlinkSync)(LOCK_FILE);if(!t())throw new Error("Another web benchmark just started. Wait for it to finish.")}finally{(0,import_node_fs22.closeSync)(s);try{(0,import_node_fs22.unlinkSync)(a)}catch{}}}lockedHere=true;return(o=false)=>{if(o)return;lockedHere=false;if(r()?.token===e){try{(0,import_node_fs22.unlinkSync)(LOCK_FILE)}catch{}}}}async function runWebBenchLocked(e,n,t){const r=e.runsPerCase??3;const i=Math.max(500,e.durationMs??5e3);const o=Math.max(0,e.settleMs??1e3);const a=e.frameTrace!==false;const s=(e.cpuSlowdown?.length?e.cpuSlowdown:[1]).map(k=>Math.max(1,k));let c=e.refreshHz??60;const l={width:e.viewport?.width??1280,height:e.viewport?.height??800,deviceScaleFactor:e.viewport?.deviceScaleFactor??1};const u=[];const d=[];let h=null;if(r<2)u.push("runsPerCase=1 gives no spread; use 3 or more before choosing.");const w=await loadChromium(e.projectRoot??process.cwd());const p=await w.launch({headless:!e.headed,args:["--enable-gpu"]});const g=[];const m=[];const f=Date.now();const v=new Date(f).toISOString();const y=e.maxBatchMs??30*6e4;let b=false;let $=false;const T={commit:gitCommit(e.projectRoot??process.cwd()),dirty:gitDirty(e.projectRoot??process.cwd())};try{const k={viewport:{width:l.width,height:l.height},deviceScaleFactor:l.deviceScaleFactor};const M=await withDeadline(p.newContext(k),3e4,async()=>{t.browserLeftRunning=true;throw new Error("Chromium didn't open a page in 30 s. Restart the MCP server and try again.")});const A=3e4+15e3+o+i+6e4;const O=async(P,N,z,F)=>{const B={};return withDeadline(j(B,P,N,z,F),A,async()=>{B.cancelled=true;if(!B.ctx)b=true;else if(!await closeWithin(B.ctx,1e4))b=true;return{...R(P.name,N,z),failed:`run took over ${Math.round(A/1e3)} s (the page may be stuck in a loop)`}})};const R=(P,N,z)=>({caseName:P,cpu:N,round:z,fps:null,frameGapP95Ms:null,frameGapMaxMs:null,longFrames:0,longTaskPct:null,loafBlockingMs:null,styleLayoutMs:null,forcedLayoutMs:null,topScripts:[],layoutShift:null,domNodesStart:null,domNodesEnd:null,mainThreadPct:null,scriptMs:null,styleMs:null,layoutMs:null,layoutCount:null,styleCount:null,heapMb:null,pageErrors:[]});const j=async(P,N,z,F,B)=>{const U=await p.newContext(k);P.ctx=U;if(P.cancelled){await closeWithin(U,1e4);throw new Error("run was cancelled during setup")}const L=await U.newPage();const H=[];L.on("pageerror",J=>H.push(String(J?.message??J)));const W={...R(N.name,z,F),pageErrors:H};try{const J=await U.newCDPSession(L);await J.send("Performance.enable",{timeDomain:"timeTicks"});if(z>1)await J.send("Emulation.setCPUThrottlingRate",{rate:z});const V=await L.goto(caseUrl(e.url,N,e.path),{waitUntil:"load",timeout:3e4});if(V&&V.status()>=400)return{...W,failed:`HTTP ${V.status()}`};if(e.readySelector)await L.waitForSelector(e.readySelector,{state:"attached",timeout:15e3});await sleep3(o);const ae=B||a;if(ae){await J.send("Tracing.start",{transferMode:"ReturnAsStream",categories:(B?FULL_TRACE_CATEGORIES:FRAME_TRACE_CATEGORIES).join(",")})}const re=e.steps?.length?await locateStepTargets(L,e.steps):new Map;if(e.steps?.length){const te=await expectsAlreadyTrue(L,e.steps);if(te)return{...W,failed:`expect ${te} already held before the steps, so it can't prove they worked`};const ne=[...re.keys()];const Z=e.steps.flatMap(oe=>"expect"in oe?[oe.expect]:[]);await L.evaluate(`window.__buoyBenchClickTargets = ${JSON.stringify(ne)}; window.__buoyBenchExpects = ${JSON.stringify(Z)}; true`)}const ee=await readMetrics(J);await L.evaluate(START_PROBE_JS);const G=Date.now();if(e.steps?.length)await runSteps(L,e.steps,re);const K=i-(Date.now()-G);if(K>0)await sleep3(K);await L.evaluate(END_PROBE_JS);const ie=await readMetrics(J);const le=Date.now()-G;const Q=await L.evaluate(COLLECT_PROBE_JS);let Y=null;if(ae){const te=new Promise(X=>J.on("Tracing.tracingComplete",se=>X(se.stream)));await J.send("Tracing.end");const ne=await te;const Z=B?(0,import_node_fs22.openSync)(B,"w"):null;const oe=[];let ce=0;try{for(;;){const X=await J.send("IO.read",{handle:ne});const se=X.base64Encoded?Buffer.from(X.data,"base64").toString("utf8"):X.data;ce+=se.length;if(Z!=null)(0,import_node_fs22.writeSync)(Z,se);if(ce<=MAX_TRACE_CHARS)oe.push(se);else oe.length=0;if(X.eof)break}}finally{await J.send("IO.close",{handle:ne}).catch(()=>{});if(Z!=null)(0,import_node_fs22.closeSync)(Z)}if(B)d.push(B);if(ce>MAX_TRACE_CHARS){u.push(`Trace for ${N.name} was over ${Math.round(MAX_TRACE_CHARS/1e6)} MB, so its frames weren't counted. A page that busy shows its problem in the table already.`)}else{try{const X=JSON.parse(oe.join(""));Y=summarizeFrameTrace(Array.isArray(X)?X:X.traceEvents??[])}catch{Y=null}}}if(!Q)return{...W,failed:"probe returned nothing (page navigated away?)"};if(Q.hidden)return{...W,failed:"page was hidden during the run"};if(Q.resized)return{...W,failed:"the window size or zoom changed during the run"};if(H.length&&!e.allowPageErrors){return{...W,failed:`page error: ${oneLine(H[0])}`}}if(e.steps?.length){const te=missedInput(e.steps,Q.clicks??[],Q.keys??[]);if(te)return{...W,failed:te};const ne=expectFailureFrom(Q.expectResults??[]);if(ne)return{...W,failed:ne};const Z=await checkTargetsStill(L,re);if(Z)return{...W,failed:Z}}const ue="Timestamp"in ee&&"Timestamp"in ie?r1((ie.Timestamp-ee.Timestamp)*1e3):null;return{...W,...summarizeProbe(Q,c),...cdpDeltas(ee,ie,le),probeSpanMs:r1(Q.end-Q.start),cdpSpanMs:ue,shownFps:Y?.shownFps??null,droppedFrames:Y?.faults??null,frameCounts:Y?{full:Y.full,partial:Y.partial,dropped:Y.dropped,faults:Y.faults}:null,droppedPct:Y?.droppedPct??null}}catch(J){return{...W,failed:oneLine(J?.message??String(J))}}finally{await closeWithin(L,5e3);if(!await closeWithin(U,1e4))b=true}};{const P=await withDeadline(M.newPage(),15e3,async()=>{throw new Error("Chromium didn't open the GPU check page in 15 s.")});try{h=await withDeadline(P.evaluate(GPU_RENDERER_JS),5e3,async()=>null)??null}catch{h=null}finally{await closeWithin(P,5e3)}if(h)n(`GPU ${h}`);if(h&&isSoftwareGpu(h)){u.push(`Chrome is drawing with a software GPU (${h}). Canvas, WebGL and Skia pages run several times slower than on a real screen, so their numbers mean little. Try headed: true, or a machine with a GPU.`)}}if(e.refreshHz==null){const P=await withDeadline(M.newPage(),15e3,async()=>{throw new Error("Chromium didn't open the calibration page in 15 s.")});try{await withDeadline(P.goto("about:blank"),15e3,async()=>null);const N=await withDeadline(P.evaluate(MEASURE_REFRESH_JS),5e3,async()=>{throw new Error("idle rate check timed out")});c=snapRefreshRate(N);n(`idle frame rate ${N.toFixed(1)} \u2192 ${c} Hz`)}catch{u.push("Couldn't measure the idle frame rate; frame budgets assume 60 Hz.")}finally{await closeWithin(P,5e3)}}n("warmup load");await O(e.cases[0],1,-1);const C=async(P,N,z,F)=>{if(b){g.push({...R(P.name,N,z),failed:"an earlier run left the browser stuck; batch stopped"});return}if(Date.now()-f>y){g.push({...R(P.name,N,z),failed:"batch time limit reached; run skipped"});return}n(F);m.push({cpu:N,round:z,caseName:P.name});g.push(await O(P,N,z))};for(const P of s){for(let N=0;N<r;N++){const z=shuffled(e.cases,2654435769^N*7919+P);for(const F of z)await C(F,P,N,`cpu ${P}x \xB7 round ${N+1}/${r} \xB7 ${F.name}`)}for(let N=0;N<(e.extraRoundsWhenClose??0);N++){const z=e.cases.map(L=>aggregateCase(g.filter(H=>H.cpu===P&&H.caseName===L.name),c));for(const L of z)L.control=e.cases.find(H=>H.name===L.caseName)?.control===true;const F=new Set([...tiedPairs(z).flat(),...z.filter(L=>!L.control&&L.validRuns<2&&L.plannedRuns>0).map(L=>L.caseName)]);if(F.size===0)break;const B=r+N;const U=shuffled(e.cases.filter(L=>F.has(L.name)),20973^B*7919+P);for(const L of U)await C(L,P,B,`cpu ${P}x \xB7 extra round ${N+1} (close call) \xB7 ${L.name}`)}}if(e.traceDir){(0,import_node_fs22.mkdirSync)(e.traceDir,{recursive:true});for(const[P,N]of e.cases.entries()){const z=(0,import_node_path21.join)(e.traceDir,`${String(P+1).padStart(2,"0")}-${N.name.replace(/[^\w.-]+/g,"_")}.json`);if(b||Date.now()-f>y){u.push(`Trace run for ${N.name} skipped (batch time limit or a stuck browser).`);continue}n(`trace \xB7 ${N.name}`);const F=await O(N,s[0],-1,z);if(F.failed)u.push(`Trace run for ${N.name} failed: ${F.failed}`)}}await closeWithin(M,1e4)}finally{const k=await closeWithin(p,15e3);t.browserLeftRunning=!k;if(!k){$=true;u.push("Chromium didn't close in 15 s and may still be running. The benchmark lock stays held; restart the MCP server before the next batch.")}}const _=[];for(const k of s){for(const M of e.cases){_.push(aggregateCase(g.filter(A=>A.cpu===k&&A.caseName===M.name),c))}}for(const k of _)k.control=e.cases.find(M=>M.name===k.caseName)?.control===true;for(const k of s){const M=_.filter(j=>j.cpu===k);const A=M.find(j=>!j.control);if(!A)continue;A.isBaseline=true;const O=j=>j.droppedMin!=null?j.median?.droppedPct??null:null;const R=O(A);for(const j of M.filter(C=>C!==A&&!C.control)){const C=O(j);j.deltaDroppedPct=R!=null&&C!=null?r1(C-R):null}}if(e.allowPageErrors&&g.some(k=>k.pageErrors.length)){u.push("Some runs threw page errors (kept because allowPageErrors is on).")}if(b)u.push("A browser context wouldn't close, so the batch stopped early. Restart and run again.");if(e.budgets)for(const k of _)k.budget=checkBudgets(k,e.budgets,e.steps??[]);const x=_.filter(k=>k.median).length;const I=_.every(k=>k.validRuns===k.plannedRuns);const D=x===0?"failed":x<_.length||!I?"partial":"ok";const E=_.filter(k=>k.median&&k.validRuns>0&&k.validRuns<k.plannedRuns);for(const k of E){const M=Array.from(new Set(k.runs.filter(A=>A.failed).map(A=>A.failed)));u.push(`${k.caseName} (CPU ${k.cpu}x): ${k.plannedRuns-k.validRuns} of ${k.plannedRuns} runs failed: ${M.join("; ")}`)}for(const k of _){const M=k.median;if(M?.probeSpanMs&&M.cdpSpanMs&&Math.abs(M.cdpSpanMs-M.probeSpanMs)/M.probeSpanMs>.15){u.push(`${k.caseName} (CPU ${k.cpu}x): Chrome's counters cover ${Math.round(M.cdpSpanMs)} ms but frames cover ${Math.round(M.probeSpanMs)} ms, so its cost columns include extra time.`)}if(M?.probeSpanMs!=null&&M.probeSpanMs<i*.8){u.push(`${k.caseName} (CPU ${k.cpu}x) recorded ${Math.round(M.probeSpanMs)} ms, not the ${i} ms asked for.`)}}const S={status:D,hasSteps:Boolean(e.steps?.length),browserLeftRunning:$,replay:{startedAt:v,...T,runOrder:m},url:e.url,browser:`Chromium ${p.version()}${e.headed?"":" (headless)"}`,gpu:h,viewport:l,refreshHz:c,durationMs:i,runsPerCase:r,results:_,traces:d,warnings:u};if(e.outFile){try{(0,import_node_fs22.writeFileSync)(e.outFile,JSON.stringify({options:e,result:S},null,2))}catch(k){S.warnings.push(`Couldn't write outFile ${e.outFile}: ${oneLine(k?.message??String(k))}`)}}return S}var MIN_DROPPED_GAP_PP=1.5;var MIN_FPS_GAP=2;function tiedPairs(e){const n=e.filter(o=>!o.control&&o.median&&o.validRuns>1);const t=n.filter(o=>o.droppedMin!=null);const r=[];if(t.length>=2&&t.length===n.length){const o=[...t].sort((a,s)=>a.median.droppedPct-s.median.droppedPct);for(let a=1;a<o.length;a++){const[s,c]=[o[a-1],o[a]];const l=c.median.droppedPct-s.median.droppedPct<=MIN_DROPPED_GAP_PP;if(c.droppedMin<=s.droppedMax||l)r.push([s.caseName,c.caseName])}return r}if(t.length>0)return r;const i=n.filter(o=>o.median.fps!=null).sort((o,a)=>a.median.fps-o.median.fps);for(let o=1;o<i.length;o++){const[a,s]=[i[o-1],i[o]];const c=a.median.fps-s.median.fps<=MIN_FPS_GAP;if((s.fpsMax??0)>=(a.fpsMin??0)||c)r.push([a.caseName,s.caseName])}return r}function closeCall(e){const n=e.filter(s=>!s.control&&s.median);const t=[];const r=n.filter(s=>s.validRuns<2);if(r.length)t.push(`**Too few runs to rank:** ${r.map(s=>s.caseName).join(", ")} (need 2 or more valid runs).`);const i=n.filter(s=>s.validRuns>1);const o=i.filter(s=>s.droppedMin!=null);if(o.length>0&&o.length<i.length){t.push(`**Not enough traced runs to compare smoothness:** ${i.filter(s=>!o.includes(s)).map(s=>`${s.caseName} (${s.tracedRuns}/${s.validRuns} traced)`).join(", ")}.`);return t.join("\n")}const a=new Map(i.map(s=>[s.caseName,s]));for(const[s,c]of tiedPairs(e)){const l=a.get(s);const u=a.get(c);t.push(o.length?`**Too close to call:** ${s} (${l.droppedMin}\u2013${l.droppedMax}% dropped) and ${c} (${u.droppedMin}\u2013${u.droppedMax}%) overlap or sit within ${MIN_DROPPED_GAP_PP} pp. No clear winner between them; more runs may separate them.`:`**Too close to call:** ${s} and ${c} overlap or sit within ${MIN_FPS_GAP} FPS. No clear winner between them; more runs may separate them.`)}return t.length?t.join("\n"):null}function formatWebBenchMarkdown(e){const n=(s,c=1)=>s==null?"\u2014":s.toFixed(c);const t=[];t.push(`### Web benchmark \xB7 ${e.url}`);t.push(`${e.browser}${e.gpu?` \xB7 GPU: ${e.gpu}${isSoftwareGpu(e.gpu)?" \u26A0\uFE0F software":""}`:""} \xB7 ${e.viewport.width}\xD7${e.viewport.height} @${e.viewport.deviceScaleFactor}x \xB7 ${e.runsPerCase} runs${e.results.some(s=>s.plannedRuns>e.runsPerCase)?" (more for close calls)":""} \xD7 ${e.durationMs/1e3}s per case, fresh browser context each run, case order shuffled each round.`);const r=e.results.map(s=>s.median?.probeSpanMs).filter(s=>s!=null);const i=e.results.map(s=>s.median?.cdpSpanMs).filter(s=>s!=null);const o=s=>`${(Math.min(...s)/1e3).toFixed(2)}\u2013${(Math.max(...s)/1e3).toFixed(2)} s`;if(r.length){t.push(`Recorded: frames over ${o(r)}${i.length?`; cost columns (Chrome's counters) over ${o(i)}`:""}, not the requested time.`)}if(e.replay?.dirty)t.push(`Note: the project had uncommitted changes, so commit ${e.replay.commit?.slice(0,10)??"?"} alone doesn't describe the code that ran.`);t.push("");t.push(`**How to read this.** Dropped % is the smoothness number: frames Chrome dropped or only partly produced that it says hurt smoothness, as a share of the frames it wanted, from its own verdicts in a trace. Rank on it first, and only across variants doing the same work. Shown FPS counts frames Chrome produced (headless Chrome displays nothing), so an animation that changes less often needs fewer; don't compare it across variants that update at different rates. Main-thread FPS and frame gaps come from requestAnimationFrame. Main thread % is Chrome's task time for the run. Desktop numbers, even with CPU slowdown, don't stand in for a real phone's GPU, memory or heat.`);const a=Array.from(new Set(e.results.map(s=>s.cpu)));for(const s of a){t.push("");t.push(s===1?`#### No CPU slowdown`:`#### CPU slowed ${s}x`);t.push("");t.push(`| Case | Runs | Shown FPS | Dropped % | Main-thread FPS (range) | p95 gap ms | Worst gap ms | Main thread % | Script ms | Style ms | Layout ms | Layouts | DOM nodes | JS heap MB | Flags |`);t.push(`|------|-----:|----------:|----------:|------------------------:|-----------:|-------------:|--------------:|----------:|---------:|----------:|--------:|----------:|--------:|-------|`);for(const h of e.results.filter(w=>w.cpu===s)){const w=h.median;if(!w){const m=h.runs.find(f=>f.failed)?.failed??"no valid runs";t.push(`| ${h.caseName} | 0/${h.plannedRuns} | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u274C FAILED (${m}) |`);continue}const p=h.fpsMin!=null&&h.fpsMax!=null&&h.validRuns>1?` (${n(h.fpsMin)}\u2013${n(h.fpsMax)})`:"";const g=h.flags.length?`\u26A0\uFE0F ${h.flags.join("; ")}`:"no flags";t.push(`| ${h.isBaseline?`${h.caseName} (baseline)`:h.control?`${h.caseName} (control)`:h.caseName} | ${h.validRuns}/${h.plannedRuns} | ${n(w.shownFps)} | ${h.droppedMin==null&&h.tracedRuns>0?`\u2014 (${h.tracedRuns}/${h.validRuns} traced)`:n(h.droppedMin==null?null:w.droppedPct)}${h.droppedMin!=null&&h.validRuns>1?` [${h.droppedMin}\u2013${h.droppedMax}]`:""}${h.deltaDroppedPct!=null?` (${h.deltaDroppedPct>0?"+":""}${h.deltaDroppedPct} pp)`:""} | ${n(w.fps)}${p} | ${n(w.frameGapP95Ms)} | ${n(w.frameGapMaxMs)} | ${n(w.mainThreadPct)} | ${n(w.scriptMs,0)} | ${n(w.styleMs,0)} | ${n(w.layoutMs,0)} | ${n(w.layoutCount,0)} | ${n(w.domNodesEnd,0)} | ${n(w.heapMb)} | ${g} |`)}const c=closeCall(e.results.filter(h=>h.cpu===s));if(c){t.push("");t.push(c)}const l=e.results.filter(h=>h.cpu===s&&h.budget);if(l.length){t.push("");t.push(`Budget:`);for(const h of l){const w=h.budget;const p=[...w.over,...w.unknown.map(m=>`${m} not measured`)].join("; ");const g=h.control?`${h.caseName} (control)`:h.caseName;t.push(`- **${g}**: ${w.meets?"meets every limit":`misses (${p||"no result"})`}`)}}const u=e.results.filter(h=>h.cpu===s&&h.median?.interactions!=null&&(e.hasSteps||h.median.interactions>0)).map(h=>{const w=h.median;const p=h.inputMin!=null&&h.inputMax!=null?` \xB7 slowest across all runs ${h.inputMax} ms (range ${h.inputMin}\u2013${h.inputMax})`:"";const g=h.runs.filter(f=>!f.failed&&f.fps!=null&&f.inputCaptureComplete===false).length;const m=g?` \xB7 \u26A0\uFE0F timing incomplete in ${g} run(s): the last input's paint came after the run ended, so its time is unknown (leave more time after the last step)`:"";if(!w.interactions)return`- **${h.caseName}**: middle run had no input entry (inputs under 16 ms aren't reported)${p}${m}`;return`- **${h.caseName}**: middle run: ${w.interactions} reported (16 ms or more), slowest ${w.worstInteractionMs} ms (waiting ${w.worstInputDelayMs} \xB7 handlers ${w.worstProcessingMs} \xB7 to paint ${w.worstPresentationMs})${p}${m}`});if(u.length){t.push("");t.push(`Input response (scripted steps, Event Timing). Inputs under 16 ms aren't reported. Under 200 ms is good.`);t.push(...u)}const d=e.results.filter(h=>h.cpu===s&&h.median&&h.median.topScripts.length).map(h=>`- **${h.caseName}**: ${h.median.topScripts.slice(0,3).map(w=>`${w.name} ${w.ms} ms`).join(", ")}`);if(d.length){t.push("");t.push(`Scripts in slow frames (Long Animation Frames; frames that ran past the end of a run are left out):`);t.push(...d)}}if(e.traces.length){t.push("");t.push(`Chrome traces (open in DevTools \u2192 Performance \u2192 Load profile): ${e.traces.join(", ")}`)}if(e.warnings.length){t.push("");t.push(...e.warnings.map(s=>`\u26A0\uFE0F ${s}`))}return t.join("\n")}function nextLoad(e,n){const t=Math.max(e+1,e*n);const r=Math.pow(10,Math.max(0,Math.floor(Math.log10(t))-1));return Math.ceil(t/r)*r}function median(e){if(!e.length)return null;const n=[...e].sort((r,i)=>r-i);const t=Math.floor(n.length/2);return n.length%2?n[t]:Math.round((n[t-1]+n[t])/2)}function bracketResolved(e,n,t){if(n-e<=1)return true;if(e<=0)return false;return(n-e)/e<=t/100}var measureFramesJs=(e,n)=>`new Promise((resolve) => {
888
889
  setTimeout(() => {
889
890
  const deltas = [];
890
891
  let start;
@@ -906,7 +907,7 @@ _Apps already running do not pick up a camera they started without \u2014 use \`
906
907
  };
907
908
  requestAnimationFrame(loop);
908
909
  }, ${e});
909
- })`;async function rampOnce(e,n){const t=[];const r=(l,u,d,h)=>({status:l,stopReason:u,highestPass:d?{load:d.load,fps:d.fps??0}:null,lowestMiss:h?{load:h.load,fps:h.fps??0}:null,resolved:l==="below_one"||l==="bracketed"&&!!d&&!!h&&bracketResolved(d.load,h.load,n.precisionPct),steps:t});const i=(l,u,d)=>r("invalid",l.fps==null?"measurement_failed":"page_error",u,d);const o=async(l,u=false)=>{const d=await e(l);if(u)d.confirm=true;t.push(d);return d};let a=null;let s=null;let c=await o(n.start);if(!c.valid)return i(c,null,null);if(c.pass)a=c;else{s=c;let l=n.start;while(!a){if(l<=1)return r("below_one","performance",null,s);if(!n.timeLeft())return r("lower_bound","deadline",null,s);l=Math.max(1,Math.floor(l/2));c=await o(l);if(!c.valid)return i(c,null,s);if(c.pass)a=c;else s=c}}while(!s||s.load<=a.load){if(a.load>=n.max)return r("lower_bound","max",a,null);if(!n.timeLeft())return r("lower_bound","deadline",a,null);c=await o(Math.min(n.max,nextLoad(a.load,n.growth)));if(!c.valid)return i(c,a,null);if(c.pass){a=c;continue}if(!n.timeLeft())return r("bracketed","performance",a,c);const l=await o(c.load,true);if(!l.valid)return i(l,a,null);if(l.pass)a=l;else s=l}while(!bracketResolved(a.load,s.load,n.precisionPct)&&n.timeLeft()){const l=Math.round((a.load+s.load)/2);if(l<=a.load||l>=s.load)break;c=await o(l);if(!c.valid)break;if(c.pass)a=c;else s=c}return r("bracketed","performance",a,s)}async function runWebRamp(e,n=()=>{}){if(!e.cases?.length)throw new Error("Pass at least one case.");if(!e.param)throw new Error('Pass `param`, the query param that sets the load (e.g. "lights").');const t=(b,$)=>{if(b!=null&&!Number.isFinite(b))throw new Error(`${$} must be a finite number.`)};for(const[b,$]of Object.entries({start:e.start,growth:e.growth,max:e.max,targetFps:e.targetFps,precisionPct:e.precisionPct,rounds:e.rounds,settleMs:e.settleMs,measureMs:e.measureMs,cpuSlowdown:e.cpuSlowdown}))t($,b);const r=Math.max(1,Math.floor(e.start??100));const i=Math.min(4,Math.max(1.05,e.growth??1.3));const o=Math.max(r,Math.floor(e.max??1e9));const a=e.targetFps??55;const s=Math.min(50,Math.max(.5,e.precisionPct??4));const c=Math.max(1,Math.min(5,Math.floor(e.rounds??1)));const l=Math.max(0,e.settleMs??1e3);const u=Math.max(500,e.measureMs??2e3);const d=Math.max(1,e.cpuSlowdown??1);const h={width:e.viewport?.width??1280,height:e.viewport?.height??800,deviceScaleFactor:e.viewport?.deviceScaleFactor??1};const w=[];const p=Date.now();const g=p+(e.maxBatchMs??40*6e4);const m=()=>g-Date.now();const f=p>>>0;const v=await waitForHostLock(Math.min(e.lockWaitMs??20*6e4,Math.max(0,m())),n);let y=false;try{const b=await loadChromium(e.projectRoot??process.cwd());const $=await b.launch({headless:!e.headed,args:["--enable-gpu","--disable-backgrounding-occluded-windows","--disable-renderer-backgrounding","--disable-background-timer-throttling"]});try{const T={viewport:{width:h.width,height:h.height},deviceScaleFactor:h.deviceScaleFactor};let _=null;let x=60;{const S=await $.newContext(T);try{const k=await S.newPage();await k.goto("about:blank");_=await k.evaluate(GPU_RENDERER_JS)??null;const M=await withDeadline(k.evaluate(measureFramesJs(200,1e3)),1e4,async()=>({fps:60}));x=snapRefreshRate(M.fps)}finally{await closeWithin(S,5e3)}}n(`GPU ${_??"unknown"} \xB7 idle ${x} Hz`);if(_&&isSoftwareGpu(_))w.push(`Chrome is drawing with a software GPU (${_}), so ceilings are far lower than on a real screen.`);if(a>x*.95){w.push(`The target (${a} fps) is at or above this browser's idle frame rate (${x} Hz), so even an empty page can miss it. Use headed: true on a faster screen, or measure with a target your contract allows.`)}const A=e.cases.map(S=>({caseName:S.name,ceiling:null,atLeast:null,rounds:[],errors:[]}));const I=async(S,k,M,D)=>{const P=D.length;const R=caseUrl(e.url,{...k,params:{...k.params??{},[e.param]:String(M)}},e.path);const j=C=>Math.max(1e3,Math.min(C,m()+15e3));try{await S.goto(R,{waitUntil:"load",timeout:j(6e4)});if(e.readySelector)await S.waitForSelector(e.readySelector,{state:"attached",timeout:j(6e4)});const C=await withDeadline(S.evaluate(measureFramesJs(l,u)),l+u+6e4,async()=>{throw new Error("the page stopped drawing (no frames for 60 s)")});const O=D.length>P?D[D.length-1]:void 0;if(O)return{load:M,fps:C.fps,p95GapMs:C.p95,valid:false,pass:false,error:O};return{load:M,fps:C.fps,p95GapMs:C.p95,valid:true,pass:C.fps>=a}}catch(C){return{load:M,fps:null,p95GapMs:null,valid:false,pass:false,error:(C?.message??String(C)).split("\n")[0].slice(0,200)}}};let E=false;for(let S=0;S<c&&!E;S++){const k=shuffled(e.cases.map((M,D)=>({c:M,i:D})),f+S*7919>>>0);for(const{c:M,i:D}of k){const P=A[D];if(E||m()<=0){P.rounds.push({round:S+1,status:"skipped",stopReason:"not_run",highestPass:null,lowestMiss:null,resolved:false,steps:[]});continue}n(`round ${S+1}/${c} \xB7 ${M.name}`);let R;try{R=await $.newContext(T);const j=await R.newPage();j.on("pageerror",O=>P.errors.push(String(O?.message??O).slice(0,200)));if(d>1){const O=await R.newCDPSession(j);await O.send("Emulation.setCPUThrottlingRate",{rate:d})}const C=await rampOnce(O=>I(j,M,O,P.errors),{start:r,growth:i,max:o,precisionPct:s,timeLeft:()=>m()>0});P.rounds.push({round:S+1,...C});n(` ${M.name}: ${C.status} ${C.highestPass?.load??"-"}`)}catch(j){P.errors.push((j?.message??String(j)).split("\n")[0].slice(0,200));P.rounds.push({round:S+1,status:"invalid",stopReason:"measurement_failed",highestPass:null,lowestMiss:null,resolved:false,steps:[]})}finally{if(R&&!await closeWithin(R,1e4)){y=true;E=true;w.push(`${M.name}'s browser context didn't close, so the batch stopped to keep later runs clean.`)}}}}for(const S of A){const k=S.rounds.filter(D=>D.status==="bracketed"||D.status==="below_one");S.ceiling=median(k.map(D=>D.highestPass?.load??0));const M=S.rounds.filter(D=>D.status==="lower_bound"&&D.highestPass).map(D=>D.highestPass.load);S.atLeast=M.length?Math.max(...M):null}if(m()<=0)w.push("The batch hit its time limit. Rounds marked skipped or lower_bound didn't finish.");return{url:e.url,browser:`Chromium ${$.version()}${e.headed?"":" (headless)"}`,gpu:_,refreshHz:x,targetFps:a,cpuSlowdown:d,viewport:h,seed:f,results:A,warnings:w}}finally{if(!await closeWithin($,1e4))y=true}}finally{v(y)}}function formatWebRampMarkdown(e){const n=o=>o==null?"\u2014":o.toLocaleString("en-US");const t=o=>o?`${n(o.load)} @ ${o.fps.toFixed(1)}`:"\u2014";const r=[];r.push(`### Web ceiling \xB7 ${e.url}`);r.push(`${e.browser}${e.gpu?` \xB7 GPU: ${e.gpu}${isSoftwareGpu(e.gpu)?" \u26A0\uFE0F software":""}`:""} \xB7 ${e.viewport.width}\xD7${e.viewport.height} @${e.viewport.deviceScaleFactor}x \xB7 idle ${e.refreshHz} Hz \xB7 target ${e.targetFps} fps${e.cpuSlowdown>1?` \xB7 CPU slowed ${e.cpuSlowdown}x`:""}`);r.push("");r.push("**Ceiling** is the most load that held the target, timed from main-thread `requestAnimationFrame` callbacks (a stand-in for drawing speed; it can't see a canvas that stopped updating, so check the looks too). Each round ramps ~30% a step, confirms the first miss, then bisects. With several rounds the ceiling is their median. Ceilings within about 10% are a tie until more rounds agree.");r.push("");const i=Math.max(0,...e.results.map(o=>o.ceiling??0));r.push("| Case | Ceiling | Each round: highest pass @ fps \u2192 lowest miss @ fps | Notes |");r.push("|------|--------:|------------------------------------------------------|-------|");for(const o of e.results){const a=o.rounds.map(c=>{if(c.status==="skipped")return`r${c.round}: not run`;if(c.status==="invalid")return`r${c.round}: invalid (${c.stopReason}) after ${t(c.highestPass)}`;if(c.status==="lower_bound")return`r${c.round}: at least ${t(c.highestPass)} (${c.stopReason})`;if(c.status==="below_one")return`r${c.round}: even 1 missed (${t(c.lowestMiss)})`;return`r${c.round}: ${t(c.highestPass)} \u2192 ${t(c.lowestMiss)}${c.resolved?"":" (wide)"}`}).join("<br>");const s=[o.ceiling===i&&i>0?"best":"",o.atLeast!=null?`at least ${n(o.atLeast)}`:"",o.rounds.some(c=>c.status==="invalid")?"a round broke: check the page before trusting it":"",o.errors.length?`${o.errors.length} page error(s): ${o.errors[0]}`:""].filter(Boolean);r.push(`| ${o.caseName} | ${n(o.ceiling)} | ${a} | ${s.join("; ")} |`)}if(e.warnings.length){r.push("");for(const o of e.warnings)r.push(`- \u26A0\uFE0F ${o}`)}return r.join("\n")}var import_fs=require("fs");var import_path=require("path");var safe=e=>e.replace(/[^\w.-]+/g,"_").slice(0,80);async function runWebShots(e,n=()=>{}){if(!e.cases?.length)throw new Error("Pass at least one case.");if(!e.outDir)throw new Error("Pass outDir, the folder to save screenshots in.");const t=[...new Set((e.atMs?.length?e.atMs:[500,2e3]).map(c=>Math.max(0,Math.round(c))))].sort((c,l)=>c-l);const r=(0,import_path.join)(e.outDir,new Date().toISOString().replace(/[:.]/g,"-"));(0,import_fs.mkdirSync)(r,{recursive:true});const i={width:e.viewport?.width??1280,height:e.viewport?.height??800,deviceScaleFactor:e.viewport?.deviceScaleFactor??1};const o={dir:"",files:[],pageErrors:[],diffs:[],outliers:[]};o.dir=r;const a=await waitForHostLock(e.lockWaitMs??20*6e4,n);let s=false;try{const c=await loadChromium(e.projectRoot??process.cwd());const l=await c.launch({headless:true,args:["--enable-gpu"]});try{for(const[u,d]of e.cases.entries()){let h;try{h=await l.newContext({viewport:{width:i.width,height:i.height},deviceScaleFactor:i.deviceScaleFactor});const w=await h.newPage();w.on("pageerror",g=>o.pageErrors.push({caseName:d.name,error:String(g?.message??g).slice(0,200)}));await w.goto(caseUrl(e.url,d,e.path),{waitUntil:"load",timeout:6e4});if(e.readySelector)await w.waitForSelector(e.readySelector,{state:"attached",timeout:6e4});const p=Date.now();for(const g of t){const m=p+g-Date.now();if(m>0)await w.waitForTimeout(m);const f=Date.now()-p;const v=(0,import_path.join)(r,`${String(u+1).padStart(2,"0")}-${safe(d.name)}-${g}ms.png`);try{if(e.clipSelector){const y=await w.$(e.clipSelector);if(!y)throw new Error(`clipSelector ${e.clipSelector} not found`);await y.screenshot({path:v})}else await w.screenshot({path:v});o.files.push({caseName:d.name,atMs:g,actualMs:f,file:v})}catch(y){o.files.push({caseName:d.name,atMs:g,actualMs:f,file:null,error:(y?.message??String(y)).split("\n")[0]})}}n(`${d.name}: ${t.length} shot(s)`)}catch(w){for(const p of t)o.files.push({caseName:d.name,atMs:p,file:null,error:(w?.message??String(w)).split("\n")[0]})}finally{if(h&&!await closeWithin(h,1e4))s=true}}if(e.cases.length>1){let u;try{u=await l.newContext({viewport:{width:400,height:300}});const d=await u.newPage();const h=e.cases[0].name;for(const f of t){const v=o.files.find(b=>b.caseName===h&&b.atMs===f&&b.file)?.file;if(!v)continue;const y=(0,import_fs.readFileSync)(v).toString("base64");for(const b of o.files.filter($=>$.caseName!==h&&$.atMs===f&&$.file)){const $=await d.evaluate(diffJs(y,(0,import_fs.readFileSync)(b.file).toString("base64")));if($)o.diffs.push({caseName:b.caseName,atMs:f,...$})}}const w=new Map;for(const f of o.diffs)w.set(f.caseName,[...w.get(f.caseName)??[],f.changedPct]);const p=[...w].map(([f,v])=>[f,v.reduce((y,b)=>y+b,0)/v.length]);const g=p.map(([,f])=>f).sort((f,v)=>f-v);const m=g.length?g[Math.floor(g.length/2)]:0;o.outliers=p.filter(([,f])=>f>Math.max(1,m*2)).map(([f])=>f)}catch{}finally{if(u)await closeWithin(u,1e4)}}}finally{if(!await closeWithin(l,1e4))s=true}}finally{a(s)}return o}var diffJs=(e,n)=>`(async () => {
910
+ })`;async function rampOnce(e,n){const t=[];const r=(l,u,d,h)=>({status:l,stopReason:u,highestPass:d?{load:d.load,fps:d.fps??0}:null,lowestMiss:h?{load:h.load,fps:h.fps??0}:null,resolved:l==="below_one"||l==="bracketed"&&!!d&&!!h&&bracketResolved(d.load,h.load,n.precisionPct),steps:t});const i=(l,u,d)=>r("invalid",l.fps==null?"measurement_failed":"page_error",u,d);const o=async(l,u=false)=>{const d=await e(l);if(u)d.confirm=true;t.push(d);return d};let a=null;let s=null;let c=await o(n.start);if(!c.valid)return i(c,null,null);if(c.pass)a=c;else{s=c;let l=n.start;while(!a){if(l<=1)return r("below_one","performance",null,s);if(!n.timeLeft())return r("lower_bound","deadline",null,s);l=Math.max(1,Math.floor(l/2));c=await o(l);if(!c.valid)return i(c,null,s);if(c.pass)a=c;else s=c}}while(!s||s.load<=a.load){if(a.load>=n.max)return r("lower_bound","max",a,null);if(!n.timeLeft())return r("lower_bound","deadline",a,null);c=await o(Math.min(n.max,nextLoad(a.load,n.growth)));if(!c.valid)return i(c,a,null);if(c.pass){a=c;continue}if(!n.timeLeft())return r("bracketed","performance",a,c);const l=await o(c.load,true);if(!l.valid)return i(l,a,null);if(l.pass)a=l;else s=l}while(!bracketResolved(a.load,s.load,n.precisionPct)&&n.timeLeft()){const l=Math.round((a.load+s.load)/2);if(l<=a.load||l>=s.load)break;c=await o(l);if(!c.valid)break;if(c.pass)a=c;else s=c}return r("bracketed","performance",a,s)}async function runWebRamp(e,n=()=>{}){if(!e.cases?.length)throw new Error("Pass at least one case.");if(!e.param)throw new Error('Pass `param`, the query param that sets the load (e.g. "lights").');const t=(b,$)=>{if(b!=null&&!Number.isFinite(b))throw new Error(`${$} must be a finite number.`)};for(const[b,$]of Object.entries({start:e.start,growth:e.growth,max:e.max,targetFps:e.targetFps,precisionPct:e.precisionPct,rounds:e.rounds,settleMs:e.settleMs,measureMs:e.measureMs,cpuSlowdown:e.cpuSlowdown}))t($,b);const r=Math.max(1,Math.floor(e.start??100));const i=Math.min(4,Math.max(1.05,e.growth??1.3));const o=Math.max(r,Math.floor(e.max??1e9));const a=e.targetFps??55;const s=Math.min(50,Math.max(.5,e.precisionPct??4));const c=Math.max(1,Math.min(5,Math.floor(e.rounds??1)));const l=Math.max(0,e.settleMs??1e3);const u=Math.max(500,e.measureMs??2e3);const d=Math.max(1,e.cpuSlowdown??1);const h={width:e.viewport?.width??1280,height:e.viewport?.height??800,deviceScaleFactor:e.viewport?.deviceScaleFactor??1};const w=[];const p=Date.now();const g=p+(e.maxBatchMs??40*6e4);const m=()=>g-Date.now();const f=p>>>0;const v=await waitForHostLock(Math.min(e.lockWaitMs??20*6e4,Math.max(0,m())),n);let y=false;try{const b=await loadChromium(e.projectRoot??process.cwd());const $=await b.launch({headless:!e.headed,args:["--enable-gpu","--disable-backgrounding-occluded-windows","--disable-renderer-backgrounding","--disable-background-timer-throttling"]});try{const T={viewport:{width:h.width,height:h.height},deviceScaleFactor:h.deviceScaleFactor};let _=null;let x=60;{const S=await $.newContext(T);try{const k=await S.newPage();await k.goto("about:blank");_=await k.evaluate(GPU_RENDERER_JS)??null;const M=await withDeadline(k.evaluate(measureFramesJs(200,1e3)),1e4,async()=>({fps:60}));x=snapRefreshRate(M.fps)}finally{await closeWithin(S,5e3)}}n(`GPU ${_??"unknown"} \xB7 idle ${x} Hz`);if(_&&isSoftwareGpu(_))w.push(`Chrome is drawing with a software GPU (${_}), so ceilings are far lower than on a real screen.`);if(a>x*.95){w.push(`The target (${a} fps) is at or above this browser's idle frame rate (${x} Hz), so even an empty page can miss it. Use headed: true on a faster screen, or measure with a target your contract allows.`)}const I=e.cases.map(S=>({caseName:S.name,ceiling:null,atLeast:null,rounds:[],errors:[]}));const D=async(S,k,M,A)=>{const O=A.length;const R=caseUrl(e.url,{...k,params:{...k.params??{},[e.param]:String(M)}},e.path);const j=C=>Math.max(1e3,Math.min(C,m()+15e3));try{await S.goto(R,{waitUntil:"load",timeout:j(6e4)});if(e.readySelector)await S.waitForSelector(e.readySelector,{state:"attached",timeout:j(6e4)});const C=await withDeadline(S.evaluate(measureFramesJs(l,u)),l+u+6e4,async()=>{throw new Error("the page stopped drawing (no frames for 60 s)")});const P=A.length>O?A[A.length-1]:void 0;if(P)return{load:M,fps:C.fps,p95GapMs:C.p95,valid:false,pass:false,error:P};return{load:M,fps:C.fps,p95GapMs:C.p95,valid:true,pass:C.fps>=a}}catch(C){return{load:M,fps:null,p95GapMs:null,valid:false,pass:false,error:(C?.message??String(C)).split("\n")[0].slice(0,200)}}};let E=false;for(let S=0;S<c&&!E;S++){const k=shuffled(e.cases.map((M,A)=>({c:M,i:A})),f+S*7919>>>0);for(const{c:M,i:A}of k){const O=I[A];if(E||m()<=0){O.rounds.push({round:S+1,status:"skipped",stopReason:"not_run",highestPass:null,lowestMiss:null,resolved:false,steps:[]});continue}n(`round ${S+1}/${c} \xB7 ${M.name}`);let R;try{R=await $.newContext(T);const j=await R.newPage();j.on("pageerror",P=>O.errors.push(String(P?.message??P).slice(0,200)));if(d>1){const P=await R.newCDPSession(j);await P.send("Emulation.setCPUThrottlingRate",{rate:d})}const C=await rampOnce(P=>D(j,M,P,O.errors),{start:r,growth:i,max:o,precisionPct:s,timeLeft:()=>m()>0});O.rounds.push({round:S+1,...C});n(` ${M.name}: ${C.status} ${C.highestPass?.load??"-"}`)}catch(j){O.errors.push((j?.message??String(j)).split("\n")[0].slice(0,200));O.rounds.push({round:S+1,status:"invalid",stopReason:"measurement_failed",highestPass:null,lowestMiss:null,resolved:false,steps:[]})}finally{if(R&&!await closeWithin(R,1e4)){y=true;E=true;w.push(`${M.name}'s browser context didn't close, so the batch stopped to keep later runs clean.`)}}}}for(const S of I){const k=S.rounds.filter(A=>A.status==="bracketed"||A.status==="below_one");S.ceiling=median(k.map(A=>A.highestPass?.load??0));const M=S.rounds.filter(A=>A.status==="lower_bound"&&A.highestPass).map(A=>A.highestPass.load);S.atLeast=M.length?Math.max(...M):null}if(m()<=0)w.push("The batch hit its time limit. Rounds marked skipped or lower_bound didn't finish.");return{url:e.url,browser:`Chromium ${$.version()}${e.headed?"":" (headless)"}`,gpu:_,refreshHz:x,targetFps:a,cpuSlowdown:d,viewport:h,seed:f,results:I,warnings:w}}finally{if(!await closeWithin($,1e4))y=true}}finally{v(y)}}function formatWebRampMarkdown(e){const n=o=>o==null?"\u2014":o.toLocaleString("en-US");const t=o=>o?`${n(o.load)} @ ${o.fps.toFixed(1)}`:"\u2014";const r=[];r.push(`### Web ceiling \xB7 ${e.url}`);r.push(`${e.browser}${e.gpu?` \xB7 GPU: ${e.gpu}${isSoftwareGpu(e.gpu)?" \u26A0\uFE0F software":""}`:""} \xB7 ${e.viewport.width}\xD7${e.viewport.height} @${e.viewport.deviceScaleFactor}x \xB7 idle ${e.refreshHz} Hz \xB7 target ${e.targetFps} fps${e.cpuSlowdown>1?` \xB7 CPU slowed ${e.cpuSlowdown}x`:""}`);r.push("");r.push("**Ceiling** is the most load that held the target, timed from main-thread `requestAnimationFrame` callbacks (a stand-in for drawing speed; it can't see a canvas that stopped updating, so check the looks too). Each round ramps ~30% a step, confirms the first miss, then bisects. With several rounds the ceiling is their median. Ceilings within about 10% are a tie until more rounds agree.");r.push("");const i=Math.max(0,...e.results.map(o=>o.ceiling??0));r.push("| Case | Ceiling | Each round: highest pass @ fps \u2192 lowest miss @ fps | Notes |");r.push("|------|--------:|------------------------------------------------------|-------|");for(const o of e.results){const a=o.rounds.map(c=>{if(c.status==="skipped")return`r${c.round}: not run`;if(c.status==="invalid")return`r${c.round}: invalid (${c.stopReason}) after ${t(c.highestPass)}`;if(c.status==="lower_bound")return`r${c.round}: at least ${t(c.highestPass)} (${c.stopReason})`;if(c.status==="below_one")return`r${c.round}: even 1 missed (${t(c.lowestMiss)})`;return`r${c.round}: ${t(c.highestPass)} \u2192 ${t(c.lowestMiss)}${c.resolved?"":" (wide)"}`}).join("<br>");const s=[o.ceiling===i&&i>0?"best":"",o.atLeast!=null?`at least ${n(o.atLeast)}`:"",o.rounds.some(c=>c.status==="invalid")?"a round broke: check the page before trusting it":"",o.errors.length?`${o.errors.length} page error(s): ${o.errors[0]}`:""].filter(Boolean);r.push(`| ${o.caseName} | ${n(o.ceiling)} | ${a} | ${s.join("; ")} |`)}if(e.warnings.length){r.push("");for(const o of e.warnings)r.push(`- \u26A0\uFE0F ${o}`)}return r.join("\n")}var import_fs=require("fs");var import_path=require("path");var safe=e=>e.replace(/[^\w.-]+/g,"_").slice(0,80);async function runWebShots(e,n=()=>{}){if(!e.cases?.length)throw new Error("Pass at least one case.");if(!e.outDir)throw new Error("Pass outDir, the folder to save screenshots in.");const t=[...new Set((e.atMs?.length?e.atMs:[500,2e3]).map(c=>Math.max(0,Math.round(c))))].sort((c,l)=>c-l);const r=(0,import_path.join)(e.outDir,new Date().toISOString().replace(/[:.]/g,"-"));(0,import_fs.mkdirSync)(r,{recursive:true});const i={width:e.viewport?.width??1280,height:e.viewport?.height??800,deviceScaleFactor:e.viewport?.deviceScaleFactor??1};const o={dir:"",files:[],pageErrors:[],diffs:[],outliers:[]};o.dir=r;const a=await waitForHostLock(e.lockWaitMs??20*6e4,n);let s=false;try{const c=await loadChromium(e.projectRoot??process.cwd());const l=await c.launch({headless:true,args:["--enable-gpu"]});try{for(const[u,d]of e.cases.entries()){let h;try{h=await l.newContext({viewport:{width:i.width,height:i.height},deviceScaleFactor:i.deviceScaleFactor});const w=await h.newPage();w.on("pageerror",g=>o.pageErrors.push({caseName:d.name,error:String(g?.message??g).slice(0,200)}));await w.goto(caseUrl(e.url,d,e.path),{waitUntil:"load",timeout:6e4});if(e.readySelector)await w.waitForSelector(e.readySelector,{state:"attached",timeout:6e4});const p=Date.now();for(const g of t){const m=p+g-Date.now();if(m>0)await w.waitForTimeout(m);const f=Date.now()-p;const v=(0,import_path.join)(r,`${String(u+1).padStart(2,"0")}-${safe(d.name)}-${g}ms.png`);try{if(e.clipSelector){const y=await w.$(e.clipSelector);if(!y)throw new Error(`clipSelector ${e.clipSelector} not found`);await y.screenshot({path:v})}else await w.screenshot({path:v});o.files.push({caseName:d.name,atMs:g,actualMs:f,file:v})}catch(y){o.files.push({caseName:d.name,atMs:g,actualMs:f,file:null,error:(y?.message??String(y)).split("\n")[0]})}}n(`${d.name}: ${t.length} shot(s)`)}catch(w){for(const p of t)o.files.push({caseName:d.name,atMs:p,file:null,error:(w?.message??String(w)).split("\n")[0]})}finally{if(h&&!await closeWithin(h,1e4))s=true}}if(e.cases.length>1){let u;try{u=await l.newContext({viewport:{width:400,height:300}});const d=await u.newPage();const h=e.cases[0].name;for(const f of t){const v=o.files.find(b=>b.caseName===h&&b.atMs===f&&b.file)?.file;if(!v)continue;const y=(0,import_fs.readFileSync)(v).toString("base64");for(const b of o.files.filter($=>$.caseName!==h&&$.atMs===f&&$.file)){const $=await d.evaluate(diffJs(y,(0,import_fs.readFileSync)(b.file).toString("base64")));if($)o.diffs.push({caseName:b.caseName,atMs:f,...$})}}const w=new Map;for(const f of o.diffs)w.set(f.caseName,[...w.get(f.caseName)??[],f.changedPct]);const p=[...w].map(([f,v])=>[f,v.reduce((y,b)=>y+b,0)/v.length]);const g=p.map(([,f])=>f).sort((f,v)=>f-v);const m=g.length?g[Math.floor(g.length/2)]:0;o.outliers=p.filter(([,f])=>f>Math.max(1,m*2)).map(([f])=>f)}catch{}finally{if(u)await closeWithin(u,1e4)}}}finally{if(!await closeWithin(l,1e4))s=true}}finally{a(s)}return o}var diffJs=(e,n)=>`(async () => {
910
911
  const load = (s) => new Promise((res, rej) => { const i = new Image(); i.onload = () => res(i); i.onerror = rej; i.src = "data:image/png;base64," + s; });
911
912
  const [ia, ib] = await Promise.all([load(${JSON.stringify(e)}), load(${JSON.stringify(n)})]);
912
913
  const w = ia.naturalWidth, h = ia.naturalHeight;
@@ -926,61 +927,61 @@ _Apps already running do not pick up a camera they started without \u2014 use \`
926
927
 
927
928
  \u23F1 **Buoy Optimize: ${t} min left** (deadline ${clock(n)}). Confirm the best checked version, install it and finish the report.`}return`
928
929
 
929
- \u23F1 **Buoy Optimize: the deadline (${clock(n)}) has passed.** Leave the best checked version in place and report.`}var text7=e=>({content:[{type:"text",text:e}]});var fail9=e=>({isError:true,content:[{type:"text",text:e}]});var PRO_REQUIRED="`run_web_benchmark` is a Buoy Pro feature. Running benchmarks from an agent needs Pro.\n\n_Tell the user to sign in to Buoy Desktop with a Pro account, or open an app signed in to Pro. See https://buoy.gg/pricing. Don't try to work around it._";function hasPro(e){if(readEntitlement().isPro)return true;return e.connectedDevices().some(n=>n.tier==="pro")}function registerWebBenchTools(e,n){e.registerTool("run_web_benchmark",{description:"Benchmark variants of a web page in a fresh headless Chromium (needs Playwright in the project). Each case is a path + query params on a running app; each run loads a fresh page, waits until ready, then records frame rate, frame gaps, long tasks, Long Animation Frames (with script names), layout shifts, DOM size, and Chrome's own main-thread, script, style and layout time. Cases run in rounds with the order shuffled each round. `cpuSlowdown` repeats everything with Chrome's CPU throttled (e.g. [1, 4, 6]) as a stand-in for slower phones; it doesn't slow the GPU. Blocks until done.",inputSchema:{url:import_zod26.z.string().describe("Origin of the running app, e.g. http://localhost:5173"),path:import_zod26.z.string().optional().describe("Default path for cases, e.g. /bench/lights"),cases:import_zod26.z.array(import_zod26.z.object({name:import_zod26.z.string(),path:import_zod26.z.string().optional(),params:import_zod26.z.record(import_zod26.z.string()).optional(),control:import_zod26.z.boolean().optional().describe("Does different work (e.g. an empty page). Shown, never the baseline or a candidate.")})).min(1).describe("Variants to compare. The first is the baseline."),runsPerCase:import_zod26.z.number().optional().describe("Measured runs per case (1\u201310). Default 3."),perCaseDurationMs:import_zod26.z.number().optional().describe("Recording length per run. Default 5000."),settleMs:import_zod26.z.number().optional().describe("Wait after the page is ready, before recording. Default 1000."),cpuSlowdown:import_zod26.z.array(import_zod26.z.number()).optional().describe("CPU throttling rates; 1 = none. Default [1]."),viewport:import_zod26.z.object({width:import_zod26.z.number(),height:import_zod26.z.number(),deviceScaleFactor:import_zod26.z.number().optional()}).optional().describe("Fixed viewport. Default 1280\xD7800 at 1x."),readySelector:import_zod26.z.string().optional().describe("CSS selector that must appear before a run counts as ready."),steps:import_zod26.z.array(import_zod26.z.union([import_zod26.z.object({click:import_zod26.z.string()}),import_zod26.z.object({press:import_zod26.z.string()}),import_zod26.z.object({type:import_zod26.z.object({selector:import_zod26.z.string(),text:import_zod26.z.string()})}),import_zod26.z.object({scroll:import_zod26.z.number()}),import_zod26.z.object({wait:import_zod26.z.number()}),import_zod26.z.object({expect:import_zod26.z.object({selector:import_zod26.z.string(),text:import_zod26.z.string().optional()})})])).optional().describe("Real input during each run, in order: {click: selector}, {press: key}, {type: {selector, text}}, {scroll: px}, {wait: ms}, {expect: {selector, text?}} (checked after the run; fails runs that skipped the work). Click targets are located before recording and must not move. Adds input delay, handler time and time to next paint per case."),traceDir:import_zod26.z.string().optional().describe("Save one Chrome trace per case here (extra, unranked runs)."),headed:import_zod26.z.boolean().optional().describe("Show the browser window. Default false."),allowPageErrors:import_zod26.z.boolean().optional().describe("Keep runs whose page threw an uncaught error. Default false: such runs fail."),projectRoot:import_zod26.z.string().optional().describe("Folder to load Playwright from. Default: the server's working directory."),outFile:import_zod26.z.string().optional().describe("Also save the full result and options as JSON here, to read again later."),extraRoundsWhenClose:import_zod26.z.number().optional().describe("If the two smoothest cases are too close to call, run up to this many extra rounds of just those two. Default 0."),maxBatchMs:import_zod26.z.number().optional().describe("Stop starting new runs after this long. Default 30 minutes."),budgets:import_zod26.z.object({droppedPct:import_zod26.z.number().optional(),inputMs:import_zod26.z.number().optional(),freezeMs:import_zod26.z.number().optional(),mainThreadPct:import_zod26.z.number().optional(),jsHeapMb:import_zod26.z.number().optional()}).optional().describe("Hard limits. The report says which cases meet all of them; an unmeasured limit counts as not met.")}},async t=>{if(!hasPro(n))return fail9(PRO_REQUIRED);try{const r=await runWebBench({url:t.url,path:t.path,cases:t.cases,runsPerCase:t.runsPerCase,durationMs:t.perCaseDurationMs,settleMs:t.settleMs,cpuSlowdown:t.cpuSlowdown,viewport:t.viewport,readySelector:t.readySelector,steps:t.steps,traceDir:t.traceDir,headed:t.headed,allowPageErrors:t.allowPageErrors,projectRoot:t.projectRoot,outFile:t.outFile,extraRoundsWhenClose:t.extraRoundsWhenClose,maxBatchMs:t.maxBatchMs,budgets:t.budgets},a=>process.stderr.write(`[buoy-mcp] web-bench: ${a}
930
+ \u23F1 **Buoy Optimize: the deadline (${clock(n)}) has passed.** Leave the best checked version in place and report.`}var text8=e=>({content:[{type:"text",text:e}]});var fail10=e=>({isError:true,content:[{type:"text",text:e}]});var PRO_REQUIRED="`run_web_benchmark` is a Buoy Pro feature. Running benchmarks from an agent needs Pro.\n\n_Tell the user to sign in to Buoy Desktop with a Pro account, or open an app signed in to Pro. See https://buoy.gg/pricing. Don't try to work around it._";function hasPro(e){if(readEntitlement().isPro)return true;return e.connectedDevices().some(n=>n.tier==="pro")}function registerWebBenchTools(e,n){e.registerTool("run_web_benchmark",{description:"Benchmark variants of a web page in a fresh headless Chromium (needs Playwright in the project). Each case is a path + query params on a running app; each run loads a fresh page, waits until ready, then records frame rate, frame gaps, long tasks, Long Animation Frames (with script names), layout shifts, DOM size, and Chrome's own main-thread, script, style and layout time. Cases run in rounds with the order shuffled each round. `cpuSlowdown` repeats everything with Chrome's CPU throttled (e.g. [1, 4, 6]) as a stand-in for slower phones; it doesn't slow the GPU. Blocks until done.",inputSchema:{url:import_zod27.z.string().describe("Origin of the running app, e.g. http://localhost:5173"),path:import_zod27.z.string().optional().describe("Default path for cases, e.g. /bench/lights"),cases:import_zod27.z.array(import_zod27.z.object({name:import_zod27.z.string(),path:import_zod27.z.string().optional(),params:import_zod27.z.record(import_zod27.z.string()).optional(),control:import_zod27.z.boolean().optional().describe("Does different work (e.g. an empty page). Shown, never the baseline or a candidate.")})).min(1).describe("Variants to compare. The first is the baseline."),runsPerCase:import_zod27.z.number().optional().describe("Measured runs per case (1\u201310). Default 3."),perCaseDurationMs:import_zod27.z.number().optional().describe("Recording length per run. Default 5000."),settleMs:import_zod27.z.number().optional().describe("Wait after the page is ready, before recording. Default 1000."),cpuSlowdown:import_zod27.z.array(import_zod27.z.number()).optional().describe("CPU throttling rates; 1 = none. Default [1]."),viewport:import_zod27.z.object({width:import_zod27.z.number(),height:import_zod27.z.number(),deviceScaleFactor:import_zod27.z.number().optional()}).optional().describe("Fixed viewport. Default 1280\xD7800 at 1x."),readySelector:import_zod27.z.string().optional().describe("CSS selector that must appear before a run counts as ready."),steps:import_zod27.z.array(import_zod27.z.union([import_zod27.z.object({click:import_zod27.z.string()}),import_zod27.z.object({press:import_zod27.z.string()}),import_zod27.z.object({type:import_zod27.z.object({selector:import_zod27.z.string(),text:import_zod27.z.string()})}),import_zod27.z.object({scroll:import_zod27.z.number()}),import_zod27.z.object({wait:import_zod27.z.number()}),import_zod27.z.object({expect:import_zod27.z.object({selector:import_zod27.z.string(),text:import_zod27.z.string().optional()})})])).optional().describe("Real input during each run, in order: {click: selector}, {press: key}, {type: {selector, text}}, {scroll: px}, {wait: ms}, {expect: {selector, text?}} (checked after the run; fails runs that skipped the work). Click targets are located before recording and must not move. Adds input delay, handler time and time to next paint per case."),traceDir:import_zod27.z.string().optional().describe("Save one Chrome trace per case here (extra, unranked runs)."),headed:import_zod27.z.boolean().optional().describe("Show the browser window. Default false."),allowPageErrors:import_zod27.z.boolean().optional().describe("Keep runs whose page threw an uncaught error. Default false: such runs fail."),projectRoot:import_zod27.z.string().optional().describe("Folder to load Playwright from. Default: the server's working directory."),outFile:import_zod27.z.string().optional().describe("Also save the full result and options as JSON here, to read again later."),extraRoundsWhenClose:import_zod27.z.number().optional().describe("If the two smoothest cases are too close to call, run up to this many extra rounds of just those two. Default 0."),maxBatchMs:import_zod27.z.number().optional().describe("Stop starting new runs after this long. Default 30 minutes."),budgets:import_zod27.z.object({droppedPct:import_zod27.z.number().optional(),inputMs:import_zod27.z.number().optional(),freezeMs:import_zod27.z.number().optional(),mainThreadPct:import_zod27.z.number().optional(),jsHeapMb:import_zod27.z.number().optional()}).optional().describe("Hard limits. The report says which cases meet all of them; an unmeasured limit counts as not met.")}},async t=>{if(!hasPro(n))return fail10(PRO_REQUIRED);try{const r=await runWebBench({url:t.url,path:t.path,cases:t.cases,runsPerCase:t.runsPerCase,durationMs:t.perCaseDurationMs,settleMs:t.settleMs,cpuSlowdown:t.cpuSlowdown,viewport:t.viewport,readySelector:t.readySelector,steps:t.steps,traceDir:t.traceDir,headed:t.headed,allowPageErrors:t.allowPageErrors,projectRoot:t.projectRoot,outFile:t.outFile,extraRoundsWhenClose:t.extraRoundsWhenClose,maxBatchMs:t.maxBatchMs,budgets:t.budgets},a=>process.stderr.write(`[buoy-mcp] web-bench: ${a}
930
931
  `));const i={status:r.status,browser:r.browser,gpu:r.gpu??null,viewport:r.viewport,results:r.results.map(a=>({caseName:a.caseName,cpu:a.cpu,validRuns:a.validRuns,fpsMin:a.fpsMin,fpsMax:a.fpsMax,plannedRuns:a.plannedRuns,isBaseline:a.isBaseline,control:a.control===true,deltaDroppedPct:a.deltaDroppedPct,droppedRange:a.droppedMin==null?null:[a.droppedMin,a.droppedMax],flags:a.flags,budget:a.budget,median:a.median,failures:a.runs.filter(s=>s.failed).map(s=>s.failed)})),traces:r.traces,warnings:r.warnings,replay:r.replay};const o=`${formatWebBenchMarkdown(r)}
931
932
 
932
933
  \`\`\`json
933
934
  ${JSON.stringify(i,null,2)}
934
- \`\`\``;return r.status==="failed"?fail9(`Every case failed.
935
+ \`\`\``;return r.status==="failed"?fail10(`Every case failed.
935
936
 
936
- ${o}`):text7(o)}catch(r){return fail9(r?.message??String(r))}});e.registerTool("find_web_ceiling",{description:"Find the most load each web variant can hold at a target frame rate, with no cap. For each case, a fresh headless Chromium (real GPU) opens the page with `param` set (e.g. ?lights=100), waits until ready, settles, then counts requestAnimationFrame callbacks. It raises the load ~30% a step until a valid sample misses `targetFps`, confirms the miss, then bisects to within a few percent; if the first load misses it searches down. A page error ends the round as invalid instead of counting as a miss. An app's own capped test is not the ceiling. Needs Playwright in the project. Blocks until done.",inputSchema:{url:import_zod26.z.string().describe("Origin of the running app, e.g. http://localhost:5173"),path:import_zod26.z.string().optional().describe("Default path for cases."),cases:import_zod26.z.array(import_zod26.z.object({name:import_zod26.z.string(),path:import_zod26.z.string().optional(),params:import_zod26.z.record(import_zod26.z.string()).optional()})).min(1).describe("Variants to ramp, e.g. [{name: 'baseline', params: {variant: 'baseline'}}, {name: 'atlas', params: {variant: 'atlas'}}]."),param:import_zod26.z.string().describe("Query param that sets the load, e.g. 'lights' or 'count'."),start:import_zod26.z.number().optional().describe("First load. Default 100."),growth:import_zod26.z.number().optional().describe("Growth per step. Default 1.3."),max:import_zod26.z.number().optional().describe("Highest load to try. Default 1,000,000,000."),targetFps:import_zod26.z.number().optional().describe("Frame rate each step must hold. Default 55."),precisionPct:import_zod26.z.number().optional().describe("Bisect until the pass/miss gap is within this percent. Default 4."),rounds:import_zod26.z.number().optional().describe("Ramps per case (1\u20135); the ceiling is the median of valid rounds. Default 1. Use 3 to settle close calls."),maxBatchMs:import_zod26.z.number().optional().describe("Stop the whole batch after this long. Default 40 minutes."),settleMs:import_zod26.z.number().optional().describe("Wait after ready before counting frames. Default 1000."),measureMs:import_zod26.z.number().optional().describe("How long to count frames per step. Default 2000."),cpuSlowdown:import_zod26.z.number().optional().describe("CPU throttling rate; 1 = none. Default 1."),viewport:import_zod26.z.object({width:import_zod26.z.number(),height:import_zod26.z.number(),deviceScaleFactor:import_zod26.z.number().optional()}).optional(),readySelector:import_zod26.z.string().optional().describe("CSS selector that must exist before counting frames."),headed:import_zod26.z.boolean().optional().describe("Show the browser window (uses the screen's refresh rate). Default false."),projectRoot:import_zod26.z.string().optional().describe("Folder to load Playwright from.")}},async t=>{if(!hasPro(n))return fail9(PRO_REQUIRED.replace("run_web_benchmark","find_web_ceiling"));try{const r=await runWebRamp(t,a=>process.stderr.write(`[buoy-mcp] web-ceiling: ${a}
937
+ ${o}`):text8(o)}catch(r){return fail10(r?.message??String(r))}});e.registerTool("find_web_ceiling",{description:"Find the most load each web variant can hold at a target frame rate, with no cap. For each case, a fresh headless Chromium (real GPU) opens the page with `param` set (e.g. ?lights=100), waits until ready, settles, then counts requestAnimationFrame callbacks. It raises the load ~30% a step until a valid sample misses `targetFps`, confirms the miss, then bisects to within a few percent; if the first load misses it searches down. A page error ends the round as invalid instead of counting as a miss. An app's own capped test is not the ceiling. Needs Playwright in the project. Blocks until done.",inputSchema:{url:import_zod27.z.string().describe("Origin of the running app, e.g. http://localhost:5173"),path:import_zod27.z.string().optional().describe("Default path for cases."),cases:import_zod27.z.array(import_zod27.z.object({name:import_zod27.z.string(),path:import_zod27.z.string().optional(),params:import_zod27.z.record(import_zod27.z.string()).optional()})).min(1).describe("Variants to ramp, e.g. [{name: 'baseline', params: {variant: 'baseline'}}, {name: 'atlas', params: {variant: 'atlas'}}]."),param:import_zod27.z.string().describe("Query param that sets the load, e.g. 'lights' or 'count'."),start:import_zod27.z.number().optional().describe("First load. Default 100."),growth:import_zod27.z.number().optional().describe("Growth per step. Default 1.3."),max:import_zod27.z.number().optional().describe("Highest load to try. Default 1,000,000,000."),targetFps:import_zod27.z.number().optional().describe("Frame rate each step must hold. Default 55."),precisionPct:import_zod27.z.number().optional().describe("Bisect until the pass/miss gap is within this percent. Default 4."),rounds:import_zod27.z.number().optional().describe("Ramps per case (1\u20135); the ceiling is the median of valid rounds. Default 1. Use 3 to settle close calls."),maxBatchMs:import_zod27.z.number().optional().describe("Stop the whole batch after this long. Default 40 minutes."),settleMs:import_zod27.z.number().optional().describe("Wait after ready before counting frames. Default 1000."),measureMs:import_zod27.z.number().optional().describe("How long to count frames per step. Default 2000."),cpuSlowdown:import_zod27.z.number().optional().describe("CPU throttling rate; 1 = none. Default 1."),viewport:import_zod27.z.object({width:import_zod27.z.number(),height:import_zod27.z.number(),deviceScaleFactor:import_zod27.z.number().optional()}).optional(),readySelector:import_zod27.z.string().optional().describe("CSS selector that must exist before counting frames."),headed:import_zod27.z.boolean().optional().describe("Show the browser window (uses the screen's refresh rate). Default false."),projectRoot:import_zod27.z.string().optional().describe("Folder to load Playwright from.")}},async t=>{if(!hasPro(n))return fail10(PRO_REQUIRED.replace("run_web_benchmark","find_web_ceiling"));try{const r=await runWebRamp(t,a=>process.stderr.write(`[buoy-mcp] web-ceiling: ${a}
937
938
  `));const i=r.results.map(a=>({caseName:a.caseName,ceiling:a.ceiling,atLeast:a.atLeast,rounds:a.rounds.map(s=>({status:s.status,stopReason:s.stopReason,highestPass:s.highestPass,lowestMiss:s.lowestMiss,resolved:s.resolved})),errors:a.errors.slice(0,3)}));const o=`${formatWebRampMarkdown(r)}
938
939
 
939
940
  \`\`\`json
940
941
  ${JSON.stringify({gpu:r.gpu,refreshHz:r.refreshHz,seed:r.seed,results:i},null,2)}
941
- \`\`\``;return text7(o)}catch(r){return fail9(r?.message??String(r))}});e.registerTool("screenshot_web_variants",{description:"Screenshot every web variant at the same moments after it's ready, in a fresh headless Chromium (real GPU), and save PNGs in a new timestamped folder inside outDir. Use it to check each variant still looks right: open the files and compare them side by side with the baseline. Use the same params (e.g. the same count and pattern) for every case. Animated scenes differ by timing, so compare shapes, colors, glow and layout, and take several moments to catch frozen or broken motion.",inputSchema:{url:import_zod26.z.string().describe("Origin of the running app."),path:import_zod26.z.string().optional(),cases:import_zod26.z.array(import_zod26.z.object({name:import_zod26.z.string(),path:import_zod26.z.string().optional(),params:import_zod26.z.record(import_zod26.z.string()).optional()})).min(1),atMs:import_zod26.z.array(import_zod26.z.number()).optional().describe("Times after ready to capture, in ms. Default [500, 2000]."),outDir:import_zod26.z.string().describe("Folder to save the PNGs in."),viewport:import_zod26.z.object({width:import_zod26.z.number(),height:import_zod26.z.number(),deviceScaleFactor:import_zod26.z.number().optional()}).optional(),readySelector:import_zod26.z.string().optional(),clipSelector:import_zod26.z.string().optional().describe("Crop to this element, e.g. 'canvas'."),projectRoot:import_zod26.z.string().optional()}},async t=>{if(!hasPro(n))return fail9(PRO_REQUIRED.replace("run_web_benchmark","screenshot_web_variants"));try{const r=await runWebShots(t,c=>process.stderr.write(`[buoy-mcp] web-shots: ${c}
942
+ \`\`\``;return text8(o)}catch(r){return fail10(r?.message??String(r))}});e.registerTool("screenshot_web_variants",{description:"Screenshot every web variant at the same moments after it's ready, in a fresh headless Chromium (real GPU), and save PNGs in a new timestamped folder inside outDir. Use it to check each variant still looks right: open the files and compare them side by side with the baseline. Use the same params (e.g. the same count and pattern) for every case. Animated scenes differ by timing, so compare shapes, colors, glow and layout, and take several moments to catch frozen or broken motion.",inputSchema:{url:import_zod27.z.string().describe("Origin of the running app."),path:import_zod27.z.string().optional(),cases:import_zod27.z.array(import_zod27.z.object({name:import_zod27.z.string(),path:import_zod27.z.string().optional(),params:import_zod27.z.record(import_zod27.z.string()).optional()})).min(1),atMs:import_zod27.z.array(import_zod27.z.number()).optional().describe("Times after ready to capture, in ms. Default [500, 2000]."),outDir:import_zod27.z.string().describe("Folder to save the PNGs in."),viewport:import_zod27.z.object({width:import_zod27.z.number(),height:import_zod27.z.number(),deviceScaleFactor:import_zod27.z.number().optional()}).optional(),readySelector:import_zod27.z.string().optional(),clipSelector:import_zod27.z.string().optional().describe("Crop to this element, e.g. 'canvas'."),projectRoot:import_zod27.z.string().optional()}},async t=>{if(!hasPro(n))return fail10(PRO_REQUIRED.replace("run_web_benchmark","screenshot_web_variants"));try{const r=await runWebShots(t,c=>process.stderr.write(`[buoy-mcp] web-shots: ${c}
942
943
  `));const i=r.files.map(c=>`- ${c.caseName} @ ${c.atMs} ms${c.actualMs!=null&&Math.abs(c.actualMs-c.atMs)>50?` (taken at ${c.actualMs} ms)`:""}: ${c.file??`failed (${c.error})`}`);const o=r.pageErrors.map(c=>`- ${c.caseName}: ${c.error}`);const a=t.cases[0]?.name;const s=r.diffs.length?`
943
944
 
944
945
  **Difference from ${a}** (same moment; mean 0\u2013255, and % of pixels off by more than 32):
945
946
  `+r.diffs.map(c=>`- ${c.caseName} @ ${c.atMs} ms: mean ${c.meanDiff}, ${c.changedPct}% changed${r.outliers.includes(c.caseName)?" \u26A0\uFE0F outlier":""}`).join("\n")+(r.outliers.length?`
946
947
 
947
- \u26A0\uFE0F ${r.outliers.join(", ")} differ from ${a} far more than the other variants. Something may be missing or wrong (lights not drawn, wrong colors, frozen motion). Open those images first.`:""):"";return text7(`### Variant screenshots
948
+ \u26A0\uFE0F ${r.outliers.join(", ")} differ from ${a} far more than the other variants. Something may be missing or wrong (lights not drawn, wrong colors, frozen motion). Open those images first.`:""):"";return text8(`### Variant screenshots
948
949
 
949
950
  ${i.join("\n")}${o.length?`
950
951
 
951
952
  **Page errors**
952
953
  ${o.join("\n")}`:""}${s}
953
954
 
954
- Open the files and compare each variant with the baseline at the same moment. Put the baseline first in \`cases\` so the difference numbers compare against it. Animation makes some difference normal; a variant far from the rest needs a close look. A variant that looks wrong can't win.`)}catch(r){return fail9(r?.message??String(r))}});e.registerTool("start_optimize_session",{description:"Start the Buoy Optimize clock. Pass how long the session lasts (`minutes`) or when it ends (`deadline`, ISO time). After this, every Buoy tool result shows the time left, so the loop keeps going until the deadline. Call it once at the start of an optimize session. Pass minutes: 0 to stop the clock.",inputSchema:{minutes:import_zod26.z.number().optional().describe("Session length from now, in minutes."),deadline:import_zod26.z.string().optional().describe("When the session ends, as an ISO time, e.g. 2026-10-04T07:12:00-06:00.")}},async t=>{if(t.minutes===0){setOptimizeDeadline(null);return text7("Optimize clock stopped.")}const r=t.deadline?Date.parse(t.deadline):t.minutes!=null?Date.now()+t.minutes*6e4:NaN;if(!Number.isFinite(r))return fail9("Pass `minutes` (a number) or `deadline` (an ISO time).");if(r<=Date.now())return fail9("That deadline has already passed.");setOptimizeDeadline(r);return text7(`Optimize clock started. Deadline: ${new Date(r).toISOString()}.${optimizeNote()??""}`)})}var import_zod27=require("zod");var import_node_child_process18=require("child_process");var import_node_util16=require("util");var import_node_fs15=require("fs");var import_node_os12=__toESM(require("os"));var import_node_path16=__toESM(require("path"));var import_node_crypto7=require("crypto");var execFileAsync16=(0,import_node_util16.promisify)(import_node_child_process18.execFile);async function run4(e,n,t=2e4){try{const{stdout:r}=await execFileAsync16(e,n,{timeout:t});return r}catch(r){const i=r;throw new Error(`${e} ${n.slice(0,3).join(" ")} failed: ${(i.stderr||i.message||"").trim().split("\n").slice(-2).join(" ").slice(0,300)}`)}}var devicectl2=e=>run4("xcrun",["devicectl",...e,"--quiet"]);var IOS_ORIENTATION={portrait:"portrait",landscape_left:"landscapeLeft",landscape_right:"landscapeRight",upside_down:"portraitUpsideDown"};var ANDROID_ROTATION={portrait:0,landscape_left:1,upside_down:2,landscape_right:3};async function rotate(e,n){if(e.platform==="android"){await adbShell(e.serial,"settings put system accelerometer_rotation 0");await adbShell(e.serial,`settings put system user_rotation ${ANDROID_ROTATION[n]}`);return`Rotated to ${n.replace("_"," ")} (auto-rotate is now off on this device; rotate to portrait to go back).`}await devicectl2(["device","orientation","set","--device",e.udid,IOS_ORIENTATION[n]]);return`Rotated the device to ${n.replace("_"," ")}. An app that only supports portrait keeps its screen upright.`}async function shake(e){if(e.platform==="ios"){await run4("xcrun",["simctl","spawn",e.udid,"notifyutil","-p","com.apple.UIKit.SimulatorShake"]);return"Sent a shake to the simulator (the same event as Device > Shake). Check the screen: an app only reacts if it listens for shakes."}if(e.platform==="android"){if(!/^emulator-\d+$/.test(e.serial))throw new Error("A physical Android phone can't be shaken from the computer. Use an emulator, or shake the phone.");for(const n of["0:25:0","0:-25:0","0:25:0","0:-25:0","0:9.81:0"]){await adb(e.serial,["emu","sensor","set","acceleration",n]);await new Promise(t=>setTimeout(t,80))}return"Shook the emulator (an accelerometer burst). Check the screen: an app only reacts if it listens for shakes."}throw new Error("A physical iPhone can't be shaken from the computer. Use a simulator, or shake the phone.")}async function setClipboard(e,n){if(e.platform==="ios"){await new Promise((t,r)=>{const i=(0,import_node_child_process18.spawn)("xcrun",["simctl","pbcopy",e.udid],{stdio:["pipe","ignore","pipe"]});let o="";i.stderr.on("data",a=>o+=a);i.on("error",r);i.on("exit",a=>a===0?t():r(new Error(`simctl pbcopy failed: ${o.trim()}`)));i.stdin.end(n)})}else if(e.platform==="ios-device"){const t=import_node_path16.default.join(import_node_os12.default.tmpdir(),`buoy-clip-${(0,import_node_crypto7.randomUUID)()}.txt`);await import_node_fs15.promises.writeFile(t,n,{mode:384});try{await devicectl2(["device","pasteboard","copy","--device",e.udid,"--type","public.utf8-plain-text","--file",t])}finally{await import_node_fs15.promises.unlink(t).catch(()=>void 0)}}else{throw new Error("Setting the clipboard from the computer isn't supported on Android. Use native_type to type the text instead.")}return e.platform==="ios-device"?"Put the text on the iPhone's clipboard. To paste it for real, long-press the field (native_tap with holdMs: 600) and tap Paste (native_tap with x and y; labels don't work on a phone).":'Put the text on the clipboard. To paste it for real, long-press the field (native_tap with holdMs: 600) and tap Paste (native_tap label: "Paste").'}async function biometrics(e,n,t){if(e.platform==="android"){if(!/^emulator-\d+$/.test(e.serial))throw new Error("Biometrics can be simulated on an Android emulator only.");const r=await adbShell(e.serial,"dumpsys fingerprint").catch(()=>"");if(n&&/"count"\s*:\s*0|enrolled[^\n]*\b0\b/i.test(r)){throw new Error("No fingerprint is enrolled on this emulator. Enroll one in Settings > Security, then try again.")}const i=t??(n?1:9731);await adb(e.serial,["emu","finger","touch",String(i)]);return n?`Touched fingerprint id ${i}. It matches only if that finger is enrolled in the emulator's Settings (enroll one there first if the app says no fingerprints).`:`Touched fingerprint id ${i}, meant to fail. It would match instead if id ${i} is enrolled; pass another fingerId if so.`}await devicectl2(["device","simulate","biometrics","--device",e.udid,n?"--success":"--failure"]);return n?"Simulated a matching Face ID / Touch ID.":"Simulated a Face ID / Touch ID that doesn't match."}function registerDeviceTools(e,n){e.registerTool("device_control",{_meta:coreTool(),description:"Do something to the device itself: rotate (orientation), shake (shake-to-undo, shake-to-report, dev menus), clipboard (text on the clipboard for a real paste), biometrics (Face ID / Touch ID / fingerprint match or fail). iOS Simulator, physical iPhone (rotate, clipboard) and Android (rotate, emulator shake and fingerprint). Returns the screen after when the app is connected (not for clipboard).",inputSchema:{action:import_zod27.z.enum(["rotate","shake","clipboard","biometrics"]),orientation:import_zod27.z.enum(["portrait","landscape_left","landscape_right","upside_down"]).optional().describe("rotate (required)."),text:import_zod27.z.string().optional().describe("clipboard (required). {{secret:NAME}} works here too."),match:import_zod27.z.boolean().optional().describe("biometrics: true for a match (default), false for a failed one."),fingerId:import_zod27.z.number().int().min(1).optional().describe("biometrics on an Android emulator: the finger id to touch: an enrolled one for a match (default 1), one that is not enrolled for a failure (default 9731)."),serial:import_zod27.z.string().optional().describe("Android: the adb serial, when several devices are connected."),deviceId:deviceIdInput}},async t=>{try{const{id:r,host:i,online:o}=await hostTarget(n,t.deviceId,{serial:t.serial},{allowOffline:t.action!=="clipboard"});let a;switch(t.action){case"rotate":if(!t.orientation)return fail2("rotate requires `orientation`.");a=await rotate(i,t.orientation);if(i.platform!=="android")forgetScreenSize(i.udid);break;case"shake":a=await shake(i);break;case"clipboard":if(t.text===void 0)return fail2("clipboard requires `text`.");a=await setClipboard(i,fillSecrets(t.text));break;case"biometrics":a=await biometrics(i,t.match!==false,t.fingerId);break}if(t.action!=="rotate"||i.platform!=="ios")await new Promise(c=>setTimeout(c,700));const s=o&&t.action!=="clipboard"?await observeAfterAction(n,r):"";return text(`${a} (${hostLabel(i)})${s}`)}catch(r){return fail2(errMsg2(r))}})}var import_node_path17=__toESM(require("path"));var import_node_url2=require("url");var import_zod28=require("zod");function parseReact19Frames(e,n=10){const t=[];for(const r of e.split("\n")){if(t.length>=n)break;const i=parseReact19Stack(r);if(i)t.push(i)}return t}function parseReact19Stack(e){for(const n of e.split("\n")){if(/\b(?:react[-_]stack[-_](?:top|bottom)[-_]frame|jsxDEV(?:Impl)?|jsxWithValidation|createElement)\b/.test(n))continue;const t=n.trim();const r=/:(\d+):(\d+)\)?\s*$/.exec(t);if(!r)continue;const i=t.slice(0,r.index);const o=/\s\((?=https?:\/\/|file:\/\/|address at |\/|[A-Za-z]:[\\/])/.exec(i);let a;let s;if(o){a=i.slice(o.index+2);s=o.index}else{const d=/(?:^at\s+|@)((?:https?:\/\/|file:\/\/|\/|[A-Za-z]:[\\/]).*)$/.exec(i);if(!d)continue;a=d[1];s=d.index}const c=Object.assign([t,a,r[1],r[2]],{index:s});const l=Number(c[2]);const u=Number(c[3]);if(!Number.isSafeInteger(l)||l<1||!Number.isSafeInteger(u))continue;return{file:c[1].replace(/^address at\s+/,""),lineNumber:l,column:u,methodName:t.slice(0,c.index).replace(/^at\s+/,"").replace(/[(@\s]+$/,"")||"x"}}return null}function isBundleURL(e){return/^https?:\/\//i.test(e)}function relativeSourcePath(e,n=process.env.BUOY_PROJECT_ROOT||process.cwd()){let t=e;if(t.startsWith("file://")){try{t=(0,import_node_url2.fileURLToPath)(t)}catch{return e}}if(isBundleURL(t))return t;const r=/^[A-Za-z]:[\\/]/.test(t)&&/^[A-Za-z]:[\\/]/.test(n)?import_node_path17.default.win32:import_node_path17.default;if(!r.isAbsolute(t))return t;const i=r.relative(r.resolve(n),t);return i&&i!==".."&&!i.startsWith(`..${r.sep}`)&&!r.isAbsolute(i)?i.split(r.sep).join("/"):t}async function symbolicateFrame(e,n,t=fetch){const r=await t(`${n.replace(/\/$/,"")}/symbolicate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({stack:[e]}),signal:AbortSignal.timeout(5e3)});if(!r.ok)throw new Error(`Metro could not map this frame (HTTP ${r.status}).`);const i=await r.json();const o=i?.stack?.[0];if(typeof o?.file!=="string"||!o.file||isBundleURL(o.file)||typeof o.lineNumber!=="number"||!Number.isInteger(o.lineNumber)||o.lineNumber<1){throw new Error("Metro did not return a source file and line.")}return{fileName:o.file,lineNumber:o.lineNumber,...typeof o.column==="number"&&Number.isInteger(o.column)&&o.column>=0?{columnNumber:o.column}:{}}}var LIBRARY=/node_modules\/|\/react-native\/|\/Libraries\/|\/expo-router\//;async function symbolicateAppFrame(e,n,t=fetch){const r=await t(`${n.replace(/\/$/,"")}/symbolicate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({stack:e}),signal:AbortSignal.timeout(5e3)});if(!r.ok){const o=(await r.json().catch(()=>null))?.error;const a=typeof o==="string"&&o?` Metro said: ${o.slice(0,200)}`:"";const s=/serialized source map/i.test(a)?" Its cache looks stale; restarting Metro with --clear usually fixes this.":"";throw new Error(`Metro could not map these frames (HTTP ${r.status}).${a}${s}`)}const i=await r.json();for(const o of i?.stack??[]){if(typeof o?.file!=="string"||!o.file||isBundleURL(o.file)||LIBRARY.test(o.file))continue;if(typeof o.lineNumber!=="number"||!Number.isInteger(o.lineNumber)||o.lineNumber<1)continue;return{fileName:o.file,lineNumber:o.lineNumber,...typeof o.column==="number"&&o.column>=0?{columnNumber:o.column}:{}}}throw new Error("Every frame mapped into library code, none into the app.")}async function resolveEntry(e,n){if(!e.source&&e.rawStack&&n){const r=parseReact19Frames(e.rawStack).filter(i=>isBundleURL(i.file));if(r.length){try{return{...e,source:await symbolicateAppFrame(r,n)}}catch(i){const o=/library code/.test(errMsg2(i));return{...e,source:void 0,reason:o?"rendered by library code (no line in the app).":`Could not map the source frame: ${errMsg2(i)}`}}}}const t=e.source&&isBundleURL(e.source.fileName)?{file:e.source.fileName,lineNumber:e.source.lineNumber??0,column:e.source.columnNumber??0,methodName:"x"}:!e.source&&e.rawStack?parseReact19Stack(e.rawStack):null;if(e.source&&!isBundleURL(e.source.fileName))return e;if(!t)return{...e,source:void 0,reason:"React gave no source frame. Use a dev build."};if(!isBundleURL(t.file)){return{...e,source:{fileName:t.file,lineNumber:t.lineNumber,columnNumber:t.column}}}if(!n)return{...e,source:void 0,reason:"The dev server address is not known."};try{return{...e,source:await symbolicateFrame(t,n)}}catch(r){return{...e,source:void 0,reason:`Could not map the source frame: ${errMsg2(r)}`}}}function formatComponentSource(e,n){if(!e.found)return e.reason;let t="";const r=i=>{const o=i.source;let a;if(o){a=relativeSourcePath(o.fileName,n)+(o.lineNumber!=null?`:${o.lineNumber}`:"")+(o.lineNumber!=null&&o.columnNumber!=null?`:${o.columnNumber}`:"")}else if(i.reason?.startsWith("rendered by library")){a=i.reason}else{const s=i.reason??"React gave no source frame. Use a dev build.";a=s===t?"no source (same reason as above).":`no source. ${s}`;t=s}return`${i.name}: ${a} [memo: ${i.memo?"yes":"no"}; forwardRef: ${i.forwardRef?"yes":"no"}]`};return[r(e.component),...e.owners.slice(0,6).map(i=>` owner ${r(i)}`),"Lines after the name are where each component is used (its JSX call site in the parent's file)."].join("\n")}function registerSourceTools(e,n){e.registerTool("get_component_source",{description:"Find where a React view is used in code. Use its name, testID, text, or nativeTag from describe_screen. Get file paths, lines, and up to six owners. See memo and forwardRef flags too. These paths point to JSX calls. Needs a dev build and Buoy Pro.",inputSchema:{query:import_zod28.z.string().trim().min(1).optional().describe("A component name, testID, or text from describe_screen."),nativeTag:import_zod28.z.number().int().nonnegative().optional().describe("The nativeTag from describe_screen. Takes priority over query."),deviceId:deviceIdInput}},async({query:t,nativeTag:r,deviceId:i})=>{try{const o=n.requireProDevice(i);if(r==null&&!t?.trim())return fail2("Pass a query or nativeTag.");const a=await n.callAction("highlight-updates","getComponentSource",{query:t,nativeTag:r},o);if(!a)return fail2("The app gave no source result. Turn on highlight-updates or update Buoy.");if(!a.found)return text(a.reason);const s=n.devServerOrigin(o);const c=await Promise.all([a.component,...a.owners.slice(0,6)].map(d=>resolveEntry(d,s)));const l=a.component.definedIn?await resolveEntry({name:a.component.name,memo:false,forwardRef:false,source:a.component.definedIn.source,rawStack:a.component.definedIn.rawStack},s):null;const u=l?.source?`Its own JSX starts in: ${relativeSourcePath(l.source.fileName)}${l.source.lineNumber!=null?` (line ${l.source.lineNumber})`:""} (usually its definition; a helper that builds JSX can show here instead)
955
- `:"";return text(u+formatComponentSource({found:true,component:c[0],owners:c.slice(1)}))}catch(o){return fail2(errMsg2(o))}})}var import_zod29=require("zod");var JS_TOP_TOOL_ID="js-top";var SPARK_CHARS="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function sparkline(e){const n=Math.max(1,...e);return e.map(t=>SPARK_CHARS[Math.min(7,Math.floor(t/n*7.999))]).join("")}function formatTopMarkdown(e,n){const t=[];t.push(`## JS thread top (${(n/1e3).toFixed(1)}s sample)`);t.push("");t.push(`Thread busy: **${e.busyPct.toFixed(1)}%** of the trailing 5s window.`);if(e.freezeSummary.count>0){t.push(`Freezes (\u226550ms single-task blocks, last 60s): **${e.freezeSummary.count}**, worst **${e.freezeSummary.worstMs}ms** \u2014 during these, taps and JS animations stall.`)}if(!e.tiers.bridge){t.push("_New Architecture device: touch/React commit work appears as \u201Cunattributed\u201D; timers, rAF and Promise chains are fully attributed._")}t.push("");t.push("| # | task origin | api | 5s ms | % busy | calls | avg ms | max ms | freezes |");t.push("|---|---|---|---|---|---|---|---|---|");e.rows.slice(0,15).forEach((r,i)=>{const o=r.freezes>0?`\u26A0 ${r.freezes} (worst ${r.worstFreezeMs}ms)`:"\u2013";t.push(`| ${i+1} | ${r.label} | ${r.api} | ${r.windowMs.toFixed(1)} | ${r.pctOfBusy.toFixed(1)} | ${r.calls} | ${r.avgMs.toFixed(2)} | ${r.maxMs.toFixed(1)} | ${o} |`)});t.push("");t.push("_Drill into any row with `get_js_thread_origin_detail` using its `key` from the JSON below._");return t.join("\n")}function formatDetailMarkdown(e){const n=[];n.push(`## Origin detail \u2014 ${e.label}`);n.push("");n.push(`API: \`${e.api}\` \xB7 key: \`${e.key}\``);n.push("");n.push(`Activity last 5s (250ms buckets): \`${sparkline(e.buckets)}\` \u2014 ${e.windowMs.toFixed(1)}ms in window, ${e.pctOfBusy.toFixed(1)}% of busy time.`);n.push("");n.push("| runs | scheduled | avg/run | max/run | total | last run | freezes (60s) | worst freeze |");n.push("|---|---|---|---|---|---|---|---|");n.push(`| ${e.calls} | ${e.scheduleCount} | ${e.avgMs.toFixed(2)}ms | ${e.maxMs.toFixed(1)}ms | ${e.totalMs.toFixed(1)}ms | ${e.lastSeenAgoMs>0?`${Math.round(e.lastSeenAgoMs/1e3)}s ago`:"\u2014"} | ${e.freezes} | ${e.worstFreezeMs>0?`${e.worstFreezeMs}ms`:"\u2014"} |`);if(e.caller||e.file){n.push("");n.push(`Scheduled from: **${e.caller?`${e.caller}()`:"unknown caller"}**${e.file?` \u2014 ${e.file}${e.line!=null?`:${e.line}`:""}`:""}`);if(e.frames?.length){n.push(`Raw frames (Hermes bundle offsets): ${e.frames.map(t=>`${t.file}:${t.line}:${t.col}`).join(" \xB7 ")}`)}}else if(e.api!=="unattributed"&&e.api!=="other"){n.push("");n.push(e.promoted?"_Scheduling stack not captured yet \u2014 the next schedule from this site records it._":"_Not hot enough for stack capture yet (threshold: 25 schedules or 50ms total)._")}return n.join("\n")}function registerJsThreadTools(e,n){e.registerTool("get_js_thread_top",{description:"Sample instrumented JavaScript task origins and return available timing, busy percentage and freeze attribution. Coverage depends on installed hooks; unattributed work can remain. Requires @buoy-gg/js-top and Buoy Pro. The call waits for the sample: arrange the interaction during that window using an available concurrent driver or a person, rather than starting it after this call returns. clearFirst resets tracked statistics before sampling. Use get_js_thread_origin_detail for a returned row key and measure_renders for component render diagnostics.",inputSchema:{deviceId:deviceIdInput,durationMs:import_zod29.z.number().optional().describe("How long to sample before reading the table. Default 3000; clamped to 250\u201330000."),clearFirst:import_zod29.z.boolean().optional().describe("Reset tracked statistics before sampling. Hook coverage and attribution limits still apply.")}},async({deviceId:t,durationMs:r,clearFirst:i})=>{try{const o=n.requireProDevice(t);const a=Math.min(Math.max(r??3e3,250),3e4);const s=await n.callAction(JS_TOP_TOOL_ID,"sample",{durationMs:a,clearFirst:i===true},o);if(!s)return fail2("Device returned no snapshot \u2014 is @buoy-gg/js-top installed in the app?");const c=formatTopMarkdown(s,a);const l={busyPct:Math.round(s.busyPct*10)/10,freezeSummary:s.freezeSummary,tiers:s.tiers,rows:s.rows.slice(0,15).map(u=>({key:u.key,api:u.api,windowMs:Math.round(u.windowMs*10)/10,pctOfBusy:Math.round(u.pctOfBusy*10)/10,calls:u.calls,avgMs:Math.round(u.avgMs*100)/100,maxMs:Math.round(u.maxMs*10)/10,totalMs:Math.round(u.totalMs),freezes:u.freezes,worstFreezeMs:u.worstFreezeMs}))};return text(`${c}
955
+ Open the files and compare each variant with the baseline at the same moment. Put the baseline first in \`cases\` so the difference numbers compare against it. Animation makes some difference normal; a variant far from the rest needs a close look. A variant that looks wrong can't win.`)}catch(r){return fail10(r?.message??String(r))}});e.registerTool("start_optimize_session",{description:"Start the Buoy Optimize clock. Pass how long the session lasts (`minutes`) or when it ends (`deadline`, ISO time). After this, every Buoy tool result shows the time left, so the loop keeps going until the deadline. Call it once at the start of an optimize session. Pass minutes: 0 to stop the clock.",inputSchema:{minutes:import_zod27.z.number().optional().describe("Session length from now, in minutes."),deadline:import_zod27.z.string().optional().describe("When the session ends, as an ISO time, e.g. 2026-10-04T07:12:00-06:00.")}},async t=>{if(t.minutes===0){setOptimizeDeadline(null);return text8("Optimize clock stopped.")}const r=t.deadline?Date.parse(t.deadline):t.minutes!=null?Date.now()+t.minutes*6e4:NaN;if(!Number.isFinite(r))return fail10("Pass `minutes` (a number) or `deadline` (an ISO time).");if(r<=Date.now())return fail10("That deadline has already passed.");setOptimizeDeadline(r);return text8(`Optimize clock started. Deadline: ${new Date(r).toISOString()}.${optimizeNote()??""}`)})}var import_zod28=require("zod");var import_node_child_process20=require("child_process");var import_node_util16=require("util");var import_node_fs23=require("fs");var import_node_os15=__toESM(require("os"));var import_node_path22=__toESM(require("path"));var import_node_crypto14=require("crypto");var execFileAsync16=(0,import_node_util16.promisify)(import_node_child_process20.execFile);async function run5(e,n,t=2e4){try{const{stdout:r}=await execFileAsync16(e,n,{timeout:t});return r}catch(r){const i=r;throw new Error(`${e} ${n.slice(0,3).join(" ")} failed: ${(i.stderr||i.message||"").trim().split("\n").slice(-2).join(" ").slice(0,300)}`)}}var devicectl2=e=>run5("xcrun",["devicectl",...e,"--quiet"]);var IOS_ORIENTATION={portrait:"portrait",landscape_left:"landscapeLeft",landscape_right:"landscapeRight",upside_down:"portraitUpsideDown"};var ANDROID_ROTATION={portrait:0,landscape_left:1,upside_down:2,landscape_right:3};async function rotate(e,n){if(e.platform==="android"){await adbShell(e.serial,"settings put system accelerometer_rotation 0");await adbShell(e.serial,`settings put system user_rotation ${ANDROID_ROTATION[n]}`);return`Rotated to ${n.replace("_"," ")} (auto-rotate is now off on this device; rotate to portrait to go back).`}await devicectl2(["device","orientation","set","--device",e.udid,IOS_ORIENTATION[n]]);return`Rotated the device to ${n.replace("_"," ")}. An app that only supports portrait keeps its screen upright.`}async function shake(e){if(e.platform==="ios"){await run5("xcrun",["simctl","spawn",e.udid,"notifyutil","-p","com.apple.UIKit.SimulatorShake"]);return"Sent a shake to the simulator (the same event as Device > Shake). Check the screen: an app only reacts if it listens for shakes."}if(e.platform==="android"){if(!/^emulator-\d+$/.test(e.serial))throw new Error("A physical Android phone can't be shaken from the computer. Use an emulator, or shake the phone.");for(const n of["0:25:0","0:-25:0","0:25:0","0:-25:0","0:9.81:0"]){await adb(e.serial,["emu","sensor","set","acceleration",n]);await new Promise(t=>setTimeout(t,80))}return"Shook the emulator (an accelerometer burst). Check the screen: an app only reacts if it listens for shakes."}throw new Error("A physical iPhone can't be shaken from the computer. Use a simulator, or shake the phone.")}async function setClipboard(e,n){if(e.platform==="ios"){await new Promise((t,r)=>{const i=(0,import_node_child_process20.spawn)("xcrun",["simctl","pbcopy",e.udid],{stdio:["pipe","ignore","pipe"]});let o="";i.stderr.on("data",a=>o+=a);i.on("error",r);i.on("exit",a=>a===0?t():r(new Error(`simctl pbcopy failed: ${o.trim()}`)));i.stdin.end(n)})}else if(e.platform==="ios-device"){const t=import_node_path22.default.join(import_node_os15.default.tmpdir(),`buoy-clip-${(0,import_node_crypto14.randomUUID)()}.txt`);await import_node_fs23.promises.writeFile(t,n,{mode:384});try{await devicectl2(["device","pasteboard","copy","--device",e.udid,"--type","public.utf8-plain-text","--file",t])}finally{await import_node_fs23.promises.unlink(t).catch(()=>void 0)}}else{throw new Error("Setting the clipboard from the computer isn't supported on Android. Use native_type to type the text instead.")}return e.platform==="ios-device"?"Put the text on the iPhone's clipboard. To paste it for real, long-press the field (native_tap with holdMs: 600) and tap Paste (native_tap with x and y; labels don't work on a phone).":'Put the text on the clipboard. To paste it for real, long-press the field (native_tap with holdMs: 600) and tap Paste (native_tap label: "Paste").'}async function biometrics(e,n,t){if(e.platform==="android"){if(!/^emulator-\d+$/.test(e.serial))throw new Error("Biometrics can be simulated on an Android emulator only.");const r=await adbShell(e.serial,"dumpsys fingerprint").catch(()=>"");if(n&&/"count"\s*:\s*0|enrolled[^\n]*\b0\b/i.test(r)){throw new Error("No fingerprint is enrolled on this emulator. Enroll one in Settings > Security, then try again.")}const i=t??(n?1:9731);await adb(e.serial,["emu","finger","touch",String(i)]);return n?`Touched fingerprint id ${i}. It matches only if that finger is enrolled in the emulator's Settings (enroll one there first if the app says no fingerprints).`:`Touched fingerprint id ${i}, meant to fail. It would match instead if id ${i} is enrolled; pass another fingerId if so.`}await devicectl2(["device","simulate","biometrics","--device",e.udid,n?"--success":"--failure"]);return n?"Simulated a matching Face ID / Touch ID.":"Simulated a Face ID / Touch ID that doesn't match."}function registerDeviceTools(e,n){e.registerTool("device_control",{_meta:coreTool(),description:"Do something to the device itself: rotate (orientation), shake (shake-to-undo, shake-to-report, dev menus), clipboard (text on the clipboard for a real paste), biometrics (Face ID / Touch ID / fingerprint match or fail). iOS Simulator, physical iPhone (rotate, clipboard) and Android (rotate, emulator shake and fingerprint). Returns the screen after when the app is connected (not for clipboard).",inputSchema:{action:import_zod28.z.enum(["rotate","shake","clipboard","biometrics"]),orientation:import_zod28.z.enum(["portrait","landscape_left","landscape_right","upside_down"]).optional().describe("rotate (required)."),text:import_zod28.z.string().optional().describe("clipboard (required). {{secret:NAME}} works here too."),match:import_zod28.z.boolean().optional().describe("biometrics: true for a match (default), false for a failed one."),fingerId:import_zod28.z.number().int().min(1).optional().describe("biometrics on an Android emulator: the finger id to touch: an enrolled one for a match (default 1), one that is not enrolled for a failure (default 9731)."),serial:import_zod28.z.string().optional().describe("Android: the adb serial, when several devices are connected."),deviceId:deviceIdInput}},async t=>{try{const{id:r,host:i,online:o}=await hostTarget(n,t.deviceId,{serial:t.serial},{allowOffline:t.action!=="clipboard"});let a;switch(t.action){case"rotate":if(!t.orientation)return fail2("rotate requires `orientation`.");a=await rotate(i,t.orientation);if(i.platform!=="android")forgetScreenSize(i.udid);break;case"shake":a=await shake(i);break;case"clipboard":if(t.text===void 0)return fail2("clipboard requires `text`.");a=await setClipboard(i,fillSecrets(t.text));break;case"biometrics":a=await biometrics(i,t.match!==false,t.fingerId);break}if(t.action!=="rotate"||i.platform!=="ios")await new Promise(c=>setTimeout(c,700));const s=o&&t.action!=="clipboard"?await observeAfterAction(n,r):"";return text(`${a} (${hostLabel(i)})${s}`)}catch(r){return fail2(errMsg2(r))}})}var import_node_path23=__toESM(require("path"));var import_node_url2=require("url");var import_zod29=require("zod");function parseReact19Frames(e,n=10){const t=[];for(const r of e.split("\n")){if(t.length>=n)break;const i=parseReact19Stack(r);if(i)t.push(i)}return t}function parseReact19Stack(e){for(const n of e.split("\n")){if(/\b(?:react[-_]stack[-_](?:top|bottom)[-_]frame|jsxDEV(?:Impl)?|jsxWithValidation|createElement)\b/.test(n))continue;const t=n.trim();const r=/:(\d+):(\d+)\)?\s*$/.exec(t);if(!r)continue;const i=t.slice(0,r.index);const o=/\s\((?=https?:\/\/|file:\/\/|address at |\/|[A-Za-z]:[\\/])/.exec(i);let a;let s;if(o){a=i.slice(o.index+2);s=o.index}else{const d=/(?:^at\s+|@)((?:https?:\/\/|file:\/\/|\/|[A-Za-z]:[\\/]).*)$/.exec(i);if(!d)continue;a=d[1];s=d.index}const c=Object.assign([t,a,r[1],r[2]],{index:s});const l=Number(c[2]);const u=Number(c[3]);if(!Number.isSafeInteger(l)||l<1||!Number.isSafeInteger(u))continue;return{file:c[1].replace(/^address at\s+/,""),lineNumber:l,column:u,methodName:t.slice(0,c.index).replace(/^at\s+/,"").replace(/[(@\s]+$/,"")||"x"}}return null}function isBundleURL(e){return/^https?:\/\//i.test(e)}function relativeSourcePath(e,n=process.env.BUOY_PROJECT_ROOT||process.cwd()){let t=e;if(t.startsWith("file://")){try{t=(0,import_node_url2.fileURLToPath)(t)}catch{return e}}if(isBundleURL(t))return t;const r=/^[A-Za-z]:[\\/]/.test(t)&&/^[A-Za-z]:[\\/]/.test(n)?import_node_path23.default.win32:import_node_path23.default;if(!r.isAbsolute(t))return t;const i=r.relative(r.resolve(n),t);return i&&i!==".."&&!i.startsWith(`..${r.sep}`)&&!r.isAbsolute(i)?i.split(r.sep).join("/"):t}async function symbolicateFrame(e,n,t=fetch){const r=await t(`${n.replace(/\/$/,"")}/symbolicate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({stack:[e]}),signal:AbortSignal.timeout(5e3)});if(!r.ok)throw new Error(`Metro could not map this frame (HTTP ${r.status}).`);const i=await r.json();const o=i?.stack?.[0];if(typeof o?.file!=="string"||!o.file||isBundleURL(o.file)||typeof o.lineNumber!=="number"||!Number.isInteger(o.lineNumber)||o.lineNumber<1){throw new Error("Metro did not return a source file and line.")}return{fileName:o.file,lineNumber:o.lineNumber,...typeof o.column==="number"&&Number.isInteger(o.column)&&o.column>=0?{columnNumber:o.column}:{}}}var LIBRARY=/node_modules\/|\/react-native\/|\/Libraries\/|\/expo-router\//;async function symbolicateAppFrame(e,n,t=fetch){const r=await t(`${n.replace(/\/$/,"")}/symbolicate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({stack:e}),signal:AbortSignal.timeout(5e3)});if(!r.ok){const o=(await r.json().catch(()=>null))?.error;const a=typeof o==="string"&&o?` Metro said: ${o.slice(0,200)}`:"";const s=/serialized source map/i.test(a)?" Its cache looks stale; restarting Metro with --clear usually fixes this.":"";throw new Error(`Metro could not map these frames (HTTP ${r.status}).${a}${s}`)}const i=await r.json();for(const o of i?.stack??[]){if(typeof o?.file!=="string"||!o.file||isBundleURL(o.file)||LIBRARY.test(o.file))continue;if(typeof o.lineNumber!=="number"||!Number.isInteger(o.lineNumber)||o.lineNumber<1)continue;return{fileName:o.file,lineNumber:o.lineNumber,...typeof o.column==="number"&&o.column>=0?{columnNumber:o.column}:{}}}throw new Error("Every frame mapped into library code, none into the app.")}async function resolveEntry(e,n){if(!e.source&&e.rawStack&&n){const r=parseReact19Frames(e.rawStack).filter(i=>isBundleURL(i.file));if(r.length){try{return{...e,source:await symbolicateAppFrame(r,n)}}catch(i){const o=/library code/.test(errMsg2(i));return{...e,source:void 0,reason:o?"rendered by library code (no line in the app).":`Could not map the source frame: ${errMsg2(i)}`}}}}const t=e.source&&isBundleURL(e.source.fileName)?{file:e.source.fileName,lineNumber:e.source.lineNumber??0,column:e.source.columnNumber??0,methodName:"x"}:!e.source&&e.rawStack?parseReact19Stack(e.rawStack):null;if(e.source&&!isBundleURL(e.source.fileName))return e;if(!t)return{...e,source:void 0,reason:"React gave no source frame. Use a dev build."};if(!isBundleURL(t.file)){return{...e,source:{fileName:t.file,lineNumber:t.lineNumber,columnNumber:t.column}}}if(!n)return{...e,source:void 0,reason:"The dev server address is not known."};try{return{...e,source:await symbolicateFrame(t,n)}}catch(r){return{...e,source:void 0,reason:`Could not map the source frame: ${errMsg2(r)}`}}}function formatComponentSource(e,n){if(!e.found)return e.reason;let t="";const r=i=>{const o=i.source;let a;if(o){a=relativeSourcePath(o.fileName,n)+(o.lineNumber!=null?`:${o.lineNumber}`:"")+(o.lineNumber!=null&&o.columnNumber!=null?`:${o.columnNumber}`:"")}else if(i.reason?.startsWith("rendered by library")){a=i.reason}else{const s=i.reason??"React gave no source frame. Use a dev build.";a=s===t?"no source (same reason as above).":`no source. ${s}`;t=s}return`${i.name}: ${a} [memo: ${i.memo?"yes":"no"}; forwardRef: ${i.forwardRef?"yes":"no"}]`};return[r(e.component),...e.owners.slice(0,6).map(i=>` owner ${r(i)}`),"Lines after the name are where each component is used (its JSX call site in the parent's file)."].join("\n")}function registerSourceTools(e,n){e.registerTool("get_component_source",{description:"Find where a React view is used in code. Use its name, testID, text, or nativeTag from describe_screen. Get file paths, lines, and up to six owners. See memo and forwardRef flags too. These paths point to JSX calls. Needs a dev build and Buoy Pro.",inputSchema:{query:import_zod29.z.string().trim().min(1).optional().describe("A component name, testID, or text from describe_screen."),nativeTag:import_zod29.z.number().int().nonnegative().optional().describe("The nativeTag from describe_screen. Takes priority over query."),deviceId:deviceIdInput}},async({query:t,nativeTag:r,deviceId:i})=>{try{const o=n.requireProDevice(i);if(r==null&&!t?.trim())return fail2("Pass a query or nativeTag.");const a=await n.callAction("highlight-updates","getComponentSource",{query:t,nativeTag:r},o);if(!a)return fail2("The app gave no source result. Turn on highlight-updates or update Buoy.");if(!a.found)return text(a.reason);const s=n.devServerOrigin(o);const c=await Promise.all([a.component,...a.owners.slice(0,6)].map(d=>resolveEntry(d,s)));const l=a.component.definedIn?await resolveEntry({name:a.component.name,memo:false,forwardRef:false,source:a.component.definedIn.source,rawStack:a.component.definedIn.rawStack},s):null;const u=l?.source?`Its own JSX starts in: ${relativeSourcePath(l.source.fileName)}${l.source.lineNumber!=null?` (line ${l.source.lineNumber})`:""} (usually its definition; a helper that builds JSX can show here instead)
956
+ `:"";return text(u+formatComponentSource({found:true,component:c[0],owners:c.slice(1)}))}catch(o){return fail2(errMsg2(o))}})}var import_zod30=require("zod");var JS_TOP_TOOL_ID="js-top";var SPARK_CHARS="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function sparkline(e){const n=Math.max(1,...e);return e.map(t=>SPARK_CHARS[Math.min(7,Math.floor(t/n*7.999))]).join("")}function formatTopMarkdown(e,n){const t=[];t.push(`## JS thread top (${(n/1e3).toFixed(1)}s sample)`);t.push("");t.push(`Thread busy: **${e.busyPct.toFixed(1)}%** of the trailing 5s window.`);if(e.freezeSummary.count>0){t.push(`Freezes (\u226550ms single-task blocks, last 60s): **${e.freezeSummary.count}**, worst **${e.freezeSummary.worstMs}ms** \u2014 during these, taps and JS animations stall.`)}if(!e.tiers.bridge){t.push("_New Architecture device: touch/React commit work appears as \u201Cunattributed\u201D; timers, rAF and Promise chains are fully attributed._")}t.push("");t.push("| # | task origin | api | 5s ms | % busy | calls | avg ms | max ms | freezes |");t.push("|---|---|---|---|---|---|---|---|---|");e.rows.slice(0,15).forEach((r,i)=>{const o=r.freezes>0?`\u26A0 ${r.freezes} (worst ${r.worstFreezeMs}ms)`:"\u2013";t.push(`| ${i+1} | ${r.label} | ${r.api} | ${r.windowMs.toFixed(1)} | ${r.pctOfBusy.toFixed(1)} | ${r.calls} | ${r.avgMs.toFixed(2)} | ${r.maxMs.toFixed(1)} | ${o} |`)});t.push("");t.push("_Drill into any row with `get_js_thread_origin_detail` using its `key` from the JSON below._");return t.join("\n")}function formatDetailMarkdown(e){const n=[];n.push(`## Origin detail \u2014 ${e.label}`);n.push("");n.push(`API: \`${e.api}\` \xB7 key: \`${e.key}\``);n.push("");n.push(`Activity last 5s (250ms buckets): \`${sparkline(e.buckets)}\` \u2014 ${e.windowMs.toFixed(1)}ms in window, ${e.pctOfBusy.toFixed(1)}% of busy time.`);n.push("");n.push("| runs | scheduled | avg/run | max/run | total | last run | freezes (60s) | worst freeze |");n.push("|---|---|---|---|---|---|---|---|");n.push(`| ${e.calls} | ${e.scheduleCount} | ${e.avgMs.toFixed(2)}ms | ${e.maxMs.toFixed(1)}ms | ${e.totalMs.toFixed(1)}ms | ${e.lastSeenAgoMs>0?`${Math.round(e.lastSeenAgoMs/1e3)}s ago`:"\u2014"} | ${e.freezes} | ${e.worstFreezeMs>0?`${e.worstFreezeMs}ms`:"\u2014"} |`);if(e.caller||e.file){n.push("");n.push(`Scheduled from: **${e.caller?`${e.caller}()`:"unknown caller"}**${e.file?` \u2014 ${e.file}${e.line!=null?`:${e.line}`:""}`:""}`);if(e.frames?.length){n.push(`Raw frames (Hermes bundle offsets): ${e.frames.map(t=>`${t.file}:${t.line}:${t.col}`).join(" \xB7 ")}`)}}else if(e.api!=="unattributed"&&e.api!=="other"){n.push("");n.push(e.promoted?"_Scheduling stack not captured yet \u2014 the next schedule from this site records it._":"_Not hot enough for stack capture yet (threshold: 25 schedules or 50ms total)._")}return n.join("\n")}function registerJsThreadTools(e,n){e.registerTool("get_js_thread_top",{description:"Sample instrumented JavaScript task origins and return available timing, busy percentage and freeze attribution. Coverage depends on installed hooks; unattributed work can remain. Requires @buoy-gg/js-top and Buoy Pro. The call waits for the sample: arrange the interaction during that window using an available concurrent driver or a person, rather than starting it after this call returns. clearFirst resets tracked statistics before sampling. Use get_js_thread_origin_detail for a returned row key and measure_renders for component render diagnostics.",inputSchema:{deviceId:deviceIdInput,durationMs:import_zod30.z.number().optional().describe("How long to sample before reading the table. Default 3000; clamped to 250\u201330000."),clearFirst:import_zod30.z.boolean().optional().describe("Reset tracked statistics before sampling. Hook coverage and attribution limits still apply.")}},async({deviceId:t,durationMs:r,clearFirst:i})=>{try{const o=n.requireProDevice(t);const a=Math.min(Math.max(r??3e3,250),3e4);const s=await n.callAction(JS_TOP_TOOL_ID,"sample",{durationMs:a,clearFirst:i===true},o);if(!s)return fail2("Device returned no snapshot \u2014 is @buoy-gg/js-top installed in the app?");const c=formatTopMarkdown(s,a);const l={busyPct:Math.round(s.busyPct*10)/10,freezeSummary:s.freezeSummary,tiers:s.tiers,rows:s.rows.slice(0,15).map(u=>({key:u.key,api:u.api,windowMs:Math.round(u.windowMs*10)/10,pctOfBusy:Math.round(u.pctOfBusy*10)/10,calls:u.calls,avgMs:Math.round(u.avgMs*100)/100,maxMs:Math.round(u.maxMs*10)/10,totalMs:Math.round(u.totalMs),freezes:u.freezes,worstFreezeMs:u.worstFreezeMs}))};return text(`${c}
956
957
 
957
958
  \`\`\`json
958
959
  ${JSON.stringify(l)}
959
- \`\`\``)}catch(o){return fail2(errMsg2(o))}});e.registerTool("get_js_thread_origin_detail",{description:'Inspect one js-top task origin in depth: schedules vs runs, avg/max/total exclusive ms, a 5s activity sparkline, freeze attribution, and the captured scheduling site (caller function + stack frames). Pass a row `key` from get_js_thread_top\'s JSON (e.g. "interval|pollFeed" or "unattributed" for the system row).',inputSchema:{deviceId:deviceIdInput,key:import_zod29.z.string().describe("Origin key from get_js_thread_top's JSON rows.")}},async({deviceId:t,key:r})=>{try{const i=n.requireProDevice(t);const o=await n.callAction(JS_TOP_TOOL_ID,"getOriginDetail",{key:r},i);if(!o){return fail2(`Origin "${r}" is not tracked (cleared, evicted, or never existed). Re-run get_js_thread_top for current keys.`)}const a=formatDetailMarkdown(o);return text(`${a}
960
+ \`\`\``)}catch(o){return fail2(errMsg2(o))}});e.registerTool("get_js_thread_origin_detail",{description:'Inspect one js-top task origin in depth: schedules vs runs, avg/max/total exclusive ms, a 5s activity sparkline, freeze attribution, and the captured scheduling site (caller function + stack frames). Pass a row `key` from get_js_thread_top\'s JSON (e.g. "interval|pollFeed" or "unattributed" for the system row).',inputSchema:{deviceId:deviceIdInput,key:import_zod30.z.string().describe("Origin key from get_js_thread_top's JSON rows.")}},async({deviceId:t,key:r})=>{try{const i=n.requireProDevice(t);const o=await n.callAction(JS_TOP_TOOL_ID,"getOriginDetail",{key:r},i);if(!o){return fail2(`Origin "${r}" is not tracked (cleared, evicted, or never existed). Re-run get_js_thread_top for current keys.`)}const a=formatDetailMarkdown(o);return text(`${a}
960
961
 
961
962
  \`\`\`json
962
963
  ${JSON.stringify(o)}
963
- \`\`\``)}catch(i){return fail2(errMsg2(i))}});e.registerTool("clear_js_thread_stats",{description:"Reset the js-top task table, freeze history, and busy history on the device (fresh measurement window).",inputSchema:{deviceId:deviceIdInput}},async({deviceId:t})=>{try{const r=n.requireProDevice(t);await n.callAction(JS_TOP_TOOL_ID,"clear",{},r);return text("Cleared js-top stats.")}catch(r){return fail2(errMsg2(r))}})}var import_zod30=require("zod");var IMAGES_TOOL_ID="images";function uriTail(e){if(!e)return"(no source)";const n=e.match(/[?&]unstable_path=([^&?]+)/);const t=n?decodeURIComponent(n[1]):e;const r=t.split("?")[0]??t;const i=r.split("/").filter(Boolean);return i[i.length-1]??t}function verdictLabel(e){if(e.oversizeFactor==null)return"\u2013";if(e.oversizeFactor<.9)return`${e.oversizeFactor.toFixed(1)}\xD7 upscaled`;if(e.oversizeFactor<=1.1)return"right-sized";return`${e.oversizeFactor.toFixed(1)}\xD7 oversized (${e.wastedKB}KB wasted)`}function cacheLabel(e){if(e.cache)return e.cache;if(e.progressSeen)return"network";return"?"}function mb(e){return`${(e/(1024*1024)).toFixed(1)}MB`}function formatListMarkdown(e,n){const t=[];const r=e.stats;t.push(`## Images registry (${e.total} records, showing ${Math.min(n,e.records.length)})`);t.push("");t.push(`${r.loaded} loaded \xB7 ${r.errors} failed \xB7 ${r.loading} in flight \xB7 \u2248${mb(r.estDecodedBytes)} decoded`+(r.estWastedBytes>0?` \xB7 **${mb(r.estWastedBytes)} wasted on oversized sources**`:""));const i=e.insights;if(i){const a=[];if(i.duplicates.length>0)a.push(`${i.duplicates.length} duplicate URL(s): ${i.duplicates.slice(0,3).map(s=>`${uriTail(s.uri)}\xD7${s.count}`).join(", ")}`);if(i.retryStorms.length>0)a.push(`${i.retryStorms.length} retry storm(s): ${i.retryStorms.slice(0,3).map(s=>`#${s.id}(${s.loadCount} loads)`).join(", ")}`);if(i.queueSaturated)a.push("iOS image queue saturated (>4 concurrent loads)");if(i.missingAlt>0)a.push(`${i.missingAlt} image(s) missing alt/accessibilityLabel`);if(i.layoutShifters.length>0)a.push(`${i.layoutShifters.length} layout-shifting image(s): ${i.layoutShifters.slice(0,3).map(s=>`#${s.id}`).join(", ")} \u2014 reserve explicit dimensions`);if(a.length>0){t.push("");t.push(`**Insights:** ${a.join(" \xB7 ")}`)}}const o=e.captureStatus;if(o.rnDecoratorTooLate){t.push("");t.push('\u26A0 RN <Image> capture missed the module-load race \u2014 add `import "@buoy-gg/images/register"` as the FIRST import of the app entry file.')}if(e.globalModes.network!=="normal"||e.globalModes.blank){t.push("");t.push(`\u26A0 Simulation active: network=${e.globalModes.network}${e.globalModes.blank?", blank images ON":""} (set_image_simulation to reset).`)}t.push("");t.push("| id | image | lib | status | cache | ms | decoded px | shown dp | verdict | sim |");t.push("|---|---|---|---|---|---|---|---|---|---|");for(const a of e.records){const s=a.intrinsic?`${a.intrinsic.width}\xD7${a.intrinsic.height}`:"\u2013";const c=a.layout?`${a.layout.width}\xD7${a.layout.height}`:"\u2013";const l=a.status==="error"?`**error**${a.errorCode?` (${a.errorCode})`:""}`:a.status;t.push(`| ${a.id} | ${uriTail(a.uri)} | ${a.lib} | ${l}${a.mounted?"":" (unmounted)"} | ${cacheLabel(a)} | ${a.ms??"\u2013"} | ${s} | ${c} | ${verdictLabel(a)} | ${a.overrideLabel??"\u2013"} |`)}t.push("");t.push("_Act on a row with `image_action` using its `id` (hard_reload / retry / force_error / force_loading / force_blank / swap_url / flash / restore / evict_disk)._");return t.join("\n")}var ACTION_MAP={hard_reload:{action:"hardReload"},retry:{action:"retry"},evict_disk:{action:"evictDisk"},flash:{action:"flash"},restore:{action:"clearOverride"},force_error:{action:"setOverride",params:()=>({kind:"error"})},force_loading:{action:"setOverride",params:()=>({kind:"hang"})},force_blank:{action:"setOverride",params:()=>({kind:"blank"})},swap_url:{action:"setOverride",params:e=>({kind:"url",uri:e})}};function registerImagesTools(e,n){e.registerTool("get_images",{description:"Inspect image loads reported through the Buoy image integration, including available cache origin, load timing, size estimates, errors and simulation overrides. Coverage depends on instrumented components and platform support. Requires @buoy-gg/images on the device.",inputSchema:{deviceId:deviceIdInput,limit:import_zod30.z.number().optional().describe("Max records to return (newest first). Default 30, max 200."),status:import_zod30.z.enum(["pending","loading","loaded","error"]).optional().describe("Only records in this state (e.g. 'error' for the failure log).")}},async({deviceId:t,limit:r,status:i})=>{try{const o=n.requireProDevice(t);const a=Math.min(Math.max(r??30,1),200);const s=await n.callAction(IMAGES_TOOL_ID,"list",{limit:a,status:i},o);if(!s)return fail2("Device returned nothing \u2014 is @buoy-gg/images installed in the app?");const c=formatListMarkdown(s,a);const l={stats:s.stats,insights:s.insights,captureStatus:s.captureStatus,globalModes:s.globalModes,records:s.records.map(u=>({id:u.id,uri:u.uri,lib:u.lib,status:u.status,mounted:u.mounted,cache:u.cache,ms:u.ms,intrinsic:u.intrinsic,layout:u.layout,oversizeFactor:u.oversizeFactor,wastedKB:u.wastedKB,error:u.error,errorCode:u.errorCode,overrideLabel:u.overrideLabel,loadCount:u.loadCount,hasAltText:u.hasAltText,layoutShifts:u.layoutShifts}))};return text(`${c}
964
+ \`\`\``)}catch(i){return fail2(errMsg2(i))}});e.registerTool("clear_js_thread_stats",{description:"Reset the js-top task table, freeze history, and busy history on the device (fresh measurement window).",inputSchema:{deviceId:deviceIdInput}},async({deviceId:t})=>{try{const r=n.requireProDevice(t);await n.callAction(JS_TOP_TOOL_ID,"clear",{},r);return text("Cleared js-top stats.")}catch(r){return fail2(errMsg2(r))}})}var import_zod31=require("zod");var IMAGES_TOOL_ID="images";function uriTail(e){if(!e)return"(no source)";const n=e.match(/[?&]unstable_path=([^&?]+)/);const t=n?decodeURIComponent(n[1]):e;const r=t.split("?")[0]??t;const i=r.split("/").filter(Boolean);return i[i.length-1]??t}function verdictLabel(e){if(e.oversizeFactor==null)return"\u2013";if(e.oversizeFactor<.9)return`${e.oversizeFactor.toFixed(1)}\xD7 upscaled`;if(e.oversizeFactor<=1.1)return"right-sized";return`${e.oversizeFactor.toFixed(1)}\xD7 oversized (${e.wastedKB}KB wasted)`}function cacheLabel(e){if(e.cache)return e.cache;if(e.progressSeen)return"network";return"?"}function mb(e){return`${(e/(1024*1024)).toFixed(1)}MB`}function formatListMarkdown(e,n){const t=[];const r=e.stats;t.push(`## Images registry (${e.total} records, showing ${Math.min(n,e.records.length)})`);t.push("");t.push(`${r.loaded} loaded \xB7 ${r.errors} failed \xB7 ${r.loading} in flight \xB7 \u2248${mb(r.estDecodedBytes)} decoded`+(r.estWastedBytes>0?` \xB7 **${mb(r.estWastedBytes)} wasted on oversized sources**`:""));const i=e.insights;if(i){const a=[];if(i.duplicates.length>0)a.push(`${i.duplicates.length} duplicate URL(s): ${i.duplicates.slice(0,3).map(s=>`${uriTail(s.uri)}\xD7${s.count}`).join(", ")}`);if(i.retryStorms.length>0)a.push(`${i.retryStorms.length} retry storm(s): ${i.retryStorms.slice(0,3).map(s=>`#${s.id}(${s.loadCount} loads)`).join(", ")}`);if(i.queueSaturated)a.push("iOS image queue saturated (>4 concurrent loads)");if(i.missingAlt>0)a.push(`${i.missingAlt} image(s) missing alt/accessibilityLabel`);if(i.layoutShifters.length>0)a.push(`${i.layoutShifters.length} layout-shifting image(s): ${i.layoutShifters.slice(0,3).map(s=>`#${s.id}`).join(", ")} \u2014 reserve explicit dimensions`);if(a.length>0){t.push("");t.push(`**Insights:** ${a.join(" \xB7 ")}`)}}const o=e.captureStatus;if(o.rnDecoratorTooLate){t.push("");t.push('\u26A0 RN <Image> capture missed the module-load race \u2014 add `import "@buoy-gg/images/register"` as the FIRST import of the app entry file.')}if(e.globalModes.network!=="normal"||e.globalModes.blank){t.push("");t.push(`\u26A0 Simulation active: network=${e.globalModes.network}${e.globalModes.blank?", blank images ON":""} (set_image_simulation to reset).`)}t.push("");t.push("| id | image | lib | status | cache | ms | decoded px | shown dp | verdict | sim |");t.push("|---|---|---|---|---|---|---|---|---|---|");for(const a of e.records){const s=a.intrinsic?`${a.intrinsic.width}\xD7${a.intrinsic.height}`:"\u2013";const c=a.layout?`${a.layout.width}\xD7${a.layout.height}`:"\u2013";const l=a.status==="error"?`**error**${a.errorCode?` (${a.errorCode})`:""}`:a.status;t.push(`| ${a.id} | ${uriTail(a.uri)} | ${a.lib} | ${l}${a.mounted?"":" (unmounted)"} | ${cacheLabel(a)} | ${a.ms??"\u2013"} | ${s} | ${c} | ${verdictLabel(a)} | ${a.overrideLabel??"\u2013"} |`)}t.push("");t.push("_Act on a row with `image_action` using its `id` (hard_reload / retry / force_error / force_loading / force_blank / swap_url / flash / restore / evict_disk)._");return t.join("\n")}var ACTION_MAP={hard_reload:{action:"hardReload"},retry:{action:"retry"},evict_disk:{action:"evictDisk"},flash:{action:"flash"},restore:{action:"clearOverride"},force_error:{action:"setOverride",params:()=>({kind:"error"})},force_loading:{action:"setOverride",params:()=>({kind:"hang"})},force_blank:{action:"setOverride",params:()=>({kind:"blank"})},swap_url:{action:"setOverride",params:e=>({kind:"url",uri:e})}};function registerImagesTools(e,n){e.registerTool("get_images",{description:"Inspect image loads reported through the Buoy image integration, including available cache origin, load timing, size estimates, errors and simulation overrides. Coverage depends on instrumented components and platform support. Requires @buoy-gg/images on the device.",inputSchema:{deviceId:deviceIdInput,limit:import_zod31.z.number().optional().describe("Max records to return (newest first). Default 30, max 200."),status:import_zod31.z.enum(["pending","loading","loaded","error"]).optional().describe("Only records in this state (e.g. 'error' for the failure log).")}},async({deviceId:t,limit:r,status:i})=>{try{const o=n.requireProDevice(t);const a=Math.min(Math.max(r??30,1),200);const s=await n.callAction(IMAGES_TOOL_ID,"list",{limit:a,status:i},o);if(!s)return fail2("Device returned nothing \u2014 is @buoy-gg/images installed in the app?");const c=formatListMarkdown(s,a);const l={stats:s.stats,insights:s.insights,captureStatus:s.captureStatus,globalModes:s.globalModes,records:s.records.map(u=>({id:u.id,uri:u.uri,lib:u.lib,status:u.status,mounted:u.mounted,cache:u.cache,ms:u.ms,intrinsic:u.intrinsic,layout:u.layout,oversizeFactor:u.oversizeFactor,wastedKB:u.wastedKB,error:u.error,errorCode:u.errorCode,overrideLabel:u.overrideLabel,loadCount:u.loadCount,hasAltText:u.hasAltText,layoutShifts:u.layoutShifts}))};return text(`${c}
964
965
 
965
966
  \`\`\`json
966
967
  ${JSON.stringify(l)}
967
- \`\`\``)}catch(o){return fail2(errMsg2(o))}});e.registerTool("image_action",{description:"Request an action for a registered image ID: hard_reload, retry, evict_disk, flash, prove_savings or a supported simulation override. swap_url requires url; restore removes the override. Support depends on the component and platform. prove_savings attempts a WebP conversion at displayed size and reports available byte comparisons and a device-local URI; inspect visual quality and originalBytesSource before using the result. Other actions return an acknowledgement and, when available, a later record snapshot; that snapshot may precede load completion. A device-local URI is not necessarily accessible from the editor host.",inputSchema:{deviceId:deviceIdInput,id:import_zod30.z.number().describe("Record id from get_images."),action:import_zod30.z.enum(["hard_reload","retry","evict_disk","flash","prove_savings","force_error","force_loading","force_blank","swap_url","restore"]).describe("What to do."),url:import_zod30.z.string().optional().describe("Replacement URL (swap_url only).")}},async({deviceId:t,id:r,action:i,url:o})=>{try{const a=n.requireProDevice(t);if(i==="prove_savings"){const h=await n.callAction(IMAGES_TOOL_ID,"proveSavings",{id:r},a);if(!h)return fail2("Device returned nothing for proveSavings.");if(!h.ok)return fail2(h.message);const w=[`**prove_savings** on #${r}: ${h.message}`];if(h.originalBytes!=null)w.push(`Original: ${Math.round(h.originalBytes/1024)}KB (${h.originalBytesSource})`);if(h.optimizedBytes!=null)w.push(`Optimized: ${Math.round(h.optimizedBytes/1024)}KB \u2014 ${h.optimizedDims?.width}\xD7${h.optimizedDims?.height} WebP`);if(h.savedBytes!=null)w.push(`**Saved: ${Math.round(h.savedBytes/1024)}KB (${h.savedPct}%)**`);if(h.optimizedUri)w.push(`Preview in place: image_action {id:${r}, action:"swap_url", url:"${h.optimizedUri}"}`);return text(w.join("\n"))}const s=ACTION_MAP[i];if(!s)return fail2(`Unknown action: ${i}`);if(i==="swap_url"&&!o)return fail2("swap_url requires the `url` param.");const c=await n.callAction(IMAGES_TOOL_ID,s.action,{id:r,...s.params?.(o)??{}},a);const l=i==="flash"?0:1500;if(l>0)await new Promise(h=>setTimeout(h,l));const u=await n.callAction(IMAGES_TOOL_ID,"getDetail",{id:r},a).catch(()=>null);const d=[`**${i}** on #${r}: ${c?.message??(c?.ok===false?"failed":"done")}`];if(u){d.push("");d.push(`Now: status=${u.status}${u.errorCode?` (${u.errorCode})`:""} \xB7 cache=${cacheLabel(u)} \xB7 ms=${u.ms??"\u2013"} \xB7 loads=${u.loadCount}${u.overrideLabel?` \xB7 sim="${u.overrideLabel}"`:""}${u.mounted?"":" \xB7 UNMOUNTED"}`);if(u.error)d.push(`Error: ${u.error}`)}return text(d.join("\n"))}catch(a){return fail2(errMsg2(a))}});e.registerTool("set_image_simulation",{description:"Configure supported instrumented image loads: offline simulates network-load failures while bundled assets can still load; cold requests cache bypass; normal resets the network mode. Reload or remount existing images as needed. blankImages removes sources from integrated images; massAction targets registered mounted images. Can also clear the registry or supported Expo caches. These modes do not change device connectivity.",inputSchema:{deviceId:deviceIdInput,network:import_zod30.z.enum(["normal","offline","cold"]).optional().describe("Network simulation mode."),blankImages:import_zod30.z.boolean().optional().describe("Render integrated images without a source."),massAction:import_zod30.z.enum(["error","loading","blank","reload","flash","restore"]).optional().describe("Apply to registered mounted images: force error/loading/blank overrides, hard-reload all, flash all, or restore all overrides."),clearRegistry:import_zod30.z.boolean().optional().describe("Clear the captured image log."),clearExpoCaches:import_zod30.z.boolean().optional().describe("Clear expo-image memory + disk caches.")}},async({deviceId:t,network:r,blankImages:i,massAction:o,clearRegistry:a,clearExpoCaches:s})=>{try{const c=n.requireProDevice(t);const l=[];if(o){const u=await n.callAction(IMAGES_TOOL_ID,"massAction",{kind:o},c);l.push(u?.message??`mass ${o} applied`)}if(r){await n.callAction(IMAGES_TOOL_ID,"setNetworkMode",{mode:r},c);l.push(`network=${r}`)}if(i!=null){await n.callAction(IMAGES_TOOL_ID,"setBlankImages",{enabled:i},c);l.push(`blankImages=${i}`)}if(a){await n.callAction(IMAGES_TOOL_ID,"clearRecords",{},c);l.push("registry cleared")}if(s){const u=await n.callAction(IMAGES_TOOL_ID,"clearExpoCaches",{},c);l.push(u?.message??"expo caches cleared")}if(l.length===0)return fail2("Pass at least one of: network, blankImages, massAction, clearRegistry, clearExpoCaches.");return text(`Applied: ${l.join(" \xB7 ")}`)}catch(c){return fail2(errMsg2(c))}})}var import_zod31=require("zod");function graphUnavailableNote(e){if(e.graphSupported&&e.graphCount!=null)return null;const n=(e.graphError??"").trim();const t=e.dev===true||!!n;if(t){return n?`\u26A0 Metro bundle graph unavailable (${n}) \u2014 showing runtime-registered assets only; never-loaded detection unavailable.`:"\u26A0 Metro bundle graph unavailable \u2014 showing runtime-registered assets only; never-loaded detection unavailable."}return"\u26A0 No Metro bundle graph (release build, or graph fetch failed) \u2014 showing runtime-registered assets only; never-loaded detection unavailable."}var ASSETS_TOOL_ID="assets";function kb2(e){if(e==null||e<=0)return"\u2013";if(e<1024)return`${e}B`;if(e<1024*1024)return`${(e/1024).toFixed(1)}KB`;return`${(e/(1024*1024)).toFixed(2)}MB`}function sizeLabel(e){if(e.sizeBytes==null)return"\u2013";return e.sizeSource==="measured"?kb2(e.sizeBytes):`~${kb2(e.sizeBytes)}`}function scalesLabel(e){if(!e.length)return"\u2013";return e.map(n=>`@${n}x`).join(" ")}function flagsLabel(e,n){const t=[];if(!e.loaded)t.push("UNUSED");if(n.overDecode.includes(e.id))t.push("OVERSIZE");if(n.duplicates.some(r=>r.ids.includes(e.id)))t.push("DUP");if(n.heavyGifs.includes(e.id)||n.heavyFonts.includes(e.id))t.push("HEAVY");if(n.scaleAnomalies.includes(e.id))t.push("BAD-SCALE");else if(n.scaleGaps.includes(e.id))t.push("LOW-RES");if(n.webpCandidates.includes(e.id))t.push("WEBP");return t.length?t.join(" "):"\u2013"}function formatListMarkdown2(e,n){const t=[];const r=e.stats;const i=e.scanStatus;t.push(`## Asset inventory (${e.total} assets, showing ${Math.min(n,e.records.length)}, largest first)`);t.push("");const o=Object.entries(r.byKind).filter(([,u])=>u.count>0).map(([u,d])=>`${d.count} ${u}${d.bytes>0?` (${kb2(d.bytes)})`:""}`);t.push(`${r.loaded} loaded \xB7 ${r.neverLoaded} never loaded \xB7 `+(r.totalBytes>0?`${kb2(r.totalBytes)} measured (${r.measuredCount}/${r.total})`:"sizes not measured")+` \xB7 ${o.join(" \xB7 ")}`);if(i.fontFamilies.length>0){t.push(`Loaded font families: ${i.fontFamilies.join(", ")}`)}const a=graphUnavailableNote(i);if(a)t.push(a);if(i.measuring)t.push("\u26A0 Size measurement in progress \u2014 byte totals are partial; re-run get_assets shortly.");const s=e.insights;const c=[];if(s.neverLoaded.length)c.push(`${s.neverLoaded.length} never loaded`);if(s.duplicates.length){const u=s.duplicates.reduce((d,h)=>d+(h.wastedBytes??0),0);c.push(`${s.duplicates.length} duplicate group(s)${u>0?` (${kb2(u)} wasted)`:""}`)}if(s.overDecode.length)c.push(`${s.overDecode.length} decode larger than 2\xD7 the screen`);if(s.webpCandidates.length)c.push(`${s.webpCandidates.length} WebP candidate(s)`);if(s.heavyGifs.length)c.push(`${s.heavyGifs.length} heavy GIF(s)`);if(s.heavyFonts.length)c.push(`${s.heavyFonts.length} heavy font(s)`);if(s.scaleGaps.length)c.push(`${s.scaleGaps.length} scale gap(s)`);if(s.scaleAnomalies.length)c.push(`${s.scaleAnomalies.length} scale anomaly(ies)`);if(c.length){t.push("");t.push(`**Findings:** ${c.join(" \xB7 ")}`)}const l=e.diff;if(l){const u=l.netBytes==null?"net unknown":Math.abs(l.netBytes)<1024?"\xB10 net":`${l.netBytes>=0?"+":"\u2212"}${kb2(Math.abs(l.netBytes))} net`;t.push("");t.push(`**Since baseline** (${new Date(l.baselineSavedAt).toISOString()}): ${l.added.length} added \xB7 ${l.removed.length} removed \xB7 ${l.grown.length} grew \xB7 ${u}`+(l.removed.length?` \u2014 removed: ${l.removed.slice(0,5).map(d=>`${d.name}.${d.type}`).join(", ")}${l.removed.length>5?"\u2026":""}`:""))}t.push("");t.push("| id | asset | kind | dims | scales | size | flags |");t.push("|---|---|---|---|---|---|---|");for(const u of e.records){const d=u.width!=null&&u.height!=null?`${Math.round(u.width)}\xD7${Math.round(u.height)}`:"\u2013";t.push(`| ${u.id} | ${u.name}.${u.type} | ${u.kind} | ${d} | ${scalesLabel(u.scales)} | ${sizeLabel(u)} | ${flagsLabel(u,s)} |`)}t.push("");t.push("_Sizes marked ~ are decoded-memory estimates (unmeasurable in this environment). Use `asset_action` for rescan / measure_sizes / detail / baseline ops._");return t.join("\n")}function registerAssetsTools(e,n){e.registerTool("get_assets",{description:"Inspect assets reported by the configured manifest, runtime registry and available Metro bundle graph. Includes available dimensions, scale coverage, byte sizes, observed load history, audit findings and saved-baseline differences. Size measurement and coverage depend on setup; not observed loading does not mean unused. Use get_images for instrumented runtime image loads. Requires @buoy-gg/assets on the device.",inputSchema:{deviceId:deviceIdInput,limit:import_zod31.z.number().optional().describe("Max records to return (largest first). Default 40, max 500."),kind:import_zod31.z.enum(["image","font","video","audio","data","other"]).optional().describe("Only assets of this kind."),unusedOnly:import_zod31.z.boolean().optional().describe("Only assets shipped in the bundle but never loaded at runtime.")}},async({deviceId:t,limit:r,kind:i,unusedOnly:o})=>{try{const a=n.requireProDevice(t);const s=Math.min(Math.max(r??40,1),500);const c=await n.callAction(ASSETS_TOOL_ID,"list",{limit:o?500:s,kind:i,loadedOnly:false},a);if(!c)return fail2("Device returned nothing \u2014 is @buoy-gg/assets installed in the app?");if(o){c.records=c.records.filter(d=>!d.loaded).slice(0,s)}const l=formatListMarkdown2(c,s);const u={stats:c.stats,scanStatus:c.scanStatus,insights:c.insights,diff:c.diff,records:c.records.map(d=>({id:d.id,name:d.name,type:d.type,kind:d.kind,hash:d.hash,width:d.width,height:d.height,scales:d.scales,loaded:d.loaded,sizeBytes:d.sizeBytes,sizeSource:d.sizeSource}))};return text(`${l}
968
+ \`\`\``)}catch(o){return fail2(errMsg2(o))}});e.registerTool("image_action",{description:"Request an action for a registered image ID: hard_reload, retry, evict_disk, flash, prove_savings or a supported simulation override. swap_url requires url; restore removes the override. Support depends on the component and platform. prove_savings attempts a WebP conversion at displayed size and reports available byte comparisons and a device-local URI; inspect visual quality and originalBytesSource before using the result. Other actions return an acknowledgement and, when available, a later record snapshot; that snapshot may precede load completion. A device-local URI is not necessarily accessible from the editor host.",inputSchema:{deviceId:deviceIdInput,id:import_zod31.z.number().describe("Record id from get_images."),action:import_zod31.z.enum(["hard_reload","retry","evict_disk","flash","prove_savings","force_error","force_loading","force_blank","swap_url","restore"]).describe("What to do."),url:import_zod31.z.string().optional().describe("Replacement URL (swap_url only).")}},async({deviceId:t,id:r,action:i,url:o})=>{try{const a=n.requireProDevice(t);if(i==="prove_savings"){const h=await n.callAction(IMAGES_TOOL_ID,"proveSavings",{id:r},a);if(!h)return fail2("Device returned nothing for proveSavings.");if(!h.ok)return fail2(h.message);const w=[`**prove_savings** on #${r}: ${h.message}`];if(h.originalBytes!=null)w.push(`Original: ${Math.round(h.originalBytes/1024)}KB (${h.originalBytesSource})`);if(h.optimizedBytes!=null)w.push(`Optimized: ${Math.round(h.optimizedBytes/1024)}KB \u2014 ${h.optimizedDims?.width}\xD7${h.optimizedDims?.height} WebP`);if(h.savedBytes!=null)w.push(`**Saved: ${Math.round(h.savedBytes/1024)}KB (${h.savedPct}%)**`);if(h.optimizedUri)w.push(`Preview in place: image_action {id:${r}, action:"swap_url", url:"${h.optimizedUri}"}`);return text(w.join("\n"))}const s=ACTION_MAP[i];if(!s)return fail2(`Unknown action: ${i}`);if(i==="swap_url"&&!o)return fail2("swap_url requires the `url` param.");const c=await n.callAction(IMAGES_TOOL_ID,s.action,{id:r,...s.params?.(o)??{}},a);const l=i==="flash"?0:1500;if(l>0)await new Promise(h=>setTimeout(h,l));const u=await n.callAction(IMAGES_TOOL_ID,"getDetail",{id:r},a).catch(()=>null);const d=[`**${i}** on #${r}: ${c?.message??(c?.ok===false?"failed":"done")}`];if(u){d.push("");d.push(`Now: status=${u.status}${u.errorCode?` (${u.errorCode})`:""} \xB7 cache=${cacheLabel(u)} \xB7 ms=${u.ms??"\u2013"} \xB7 loads=${u.loadCount}${u.overrideLabel?` \xB7 sim="${u.overrideLabel}"`:""}${u.mounted?"":" \xB7 UNMOUNTED"}`);if(u.error)d.push(`Error: ${u.error}`)}return text(d.join("\n"))}catch(a){return fail2(errMsg2(a))}});e.registerTool("set_image_simulation",{description:"Configure supported instrumented image loads: offline simulates network-load failures while bundled assets can still load; cold requests cache bypass; normal resets the network mode. Reload or remount existing images as needed. blankImages removes sources from integrated images; massAction targets registered mounted images. Can also clear the registry or supported Expo caches. These modes do not change device connectivity.",inputSchema:{deviceId:deviceIdInput,network:import_zod31.z.enum(["normal","offline","cold"]).optional().describe("Network simulation mode."),blankImages:import_zod31.z.boolean().optional().describe("Render integrated images without a source."),massAction:import_zod31.z.enum(["error","loading","blank","reload","flash","restore"]).optional().describe("Apply to registered mounted images: force error/loading/blank overrides, hard-reload all, flash all, or restore all overrides."),clearRegistry:import_zod31.z.boolean().optional().describe("Clear the captured image log."),clearExpoCaches:import_zod31.z.boolean().optional().describe("Clear expo-image memory + disk caches.")}},async({deviceId:t,network:r,blankImages:i,massAction:o,clearRegistry:a,clearExpoCaches:s})=>{try{const c=n.requireProDevice(t);const l=[];if(o){const u=await n.callAction(IMAGES_TOOL_ID,"massAction",{kind:o},c);l.push(u?.message??`mass ${o} applied`)}if(r){await n.callAction(IMAGES_TOOL_ID,"setNetworkMode",{mode:r},c);l.push(`network=${r}`)}if(i!=null){await n.callAction(IMAGES_TOOL_ID,"setBlankImages",{enabled:i},c);l.push(`blankImages=${i}`)}if(a){await n.callAction(IMAGES_TOOL_ID,"clearRecords",{},c);l.push("registry cleared")}if(s){const u=await n.callAction(IMAGES_TOOL_ID,"clearExpoCaches",{},c);l.push(u?.message??"expo caches cleared")}if(l.length===0)return fail2("Pass at least one of: network, blankImages, massAction, clearRegistry, clearExpoCaches.");return text(`Applied: ${l.join(" \xB7 ")}`)}catch(c){return fail2(errMsg2(c))}})}var import_zod32=require("zod");function registerThreeTools(e,n){for(const[t,r,i]of[["get_three_scene","getScene","Read the scene tree. Each tree has at most 500 nodes. Requires @buoy-gg/three."],["get_three_stats","getStats","Read the last render counts. Unknown fields are null. Counts are not bytes."]]){e.registerTool(t,{description:i,inputSchema:{deviceId:deviceIdInput}},async({deviceId:o})=>{try{const a=n.requireProDevice(o);const s=await n.callAction("three",r,{},a);return s==null?fail2("No scene data. Check that @buoy-gg/three is set up."):text(JSON.stringify(s))}catch(a){return fail2(errMsg2(a))}})}e.registerTool("three_action",{description:"Pick a scene node or change its values. Turn values use radians. Colors use six digit hex.",inputSchema:{deviceId:deviceIdInput,rendererId:import_zod32.z.string().describe("Scene group ID from get_three_scene."),id:import_zod32.z.string().optional().describe("Node ID. Needed except for clearSelection."),action:import_zod32.z.enum(["select","clearSelection","visible","position","rotation","scale","color"]),value:import_zod32.z.union([import_zod32.z.boolean(),import_zod32.z.tuple([import_zod32.z.number().finite(),import_zod32.z.number().finite(),import_zod32.z.number().finite()]),import_zod32.z.string()]).optional()}},async({deviceId:t,...r})=>{try{const i=n.requireProDevice(t);const o=await n.callAction("three","action",r,i);return o==null?fail2("No reply from the scene."):text(JSON.stringify(o))}catch(i){return fail2(errMsg2(i))}})}var import_zod33=require("zod");function graphUnavailableNote(e){if(e.graphSupported&&e.graphCount!=null)return null;const n=(e.graphError??"").trim();const t=e.dev===true||!!n;if(t){return n?`\u26A0 Metro bundle graph unavailable (${n}) \u2014 showing runtime-registered assets only; never-loaded detection unavailable.`:"\u26A0 Metro bundle graph unavailable \u2014 showing runtime-registered assets only; never-loaded detection unavailable."}return"\u26A0 No Metro bundle graph (release build, or graph fetch failed) \u2014 showing runtime-registered assets only; never-loaded detection unavailable."}var ASSETS_TOOL_ID="assets";function kb2(e){if(e==null||e<=0)return"\u2013";if(e<1024)return`${e}B`;if(e<1024*1024)return`${(e/1024).toFixed(1)}KB`;return`${(e/(1024*1024)).toFixed(2)}MB`}function sizeLabel(e){if(e.sizeBytes==null)return"\u2013";return e.sizeSource==="measured"?kb2(e.sizeBytes):`~${kb2(e.sizeBytes)}`}function scalesLabel(e){if(!e.length)return"\u2013";return e.map(n=>`@${n}x`).join(" ")}function flagsLabel(e,n){const t=[];if(!e.loaded)t.push("UNUSED");if(n.overDecode.includes(e.id))t.push("OVERSIZE");if(n.duplicates.some(r=>r.ids.includes(e.id)))t.push("DUP");if(n.heavyGifs.includes(e.id)||n.heavyFonts.includes(e.id))t.push("HEAVY");if(n.scaleAnomalies.includes(e.id))t.push("BAD-SCALE");else if(n.scaleGaps.includes(e.id))t.push("LOW-RES");if(n.webpCandidates.includes(e.id))t.push("WEBP");return t.length?t.join(" "):"\u2013"}function formatListMarkdown2(e,n){const t=[];const r=e.stats;const i=e.scanStatus;t.push(`## Asset inventory (${e.total} assets, showing ${Math.min(n,e.records.length)}, largest first)`);t.push("");const o=Object.entries(r.byKind).filter(([,u])=>u.count>0).map(([u,d])=>`${d.count} ${u}${d.bytes>0?` (${kb2(d.bytes)})`:""}`);t.push(`${r.loaded} loaded \xB7 ${r.neverLoaded} never loaded \xB7 `+(r.totalBytes>0?`${kb2(r.totalBytes)} measured (${r.measuredCount}/${r.total})`:"sizes not measured")+` \xB7 ${o.join(" \xB7 ")}`);if(i.fontFamilies.length>0){t.push(`Loaded font families: ${i.fontFamilies.join(", ")}`)}const a=graphUnavailableNote(i);if(a)t.push(a);if(i.measuring)t.push("\u26A0 Size measurement in progress \u2014 byte totals are partial; re-run get_assets shortly.");const s=e.insights;const c=[];if(s.neverLoaded.length)c.push(`${s.neverLoaded.length} never loaded`);if(s.duplicates.length){const u=s.duplicates.reduce((d,h)=>d+(h.wastedBytes??0),0);c.push(`${s.duplicates.length} duplicate group(s)${u>0?` (${kb2(u)} wasted)`:""}`)}if(s.overDecode.length)c.push(`${s.overDecode.length} decode larger than 2\xD7 the screen`);if(s.webpCandidates.length)c.push(`${s.webpCandidates.length} WebP candidate(s)`);if(s.heavyGifs.length)c.push(`${s.heavyGifs.length} heavy GIF(s)`);if(s.heavyFonts.length)c.push(`${s.heavyFonts.length} heavy font(s)`);if(s.scaleGaps.length)c.push(`${s.scaleGaps.length} scale gap(s)`);if(s.scaleAnomalies.length)c.push(`${s.scaleAnomalies.length} scale anomaly(ies)`);if(c.length){t.push("");t.push(`**Findings:** ${c.join(" \xB7 ")}`)}const l=e.diff;if(l){const u=l.netBytes==null?"net unknown":Math.abs(l.netBytes)<1024?"\xB10 net":`${l.netBytes>=0?"+":"\u2212"}${kb2(Math.abs(l.netBytes))} net`;t.push("");t.push(`**Since baseline** (${new Date(l.baselineSavedAt).toISOString()}): ${l.added.length} added \xB7 ${l.removed.length} removed \xB7 ${l.grown.length} grew \xB7 ${u}`+(l.removed.length?` \u2014 removed: ${l.removed.slice(0,5).map(d=>`${d.name}.${d.type}`).join(", ")}${l.removed.length>5?"\u2026":""}`:""))}t.push("");t.push("| id | asset | kind | dims | scales | size | flags |");t.push("|---|---|---|---|---|---|---|");for(const u of e.records){const d=u.width!=null&&u.height!=null?`${Math.round(u.width)}\xD7${Math.round(u.height)}`:"\u2013";t.push(`| ${u.id} | ${u.name}.${u.type} | ${u.kind} | ${d} | ${scalesLabel(u.scales)} | ${sizeLabel(u)} | ${flagsLabel(u,s)} |`)}t.push("");t.push("_Sizes marked ~ are decoded-memory estimates (unmeasurable in this environment). Use `asset_action` for rescan / measure_sizes / detail / baseline ops._");return t.join("\n")}function registerAssetsTools(e,n){e.registerTool("get_assets",{description:"Inspect assets reported by the configured manifest, runtime registry and available Metro bundle graph. Includes available dimensions, scale coverage, byte sizes, observed load history, audit findings and saved-baseline differences. Size measurement and coverage depend on setup; not observed loading does not mean unused. Use get_images for instrumented runtime image loads. Requires @buoy-gg/assets on the device.",inputSchema:{deviceId:deviceIdInput,limit:import_zod33.z.number().optional().describe("Max records to return (largest first). Default 40, max 500."),kind:import_zod33.z.enum(["image","font","video","audio","data","other"]).optional().describe("Only assets of this kind."),unusedOnly:import_zod33.z.boolean().optional().describe("Only assets shipped in the bundle but never loaded at runtime.")}},async({deviceId:t,limit:r,kind:i,unusedOnly:o})=>{try{const a=n.requireProDevice(t);const s=Math.min(Math.max(r??40,1),500);const c=await n.callAction(ASSETS_TOOL_ID,"list",{limit:o?500:s,kind:i,loadedOnly:false},a);if(!c)return fail2("Device returned nothing \u2014 is @buoy-gg/assets installed in the app?");if(o){c.records=c.records.filter(d=>!d.loaded).slice(0,s)}const l=formatListMarkdown2(c,s);const u={stats:c.stats,scanStatus:c.scanStatus,insights:c.insights,diff:c.diff,records:c.records.map(d=>({id:d.id,name:d.name,type:d.type,kind:d.kind,hash:d.hash,width:d.width,height:d.height,scales:d.scales,loaded:d.loaded,sizeBytes:d.sizeBytes,sizeSource:d.sizeSource}))};return text(`${l}
968
969
 
969
970
  \`\`\`json
970
971
  ${JSON.stringify(u)}
971
- \`\`\``)}catch(a){return fail2(errMsg2(a))}});e.registerTool("asset_action",{description:"Drive the assets tool: rescan (re-walk the registry + merge the Metro bundle graph + refresh fonts + measure sizes \u2014 run this first if the inventory looks stale or empty), measure_sizes (re-measure byte sizes only), detail (full metadata for one asset by id: source dir, per-scale sizes, resolved URI, per-file graph paths), save_baseline (persist the current inventory for before/after comparison \u2014 save, make your change, then get_assets shows added/removed/grown/net bytes), clear_baseline, clear_records (wipe + rescan rebuilds).",inputSchema:{deviceId:deviceIdInput,action:import_zod31.z.enum(["rescan","measure_sizes","detail","save_baseline","clear_baseline","clear_records"]).describe("What to do."),id:import_zod31.z.number().optional().describe("Asset id from get_assets (detail only).")}},async({deviceId:t,action:r,id:i})=>{try{const o=n.requireProDevice(t);switch(r){case"rescan":{const a=await n.callAction(ASSETS_TOOL_ID,"rescan",{},o);const s=a?.scanStatus;if(!s)return fail2("Device returned nothing for rescan.");return text(`Rescan done: ${s.registryCount} registered at runtime`+(s.graphCount!=null?` \xB7 ${s.graphCount} in the bundle graph`:" \xB7 no bundle graph")+(s.graphError?` (graph: ${s.graphError})`:"")+` \xB7 ${s.fontFamilies.length} font families`+(s.measuring?" \xB7 size measurement running \u2014 get_assets in a moment":""))}case"measure_sizes":{const a=await n.callAction(ASSETS_TOOL_ID,"measureSizes",{},o);return text(`Measured ${a?.measured??0} of ${a?.total??0} assets.`)}case"detail":{if(i==null)return fail2("detail requires the `id` param (from get_assets).");const a=await n.callAction(ASSETS_TOOL_ID,"getDetail",{id:i},o);if(!a)return fail2(`Asset ${i} not found \u2014 re-run get_assets for current ids.`);const s=[`## ${a.name}.${a.type} (#${a.id})`,"",`- Kind: ${a.kind} \xB7 ${a.loaded?"loaded at runtime":"in bundle, NEVER loaded"} (${a.origin})`];if(a.width!=null)s.push(`- Dimensions: ${a.width}\xD7${a.height} logical \xB7 scales ${scalesLabel(a.scales)}`);if(a.sizesByScale){for(const[c,l]of Object.entries(a.sizesByScale)){s.push(`- Size @${c}x: ${kb2(l)}`)}}if(a.sizeBytes!=null)s.push(`- Total: ${sizeLabel(a)}`);if(a.estDecodedBytes)s.push(`- Decoded memory: ~${kb2(a.estDecodedBytes)} (RGBA)`);if(a.hash)s.push(`- Hash: ${a.hash}`);if(a.fileSystemLocation)s.push(`- Source dir: ${a.fileSystemLocation}`);if(a.files?.length)s.push(`- Files: ${a.files.join(", ")}`);if(a.uri)s.push(`- Resolved URI: ${a.uri}`);return text(s.join("\n"))}case"save_baseline":{const a=await n.callAction(ASSETS_TOOL_ID,"saveBaseline",{},o);return text(`Baseline saved (${a?.assets??0} assets). Make your change, then get_assets reports added/removed/grown/net bytes against it.`)}case"clear_baseline":{await n.callAction(ASSETS_TOOL_ID,"clearBaseline",{},o);return text("Baseline cleared.")}case"clear_records":{const a=await n.callAction(ASSETS_TOOL_ID,"clearRecords",{},o);return text(a?.message??"Inventory cleared.")}}}catch(o){return fail2(errMsg2(o))}})}var import_zod32=require("zod");var import_ws2=require("ws");var CONNECT_TIMEOUT_MS=3e3;function messageSocketUrl(e){return`${e.replace(/^http/,"ws").replace(/\/+$/,"")}/message`}function reloadViaDevServer(e){return new Promise(n=>{let t=false;const r=s=>{if(t)return;t=true;n(s)};let i;try{i=new import_ws2.WebSocket(messageSocketUrl(e))}catch(s){r({ok:false,error:s.message});return}const o=setTimeout(()=>{try{i.close()}catch{}r({ok:false,error:`dev server at ${e} did not accept a connection`})},CONNECT_TIMEOUT_MS);let a=false;i.on("open",()=>{try{i.send(JSON.stringify({version:2,method:"reload"}));a=true;clearTimeout(o);setTimeout(()=>{try{i.close()}catch{}r({ok:true})},250)}catch(s){clearTimeout(o);r({ok:false,error:s.message})}});i.on("error",s=>{clearTimeout(o);if(a)return;r({ok:false,error:s.message})})})}var APP_TOOL_ID2="app";var RELOAD_ACTION="reloadApp";var DEFAULT_WAIT_MS2=3e4;var TEARDOWN_GRACE_MS2=1200;var PROBE_TIMEOUT_MS=1500;var PROBE_INTERVAL_MS=400;var delay7=e=>new Promise(n=>setTimeout(n,e));async function ping(e,n,t){try{const r=await e.callAction(APP_TOOL_ID2,"ping",{},n,{timeoutMs:t,silent:true});e.noteDevServerOrigin(n,r?.devServerOrigin);return typeof r?.startedAt==="number"?r.startedAt:null}catch{return null}}function assertReloadSupported(e,n){if(n===ALL_DEVICES)return;const t=e.toolActions(APP_TOOL_ID2).find(r=>r.deviceId===n);if(!t?.actions.includes(RELOAD_ACTION)){throw new Error(`This app doesn't expose remote reload \u2014 its @buoy-gg/core is too old. Upgrade @buoy-gg/core, then reload the app once by hand.`)}}async function waitForAppBack(e,n,t,r){const i=Date.now();await delay7(TEARDOWN_GRACE_MS2);while(Date.now()-i<t){const o=await ping(e,n,PROBE_TIMEOUT_MS);if(o!==null&&o!==r)return Date.now()-i;await delay7(PROBE_INTERVAL_MS)}return null}function offlineDeviceId(e){if(!/is not connected right now/.test(e))return null;return/"([^"]+)"/.exec(e)?.[1]??null}async function reloadOffline(e,n,t,r){const i=offlineDeviceId(errMsg2(n));if(!i||!e.listDevices().some(u=>u.deviceId===i&&u.isPro))throw n;const o=e.devServerOrigin(i);let a="";if(o){const u=await reloadViaDevServer(o);if(u.ok){if(!r)return text(`"${i}" was not connected, so it was reloaded through its dev server (${o}). It is restarting.`);const d=await waitForAppBack(e,i,Math.min(t,12e3),null);if(d!=null){return text(`"${i}" was not connected, so it was reloaded through its dev server. Back after ${(d/1e3).toFixed(1)}s. All in-memory state was reset.`)}a=` Its dev server (${o}) took the reload, but the app did not come back.`}else{a=` Its dev server at ${o} could not reload it: ${u.error}.`}}const s=e.listDevices().find(u=>u.deviceId===i)?.platform;const c=rememberedHost(i);const l=c?await verifyHost(i,c).catch(()=>void 0):await findHost(i,s).catch(()=>void 0);if(l){try{await hostQuit(l).catch(()=>void 0);await hostLaunch(l);if(!r)return text(`"${i}" was not connected, so it was relaunched on its ${l.platform==="ios"?"simulator":"device"}.`);const u=await waitForAppBack(e,i,t,null);if(u!=null){return text(`"${i}" was not connected, so it was relaunched on its ${l.platform==="ios"?"simulator":"device"} (a cold start). Back after ${(u/1e3).toFixed(1)}s. All in-memory state was reset.`)}}catch{}}return fail2(`"${i}" is not connected and could not be brought back.${a} Open the app by hand, then run list_devices.`)}function registerReloadTools(e,n){e.registerTool("reload_app",{description:"Request a JS reload for a supported app using DevSettings in development or installed expo-updates where available. For an unresponsive app, can try its known dev server when reachable. Recovery is not guaranteed. Reload can discard in-memory state and evidence; collect needed observations first when possible. By default waits for reconnection up to timeoutMs. Requires configured @buoy-gg/core support and Buoy Pro.",inputSchema:{strategy:import_zod32.z.enum(["auto","dev-settings","expo-updates"]).optional().describe("Reload mechanism. 'auto' (default) uses DevSettings in dev builds and expo-updates otherwise. Force one only when debugging the reload itself."),wait:import_zod32.z.boolean().optional().describe("Wait for the app to come back before returning. Default true \u2014 turn off for fire-and-forget."),timeoutMs:import_zod32.z.number().optional().describe("How long to wait for the app to reconnect, in ms. Default 30000."),deviceId:import_zod32.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 reload every connected app.')}},async t=>{try{let r;try{r=n.requireProDevice(t.deviceId)}catch(u){return await reloadOffline(n,u,t.timeoutMs??DEFAULT_WAIT_MS2,t.wait!==false)}assertReloadSupported(n,r);const i=t.wait===false?null:await ping(n,r,PROBE_TIMEOUT_MS);let o=null;let a=false;const s=async u=>{const d=n.devServerOrigin(r);if(!d){if(u)throw u;throw new Error("The app is not answering and no dev-server origin is known (it was never learned from a successful ping). Reload the app by hand.")}const h=await reloadViaDevServer(d);if(!h.ok){throw new Error(`The app is not answering (it looks crashed) and the dev server at ${d} could not be reached either: ${h.error}. Reload the app by hand.`)}a=true};if(n.isUnresponsive(r)&&n.devServerOrigin(r)){await s()}else{try{o=await n.callAction(APP_TOOL_ID2,RELOAD_ACTION,{strategy:t.strategy??"auto"},r)}catch(u){await s(u)}}const c=a?` via the dev server (the app was unresponsive \u2014 its own reload could not be reached)`:o?.strategy?` via ${o.strategy}`:"";if(t.wait===false){return text(`Reload requested${c}. The app is restarting \u2014 its in-memory state is gone; re-read anything you cached.`)}const l=await waitForAppBack(n,r,t.timeoutMs??DEFAULT_WAIT_MS2,i);if(l==null){return fail2(`Reload was accepted${c}, but the app hasn't reconnected yet. It may still be building the bundle (a cold Metro rebuild can take a while) \u2014 check the device, then run list_devices.`)}return text(`Reloaded the app${c} \u2014 back and connected after ${(l/1e3).toFixed(1)}s. All in-memory state was reset, so re-read any state you cached before this.`)}catch(r){return fail2(errMsg2(r))}})}var import_zod33=require("zod");var text8=e=>({content:[{type:"text",text:e}]});var fail10=e=>({isError:true,content:[{type:"text",text:e}]});var errMsg8=e=>e instanceof Error?e.message:String(e);var PROBE_TIMEOUT_MS2=5e3;var MAX_STORAGE_KEYS=20;var MAX_STORAGE_VALUE=400;var STORAGE_VALUE_BUDGET=1600;var MAX_LINE=160;var cap2=(e,n=MAX_LINE)=>e.length>n?`${e.slice(0,n)}\u2026`:e;function hhmmss3(e){if(!e)return"--:--:--";const n=new Date(e);const t=r=>String(r).padStart(2,"0");return`${t(n.getHours())}:${t(n.getMinutes())}:${t(n.getSeconds())}`}async function otherBackends(e,n,t){const r=[];try{const i=await e.callAction("storage","mmkv.snapshot",{},n,t);for(const o of i??[]){const a=o.entries?.length??0;if(a>0)r.push(`MMKV "${o.id}": ${a} key${a===1?"":"s"}`)}}catch{}try{const i=await e.callAction("storage","secure.keys",{},n,t);if(i?.length)r.push(`SecureStore: ${i.length} key${i.length===1?"":"s"}`)}catch{}return r.length?`
972
+ \`\`\``)}catch(a){return fail2(errMsg2(a))}});e.registerTool("asset_action",{description:"Drive the assets tool: rescan (re-walk the registry + merge the Metro bundle graph + refresh fonts + measure sizes \u2014 run this first if the inventory looks stale or empty), measure_sizes (re-measure byte sizes only), detail (full metadata for one asset by id: source dir, per-scale sizes, resolved URI, per-file graph paths), save_baseline (persist the current inventory for before/after comparison \u2014 save, make your change, then get_assets shows added/removed/grown/net bytes), clear_baseline, clear_records (wipe + rescan rebuilds).",inputSchema:{deviceId:deviceIdInput,action:import_zod33.z.enum(["rescan","measure_sizes","detail","save_baseline","clear_baseline","clear_records"]).describe("What to do."),id:import_zod33.z.number().optional().describe("Asset id from get_assets (detail only).")}},async({deviceId:t,action:r,id:i})=>{try{const o=n.requireProDevice(t);switch(r){case"rescan":{const a=await n.callAction(ASSETS_TOOL_ID,"rescan",{},o);const s=a?.scanStatus;if(!s)return fail2("Device returned nothing for rescan.");return text(`Rescan done: ${s.registryCount} registered at runtime`+(s.graphCount!=null?` \xB7 ${s.graphCount} in the bundle graph`:" \xB7 no bundle graph")+(s.graphError?` (graph: ${s.graphError})`:"")+` \xB7 ${s.fontFamilies.length} font families`+(s.measuring?" \xB7 size measurement running \u2014 get_assets in a moment":""))}case"measure_sizes":{const a=await n.callAction(ASSETS_TOOL_ID,"measureSizes",{},o);return text(`Measured ${a?.measured??0} of ${a?.total??0} assets.`)}case"detail":{if(i==null)return fail2("detail requires the `id` param (from get_assets).");const a=await n.callAction(ASSETS_TOOL_ID,"getDetail",{id:i},o);if(!a)return fail2(`Asset ${i} not found \u2014 re-run get_assets for current ids.`);const s=[`## ${a.name}.${a.type} (#${a.id})`,"",`- Kind: ${a.kind} \xB7 ${a.loaded?"loaded at runtime":"in bundle, NEVER loaded"} (${a.origin})`];if(a.width!=null)s.push(`- Dimensions: ${a.width}\xD7${a.height} logical \xB7 scales ${scalesLabel(a.scales)}`);if(a.sizesByScale){for(const[c,l]of Object.entries(a.sizesByScale)){s.push(`- Size @${c}x: ${kb2(l)}`)}}if(a.sizeBytes!=null)s.push(`- Total: ${sizeLabel(a)}`);if(a.estDecodedBytes)s.push(`- Decoded memory: ~${kb2(a.estDecodedBytes)} (RGBA)`);if(a.hash)s.push(`- Hash: ${a.hash}`);if(a.fileSystemLocation)s.push(`- Source dir: ${a.fileSystemLocation}`);if(a.files?.length)s.push(`- Files: ${a.files.join(", ")}`);if(a.uri)s.push(`- Resolved URI: ${a.uri}`);return text(s.join("\n"))}case"save_baseline":{const a=await n.callAction(ASSETS_TOOL_ID,"saveBaseline",{},o);return text(`Baseline saved (${a?.assets??0} assets). Make your change, then get_assets reports added/removed/grown/net bytes against it.`)}case"clear_baseline":{await n.callAction(ASSETS_TOOL_ID,"clearBaseline",{},o);return text("Baseline cleared.")}case"clear_records":{const a=await n.callAction(ASSETS_TOOL_ID,"clearRecords",{},o);return text(a?.message??"Inventory cleared.")}}}catch(o){return fail2(errMsg2(o))}})}var import_zod34=require("zod");var import_ws2=require("ws");var CONNECT_TIMEOUT_MS=3e3;function messageSocketUrl(e){return`${e.replace(/^http/,"ws").replace(/\/+$/,"")}/message`}function reloadViaDevServer(e){return new Promise(n=>{let t=false;const r=s=>{if(t)return;t=true;n(s)};let i;try{i=new import_ws2.WebSocket(messageSocketUrl(e))}catch(s){r({ok:false,error:s.message});return}const o=setTimeout(()=>{try{i.close()}catch{}r({ok:false,error:`dev server at ${e} did not accept a connection`})},CONNECT_TIMEOUT_MS);let a=false;i.on("open",()=>{try{i.send(JSON.stringify({version:2,method:"reload"}));a=true;clearTimeout(o);setTimeout(()=>{try{i.close()}catch{}r({ok:true})},250)}catch(s){clearTimeout(o);r({ok:false,error:s.message})}});i.on("error",s=>{clearTimeout(o);if(a)return;r({ok:false,error:s.message})})})}var APP_TOOL_ID2="app";var RELOAD_ACTION="reloadApp";var DEFAULT_WAIT_MS2=3e4;var TEARDOWN_GRACE_MS2=1200;var PROBE_TIMEOUT_MS=1500;var PROBE_INTERVAL_MS=400;var delay7=e=>new Promise(n=>setTimeout(n,e));async function ping(e,n,t){try{const r=await e.callAction(APP_TOOL_ID2,"ping",{},n,{timeoutMs:t,silent:true});e.noteDevServerOrigin(n,r?.devServerOrigin);return typeof r?.startedAt==="number"?r.startedAt:null}catch{return null}}function assertReloadSupported(e,n){if(n===ALL_DEVICES)return;const t=e.toolActions(APP_TOOL_ID2).find(r=>r.deviceId===n);if(!t?.actions.includes(RELOAD_ACTION)){throw new Error(`This app doesn't expose remote reload \u2014 its @buoy-gg/core is too old. Upgrade @buoy-gg/core, then reload the app once by hand.`)}}async function waitForAppBack(e,n,t,r){const i=Date.now();await delay7(TEARDOWN_GRACE_MS2);while(Date.now()-i<t){const o=await ping(e,n,PROBE_TIMEOUT_MS);if(o!==null&&o!==r)return Date.now()-i;await delay7(PROBE_INTERVAL_MS)}return null}function offlineDeviceId(e){if(!/is not connected right now/.test(e))return null;return/"([^"]+)"/.exec(e)?.[1]??null}async function reloadOffline(e,n,t,r){const i=offlineDeviceId(errMsg2(n));if(!i||!e.listDevices().some(u=>u.deviceId===i&&u.isPro))throw n;const o=e.devServerOrigin(i);let a="";if(o){const u=await reloadViaDevServer(o);if(u.ok){if(!r)return text(`"${i}" was not connected, so it was reloaded through its dev server (${o}). It is restarting.`);const d=await waitForAppBack(e,i,Math.min(t,12e3),null);if(d!=null){return text(`"${i}" was not connected, so it was reloaded through its dev server. Back after ${(d/1e3).toFixed(1)}s. All in-memory state was reset.`)}a=` Its dev server (${o}) took the reload, but the app did not come back.`}else{a=` Its dev server at ${o} could not reload it: ${u.error}.`}}const s=e.listDevices().find(u=>u.deviceId===i)?.platform;const c=rememberedHost(i);const l=c?await verifyHost(i,c).catch(()=>void 0):await findHost(i,s).catch(()=>void 0);if(l){try{await hostQuit(l).catch(()=>void 0);await hostLaunch(l);if(!r)return text(`"${i}" was not connected, so it was relaunched on its ${l.platform==="ios"?"simulator":"device"}.`);const u=await waitForAppBack(e,i,t,null);if(u!=null){return text(`"${i}" was not connected, so it was relaunched on its ${l.platform==="ios"?"simulator":"device"} (a cold start). Back after ${(u/1e3).toFixed(1)}s. All in-memory state was reset.`)}}catch{}}return fail2(`"${i}" is not connected and could not be brought back.${a} Open the app by hand, then run list_devices.`)}function registerReloadTools(e,n){e.registerTool("reload_app",{description:"Request a JS reload for a supported app using DevSettings in development or installed expo-updates where available. For an unresponsive app, can try its known dev server when reachable. Recovery is not guaranteed. Reload can discard in-memory state and evidence; collect needed observations first when possible. By default waits for reconnection up to timeoutMs. Requires configured @buoy-gg/core support and Buoy Pro.",inputSchema:{strategy:import_zod34.z.enum(["auto","dev-settings","expo-updates"]).optional().describe("Reload mechanism. 'auto' (default) uses DevSettings in dev builds and expo-updates otherwise. Force one only when debugging the reload itself."),wait:import_zod34.z.boolean().optional().describe("Wait for the app to come back before returning. Default true \u2014 turn off for fire-and-forget."),timeoutMs:import_zod34.z.number().optional().describe("How long to wait for the app to reconnect, in ms. Default 30000."),deviceId:import_zod34.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 reload every connected app.')}},async t=>{try{let r;try{r=n.requireProDevice(t.deviceId)}catch(u){return await reloadOffline(n,u,t.timeoutMs??DEFAULT_WAIT_MS2,t.wait!==false)}assertReloadSupported(n,r);const i=t.wait===false?null:await ping(n,r,PROBE_TIMEOUT_MS);let o=null;let a=false;const s=async u=>{const d=n.devServerOrigin(r);if(!d){if(u)throw u;throw new Error("The app is not answering and no dev-server origin is known (it was never learned from a successful ping). Reload the app by hand.")}const h=await reloadViaDevServer(d);if(!h.ok){throw new Error(`The app is not answering (it looks crashed) and the dev server at ${d} could not be reached either: ${h.error}. Reload the app by hand.`)}a=true};if(n.isUnresponsive(r)&&n.devServerOrigin(r)){await s()}else{try{o=await n.callAction(APP_TOOL_ID2,RELOAD_ACTION,{strategy:t.strategy??"auto"},r)}catch(u){await s(u)}}const c=a?` via the dev server (the app was unresponsive \u2014 its own reload could not be reached)`:o?.strategy?` via ${o.strategy}`:"";if(t.wait===false){return text(`Reload requested${c}. The app is restarting \u2014 its in-memory state is gone; re-read anything you cached.`)}const l=await waitForAppBack(n,r,t.timeoutMs??DEFAULT_WAIT_MS2,i);if(l==null){return fail2(`Reload was accepted${c}, but the app hasn't reconnected yet. It may still be building the bundle (a cold Metro rebuild can take a while) \u2014 check the device, then run list_devices.`)}return text(`Reloaded the app${c} \u2014 back and connected after ${(l/1e3).toFixed(1)}s. All in-memory state was reset, so re-read any state you cached before this.`)}catch(r){return fail2(errMsg2(r))}})}var import_zod35=require("zod");var text9=e=>({content:[{type:"text",text:e}]});var fail11=e=>({isError:true,content:[{type:"text",text:e}]});var errMsg8=e=>e instanceof Error?e.message:String(e);var PROBE_TIMEOUT_MS2=5e3;var MAX_STORAGE_KEYS=20;var MAX_STORAGE_VALUE=400;var STORAGE_VALUE_BUDGET=1600;var MAX_LINE=160;var cap2=(e,n=MAX_LINE)=>e.length>n?`${e.slice(0,n)}\u2026`:e;function hhmmss3(e){if(!e)return"--:--:--";const n=new Date(e);const t=r=>String(r).padStart(2,"0");return`${t(n.getHours())}:${t(n.getMinutes())}:${t(n.getSeconds())}`}async function otherBackends(e,n,t){const r=[];try{const i=await e.callAction("storage","mmkv.snapshot",{},n,t);for(const o of i??[]){const a=o.entries?.length??0;if(a>0)r.push(`MMKV "${o.id}": ${a} key${a===1?"":"s"}`)}}catch{}try{const i=await e.callAction("storage","secure.keys",{},n,t);if(i?.length)r.push(`SecureStore: ${i.length} key${i.length===1?"":"s"}`)}catch{}return r.length?`
972
973
  ${r.join(" \xB7 ")} \u2014 read with get_storage`:""}async function section(e,n){try{const t=await n();return t?`${e}
973
974
  ${t}`:null}catch(t){const r=errMsg8(t);if(/not responding|timed out|got no answer/i.test(r)){return`${e}
974
975
  (no answer \u2014 see the note above)`}return`${e}
975
- (unavailable: ${cap2(r,120)})`}}function registerTriageTools(e,n){e.registerTool("get_triage",{description:"Summarize available runtime observations for a connected app: captured console errors, recent network requests, configured storage and screen information. Use the returned sections and errors to choose follow-up tools. Missing data or an unresponsive app does not prove a crash; crash output may be unavailable. Requires Buoy Pro.",inputSchema:{deviceId:import_zod33.z.string().optional().describe("Target device id (auto-selected if one is connected).")}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=n.connectedDevices().find(g=>g.deviceId===r);const o=new Set((i?.tools??[]).map(g=>g.toolId));const a=`**${i?.deviceName??r}** (${i?.platform??"?"}, id \`${r}\`) \u2014 tools: ${[...o].join(", ")||"none"}`;const s={timeoutMs:PROBE_TIMEOUT_MS2};const[c,l,u,d]=await Promise.all([section("**Console \u2014 recent errors/warnings:**",async()=>{if(!o.has("console"))return null;const{payload:g}=await n.getSnapshot("console",r,s);const m=g;const f=Array.isArray(m)?m:m?.entries??[];const v=f.filter(b=>b.level==="error"||b.level==="warning");const y=v.slice(-8);if(y.length===0){return`(none \u2014 ${f.length} entries captured)`}return y.map(b=>`${hhmmss3(b.timestamp)} [${b.level==="error"?"ERR":"warn"}] ${cap2((b.message??"").split("\n").map($=>$.trim()).filter(Boolean).slice(0,3).join(" \u23CE "),220)}`).join("\n")}),section("**Network \u2014 recent requests:**",async()=>{if(!o.has("network"))return null;const{payload:g}=await n.getSnapshot("network",r,s);const m=Array.isArray(g)?g:g?.events??[];if(m.length===0)return"(no requests captured yet)";const f=m.slice(-8);return f.map(v=>{const y=v.error||(v.status??0)>=400?"\u274C":"\u2705";const b=v.path??v.url??"?";const $=v.error??v.status??"pending";return`${y} ${v.method??"GET"} ${cap2(String(b),80)} \u2192 ${$}${v.duration?` (${Math.round(v.duration)}ms)`:""}`}).join("\n")}),section("**Storage \u2014 persisted values:**",async()=>{if(!o.has("storage"))return null;const g=await n.callAction("storage","async.getAllKeys",{},r,s);if(!Array.isArray(g)||g.length===0){return"(no app keys)"}const m=g.slice(0,MAX_STORAGE_KEYS);let f=[];try{f=await n.callAction("storage","async.multiGet",{keys:m},r,s)??[]}catch{return`${m.map(_=>`\`${_}\``).join(", ")}
976
+ (unavailable: ${cap2(r,120)})`}}function registerTriageTools(e,n){e.registerTool("get_triage",{description:"Summarize available runtime observations for a connected app: captured console errors, recent network requests, configured storage and screen information. Use the returned sections and errors to choose follow-up tools. Missing data or an unresponsive app does not prove a crash; crash output may be unavailable. Requires Buoy Pro.",inputSchema:{deviceId:import_zod35.z.string().optional().describe("Target device id (auto-selected if one is connected).")}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=n.connectedDevices().find(g=>g.deviceId===r);const o=new Set((i?.tools??[]).map(g=>g.toolId));const a=`**${i?.deviceName??r}** (${i?.platform??"?"}, id \`${r}\`) \u2014 tools: ${[...o].join(", ")||"none"}`;const s={timeoutMs:PROBE_TIMEOUT_MS2};const[c,l,u,d]=await Promise.all([section("**Console \u2014 recent errors/warnings:**",async()=>{if(!o.has("console"))return null;const{payload:g}=await n.getSnapshot("console",r,s);const m=g;const f=Array.isArray(m)?m:m?.entries??[];const v=f.filter(b=>b.level==="error"||b.level==="warning");const y=v.slice(-8);if(y.length===0){return`(none \u2014 ${f.length} entries captured)`}return y.map(b=>`${hhmmss3(b.timestamp)} [${b.level==="error"?"ERR":"warn"}] ${cap2((b.message??"").split("\n").map($=>$.trim()).filter(Boolean).slice(0,3).join(" \u23CE "),220)}`).join("\n")}),section("**Network \u2014 recent requests:**",async()=>{if(!o.has("network"))return null;const{payload:g}=await n.getSnapshot("network",r,s);const m=Array.isArray(g)?g:g?.events??[];if(m.length===0)return"(no requests captured yet)";const f=m.slice(-8);return f.map(v=>{const y=v.error||(v.status??0)>=400?"\u274C":"\u2705";const b=v.path??v.url??"?";const $=v.error??v.status??"pending";return`${y} ${v.method??"GET"} ${cap2(String(b),80)} \u2192 ${$}${v.duration?` (${Math.round(v.duration)}ms)`:""}`}).join("\n")}),section("**Storage \u2014 persisted values:**",async()=>{if(!o.has("storage"))return null;const g=await n.callAction("storage","async.getAllKeys",{},r,s);if(!Array.isArray(g)||g.length===0){return"(no app keys)"}const m=g.slice(0,MAX_STORAGE_KEYS);let f=[];try{f=await n.callAction("storage","async.multiGet",{keys:m},r,s)??[]}catch{return`${m.map(_=>`\`${_}\``).join(", ")}
976
977
  _Values: get_storage includeValues:true_`}const v=new Map(f);let y=STORAGE_VALUE_BUDGET;const b=m.map(_=>{const x=v.get(_);if(x==null)return`- \`${_}\` = (null)`;if(x.length>MAX_STORAGE_VALUE){return`- \`${_}\` = (${(x.length/1024).toFixed(1)} KB \u2014 read with get_storage)`}if(y<=0)return`- \`${_}\` = (not shown \u2014 triage budget spent; read with get_storage)`;y-=x.length;return`- \`${_}\` = ${x}`});const $=g.length-m.length;const T=await otherBackends(n,r,s);return`${b.join("\n")}${$>0?`
977
978
  \u2026+${$} more keys`:""}${T}`}),section("**Screen \u2014 what's visible now:**",async()=>{if(!o.has("highlight-updates"))return null;const g=await n.callAction("highlight-updates","describeScreen",{},r,s);const m=(g?.elements??[]).filter(f=>f.interactive);if(m.length===0)return"(nothing interactive on screen)";return m.slice(0,20).map(f=>`\u2022 ${f.name}${f.text||f.label?` "${cap2(f.text??f.label??"",60)}"`:""}${f.testID?` [testID=${f.testID}]`:""}`).join("\n")})]);const h=n.isUnresponsive(r);const w=h?`
978
979
 
979
- \u{1F6D1} ${n.unresponsiveNote(r)}`:"";const p=[c,l,u,d].filter(Boolean).join("\n\n");return text8(`${a}${w}
980
+ \u{1F6D1} ${n.unresponsiveNote(r)}`:"";const p=[c,l,u,d].filter(Boolean).join("\n\n");return text9(`${a}${w}
980
981
 
981
982
  ${p}
982
983
 
983
- _Drill in with get_console, get_network_requests (includeBodies:true for response bodies), get_storage (includeValues:true), describe_screen._`)}catch(r){return fail10(errMsg8(r))}})}var import_zod34=require("zod");var UI_TOOL_ID3="highlight-updates";var text9=e=>({content:[{type:"text",text:e}]});var fail11=e=>({isError:true,content:[{type:"text",text:e}]});var errMsg9=e=>e instanceof Error?e.message:String(e);var delay8=e=>new Promise(n=>setTimeout(n,e));var DEFAULT_IDLE_MS=3e3;var SETTLE_MS=400;var DEFAULT_TOP=12;var lastCapture=new Map;var stepSchema2=import_zod34.z.object({tap:import_zod34.z.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),type:import_zod34.z.string().optional().describe("Text to type (needs `into`)."),into:import_zod34.z.string().optional().describe("Target text input for `type`: testID or fuzzy text."),waitMs:import_zod34.z.number().min(0).max(1e4).optional().describe("Pause after the action, in ms."),repeat:import_zod34.z.number().min(1).max(20).optional().describe("Do this step N times (default 1). Useful for 'tap it five times'.")}).describe("One interaction to measure. Keep it to the thing you're asking about.");function selector2(e){return/\s/.test(e)?{query:e}:{testID:e,query:e}}function dominant(e){if(!e)return"unknown";let n="unknown";let t=-1;for(const[r,i]of Object.entries(e)){if((i??0)>t){t=i??0;n=r}}return n}var CAUSE_HINT={propsUnstable:"props changed by IDENTITY only (a fresh function/object from the parent) \u2014 fix upstream, not in the child",parent:"parent re-rendered and nothing of its own changed \u2014 a pure cascade",props:"props genuinely changed value",hooks:"its own state/hooks changed",mount:"first render"};function formatCapture(e,n){const t=e.summary;const r=t.wastedRenders??0;const i=t.totalRenders>0?Math.round(r/t.totalRenders*100):0;const o=[];const a=t.totalRenderMs??0;o.push(`**${t.totalRenders} component renders across ${t.totalCommits} commits in ${(e.windowMs/1e3).toFixed(1)}s**`+(a>0?` \xB7 ${a.toFixed(1)}ms of render work`:"")+` \xB7 ${r} wasted (${i}%)`);const s=Object.entries(t.causes??{}).filter(([,d])=>(d??0)>0).sort((d,h)=>(h[1]??0)-(d[1]??0)).map(([d,h])=>`${d} ${h}`).join(" \xB7 ");if(s)o.push(`causes: ${s}`);o.push("");o.push("| component | self ms | renders | cause | dragged along by | changed props |");o.push("|---|---:|---:|---|---|---|");const c=[...t.topComponents].sort((d,h)=>(h.totalMs??0)-(d.totalMs??0)||h.renders-d.renders).slice(0,n);for(const d of c){o.push(`| ${d.name} | ${(d.totalMs??0).toFixed(1)} | ${d.renders} | ${dominant(d.causes)} | ${d.parentName??"\u2014"} | ${(d.changedProps??[]).join(", ")||"\u2014"} |`)}if(t.topComponents.length>n){o.push(`_\u2026+${t.topComponents.length-n} more components_`)}const l=new Set(c.map(d=>dominant(d.causes)));const u=[...l].filter(d=>CAUSE_HINT[d]).map(d=>`\`${d}\` = ${CAUSE_HINT[d]}`);if(u.length){o.push("");o.push(u.join(" \xB7 "))}o.push("");o.push("`wasted` classifies parent cascades and identity-only prop changes. Investigate whether these renders are needed before changing them. Rows are sorted by **self ms**. Compare timing and render counts for the measured workload, and check behavior before deciding whether memoization helps.");return o.join("\n")}function formatDelta(e,n){const t=(u,d)=>{const h=d-u;return`${u} \u2192 ${d} (${h>0?"+":""}${h})`};const r=e.summary;const i=n.summary;const o=[`**vs "${e.label}"**`];o.push(`- total renders: ${t(r.totalRenders,i.totalRenders)}`);o.push(`- wasted: ${t(r.wastedRenders??0,i.wastedRenders??0)}`);const a=new Map(r.topComponents.map(u=>[u.name,u.renders]));const s=[];for(const u of i.topComponents.slice(0,20)){const d=a.get(u.name)??0;if(d!==u.renders)s.push(`${u.name} ${t(d,u.renders)}`);a.delete(u.name)}for(const[u,d]of a){if(d>0)s.push(`${u} ${t(d,0)}`)}if(s.length)o.push(`- per component: ${s.slice(0,10).join(" \xB7 ")}`);const c=i.totalRenders<r.totalRenders;const l=i.totalRenders>r.totalRenders;o.push(l?"\n\u26A0\uFE0F MORE renders than before \u2014 this change made this interaction worse. Re-render fixes routinely move cost instead of removing it; check the other interactions too before moving on.":c?"\n\u2705 Fewer renders than before on this interaction. Measure the OTHER interactions too \u2014 a fix that helps typing can cost taps.":"\n\u2796 No change on this interaction.");return o.join("\n")}function registerRenderTools(e,n){e.registerTool("measure_renders",{description:"Measure captured component renders during supplied interaction steps or an idle window. Returns available timings, render counts, reported reasons and changed props. The wasted count is a diagnostic classification, not proof a render can be removed. Check interaction warnings before comparing runs. Use the same steps and comparable conditions with compareToPrevious:true after editing; the comparison alone does not prove correctness or overall performance. Requires Buoy Pro and a highlight-updates integration exposing beginMeasurement. Use run_benchmark_batch to compare route-based variants.",inputSchema:{steps:import_zod34.z.array(stepSchema2).max(20).optional().describe("The interaction to measure, e.g. [{tap:'favorite-deal-2', repeat:5}] or [{type:'bench', into:'deals-search'}]. Omit to sample the screen idle \u2014 only useful for churn that happens with nobody touching it."),idleMs:import_zod34.z.number().min(500).max(2e4).optional().describe(`Idle sample length when no steps are given. Default ${DEFAULT_IDLE_MS}.`),label:import_zod34.z.string().optional().describe('Name this measurement, e.g. "before fix". Shown in the next comparison.'),compareToPrevious:import_zod34.z.boolean().optional().describe("Compare with the previous measurement on this device. Use equivalent steps and conditions; review warnings and behavior separately."),top:import_zod34.z.number().min(1).max(40).optional().describe(`Components to list. Default ${DEFAULT_TOP}.`),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=n.connectedDevices().find(m=>m.deviceId===r);const o=(i?.tools??[]).find(m=>m.toolId===UI_TOOL_ID3);if(!o){return fail11("This app doesn't expose the highlight-updates tool, so renders can't be measured. Install @buoy-gg/highlight-updates.")}if(!(o.actions??[]).includes("beginMeasurement")){return fail11("This app's @buoy-gg/highlight-updates is too old to measure renders (needs the version with beginMeasurement). Upgrade it, then try again. Meanwhile run_benchmark_batch with captureRenders can still give counts if you have a test route.")}const a=await n.callAction(UI_TOOL_ID3,"beginMeasurement",{},r);if(a&&a.ok===false){return fail11(`Can't measure renders: ${a.reason??"capture unavailable"}`)}await delay8(SETTLE_MS);const s=Date.now();const c=[];if(t.steps?.length){for(const m of t.steps){const f=m.repeat??1;for(let v=0;v<f;v++){if(m.type!==void 0){const y=m.into??m.tap;if(!y){c.push("a `type` step needs `into`");continue}const b=await n.callAction(UI_TOOL_ID3,"tapElement",{...selector2(y),text:m.type},r);if(!b?.tapped)c.push(b?.reason??`could not type into "${y}"`);else if(b.matched?.via&&b.matched.via!=="onChangeText"){c.push(`"${y}" is not a text input \u2014 it ran ${b.matched.via}, nothing was typed`)}}else if(m.tap){const y=await n.callAction(UI_TOOL_ID3,"tapElement",selector2(m.tap),r);if(!y?.tapped)c.push(y?.reason??`no element matched "${m.tap}"`)}if(m.waitMs)await delay8(m.waitMs)}}await delay8(SETTLE_MS)}else{await delay8(t.idleMs??DEFAULT_IDLE_MS)}const l=Date.now()-s;const u=await n.callAction(UI_TOOL_ID3,"endMeasurement",{},r);const d=u?.summary;if(!d){return fail11("The capture window closed without returning anything. If the app reloaded mid-measurement, try again.")}const h={label:t.label??(t.steps?.length?"interaction":"idle"),windowMs:l,summary:d};const w=lastCapture.get(r);lastCapture.set(r,h);const p=t.steps?.length?t.steps.map(m=>(m.type!==void 0?`type "${m.type}"`:`tap "${m.tap}"`)+(m.repeat?` \xD7${m.repeat}`:"")).join(", "):`idle ${(l/1e3).toFixed(1)}s`;const g=[`**measure_renders \u2014 ${p}**`,"",formatCapture(h,t.top??DEFAULT_TOP)];if(t.compareToPrevious){g.push("",w?formatDelta(w,h):"_No previous measurement on this device to compare against._")}if(c.length)g.push("",`\u26A0\uFE0F ${c.join("; ")}`);if(d.totalRenders===0){g.push("","_Nothing re-rendered in this window. If you expected renders, check the app is on the screen you meant and that the steps actually hit something._")}else if(!t.compareToPrevious){g.push("","_Compare another run using the same steps and `compareToPrevious:true`; check behavior and interaction warnings as well._")}return text9(g.join("\n"))}catch(r){return fail11(errMsg9(r))}})}var import_node_fs16=__toESM(require("fs"));var import_node_path18=__toESM(require("path"));var WATCHED_EXT=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".json"]);var IGNORED_DIRS=new Set(["node_modules",".git",".expo","ios","android","dist","lib","build",".next","coverage","__snapshots__"]);var DEBOUNCE_MS=400;function resolveMode(e){const n=(e??"").trim().toLowerCase();if(n==="always"||n==="never"||n==="auto")return n;return"auto"}var EditWatcher=class{constructor(){this.watcher=null;this.changed=new Set;this.lastEditAt=0;this.nudgedForCurrentBatch=false;this.mode="auto";this.started=false}start(e,n){this.mode=n;if(n==="never"||this.started)return;this.started=true;try{this.watcher=import_node_fs16.default.watch(e,{recursive:true},(t,r)=>{if(!r)return;const i=String(r);if(i.split(import_node_path18.default.sep).some(o=>IGNORED_DIRS.has(o)))return;if(!WATCHED_EXT.has(import_node_path18.default.extname(i)))return;this.noteEdit(i)});this.watcher.on("error",()=>this.stop())}catch{this.stop()}}noteEdit(e){const n=Date.now();if(n-this.lastEditAt>DEBOUNCE_MS)this.nudgedForCurrentBatch=false;this.lastEditAt=n;if(this.changed.size<50)this.changed.add(e)}stop(){try{this.watcher?.close()}catch{}this.watcher=null}markVerified(){this.changed.clear();this.nudgedForCurrentBatch=false}hasUnverifiedEdits(){return this.changed.size>0}nudge(){if(this.mode==="never"||!this.hasUnverifiedEdits())return null;if(this.mode==="auto"){if(this.nudgedForCurrentBatch)return null;this.nudgedForCurrentBatch=true}const e=[...this.changed];const n=e.slice(0,3).join(", ");const t=e.length>3?` +${e.length-3} more`:"";return`
984
+ _Drill in with get_console, get_network_requests (includeBodies:true for response bodies), get_storage (includeValues:true), describe_screen._`)}catch(r){return fail11(errMsg8(r))}})}var import_zod36=require("zod");var UI_TOOL_ID3="highlight-updates";var text10=e=>({content:[{type:"text",text:e}]});var fail12=e=>({isError:true,content:[{type:"text",text:e}]});var errMsg9=e=>e instanceof Error?e.message:String(e);var delay8=e=>new Promise(n=>setTimeout(n,e));var DEFAULT_IDLE_MS=3e3;var SETTLE_MS=400;var DEFAULT_TOP=12;var lastCapture=new Map;var stepSchema2=import_zod36.z.object({tap:import_zod36.z.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),type:import_zod36.z.string().optional().describe("Text to type (needs `into`)."),into:import_zod36.z.string().optional().describe("Target text input for `type`: testID or fuzzy text."),waitMs:import_zod36.z.number().min(0).max(1e4).optional().describe("Pause after the action, in ms."),repeat:import_zod36.z.number().min(1).max(20).optional().describe("Do this step N times (default 1). Useful for 'tap it five times'.")}).describe("One interaction to measure. Keep it to the thing you're asking about.");function selector2(e){return/\s/.test(e)?{query:e}:{testID:e,query:e}}function dominant(e){if(!e)return"unknown";let n="unknown";let t=-1;for(const[r,i]of Object.entries(e)){if((i??0)>t){t=i??0;n=r}}return n}var CAUSE_HINT={propsUnstable:"props changed by IDENTITY only (a fresh function/object from the parent) \u2014 fix upstream, not in the child",parent:"parent re-rendered and nothing of its own changed \u2014 a pure cascade",props:"props genuinely changed value",hooks:"its own state/hooks changed",mount:"first render"};function formatCapture(e,n){const t=e.summary;const r=t.wastedRenders??0;const i=t.totalRenders>0?Math.round(r/t.totalRenders*100):0;const o=[];const a=t.totalRenderMs??0;o.push(`**${t.totalRenders} component renders across ${t.totalCommits} commits in ${(e.windowMs/1e3).toFixed(1)}s**`+(a>0?` \xB7 ${a.toFixed(1)}ms of render work`:"")+` \xB7 ${r} wasted (${i}%)`);const s=Object.entries(t.causes??{}).filter(([,d])=>(d??0)>0).sort((d,h)=>(h[1]??0)-(d[1]??0)).map(([d,h])=>`${d} ${h}`).join(" \xB7 ");if(s)o.push(`causes: ${s}`);o.push("");o.push("| component | self ms | renders | cause | dragged along by | changed props |");o.push("|---|---:|---:|---|---|---|");const c=[...t.topComponents].sort((d,h)=>(h.totalMs??0)-(d.totalMs??0)||h.renders-d.renders).slice(0,n);for(const d of c){o.push(`| ${d.name} | ${(d.totalMs??0).toFixed(1)} | ${d.renders} | ${dominant(d.causes)} | ${d.parentName??"\u2014"} | ${(d.changedProps??[]).join(", ")||"\u2014"} |`)}if(t.topComponents.length>n){o.push(`_\u2026+${t.topComponents.length-n} more components_`)}const l=new Set(c.map(d=>dominant(d.causes)));const u=[...l].filter(d=>CAUSE_HINT[d]).map(d=>`\`${d}\` = ${CAUSE_HINT[d]}`);if(u.length){o.push("");o.push(u.join(" \xB7 "))}o.push("");o.push("`wasted` classifies parent cascades and identity-only prop changes. Investigate whether these renders are needed before changing them. Rows are sorted by **self ms**. Compare timing and render counts for the measured workload, and check behavior before deciding whether memoization helps.");return o.join("\n")}function formatDelta(e,n){const t=(u,d)=>{const h=d-u;return`${u} \u2192 ${d} (${h>0?"+":""}${h})`};const r=e.summary;const i=n.summary;const o=[`**vs "${e.label}"**`];o.push(`- total renders: ${t(r.totalRenders,i.totalRenders)}`);o.push(`- wasted: ${t(r.wastedRenders??0,i.wastedRenders??0)}`);const a=new Map(r.topComponents.map(u=>[u.name,u.renders]));const s=[];for(const u of i.topComponents.slice(0,20)){const d=a.get(u.name)??0;if(d!==u.renders)s.push(`${u.name} ${t(d,u.renders)}`);a.delete(u.name)}for(const[u,d]of a){if(d>0)s.push(`${u} ${t(d,0)}`)}if(s.length)o.push(`- per component: ${s.slice(0,10).join(" \xB7 ")}`);const c=i.totalRenders<r.totalRenders;const l=i.totalRenders>r.totalRenders;o.push(l?"\n\u26A0\uFE0F MORE renders than before \u2014 this change made this interaction worse. Re-render fixes routinely move cost instead of removing it; check the other interactions too before moving on.":c?"\n\u2705 Fewer renders than before on this interaction. Measure the OTHER interactions too \u2014 a fix that helps typing can cost taps.":"\n\u2796 No change on this interaction.");return o.join("\n")}function registerRenderTools(e,n){e.registerTool("measure_renders",{description:"Measure captured component renders during supplied interaction steps or an idle window. Returns available timings, render counts, reported reasons and changed props. The wasted count is a diagnostic classification, not proof a render can be removed. Check interaction warnings before comparing runs. Use the same steps and comparable conditions with compareToPrevious:true after editing; the comparison alone does not prove correctness or overall performance. Requires Buoy Pro and a highlight-updates integration exposing beginMeasurement. Use run_benchmark_batch to compare route-based variants.",inputSchema:{steps:import_zod36.z.array(stepSchema2).max(20).optional().describe("The interaction to measure, e.g. [{tap:'favorite-deal-2', repeat:5}] or [{type:'bench', into:'deals-search'}]. Omit to sample the screen idle \u2014 only useful for churn that happens with nobody touching it."),idleMs:import_zod36.z.number().min(500).max(2e4).optional().describe(`Idle sample length when no steps are given. Default ${DEFAULT_IDLE_MS}.`),label:import_zod36.z.string().optional().describe('Name this measurement, e.g. "before fix". Shown in the next comparison.'),compareToPrevious:import_zod36.z.boolean().optional().describe("Compare with the previous measurement on this device. Use equivalent steps and conditions; review warnings and behavior separately."),top:import_zod36.z.number().min(1).max(40).optional().describe(`Components to list. Default ${DEFAULT_TOP}.`),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=n.connectedDevices().find(m=>m.deviceId===r);const o=(i?.tools??[]).find(m=>m.toolId===UI_TOOL_ID3);if(!o){return fail12("This app doesn't expose the highlight-updates tool, so renders can't be measured. Install @buoy-gg/highlight-updates.")}if(!(o.actions??[]).includes("beginMeasurement")){return fail12("This app's @buoy-gg/highlight-updates is too old to measure renders (needs the version with beginMeasurement). Upgrade it, then try again. Meanwhile run_benchmark_batch with captureRenders can still give counts if you have a test route.")}const a=await n.callAction(UI_TOOL_ID3,"beginMeasurement",{},r);if(a&&a.ok===false){return fail12(`Can't measure renders: ${a.reason??"capture unavailable"}`)}await delay8(SETTLE_MS);const s=Date.now();const c=[];if(t.steps?.length){for(const m of t.steps){const f=m.repeat??1;for(let v=0;v<f;v++){if(m.type!==void 0){const y=m.into??m.tap;if(!y){c.push("a `type` step needs `into`");continue}const b=await n.callAction(UI_TOOL_ID3,"tapElement",{...selector2(y),text:m.type},r);if(!b?.tapped)c.push(b?.reason??`could not type into "${y}"`);else if(b.matched?.via&&b.matched.via!=="onChangeText"){c.push(`"${y}" is not a text input \u2014 it ran ${b.matched.via}, nothing was typed`)}}else if(m.tap){const y=await n.callAction(UI_TOOL_ID3,"tapElement",selector2(m.tap),r);if(!y?.tapped)c.push(y?.reason??`no element matched "${m.tap}"`)}if(m.waitMs)await delay8(m.waitMs)}}await delay8(SETTLE_MS)}else{await delay8(t.idleMs??DEFAULT_IDLE_MS)}const l=Date.now()-s;const u=await n.callAction(UI_TOOL_ID3,"endMeasurement",{},r);const d=u?.summary;if(!d){return fail12("The capture window closed without returning anything. If the app reloaded mid-measurement, try again.")}const h={label:t.label??(t.steps?.length?"interaction":"idle"),windowMs:l,summary:d};const w=lastCapture.get(r);lastCapture.set(r,h);const p=t.steps?.length?t.steps.map(m=>(m.type!==void 0?`type "${m.type}"`:`tap "${m.tap}"`)+(m.repeat?` \xD7${m.repeat}`:"")).join(", "):`idle ${(l/1e3).toFixed(1)}s`;const g=[`**measure_renders \u2014 ${p}**`,"",formatCapture(h,t.top??DEFAULT_TOP)];if(t.compareToPrevious){g.push("",w?formatDelta(w,h):"_No previous measurement on this device to compare against._")}if(c.length)g.push("",`\u26A0\uFE0F ${c.join("; ")}`);if(d.totalRenders===0){g.push("","_Nothing re-rendered in this window. If you expected renders, check the app is on the screen you meant and that the steps actually hit something._")}else if(!t.compareToPrevious){g.push("","_Compare another run using the same steps and `compareToPrevious:true`; check behavior and interaction warnings as well._")}return text10(g.join("\n"))}catch(r){return fail12(errMsg9(r))}})}var import_node_fs24=__toESM(require("fs"));var import_node_path24=__toESM(require("path"));var WATCHED_EXT=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".json"]);var IGNORED_DIRS=new Set(["node_modules",".git",".expo","ios","android","dist","lib","build",".next","coverage","__snapshots__"]);var DEBOUNCE_MS=400;function resolveMode(e){const n=(e??"").trim().toLowerCase();if(n==="always"||n==="never"||n==="auto")return n;return"auto"}var EditWatcher=class{constructor(){this.watcher=null;this.changed=new Set;this.lastEditAt=0;this.nudgedForCurrentBatch=false;this.mode="auto";this.started=false}start(e,n){this.mode=n;if(n==="never"||this.started)return;this.started=true;try{this.watcher=import_node_fs24.default.watch(e,{recursive:true},(t,r)=>{if(!r)return;const i=String(r);if(i.split(import_node_path24.default.sep).some(o=>IGNORED_DIRS.has(o)))return;if(!WATCHED_EXT.has(import_node_path24.default.extname(i)))return;this.noteEdit(i)});this.watcher.on("error",()=>this.stop())}catch{this.stop()}}noteEdit(e){const n=Date.now();if(n-this.lastEditAt>DEBOUNCE_MS)this.nudgedForCurrentBatch=false;this.lastEditAt=n;if(this.changed.size<50)this.changed.add(e)}stop(){try{this.watcher?.close()}catch{}this.watcher=null}markVerified(){this.changed.clear();this.nudgedForCurrentBatch=false}hasUnverifiedEdits(){return this.changed.size>0}nudge(){if(this.mode==="never"||!this.hasUnverifiedEdits())return null;if(this.mode==="auto"){if(this.nudgedForCurrentBatch)return null;this.nudgedForCurrentBatch=true}const e=[...this.changed];const n=e.slice(0,3).join(", ");const t=e.length>3?` +${e.length-3} more`:"";return`
984
985
 
985
986
  ---
986
987
  \u26A0\uFE0F **${e.length} source file${e.length===1?"":"s"} changed since anything was last checked on the device** (${n}${t}).
@@ -1088,7 +1089,7 @@ After a behavior change, repeat the affected interaction and check the expected
1088
1089
  Include restart or persistence checks when relevant to the change. Use appropriate static
1089
1090
  checks for documentation-only work. Report actual checks, observations and remaining limits.
1090
1091
  BUOY_VERIFY reminders track selected edits and tool calls; clearing a reminder is not a
1091
- test result. Stay within the user's authorized task and preserve existing project work.`;var VERIFYING_TOOLS=new Set(["measure_renders","scenario_action","run_flow","run_benchmark_batch","run_web_benchmark","find_web_ceiling","screenshot_web_variants","get_triage","tap_element","describe_screen","get_console","get_network_requests","get_events","get_snapshot"]);function createMcpServer(e){const n=new import_mcp.McpServer({name:"buoy",version:VERSION},{capabilities:{tools:{}},instructions:SERVER_INSTRUCTIONS});editWatcher.start(process.cwd(),resolveMode(process.env.BUOY_VERIFY));const t=n.registerTool.bind(n);n.registerTool=((r,i,o)=>t(r,i,(async(...a)=>{const s=a[0];if(r==="list_devices"){}else if(s?.deviceId)await e.awaitBroker();else await e.settleDeviceChoice();noteAgentCall(e,r,s);const c=async()=>{const m=await o(...a);for(const f of m?.content??[]){if(f.type==="text"&&typeof f.text==="string")f.text=scrubSecrets(f.text)}return m};let l=await c();const u=m=>{const f=m;return f?.isError===true&&(f.content?.[0]?.text??"").startsWith(NOT_READY_MARK)};if(u(l)){const m=l.content[0].text;const f=/"([^"]+)"/.exec(m)?.[1];const v=Date.now()+NOT_READY_WAIT_MS;while(Date.now()<v){await new Promise(y=>setTimeout(y,250));if(f?e.accessState(f)==="ready":e.connectedDevices().some(y=>y.isPro))break}l=await c()}const d=l?.isError===true;let h=null;if(VERIFYING_TOOLS.has(r)&&!d)editWatcher.markVerified();else h=editWatcher.nudge();const w=optimizeNote();const p=[h,w].filter(m=>!!m);if(!p.length)return l;const g=l;if(Array.isArray(g?.content)){return{...g,content:[...g.content,...p.map(m=>({type:"text",text:m}))]}}return l})));registerTriageTools(n,e);registerFlowTools(n,e);registerRenderTools(n,e);registerGenericTools(n,e);registerPerfMonitorTools(n,e);registerEventsTools(n,e);registerNetworkTools(n,e);registerReactQueryTools(n,e);registerZustandTools(n,e);registerJotaiTools(n,e);registerReduxTools(n,e);registerStorageTools(n,e);registerRoutesTools(n,e);registerConsoleTools(n,e);registerSentryTools(n,e);registerTimeMachineTools(n,e);registerClockTools(n,e);registerPermissionsTools(n,e);registerLifecycleTools(n,e);registerLocationTools(n,e);registerScenariosTools(n,e);registerScreenshotTools(n,e);registerCameraTools(n);registerWebBenchTools(n,e);registerInteractTools(n,e);registerNativeTools(n,e);registerRecordingTools(n,e);registerDeviceTools(n,e);registerSourceTools(n,e);registerJsThreadTools(n,e);registerImagesTools(n,e);registerAssetsTools(n,e);registerReloadTools(n,e);return n}var deviceIdField={deviceId:import_zod35.z.string().optional().describe('Target device id (from list_devices). Omit to auto-select when exactly one device is connected. Use "All" to broadcast.')};var import_node_child_process19=require("child_process");var import_node_fs17=__toESM(require("fs"));var import_node_os13=__toESM(require("os"));var import_node_path19=__toESM(require("path"));function defaultEnv(){return{BUOY_VERIFY:"auto"}}var PUBLIC_REGISTRY="https://registry.npmjs.org";var PROBE_TIMEOUT_MS3=3e3;function runInit(e={}){const n=e.cwd??process.cwd();const t=e.skillSrcDir??import_node_path19.default.resolve(__dirname,"../skill");const r=e.log??(a=>process.stdout.write(a+"\n"));const i=resolveEntry2(e,r);const o=[];upsertMcpConfig(import_node_path19.default.join(n,".mcp.json"),"mcpServers",i,n,o);import_node_fs17.default.mkdirSync(import_node_path19.default.join(n,".cursor"),{recursive:true});upsertMcpConfig(import_node_path19.default.join(n,".cursor","mcp.json"),"mcpServers",i,n,o);if(import_node_fs17.default.existsSync(import_node_path19.default.join(n,".vscode"))){upsertMcpConfig(import_node_path19.default.join(n,".vscode","mcp.json"),"servers",i,n,o)}installSkills(t,n,o);appendDebuggingGuide(import_node_path19.default.join(n,"CLAUDE.md"),n,o);appendDebuggingGuide(import_node_path19.default.join(n,"AGENTS.md"),n,o);r("Buoy MCP configuration written:");for(const a of o)r(" \u2022 "+a);r("");r("Next steps:");r(" 1. Restart your editor (or reconnect the MCP server) to load `buoy`.");r(" 2. Complete account setup, then open an app with the required Buoy tools and sync integration.");r(" 3. Confirm the device and tools are available. MCP data/action access requires Pro.");if(i.command==="npx"){r("");r(`The editor launches the server with \`npx -y ${PACKAGE_NAME}@latest\`, so it stays`);r(`Registry access may be needed. Re-run \`npx -y ${PACKAGE_NAME}@latest init\` to refresh configuration.`)}else if(!e.cliPath){r("");r(`This uses a pinned local install (no network on startup). To update it later,`);r(`To update the local package, run: npx -y ${i.args[0]?.replace(/dist[/\\]cli\.js$/,"")??""}@latest init --local`)}}function resolveEntry2(e,n){if(e.cliPath){return{type:"stdio",command:"node",args:[e.cliPath],env:defaultEnv()}}const t=e.mode??"auto";if(t==="npx"){return npxEntry()}if(t==="local"){return localEntry(e,n)}const r=probeRegistry();if(r.reachable){return npxEntry()}n(`\u26A0 npm registry ${r.registry?`(${r.registry}) `:""}looks unreachable \u2014 \`npx @latest\` would hang your editor at startup. Falling back to a pinned local install.`);return localEntry(e,n)}function npxEntry(){return{type:"stdio",command:"npx",args:["-y",`${PACKAGE_NAME}@latest`],env:defaultEnv()}}function localEntry(e,n){const t=e.installDir??process.env.BUOY_MCP_HOME??import_node_path19.default.join(import_node_os13.default.homedir(),".buoy-mcp");const r=e.registry??PUBLIC_REGISTRY;const i=installLocalCopy(t,r,n);if(i){return{type:"stdio",command:"node",args:[i],env:defaultEnv()}}n("\u26A0 local install failed \u2014 writing the npx entry instead (see the error above).");return npxEntry()}function installLocalCopy(e,n,t){const r=`${PACKAGE_NAME}@${VERSION==="0.0.0-dev"?"latest":VERSION}`;import_node_fs17.default.mkdirSync(e,{recursive:true});const i=process.platform==="win32"?"npm.cmd":"npm";t(`Installing ${r} into ${e} from ${n} \u2026`);const o=(0,import_node_child_process19.spawnSync)(i,["install",r,"--prefix",e,"--registry",n,`--@buoy-gg:registry=${n}`,"--no-audit","--no-fund","--loglevel=error"],{stdio:["ignore","ignore","inherit"],encoding:"utf8"});if(o.status!==0){t(`\u26A0 npm install exited with code ${o.status??"?"}${o.error?` (${o.error.message})`:""}.`);return null}const a=import_node_path19.default.join(e,"node_modules",PACKAGE_NAME,"dist","cli.js");if(!import_node_fs17.default.existsSync(a)){t(`\u26A0 install finished but ${a} is missing.`);return null}return a}function probeRegistry(){const e=effectiveRegistry();if(!e)return{reachable:false,registry:null};if(/^https?:\/\/registry\.npmjs\.org\/?$/i.test(e)){return{reachable:true,registry:e}}return{reachable:hostReachable(e),registry:e}}function effectiveRegistry(){const e=npmConfigGet("@buoy-gg:registry");if(e)return e;const n=npmConfigGet("registry");return n??PUBLIC_REGISTRY}function npmConfigGet(e){const n=process.platform==="win32"?"npm.cmd":"npm";const t=(0,import_node_child_process19.spawnSync)(n,["config","get",e],{encoding:"utf8",timeout:PROBE_TIMEOUT_MS3});if(t.status!==0||typeof t.stdout!=="string")return null;const r=t.stdout.trim();if(!r||r==="undefined"||r==="null")return null;return r}function hostReachable(e){const n=(0,import_node_child_process19.spawnSync)(process.execPath,["-e",REACHABILITY_PROBE,e,String(PROBE_TIMEOUT_MS3)],{encoding:"utf8",timeout:PROBE_TIMEOUT_MS3+2e3});return n.status===0}var REACHABILITY_PROBE=`
1092
+ test result. Stay within the user's authorized task and preserve existing project work.`;var VERIFYING_TOOLS=new Set(["measure_renders","scenario_action","run_flow","run_benchmark_batch","run_web_benchmark","find_web_ceiling","screenshot_web_variants","get_triage","tap_element","describe_screen","get_console","get_network_requests","get_events","get_snapshot"]);function createMcpServer(e){const n=new import_mcp.McpServer({name:"buoy",version:VERSION},{capabilities:{tools:{}},instructions:SERVER_INSTRUCTIONS});editWatcher.start(process.cwd(),resolveMode(process.env.BUOY_VERIFY));const t=n.registerTool.bind(n);n.registerTool=((r,i,o)=>t(r,i,(async(...a)=>{const s=a[0];if(r==="list_devices"){}else if(s?.deviceId)await e.awaitBroker();else await e.settleDeviceChoice();noteAgentCall(e,r,s);const c=async()=>{const m=await o(...a);for(const f of m?.content??[]){if(f.type==="text"&&typeof f.text==="string")f.text=scrubSecrets(f.text)}return m};let l=await c();const u=m=>{const f=m;return f?.isError===true&&(f.content?.[0]?.text??"").startsWith(NOT_READY_MARK)};if(u(l)){const m=l.content[0].text;const f=/"([^"]+)"/.exec(m)?.[1];const v=Date.now()+NOT_READY_WAIT_MS;while(Date.now()<v){await new Promise(y=>setTimeout(y,250));if(f?e.accessState(f)==="ready":e.connectedDevices().some(y=>y.isPro))break}l=await c()}const d=l?.isError===true;let h=null;if(VERIFYING_TOOLS.has(r)&&!d)editWatcher.markVerified();else h=editWatcher.nudge();const w=optimizeNote();const p=[h,w].filter(m=>!!m);if(!p.length)return l;const g=l;if(Array.isArray(g?.content)){return{...g,content:[...g.content,...p.map(m=>({type:"text",text:m}))]}}return l})));registerTriageTools(n,e);registerFlowTools(n,e);registerRenderTools(n,e);registerGenericTools(n,e);registerPerfMonitorTools(n,e);registerEventsTools(n,e);registerNetworkTools(n,e);registerReactQueryTools(n,e);registerZustandTools(n,e);registerJotaiTools(n,e);registerReduxTools(n,e);registerStorageTools(n,e);registerRoutesTools(n,e);registerConsoleTools(n,e);registerSentryTools(n,e);registerTimeMachineTools(n,e);registerClockTools(n,e);registerPermissionsTools(n,e);registerLifecycleTools(n,e);registerLocationTools(n,e);registerScenariosTools(n,e);registerScreenshotTools(n,e);registerCameraTools(n);registerSimFarmTools(n);registerWebBenchTools(n,e);registerInteractTools(n,e);registerNativeTools(n,e);registerRecordingTools(n,e);registerDeviceTools(n,e);registerSourceTools(n,e);registerJsThreadTools(n,e);registerImagesTools(n,e);registerAssetsTools(n,e);registerThreeTools(n,e);registerReloadTools(n,e);return n}var deviceIdField={deviceId:import_zod37.z.string().optional().describe('Target device id (from list_devices). Omit to auto-select when exactly one device is connected. Use "All" to broadcast.')};var import_node_child_process21=require("child_process");var import_node_fs25=__toESM(require("fs"));var import_node_os16=__toESM(require("os"));var import_node_path25=__toESM(require("path"));function defaultEnv(){return{BUOY_VERIFY:"auto"}}var PUBLIC_REGISTRY="https://registry.npmjs.org";var PROBE_TIMEOUT_MS3=3e3;function runInit(e={}){const n=e.cwd??process.cwd();const t=e.skillSrcDir??import_node_path25.default.resolve(__dirname,"../skill");const r=e.log??(a=>process.stdout.write(a+"\n"));const i=resolveEntry2(e,r);const o=[];upsertMcpConfig(import_node_path25.default.join(n,".mcp.json"),"mcpServers",i,n,o);import_node_fs25.default.mkdirSync(import_node_path25.default.join(n,".cursor"),{recursive:true});upsertMcpConfig(import_node_path25.default.join(n,".cursor","mcp.json"),"mcpServers",i,n,o);if(import_node_fs25.default.existsSync(import_node_path25.default.join(n,".vscode"))){upsertMcpConfig(import_node_path25.default.join(n,".vscode","mcp.json"),"servers",i,n,o)}installSkills(t,n,o);appendDebuggingGuide(import_node_path25.default.join(n,"CLAUDE.md"),n,o);appendDebuggingGuide(import_node_path25.default.join(n,"AGENTS.md"),n,o);r("Buoy MCP configuration written:");for(const a of o)r(" \u2022 "+a);r("");r("Next steps:");r(" 1. Restart your editor (or reconnect the MCP server) to load `buoy`.");r(" 2. Complete account setup, then open an app with the required Buoy tools and sync integration.");r(" 3. Confirm the device and tools are available. MCP data/action access requires Pro.");if(i.command==="npx"){r("");r(`The editor launches the server with \`npx -y ${PACKAGE_NAME}@latest\`, so it stays`);r(`Registry access may be needed. Re-run \`npx -y ${PACKAGE_NAME}@latest init\` to refresh configuration.`)}else if(!e.cliPath){r("");r(`This uses a pinned local install (no network on startup). To update it later,`);r(`To update the local package, run: npx -y ${i.args[0]?.replace(/dist[/\\]cli\.js$/,"")??""}@latest init --local`)}}function resolveEntry2(e,n){if(e.cliPath){return{type:"stdio",command:"node",args:[e.cliPath],env:defaultEnv()}}const t=e.mode??"auto";if(t==="npx"){return npxEntry()}if(t==="local"){return localEntry(e,n)}const r=probeRegistry();if(r.reachable){return npxEntry()}n(`\u26A0 npm registry ${r.registry?`(${r.registry}) `:""}looks unreachable \u2014 \`npx @latest\` would hang your editor at startup. Falling back to a pinned local install.`);return localEntry(e,n)}function npxEntry(){return{type:"stdio",command:"npx",args:["-y",`${PACKAGE_NAME}@latest`],env:defaultEnv()}}function localEntry(e,n){const t=e.installDir??process.env.BUOY_MCP_HOME??import_node_path25.default.join(import_node_os16.default.homedir(),".buoy-mcp");const r=e.registry??PUBLIC_REGISTRY;const i=installLocalCopy(t,r,n);if(i){return{type:"stdio",command:"node",args:[i],env:defaultEnv()}}n("\u26A0 local install failed \u2014 writing the npx entry instead (see the error above).");return npxEntry()}function installLocalCopy(e,n,t){const r=`${PACKAGE_NAME}@${VERSION==="0.0.0-dev"?"latest":VERSION}`;import_node_fs25.default.mkdirSync(e,{recursive:true});const i=process.platform==="win32"?"npm.cmd":"npm";t(`Installing ${r} into ${e} from ${n} \u2026`);const o=(0,import_node_child_process21.spawnSync)(i,["install",r,"--prefix",e,"--registry",n,`--@buoy-gg:registry=${n}`,"--no-audit","--no-fund","--loglevel=error"],{stdio:["ignore","ignore","inherit"],encoding:"utf8"});if(o.status!==0){t(`\u26A0 npm install exited with code ${o.status??"?"}${o.error?` (${o.error.message})`:""}.`);return null}const a=import_node_path25.default.join(e,"node_modules",PACKAGE_NAME,"dist","cli.js");if(!import_node_fs25.default.existsSync(a)){t(`\u26A0 install finished but ${a} is missing.`);return null}return a}function probeRegistry(){const e=effectiveRegistry();if(!e)return{reachable:false,registry:null};if(/^https?:\/\/registry\.npmjs\.org\/?$/i.test(e)){return{reachable:true,registry:e}}return{reachable:hostReachable(e),registry:e}}function effectiveRegistry(){const e=npmConfigGet("@buoy-gg:registry");if(e)return e;const n=npmConfigGet("registry");return n??PUBLIC_REGISTRY}function npmConfigGet(e){const n=process.platform==="win32"?"npm.cmd":"npm";const t=(0,import_node_child_process21.spawnSync)(n,["config","get",e],{encoding:"utf8",timeout:PROBE_TIMEOUT_MS3});if(t.status!==0||typeof t.stdout!=="string")return null;const r=t.stdout.trim();if(!r||r==="undefined"||r==="null")return null;return r}function hostReachable(e){const n=(0,import_node_child_process21.spawnSync)(process.execPath,["-e",REACHABILITY_PROBE,e,String(PROBE_TIMEOUT_MS3)],{encoding:"utf8",timeout:PROBE_TIMEOUT_MS3+2e3});return n.status===0}var REACHABILITY_PROBE=`
1092
1093
  const url = process.argv[1];
1093
1094
  const ms = Number(process.argv[2]) || 3000;
1094
1095
  const c = new AbortController();
@@ -1101,7 +1102,7 @@ fetch(url, { method: 'HEAD', signal: c.signal })
1101
1102
  clearTimeout(t);
1102
1103
  process.exit(1);
1103
1104
  });
1104
- `;function upsertMcpConfig(e,n,t,r,i){let o={};if(import_node_fs17.default.existsSync(e)){try{o=JSON.parse(import_node_fs17.default.readFileSync(e,"utf8"))}catch{import_node_fs17.default.copyFileSync(e,e+".bak");i.push(`existing ${rel(e,r)} was invalid JSON \u2014 backed up to ${rel(e,r)}.bak`);o={}}}else{import_node_fs17.default.mkdirSync(import_node_path19.default.dirname(e),{recursive:true})}const a=o[n]&&typeof o[n]==="object"?o[n]:{};const s="buoy"in a;a.buoy=t;o[n]=a;import_node_fs17.default.writeFileSync(e,JSON.stringify(o,null,2)+"\n");i.push(`${s?"updated":"added"} \`buoy\` in ${rel(e,r)}`)}var GUIDE_HEADING="# Debugging with Buoy";var DEBUGGING_GUIDE=`${GUIDE_HEADING}
1105
+ `;function upsertMcpConfig(e,n,t,r,i){let o={};if(import_node_fs25.default.existsSync(e)){try{o=JSON.parse(import_node_fs25.default.readFileSync(e,"utf8"))}catch{import_node_fs25.default.copyFileSync(e,e+".bak");i.push(`existing ${rel(e,r)} was invalid JSON \u2014 backed up to ${rel(e,r)}.bak`);o={}}}else{import_node_fs25.default.mkdirSync(import_node_path25.default.dirname(e),{recursive:true})}const a=o[n]&&typeof o[n]==="object"?o[n]:{};const s="buoy"in a;a.buoy=t;o[n]=a;import_node_fs25.default.writeFileSync(e,JSON.stringify(o,null,2)+"\n");i.push(`${s?"updated":"added"} \`buoy\` in ${rel(e,r)}`)}var GUIDE_HEADING="# Debugging with Buoy";var DEBUGGING_GUIDE=`${GUIDE_HEADING}
1105
1106
 
1106
1107
  Use Buoy to inspect a connected app when runtime evidence helps the task.
1107
1108
  Complete account, tool integration and connection setup first. MCP data and
@@ -1134,4 +1135,4 @@ only source review or a build was performed.
1134
1135
  reminders, \`always\` repeats until checked, and \`never\` disables them.
1135
1136
  A reminder is not a test result. Choose checks appropriate to the change;
1136
1137
  prose-only edits do not require running device actions.
1137
- `;function appendDebuggingGuide(e,n,t){let r="";if(import_node_fs17.default.existsSync(e)){try{r=import_node_fs17.default.readFileSync(e,"utf8")}catch{t.push(`\u26A0 could not read ${rel(e,n)} \u2014 skipped the debugging guide`);return}if(r.includes(GUIDE_HEADING)){t.push(`${rel(e,n)} already has the "${GUIDE_HEADING}" block; preserved existing text. Review it against the current bundled guidance before relying on older instructions.`);return}}const i=r===""?"":r.endsWith("\n")?"\n":"\n\n";try{import_node_fs17.default.writeFileSync(e,r+i+DEBUGGING_GUIDE);t.push(`${r?"appended":"created"} "${GUIDE_HEADING}" block in ${rel(e,n)}`)}catch{t.push(`\u26A0 could not write ${rel(e,n)} \u2014 skipped the debugging guide`)}}function installSkills(e,n,t){if(!import_node_fs17.default.existsSync(e)){t.push("\u26A0 no bundled skills found \u2014 skipped");return}const r=import_node_fs17.default.readdirSync(e,{withFileTypes:true}).filter(i=>i.isDirectory()&&import_node_fs17.default.existsSync(import_node_path19.default.join(e,i.name,"SKILL.md")));if(r.length===0){t.push("\u26A0 no skills with a SKILL.md found \u2014 skipped");return}for(const i of r){const o=import_node_path19.default.join(e,i.name);const a=import_node_path19.default.join(n,".claude","skills",i.name);copyDir(o,a);t.push(`installed the ${i.name} skill \u2192 ${rel(import_node_path19.default.join(a,"SKILL.md"),n)}`)}}function copyDir(e,n){import_node_fs17.default.mkdirSync(n,{recursive:true});for(const t of import_node_fs17.default.readdirSync(e,{withFileTypes:true})){const r=import_node_path19.default.join(e,t.name);const i=import_node_path19.default.join(n,t.name);if(t.isDirectory())copyDir(r,i);else import_node_fs17.default.copyFileSync(r,i)}}function rel(e,n){const t=import_node_path19.default.relative(n,e);return t&&!t.startsWith("..")?t:e}
1138
+ `;function appendDebuggingGuide(e,n,t){let r="";if(import_node_fs25.default.existsSync(e)){try{r=import_node_fs25.default.readFileSync(e,"utf8")}catch{t.push(`\u26A0 could not read ${rel(e,n)} \u2014 skipped the debugging guide`);return}if(r.includes(GUIDE_HEADING)){t.push(`${rel(e,n)} already has the "${GUIDE_HEADING}" block; preserved existing text. Review it against the current bundled guidance before relying on older instructions.`);return}}const i=r===""?"":r.endsWith("\n")?"\n":"\n\n";try{import_node_fs25.default.writeFileSync(e,r+i+DEBUGGING_GUIDE);t.push(`${r?"appended":"created"} "${GUIDE_HEADING}" block in ${rel(e,n)}`)}catch{t.push(`\u26A0 could not write ${rel(e,n)} \u2014 skipped the debugging guide`)}}function installSkills(e,n,t){if(!import_node_fs25.default.existsSync(e)){t.push("\u26A0 no bundled skills found \u2014 skipped");return}const r=import_node_fs25.default.readdirSync(e,{withFileTypes:true}).filter(i=>i.isDirectory()&&import_node_fs25.default.existsSync(import_node_path25.default.join(e,i.name,"SKILL.md")));if(r.length===0){t.push("\u26A0 no skills with a SKILL.md found \u2014 skipped");return}for(const i of r){const o=import_node_path25.default.join(e,i.name);const a=import_node_path25.default.join(n,".claude","skills",i.name);copyDir(o,a);t.push(`installed the ${i.name} skill \u2192 ${rel(import_node_path25.default.join(a,"SKILL.md"),n)}`)}}function copyDir(e,n){import_node_fs25.default.mkdirSync(n,{recursive:true});for(const t of import_node_fs25.default.readdirSync(e,{withFileTypes:true})){const r=import_node_path25.default.join(e,t.name);const i=import_node_path25.default.join(n,t.name);if(t.isDirectory())copyDir(r,i);else import_node_fs25.default.copyFileSync(r,i)}}function rel(e,n){const t=import_node_path25.default.relative(n,e);return t&&!t.startsWith("..")?t:e}