@buoy-gg/mcp 7.0.71 → 7.0.72

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,4 +1,4 @@
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,s){this._reads.push({length:Math.abs(o),allowLess:o<0,func:s});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,s){if(!this.writable){this.emit("error",new Error("Stream not writable"));return false}let a;if(Buffer.isBuffer(o)){a=o}else{a=Buffer.from(o,s||this._encoding)}this._buffers.push(a);this._buffered+=a.length;this._process();if(this._reads&&this._reads.length===0){this._paused=true}return this.writable&&!this._paused};i.prototype.end=function(o,s){if(o){this.write(o,s)}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 s=this._buffers[0];if(s.length>o.length){this._buffered-=o.length;this._buffers[0]=s.slice(o.length);o.func.call(this,s.slice(0,o.length))}else{this._buffered-=s.length;this._buffers.shift();o.func.call(this,s)}};i.prototype._processRead=function(o){this._reads.shift();let s=0;let a=0;let c=Buffer.alloc(o.length);while(s<o.length){let l=this._buffers[a++];let u=Math.min(l.length,o.length-s);l.copy(c,s,0,u);s+=u;if(u!==l.length){this._buffers[--a]=l.slice(u)}}if(a>0){this._buffers.splice(0,a)}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 s=r%8;let a=(t-o)/8;let c=(r-s)/8;for(let l=0;l<n.length;l++){let u=n[l];let d=a*u.x.length;let h=c*u.y.length;for(let p=0;p<u.x.length;p++){if(u.x[p]<o){d++}else{break}}for(let p=0;p<u.y.length;p++){if(u.y[p]<s){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 s=r%n[o].x.length;let a=(r-s)/n[o].x.length*8+n[o].x[s];let c=i%n[o].y.length;let l=(i-c)/n[o].y.length*8+n[o].y[c];return a*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 s=r+i-o;let a=Math.abs(s-r);let c=Math.abs(s-i);let l=Math.abs(s-o);if(a<=c&&a<=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(s,a,c){let l=s*a;if(c!==8){l=Math.ceil(l/(8/c))}return l}var o=n.exports=function(s,a){let c=s.width;let l=s.height;let u=s.interlace;let d=s.bpp;let h=s.depth;this.read=a.read;this.write=a.write;this.complete=a.complete;this._imageIndex=0;this._images=[];if(u){let p=t.getImagePasses(c,l);for(let f=0;f<p.length;f++){this._images.push({byteWidth:i(p[f].width,d,h),height:p[f].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(s,a,c){let l=this._xComparison;let u=l-1;for(let d=0;d<c;d++){let h=s[1+d];let p=d>u?a[d-l]:0;a[d]=h+p}};o.prototype._unFilterType2=function(s,a,c){let l=this._lastLine;for(let u=0;u<c;u++){let d=s[1+u];let h=l?l[u]:0;a[u]=d+h}};o.prototype._unFilterType3=function(s,a,c){let l=this._xComparison;let u=l-1;let d=this._lastLine;for(let h=0;h<c;h++){let p=s[1+h];let f=d?d[h]:0;let g=h>u?a[h-l]:0;let v=Math.floor((g+f)/2);a[h]=p+v}};o.prototype._unFilterType4=function(s,a,c){let l=this._xComparison;let u=l-1;let d=this._lastLine;for(let h=0;h<c;h++){let p=s[1+h];let f=d?d[h]:0;let g=h>u?a[h-l]:0;let v=h>u&&d?d[h-l]:0;let m=r(g,f,v);a[h]=p+m}};o.prototype._reverseFilterLine=function(s){let a=s[0];let c;let l=this._images[this._imageIndex];let u=l.byteWidth;if(a===0){c=s.slice(1,u+1)}else{c=Buffer.alloc(u);switch(a){case 1:this._unFilterType1(s,c,u);break;case 2:this._unFilterType2(s,c,u);break;case 3:this._unFilterType3(s,c,u);break;case 4:this._unFilterType4(s,c,u);break;default:throw new Error("Unrecognised filter type - "+a)}}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(s){r.call(this);let a=[];let c=this;this._filter=new i(s,{read:this.read.bind(this),write:function(l){a.push(l)},complete:function(){c.emit("complete",Buffer.concat(a))}});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 s=0;s<8;s++){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 s=0;s<i.length;s++){o=t[(o^i[s])&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,s){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=s.read;this.error=s.error;this.metadata=s.metadata;this.gamma=s.gamma;this.transColor=s.transColor;this.palette=s.palette;this.parsed=s.parsed;this.inflateData=s.inflateData;this.finished=s.finished;this.simpleTransparency=s.simpleTransparency;this.headersFinished=s.headersFinished||function(){}};i.prototype.start=function(){this.read(t.PNG_SIGNATURE.length,this._parseSignature.bind(this))};i.prototype._parseSignature=function(o){let s=t.PNG_SIGNATURE;for(let a=0;a<s.length;a++){if(o[a]!==s[a]){this.error(new Error("Invalid file signature"));return}}this.read(8,this._parseChunkBegin.bind(this))};i.prototype._parseChunkBegin=function(o){let s=o.readUInt32BE(0);let a=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&&a!==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[a]){return this._chunks[a](s)}if(!l){this.error(new Error("Unsupported critical chunk type "+c));return}this.read(s+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 s=o.readInt32BE(0);let a=this._crc.crc32();if(this._options.checkCRC&&a!==s){this.error(new Error("Crc error - "+s+" - "+a));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 s=o.readUInt32BE(0);let a=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 p=t.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=true;this.metadata({width:s,height:a,depth:c,interlace:Boolean(h),palette:Boolean(l&t.COLORTYPE_PALETTE),color:Boolean(l&t.COLORTYPE_COLOR),alpha:Boolean(l&t.COLORTYPE_ALPHA),bpp:p,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 s=Math.floor(o.length/3);for(let a=0;a<s;a++){this._palette.push([o[a*3],o[a*3+1],o[a*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 s=0;s<o.length;s++){this._palette[s][3]=o[s]}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,s){this._crc.write(s);if(this._colorType===t.COLORTYPE_PALETTE_COLOR&&this._palette.length===0){throw new Error("Expected palette not found")}this.inflateData(s);let a=o-s.length;if(a>0){this._handleIDAT(a)}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(a,c,l,u){if(u===c.length){throw new Error("Ran out of data")}let d=c[u];a[l]=d;a[l+1]=d;a[l+2]=d;a[l+3]=255},function(a,c,l,u){if(u+1>=c.length){throw new Error("Ran out of data")}let d=c[u];a[l]=d;a[l+1]=d;a[l+2]=d;a[l+3]=c[u+1]},function(a,c,l,u){if(u+2>=c.length){throw new Error("Ran out of data")}a[l]=c[u];a[l+1]=c[u+1];a[l+2]=c[u+2];a[l+3]=255},function(a,c,l,u){if(u+3>=c.length){throw new Error("Ran out of data")}a[l]=c[u];a[l+1]=c[u+1];a[l+2]=c[u+2];a[l+3]=c[u+3]}];var r=[function(){},function(a,c,l,u){let d=c[0];a[l]=d;a[l+1]=d;a[l+2]=d;a[l+3]=u},function(a,c,l){let u=c[0];a[l]=u;a[l+1]=u;a[l+2]=u;a[l+3]=c[1]},function(a,c,l,u){a[l]=c[0];a[l+1]=c[1];a[l+2]=c[2];a[l+3]=u},function(a,c,l){a[l]=c[0];a[l+1]=c[1];a[l+2]=c[2];a[l+3]=c[3]}];function i(a,c){let l=[];let u=0;function d(){if(u===a.length){throw new Error("Ran out of data")}let h=a[u];u++;let p,f,g,v,m,w,b,y;switch(c){default:throw new Error("unrecognised depth");case 16:b=a[u];u++;l.push((h<<8)+b);break;case 4:b=h&15;y=h>>4;l.push(y,b);break;case 2:m=h&3;w=h>>2&3;b=h>>4&3;y=h>>6&3;l.push(y,b,w,m);break;case 1:p=h&1;f=h>>1&1;g=h>>2&1;v=h>>3&1;m=h>>4&1;w=h>>5&1;b=h>>6&1;y=h>>7&1;l.push(y,b,w,m,v,g,f,p);break}}return{get:function(h){while(l.length<h){d()}let p=l.slice(0,h);l=l.slice(h);return p},resetAfterLine:function(){l.length=0},end:function(){if(u!==a.length){throw new Error("extra data found")}}}}function o(a,c,l,u,d,h){let p=a.width;let f=a.height;let g=a.index;for(let v=0;v<f;v++){for(let m=0;m<p;m++){let w=l(m,v,g);t[u](c,d,w,h);h+=u}}return h}function s(a,c,l,u,d,h){let p=a.width;let f=a.height;let g=a.index;for(let v=0;v<f;v++){for(let m=0;m<p;m++){let w=d.get(u);let b=l(m,v,g);r[u](c,w,b,h)}d.resetAfterLine()}}e.dataToBitMap=function(a,c){let l=c.width;let u=c.height;let d=c.depth;let h=c.bpp;let p=c.interlace;let f;if(d!==8){f=i(a,d)}let g;if(d<=8){g=Buffer.alloc(l*u*4)}else{g=new Uint16Array(l*u*4)}let v=Math.pow(2,d)-1;let m=0;let w;let b;if(p){w=n.getImagePasses(l,u);b=n.getInterlaceIterator(l,u)}else{let y=0;b=function(){let _=y;y+=4;return _};w=[{width:l,height:u}]}for(let y=0;y<w.length;y++){if(d===8){m=o(w[y],g,b,h,a,m)}else{s(w[y],g,b,h,f,v)}}if(d===8){if(m!==a.length){throw new Error("extra data found")}}else{f.end()}return g}}});var require_format_normaliser=__commonJS({"../../node_modules/pngjs/lib/format-normaliser.js"(e,n){"use strict";function t(o,s,a,c,l){let u=0;for(let d=0;d<c;d++){for(let h=0;h<a;h++){let p=l[o[u]];if(!p){throw new Error("index "+o[u]+" not in palette")}for(let f=0;f<4;f++){s[u+f]=p[f]}u+=4}}}function r(o,s,a,c,l){let u=0;for(let d=0;d<c;d++){for(let h=0;h<a;h++){let p=false;if(l.length===1){if(l[0]===o[u]){p=true}}else if(l[0]===o[u]&&l[1]===o[u+1]&&l[2]===o[u+2]){p=true}if(p){for(let f=0;f<4;f++){s[u+f]=0}}u+=4}}}function i(o,s,a,c,l){let u=255;let d=Math.pow(2,l)-1;let h=0;for(let p=0;p<c;p++){for(let f=0;f<a;f++){for(let g=0;g<4;g++){s[h+g]=Math.floor(o[h+g]*u/d+.5)}h+=4}}}n.exports=function(o,s,a=false){let c=s.depth;let l=s.width;let u=s.height;let d=s.colorType;let h=s.transColor;let p=s.palette;let f=o;if(d===3){t(o,f,l,u,p)}else{if(h){r(o,f,l,u,h)}if(c!==8&&!a){if(c===16){f=Buffer.alloc(l*u*4)}i(o,f,l,u,c)}}return f}}});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 s=require_parser();var a=require_bitmapper();var c=require_format_normaliser();var l=n.exports=function(u){i.call(this);this._parser=new s(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 p=Math.max(h,r.Z_MIN_CHUNK);this._inflate=r.createInflate({chunkSize:p});let f=h;let g=this.emit.bind(this,"error");this._inflate.on("error",function(m){if(!f){return}g(m)});this._filter.on("complete",this._complete.bind(this));let v=this._filter.write.bind(this._filter);this._inflate.on("data",function(m){if(!f){return}if(m.length>f){m=m.slice(0,f)}f-=m.length;v(m)});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=a.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,s){let a=[t.COLORTYPE_COLOR_ALPHA,t.COLORTYPE_ALPHA].indexOf(s.colorType)!==-1;if(s.colorType===s.inputColorType){let m=(function(){let w=new ArrayBuffer(2);new DataView(w).setInt16(0,256,true);return new Int16Array(w)[0]!==256})();if(s.bitDepth===8||s.bitDepth===16&&m){return r}}let c=s.bitDepth!==16?r:new Uint16Array(r.buffer);let l=255;let u=t.COLORTYPE_TO_BPP_MAP[s.inputColorType];if(u===4&&!s.inputHasAlpha){u=3}let d=t.COLORTYPE_TO_BPP_MAP[s.colorType];if(s.bitDepth===16){l=65535;d*=2}let h=Buffer.alloc(i*o*d);let p=0;let f=0;let g=s.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 v(){let m;let w;let b;let y=l;switch(s.inputColorType){case t.COLORTYPE_COLOR_ALPHA:y=c[p+3];m=c[p];w=c[p+1];b=c[p+2];break;case t.COLORTYPE_COLOR:m=c[p];w=c[p+1];b=c[p+2];break;case t.COLORTYPE_ALPHA:y=c[p+1];m=c[p];w=m;b=m;break;case t.COLORTYPE_GRAYSCALE:m=c[p];w=m;b=m;break;default:throw new Error("input color type:"+s.inputColorType+" is not supported at present")}if(s.inputHasAlpha){if(!a){y/=l;m=Math.min(Math.max(Math.round((1-y)*g.red+y*m),0),l);w=Math.min(Math.max(Math.round((1-y)*g.green+y*w),0),l);b=Math.min(Math.max(Math.round((1-y)*g.blue+y*b),0),l)}}return{red:m,green:w,blue:b,alpha:y}}for(let m=0;m<o;m++){for(let w=0;w<i;w++){let b=v(c,p);switch(s.colorType){case t.COLORTYPE_COLOR_ALPHA:case t.COLORTYPE_COLOR:if(s.bitDepth===8){h[f]=b.red;h[f+1]=b.green;h[f+2]=b.blue;if(a){h[f+3]=b.alpha}}else{h.writeUInt16BE(b.red,f);h.writeUInt16BE(b.green,f+2);h.writeUInt16BE(b.blue,f+4);if(a){h.writeUInt16BE(b.alpha,f+6)}}break;case t.COLORTYPE_ALPHA:case t.COLORTYPE_GRAYSCALE:{let y=(b.red+b.green+b.blue)/3;if(s.bitDepth===8){h[f]=y;if(a){h[f+1]=b.alpha}}else{h.writeUInt16BE(y,f);if(a){h.writeUInt16BE(b.alpha,f+2)}}break}default:throw new Error("unrecognised color Type "+s.colorType)}p+=u;f+=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,v,m,w,b){for(let y=0;y<m;y++){w[b+y]=g[v+y]}}function i(g,v,m){let w=0;let b=v+m;for(let y=v;y<b;y++){w+=Math.abs(g[y])}return w}function o(g,v,m,w,b,y){for(let _=0;_<m;_++){let T=_>=y?g[v+_-y]:0;let $=g[v+_]-T;w[b+_]=$}}function s(g,v,m,w){let b=0;for(let y=0;y<m;y++){let _=y>=w?g[v+y-w]:0;let T=g[v+y]-_;b+=Math.abs(T)}return b}function a(g,v,m,w,b){for(let y=0;y<m;y++){let _=v>0?g[v+y-m]:0;let T=g[v+y]-_;w[b+y]=T}}function c(g,v,m){let w=0;let b=v+m;for(let y=v;y<b;y++){let _=v>0?g[y-m]:0;let T=g[y]-_;w+=Math.abs(T)}return w}function l(g,v,m,w,b,y){for(let _=0;_<m;_++){let T=_>=y?g[v+_-y]:0;let $=v>0?g[v+_-m]:0;let x=g[v+_]-(T+$>>1);w[b+_]=x}}function u(g,v,m,w){let b=0;for(let y=0;y<m;y++){let _=y>=w?g[v+y-w]:0;let T=v>0?g[v+y-m]:0;let $=g[v+y]-(_+T>>1);b+=Math.abs($)}return b}function d(g,v,m,w,b,y){for(let _=0;_<m;_++){let T=_>=y?g[v+_-y]:0;let $=v>0?g[v+_-m]:0;let x=v>0&&_>=y?g[v+_-(m+y)]:0;let A=g[v+_]-t(T,$,x);w[b+_]=A}}function h(g,v,m,w){let b=0;for(let y=0;y<m;y++){let _=y>=w?g[v+y-w]:0;let T=v>0?g[v+y-m]:0;let $=v>0&&y>=w?g[v+y-(m+w)]:0;let x=g[v+y]-t(_,T,$);b+=Math.abs(x)}return b}var p={0:r,1:o,2:a,3:l,4:d};var f={0:i,1:s,2:c,3:u,4:h};n.exports=function(g,v,m,w,b){let y;if(!("filterType"in w)||w.filterType===-1){y=[0,1,2,3,4]}else if(typeof w.filterType==="number"){y=[w.filterType]}else{throw new Error("unrecognised filter types")}if(w.bitDepth===16){b*=2}let _=v*b;let T=0;let $=0;let x=Buffer.alloc((_+1)*m);let A=y[0];for(let I=0;I<m;I++){if(y.length>1){let E=Infinity;for(let k=0;k<y.length;k++){let S=f[y[k]](g,$,_,b);if(S<E){A=y[k];E=S}}}x[T]=A;T++;p[A](g,$,_,x,T,b);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 s=require("zlib");var a=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||s.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")}};a.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};a.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};a.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 p=o(d,l,u,this._options,h);return p};a.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};a.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)};a.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)};a.prototype.packIDAT=function(c){return this._packChunk(t.TYPE_IDAT,c)};a.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 s=n.exports=function(a){r.call(this);let c=a||{};this._packer=new o(c);this._deflate=this._packer.createDeflate();this.readable=true};t.inherits(s,r);s.prototype.pack=function(a,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(a,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 s(d){if(!(this instanceof s)){return new s(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 a(d){return new s(d)}function c(d,h){if(h){process.nextTick(h)}if(!d._handle){return}d._handle.close();d._handle=null}s.prototype._processChunk=function(d,h,p){if(typeof p==="function"){return r.Inflate._processChunk.call(this,d,h,p)}let f=this;let g=d&&d.length;let v=this._chunkSize-this._offset;let m=this._maxLength;let w=0;let b=[];let y=0;let _;this.on("error",function(A){_=A});function T(A,I){if(f._hadError){return}let E=v-I;t(E>=0,"have should not go down");if(E>0){let k=f._buffer.slice(f._offset,f._offset+E);f._offset+=E;if(k.length>m){k=k.slice(0,m)}b.push(k);y+=k.length;m-=k.length;if(m===0){return false}}if(I===0||f._offset>=f._chunkSize){v=f._chunkSize;f._offset=0;f._buffer=Buffer.allocUnsafe(f._chunkSize)}if(I===0){w+=g-A;g=A;return true}return false}t(this._handle,"zlib binding closed");let $;do{$=this._handle.writeSync(h,d,w,g,this._buffer,this._offset,v);$=$||this._writeState}while(!this._hadError&&T($[0],$[1]));if(this._hadError){throw _}if(y>=o){c(this);throw new RangeError("Cannot create final Buffer. It would be larger than 0x"+o.toString(16)+" bytes")}let x=Buffer.concat(b,y);c(this);return x};i.inherits(s,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 p=d._finishFlushFlag;if(p==null){p=r.Z_FINISH}return d._processChunk(h,p)}function u(d,h){return l(new s(h),d)}n.exports=e=u;e.Inflate=s;e.createInflate=a;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 s=new n(r);let a=new t(i,{read:s.read.bind(s),write:function(c){o.push(c)},complete:function(){}});a.start();s.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 s=require_filter_parse_sync();var a=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 p(M){h=M}let f;function g(M){f=M}function v(M){f.transColor=M}function m(M){f.palette=M}function w(){f.alpha=true}let b;function y(M){b=M}let _=[];function T(M){_.push(M)}let $=new o(u);let x=new a(d,{read:$.read.bind($),error:p,metadata:g,gamma:y,palette:m,transColor:v,inflateData:T,simpleTransparency:w});x.start();$.process();if(h){throw h}let A=Buffer.concat(_);_.length=0;let I;if(f.interlace){I=r.inflateSync(A)}else{let M=(f.width*f.bpp*f.depth+7>>3)+1;let D=M*f.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=s.process(I,f);A=null;let k=c.dataToBitMap(E,f);E=null;let S=l(k,f,d.skipRescale);f.data=S;f.gamma=b||0;return f}}});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(s,a){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=a||{};let l=new o(c);let u=[];u.push(Buffer.from(i.PNG_SIGNATURE));u.push(l.packIHDR(s.width,s.height));if(s.gamma){u.push(l.packGAMA(s.gamma))}let d=l.filterData(s.data,s.width,s.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 s=e.PNG=function(a){t.call(this);a=a||{};this.width=a.width|0;this.height=a.height|0;this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null;if(a.fill&&this.data){this.data.fill(0)}this.gamma=0;this.readable=this.writable=true;this._parser=new r(a);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(a);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(s,t);s.sync=o;s.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};s.prototype.parse=function(a,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(a);return this};s.prototype.write=function(a){this._parser.write(a);return true};s.prototype.end=function(a){this._parser.end(a)};s.prototype._metadata=function(a){this.width=a.width;this.height=a.height;this.emit("metadata",a)};s.prototype._gamma=function(a){this.gamma=a};s.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable){this.emit("close")}};s.bitblt=function(a,c,l,u,d,h,p,f){l|=0;u|=0;d|=0;h|=0;p|=0;f|=0;if(l>a.width||u>a.height||l+d>a.width||u+h>a.height){throw new Error("bitblt reading outside image")}if(p>c.width||f>c.height||p+d>c.width||f+h>c.height){throw new Error("bitblt writing outside image")}for(let g=0;g<h;g++){a.data.copy(c.data,(f+g)*c.width+p<<2,(u+g)*a.width+l<<2,(u+g)*a.width+l+d<<2)}};s.prototype.bitblt=function(a,c,l,u,d,h,p){s.bitblt(this,a,c,l,u,d,h,p);return this};s.adjustGamma=function(a){if(a.gamma){for(let c=0;c<a.height;c++){for(let l=0;l<a.width;l++){let u=a.width*c+l<<2;for(let d=0;d<3;d++){let h=a.data[u+d]/255;h=Math.pow(h,1/2.2/a.gamma);a.data[u+d]=Math.round(h*255)}}}a.gamma=0}};s.prototype.adjustGamma=function(){s.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_crypto4;var init_profiles=__esm({"../sim-farm/src/profiles.ts"(){"use strict";import_node_crypto4=require("crypto")}});function run(e,n,t={}){const{timeoutMs:r=3e4,maxBytes:i=4*1024*1024}=t;return new Promise(o=>{const s=(0,import_node_child_process3.spawn)(e,n,{env:t.env??process.env,stdio:[t.input==null?"ignore":"pipe","pipe","pipe"]});liveChildren.add(s);let a="";let c="";let l=false;s.stdout.on("data",d=>{if(a.length<i)a+=d.toString("utf8")});s.stderr.on("data",d=>{if(c.length<i)c+=d.toString("utf8")});if(t.input!=null)s.stdin.end(t.input);const u=setTimeout(()=>{l=true;s.kill("SIGTERM");setTimeout(()=>s.kill("SIGKILL"),2e3).unref?.()},r);s.on("error",d=>{liveChildren.delete(s);clearTimeout(u);o({code:null,stdout:a,stderr:c+String(d),timedOut:l})});s.on("close",d=>{liveChildren.delete(s);clearTimeout(u);o({code:d,stdout:a,stderr:c,timedOut:l})})})}async function pidStart(e){const n=await run("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,t=false){if(!Number.isInteger(e)||e<=0)return false;try{process.kill(e,0)}catch(i){if(i.code!=="EPERM")return false}if(!n)return true;const r=await pidStart(e);if(r===null)return t;return r===n}function bootEnv(e=process.env){return Object.fromEntries(Object.entries(e).filter(([n])=>!n.startsWith("SIMCTL_CHILD_")))}var import_node_child_process3,liveChildren,sleep;var init_proc=__esm({"../sim-farm/src/proc.ts"(){"use strict";import_node_child_process3=require("child_process");liveChildren=new Set;sleep=e=>new Promise(n=>setTimeout(n,e))}});var import_node_fs4,import_node_path5,import_node_crypto5,DISABLED_STORE_ROOT;var init_disabledStore=__esm({"../sim-farm/src/disabledStore.ts"(){"use strict";import_node_fs4=require("fs");import_node_path5=__toESM(require("path"));import_node_crypto5=require("crypto");init_proc();DISABLED_STORE_ROOT=process.env.BUOY_FARM_DISABLED_ROOT||"/private/var/tmp"}});async function findDataContainer(e,n){const t=import_node_path6.default.join(e,"Containers/Data/Application");let r;try{r=await import_node_fs5.promises.readdir(t)}catch{return null}for(const i of r){const o=import_node_path6.default.join(t,i,".com.apple.mobile_container_manager.metadata.plist");if(!(0,import_node_fs5.existsSync)(o))continue;const s=await run("plutil",["-extract","MCMMetadataIdentifier","raw","-o","-",o],{timeoutMs:5e3});if(s.code===0&&s.stdout.trim()===n)return import_node_path6.default.join(t,i)}return null}async function readBuoyInstallId(e){let n;try{n=await import_node_fs5.promises.readFile(import_node_path6.default.join(e,"Documents/react-buoy/@react_buoy_sync_device_id.json"),"utf8")}catch{return null}try{const t=JSON.parse(n);if(typeof t==="string")return t||null;if(typeof t?.value==="string")return t.value||null}catch{}return n.trim()||null}var import_node_fs5,import_node_path6,import_node_crypto6;var init_seed=__esm({"../sim-farm/src/seed.ts"(){"use strict";import_node_fs5=require("fs");import_node_path6=__toESM(require("path"));import_node_crypto6=require("crypto");init_proc()}});var KEEP_MS;var init_meter=__esm({"../sim-farm/src/meter.ts"(){"use strict";KEEP_MS=2*60*6e4}});var init_phoneProfileSource_generated=__esm({"../sim-farm/src/phoneProfileSource.generated.ts"(){"use strict"}});function farmHome(){return process.env.BUOY_FARM_HOME||import_node_path7.default.join(import_node_os5.default.homedir(),".buoy","farm")}function phoneDir(e=farmHome()){return import_node_path7.default.join(e,"phone")}function joinInsertList(...e){const n=new Set;const t=[];for(const r of e){for(const i of(r??"").split(":")){const o=i.trim();if(o&&!n.has(o)){n.add(o);t.push(o)}}}return t.join(":")}function launchFilePath(e,n=farmHome()){if(!/^[0-9A-F-]{36}$/i.test(e))throw new Error(`not a UDID: ${e}`);return import_node_path7.default.join(phoneDir(n),`${e}.launch.json`)}async function readLaunchFile(e,n=farmHome()){try{const t=JSON.parse(await import_node_fs6.promises.readFile(launchFilePath(e,n),"utf8"));if(t?.udid!==e||typeof t.dylib!=="string"||!t.vars||typeof t.vars!=="object")return null;await import_node_fs6.promises.access(t.dylib);return t}catch{return null}}async function simWideInsertList(e){try{const{stdout:n}=await execFileAsync3("xcrun",["simctl","spawn",e,"launchctl","getenv","DYLD_INSERT_LIBRARIES"],{timeout:1e4});return n.trim()}catch{return""}}async function simLaunchEnv(e,n,t,r=farmHome(),i=simWideInsertList){const o=await readLaunchFile(e,r);if(!o||o.bundleId!==n){return t?{SIMCTL_CHILD_DYLD_INSERT_LIBRARIES:joinInsertList(process.env.SIMCTL_CHILD_DYLD_INSERT_LIBRARIES,await i(e),t)}:{}}const s={};for(const[a,c]of Object.entries(o.vars))s[`SIMCTL_CHILD_${a}`]=c;s.SIMCTL_CHILD_DYLD_INSERT_LIBRARIES=joinInsertList(process.env.SIMCTL_CHILD_DYLD_INSERT_LIBRARIES,await i(e),t,o.dylib);return s}var import_node_child_process4,import_node_fs6,import_node_os5,import_node_path7,import_node_util3,execFileAsync3;var init_phoneProfile=__esm({"../sim-farm/src/phoneProfile.ts"(){"use strict";import_node_child_process4=require("child_process");import_node_fs6=require("fs");import_node_os5=__toESM(require("os"));import_node_path7=__toESM(require("path"));import_node_util3=require("util");init_phoneProfileSource_generated();execFileAsync3=(0,import_node_util3.promisify)(import_node_child_process4.execFile)}});var import_node_fs7,import_node_path8,import_node_async_hooks2,import_node_crypto7,GB,PHONE_RETRY_MS;var init_engine=__esm({"../sim-farm/src/engine.ts"(){"use strict";import_node_fs7=require("fs");import_node_path8=__toESM(require("path"));import_node_async_hooks2=require("async_hooks");import_node_crypto7=require("crypto");init_disabledStore();init_profiles();init_proc();init_seed();init_meter();init_phoneProfile();init_types();GB=1024**3;PHONE_RETRY_MS=10*6e4}});var import_node_fs8,import_node_os6,import_node_path9;var init_host=__esm({"../sim-farm/src/host.ts"(){"use strict";import_node_fs8=require("fs");import_node_os6=__toESM(require("os"));import_node_path9=__toESM(require("path"));init_disabledStore();init_meter();init_proc()}});function farmHome2(){return process.env.BUOY_FARM_HOME||import_node_path10.default.join(import_node_os7.default.homedir(),".buoy","farm")}function ensureHome(e=farmHome2()){(0,import_node_fs9.mkdirSync)(e,{recursive:true,mode:448});try{(0,import_node_fs9.chmodSync)(e,448)}catch{}}function readOrCreateToken(e=farmHome2()){const n=paths(e).token;try{const t=(0,import_node_fs9.readFileSync)(n,"utf8").trim();if(t)return t}catch{}ensureHome(e);try{(0,import_node_fs9.writeFileSync)(n,(0,import_node_crypto8.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_fs9.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=farmHome2()){try{return JSON.parse(await import_node_fs9.promises.readFile(paths(e).lockOwner,"utf8"))}catch{return null}}async function ownerAlive(e){return!!e&&await pidAlive(e.pid,e.start,true)}var import_node_fs9,import_node_os7,import_node_path10,import_node_crypto8,paths;var init_store=__esm({"../sim-farm/src/store.ts"(){"use strict";import_node_fs9=require("fs");import_node_os7=__toESM(require("os"));import_node_path10=__toESM(require("path"));import_node_crypto8=require("crypto");init_proc();init_types();paths=(e=farmHome2())=>({home:e,lock:import_node_path10.default.join(e,"owner.lock"),lockOwner:import_node_path10.default.join(e,"owner.lock","owner.json"),socket:import_node_path10.default.join(e,"farmd.sock"),token:import_node_path10.default.join(e,"token"),state:import_node_path10.default.join(e,"state.json"),journal:import_node_path10.default.join(e,"journal.ndjson"),log:import_node_path10.default.join(e,"farmd.log"),shots:import_node_path10.default.join(e,"shots")})}});var import_node_net,import_node_fs10,import_node_crypto9;var init_server=__esm({"../sim-farm/src/server.ts"(){"use strict";import_node_net=__toESM(require("net"));import_node_fs10=require("fs");import_node_crypto9=require("crypto");init_engine();init_host();init_store();init_types();init_proc()}});function nodeLauncher(e,n=["farmd"]){return()=>{const t=(0,import_node_child_process5.spawn)(process.execPath,[...process.execArgv,e,...n],{detached:true,stdio:"ignore",env:bootEnv()});t.unref()}}async function connectFarm(e){return new FarmClient(e).connect()}var import_node_net2,import_node_fs11,import_node_child_process5,import_node_crypto10,FarmClient;var init_client=__esm({"../sim-farm/src/client.ts"(){"use strict";import_node_net2=__toESM(require("net"));import_node_fs11=require("fs");import_node_child_process5=require("child_process");import_node_crypto10=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??farmHome2();this.clientIdValue=`c-${(0,import_node_crypto10.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,...this.opts.agent?{agent:this.opts.agent}:{}};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 sleep(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 sleep(500);return this.connect()}}return this}tryOpen(){const e=paths(this.home).socket;if(!(0,import_node_fs11.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,s)=>{const a=setTimeout(()=>{this.pending.delete(r);s(new FarmError("HOST_ERROR",`Farm call ${e} timed out.`,void 0,true))},t.timeoutMs??3e4);this.pending.set(r,{resolve:o,reject:s,timer:a});this.sock.write(JSON.stringify(i)+"\n")})}async acquire(e){const{requestId:n,...t}=e;const r=n??`acq-${(0,import_node_crypto10.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(s=>{if(["LEASE_EXPIRED","STALE_EPOCH","RUN_STOPPED","RUN_ENDED"].includes(s.code))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",r=false){this.stopRenew(e);return this.call("release",{leaseId:e,epoch:n,reset:t,keepRun:r},{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_path11,import_node_os8,import_node_fs12;var init_discover=__esm({"../sim-farm/src/discover.ts"(){"use strict";import_node_path11=__toESM(require("path"));import_node_os8=__toESM(require("os"));import_node_fs12=require("fs");init_proc();init_seed();init_profiles()}});async function parentOf(e){const n=await run("ps",["-o","ppid=,comm=","-p",String(e)],{timeoutMs:3e3});const t=/^\s*(\d+)\s+(.+?)\s*$/.exec(n.stdout);return n.code===0&&t?{ppid:Number(t[1]),comm:t[2]}:null}async function cwdOf(e){const n=await run("lsof",["-a","-p",String(e),"-d","cwd","-Fn"],{timeoutMs:3e3});const t=n.stdout.split("\n").find(r=>r.startsWith("n"));return t?t.slice(1):null}function fromClientName(e){if(!e)return void 0;return APPS.find(n=>e.toLowerCase().includes(n.app))}async function detectAgent(e={}){const n=e.env??process.env;let t=e.pid??process.pid;let r=null;for(let u=0;u<5&&t>1;u++){const d=await parentOf(t).catch(()=>null);if(!d)break;const h=APPS.find(p=>p.match.test(d.comm));if(u>0&&h){r={app:h,pid:t};break}t=d.ppid}const i=r?.app??fromClientName(e.clientName);const o=(r?await cwdOf(r.pid).catch(()=>null):null)??process.cwd();const s=(await run("git",["-C",o,"rev-parse","--abbrev-ref","HEAD"],{timeoutMs:3e3}).catch(()=>null))?.stdout.trim();const a=n.CLAUDE_CODE_SESSION_ID?.trim();let c;let l="none";if(a&&(i?.app??"claude")==="claude"){c=`claude:${a}`;l="claude-session"}else if(r){c=`${r.app.app}:${r.pid}:${await pidStart(r.pid)??""}`;l="parent-process"}return{app:i?.app??"other",appName:i?.name??(e.clientName||"Agent"),chatKey:c,chatKeySource:l,project:import_node_path12.default.basename(o)||void 0,projectPath:o,branch:s&&s!=="HEAD"?s:void 0,clientName:e.clientName}}function agentLabel(e){return e.project?`${e.appName} \xB7 ${e.project}`:e.appName}var import_node_path12,APPS;var init_agent=__esm({"../sim-farm/src/agent.ts"(){"use strict";import_node_path12=__toESM(require("path"));init_proc();APPS=[{app:"claude",name:"Claude",match:/(^|\/)claude$/i},{app:"codex",name:"Codex",match:/(^|\/)codex$/i},{app:"cursor",name:"Cursor",match:/cursor/i}]}});var import_node_child_process6,import_node_crypto11,import_node_fs13,import_node_os9,import_node_path13,import_node_util4,execFileAsync4,MB;var init_phoneMeasure=__esm({"../sim-farm/src/phoneMeasure.ts"(){"use strict";import_node_child_process6=require("child_process");import_node_crypto11=require("crypto");import_node_fs13=require("fs");import_node_os9=__toESM(require("os"));import_node_path13=__toESM(require("path"));import_node_util4=require("util");init_phoneProfile();init_phoneProfileSource_generated();execFileAsync4=(0,import_node_util4.promisify)(import_node_child_process6.execFile);MB=1024*1024}});var import_node_path14,import_node_fs14,import_node_os10,farmHelp,HELP;var init_command=__esm({"../sim-farm/src/command.ts"(){"use strict";import_node_path14=__toESM(require("path"));import_node_fs14=require("fs");import_node_os10=__toESM(require("os"));init_client();init_server();init_host();init_types();init_profiles();init_seed();init_store();init_discover();init_phoneProfile();init_phoneMeasure();farmHelp=e=>`Usage: ${e} <command>
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,s){this._reads.push({length:Math.abs(o),allowLess:o<0,func:s});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,s){if(!this.writable){this.emit("error",new Error("Stream not writable"));return false}let a;if(Buffer.isBuffer(o)){a=o}else{a=Buffer.from(o,s||this._encoding)}this._buffers.push(a);this._buffered+=a.length;this._process();if(this._reads&&this._reads.length===0){this._paused=true}return this.writable&&!this._paused};i.prototype.end=function(o,s){if(o){this.write(o,s)}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 s=this._buffers[0];if(s.length>o.length){this._buffered-=o.length;this._buffers[0]=s.slice(o.length);o.func.call(this,s.slice(0,o.length))}else{this._buffered-=s.length;this._buffers.shift();o.func.call(this,s)}};i.prototype._processRead=function(o){this._reads.shift();let s=0;let a=0;let c=Buffer.alloc(o.length);while(s<o.length){let l=this._buffers[a++];let u=Math.min(l.length,o.length-s);l.copy(c,s,0,u);s+=u;if(u!==l.length){this._buffers[--a]=l.slice(u)}}if(a>0){this._buffers.splice(0,a)}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 s=r%8;let a=(t-o)/8;let c=(r-s)/8;for(let l=0;l<n.length;l++){let u=n[l];let d=a*u.x.length;let h=c*u.y.length;for(let p=0;p<u.x.length;p++){if(u.x[p]<o){d++}else{break}}for(let p=0;p<u.y.length;p++){if(u.y[p]<s){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 s=r%n[o].x.length;let a=(r-s)/n[o].x.length*8+n[o].x[s];let c=i%n[o].y.length;let l=(i-c)/n[o].y.length*8+n[o].y[c];return a*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 s=r+i-o;let a=Math.abs(s-r);let c=Math.abs(s-i);let l=Math.abs(s-o);if(a<=c&&a<=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(s,a,c){let l=s*a;if(c!==8){l=Math.ceil(l/(8/c))}return l}var o=n.exports=function(s,a){let c=s.width;let l=s.height;let u=s.interlace;let d=s.bpp;let h=s.depth;this.read=a.read;this.write=a.write;this.complete=a.complete;this._imageIndex=0;this._images=[];if(u){let p=t.getImagePasses(c,l);for(let f=0;f<p.length;f++){this._images.push({byteWidth:i(p[f].width,d,h),height:p[f].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(s,a,c){let l=this._xComparison;let u=l-1;for(let d=0;d<c;d++){let h=s[1+d];let p=d>u?a[d-l]:0;a[d]=h+p}};o.prototype._unFilterType2=function(s,a,c){let l=this._lastLine;for(let u=0;u<c;u++){let d=s[1+u];let h=l?l[u]:0;a[u]=d+h}};o.prototype._unFilterType3=function(s,a,c){let l=this._xComparison;let u=l-1;let d=this._lastLine;for(let h=0;h<c;h++){let p=s[1+h];let f=d?d[h]:0;let g=h>u?a[h-l]:0;let v=Math.floor((g+f)/2);a[h]=p+v}};o.prototype._unFilterType4=function(s,a,c){let l=this._xComparison;let u=l-1;let d=this._lastLine;for(let h=0;h<c;h++){let p=s[1+h];let f=d?d[h]:0;let g=h>u?a[h-l]:0;let v=h>u&&d?d[h-l]:0;let m=r(g,f,v);a[h]=p+m}};o.prototype._reverseFilterLine=function(s){let a=s[0];let c;let l=this._images[this._imageIndex];let u=l.byteWidth;if(a===0){c=s.slice(1,u+1)}else{c=Buffer.alloc(u);switch(a){case 1:this._unFilterType1(s,c,u);break;case 2:this._unFilterType2(s,c,u);break;case 3:this._unFilterType3(s,c,u);break;case 4:this._unFilterType4(s,c,u);break;default:throw new Error("Unrecognised filter type - "+a)}}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(s){r.call(this);let a=[];let c=this;this._filter=new i(s,{read:this.read.bind(this),write:function(l){a.push(l)},complete:function(){c.emit("complete",Buffer.concat(a))}});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 s=0;s<8;s++){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 s=0;s<i.length;s++){o=t[(o^i[s])&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,s){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=s.read;this.error=s.error;this.metadata=s.metadata;this.gamma=s.gamma;this.transColor=s.transColor;this.palette=s.palette;this.parsed=s.parsed;this.inflateData=s.inflateData;this.finished=s.finished;this.simpleTransparency=s.simpleTransparency;this.headersFinished=s.headersFinished||function(){}};i.prototype.start=function(){this.read(t.PNG_SIGNATURE.length,this._parseSignature.bind(this))};i.prototype._parseSignature=function(o){let s=t.PNG_SIGNATURE;for(let a=0;a<s.length;a++){if(o[a]!==s[a]){this.error(new Error("Invalid file signature"));return}}this.read(8,this._parseChunkBegin.bind(this))};i.prototype._parseChunkBegin=function(o){let s=o.readUInt32BE(0);let a=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&&a!==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[a]){return this._chunks[a](s)}if(!l){this.error(new Error("Unsupported critical chunk type "+c));return}this.read(s+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 s=o.readInt32BE(0);let a=this._crc.crc32();if(this._options.checkCRC&&a!==s){this.error(new Error("Crc error - "+s+" - "+a));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 s=o.readUInt32BE(0);let a=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 p=t.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=true;this.metadata({width:s,height:a,depth:c,interlace:Boolean(h),palette:Boolean(l&t.COLORTYPE_PALETTE),color:Boolean(l&t.COLORTYPE_COLOR),alpha:Boolean(l&t.COLORTYPE_ALPHA),bpp:p,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 s=Math.floor(o.length/3);for(let a=0;a<s;a++){this._palette.push([o[a*3],o[a*3+1],o[a*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 s=0;s<o.length;s++){this._palette[s][3]=o[s]}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,s){this._crc.write(s);if(this._colorType===t.COLORTYPE_PALETTE_COLOR&&this._palette.length===0){throw new Error("Expected palette not found")}this.inflateData(s);let a=o-s.length;if(a>0){this._handleIDAT(a)}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(a,c,l,u){if(u===c.length){throw new Error("Ran out of data")}let d=c[u];a[l]=d;a[l+1]=d;a[l+2]=d;a[l+3]=255},function(a,c,l,u){if(u+1>=c.length){throw new Error("Ran out of data")}let d=c[u];a[l]=d;a[l+1]=d;a[l+2]=d;a[l+3]=c[u+1]},function(a,c,l,u){if(u+2>=c.length){throw new Error("Ran out of data")}a[l]=c[u];a[l+1]=c[u+1];a[l+2]=c[u+2];a[l+3]=255},function(a,c,l,u){if(u+3>=c.length){throw new Error("Ran out of data")}a[l]=c[u];a[l+1]=c[u+1];a[l+2]=c[u+2];a[l+3]=c[u+3]}];var r=[function(){},function(a,c,l,u){let d=c[0];a[l]=d;a[l+1]=d;a[l+2]=d;a[l+3]=u},function(a,c,l){let u=c[0];a[l]=u;a[l+1]=u;a[l+2]=u;a[l+3]=c[1]},function(a,c,l,u){a[l]=c[0];a[l+1]=c[1];a[l+2]=c[2];a[l+3]=u},function(a,c,l){a[l]=c[0];a[l+1]=c[1];a[l+2]=c[2];a[l+3]=c[3]}];function i(a,c){let l=[];let u=0;function d(){if(u===a.length){throw new Error("Ran out of data")}let h=a[u];u++;let p,f,g,v,m,w,b,y;switch(c){default:throw new Error("unrecognised depth");case 16:b=a[u];u++;l.push((h<<8)+b);break;case 4:b=h&15;y=h>>4;l.push(y,b);break;case 2:m=h&3;w=h>>2&3;b=h>>4&3;y=h>>6&3;l.push(y,b,w,m);break;case 1:p=h&1;f=h>>1&1;g=h>>2&1;v=h>>3&1;m=h>>4&1;w=h>>5&1;b=h>>6&1;y=h>>7&1;l.push(y,b,w,m,v,g,f,p);break}}return{get:function(h){while(l.length<h){d()}let p=l.slice(0,h);l=l.slice(h);return p},resetAfterLine:function(){l.length=0},end:function(){if(u!==a.length){throw new Error("extra data found")}}}}function o(a,c,l,u,d,h){let p=a.width;let f=a.height;let g=a.index;for(let v=0;v<f;v++){for(let m=0;m<p;m++){let w=l(m,v,g);t[u](c,d,w,h);h+=u}}return h}function s(a,c,l,u,d,h){let p=a.width;let f=a.height;let g=a.index;for(let v=0;v<f;v++){for(let m=0;m<p;m++){let w=d.get(u);let b=l(m,v,g);r[u](c,w,b,h)}d.resetAfterLine()}}e.dataToBitMap=function(a,c){let l=c.width;let u=c.height;let d=c.depth;let h=c.bpp;let p=c.interlace;let f;if(d!==8){f=i(a,d)}let g;if(d<=8){g=Buffer.alloc(l*u*4)}else{g=new Uint16Array(l*u*4)}let v=Math.pow(2,d)-1;let m=0;let w;let b;if(p){w=n.getImagePasses(l,u);b=n.getInterlaceIterator(l,u)}else{let y=0;b=function(){let _=y;y+=4;return _};w=[{width:l,height:u}]}for(let y=0;y<w.length;y++){if(d===8){m=o(w[y],g,b,h,a,m)}else{s(w[y],g,b,h,f,v)}}if(d===8){if(m!==a.length){throw new Error("extra data found")}}else{f.end()}return g}}});var require_format_normaliser=__commonJS({"../../node_modules/pngjs/lib/format-normaliser.js"(e,n){"use strict";function t(o,s,a,c,l){let u=0;for(let d=0;d<c;d++){for(let h=0;h<a;h++){let p=l[o[u]];if(!p){throw new Error("index "+o[u]+" not in palette")}for(let f=0;f<4;f++){s[u+f]=p[f]}u+=4}}}function r(o,s,a,c,l){let u=0;for(let d=0;d<c;d++){for(let h=0;h<a;h++){let p=false;if(l.length===1){if(l[0]===o[u]){p=true}}else if(l[0]===o[u]&&l[1]===o[u+1]&&l[2]===o[u+2]){p=true}if(p){for(let f=0;f<4;f++){s[u+f]=0}}u+=4}}}function i(o,s,a,c,l){let u=255;let d=Math.pow(2,l)-1;let h=0;for(let p=0;p<c;p++){for(let f=0;f<a;f++){for(let g=0;g<4;g++){s[h+g]=Math.floor(o[h+g]*u/d+.5)}h+=4}}}n.exports=function(o,s,a=false){let c=s.depth;let l=s.width;let u=s.height;let d=s.colorType;let h=s.transColor;let p=s.palette;let f=o;if(d===3){t(o,f,l,u,p)}else{if(h){r(o,f,l,u,h)}if(c!==8&&!a){if(c===16){f=Buffer.alloc(l*u*4)}i(o,f,l,u,c)}}return f}}});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 s=require_parser();var a=require_bitmapper();var c=require_format_normaliser();var l=n.exports=function(u){i.call(this);this._parser=new s(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 p=Math.max(h,r.Z_MIN_CHUNK);this._inflate=r.createInflate({chunkSize:p});let f=h;let g=this.emit.bind(this,"error");this._inflate.on("error",function(m){if(!f){return}g(m)});this._filter.on("complete",this._complete.bind(this));let v=this._filter.write.bind(this._filter);this._inflate.on("data",function(m){if(!f){return}if(m.length>f){m=m.slice(0,f)}f-=m.length;v(m)});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=a.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,s){let a=[t.COLORTYPE_COLOR_ALPHA,t.COLORTYPE_ALPHA].indexOf(s.colorType)!==-1;if(s.colorType===s.inputColorType){let m=(function(){let w=new ArrayBuffer(2);new DataView(w).setInt16(0,256,true);return new Int16Array(w)[0]!==256})();if(s.bitDepth===8||s.bitDepth===16&&m){return r}}let c=s.bitDepth!==16?r:new Uint16Array(r.buffer);let l=255;let u=t.COLORTYPE_TO_BPP_MAP[s.inputColorType];if(u===4&&!s.inputHasAlpha){u=3}let d=t.COLORTYPE_TO_BPP_MAP[s.colorType];if(s.bitDepth===16){l=65535;d*=2}let h=Buffer.alloc(i*o*d);let p=0;let f=0;let g=s.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 v(){let m;let w;let b;let y=l;switch(s.inputColorType){case t.COLORTYPE_COLOR_ALPHA:y=c[p+3];m=c[p];w=c[p+1];b=c[p+2];break;case t.COLORTYPE_COLOR:m=c[p];w=c[p+1];b=c[p+2];break;case t.COLORTYPE_ALPHA:y=c[p+1];m=c[p];w=m;b=m;break;case t.COLORTYPE_GRAYSCALE:m=c[p];w=m;b=m;break;default:throw new Error("input color type:"+s.inputColorType+" is not supported at present")}if(s.inputHasAlpha){if(!a){y/=l;m=Math.min(Math.max(Math.round((1-y)*g.red+y*m),0),l);w=Math.min(Math.max(Math.round((1-y)*g.green+y*w),0),l);b=Math.min(Math.max(Math.round((1-y)*g.blue+y*b),0),l)}}return{red:m,green:w,blue:b,alpha:y}}for(let m=0;m<o;m++){for(let w=0;w<i;w++){let b=v(c,p);switch(s.colorType){case t.COLORTYPE_COLOR_ALPHA:case t.COLORTYPE_COLOR:if(s.bitDepth===8){h[f]=b.red;h[f+1]=b.green;h[f+2]=b.blue;if(a){h[f+3]=b.alpha}}else{h.writeUInt16BE(b.red,f);h.writeUInt16BE(b.green,f+2);h.writeUInt16BE(b.blue,f+4);if(a){h.writeUInt16BE(b.alpha,f+6)}}break;case t.COLORTYPE_ALPHA:case t.COLORTYPE_GRAYSCALE:{let y=(b.red+b.green+b.blue)/3;if(s.bitDepth===8){h[f]=y;if(a){h[f+1]=b.alpha}}else{h.writeUInt16BE(y,f);if(a){h.writeUInt16BE(b.alpha,f+2)}}break}default:throw new Error("unrecognised color Type "+s.colorType)}p+=u;f+=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,v,m,w,b){for(let y=0;y<m;y++){w[b+y]=g[v+y]}}function i(g,v,m){let w=0;let b=v+m;for(let y=v;y<b;y++){w+=Math.abs(g[y])}return w}function o(g,v,m,w,b,y){for(let _=0;_<m;_++){let T=_>=y?g[v+_-y]:0;let $=g[v+_]-T;w[b+_]=$}}function s(g,v,m,w){let b=0;for(let y=0;y<m;y++){let _=y>=w?g[v+y-w]:0;let T=g[v+y]-_;b+=Math.abs(T)}return b}function a(g,v,m,w,b){for(let y=0;y<m;y++){let _=v>0?g[v+y-m]:0;let T=g[v+y]-_;w[b+y]=T}}function c(g,v,m){let w=0;let b=v+m;for(let y=v;y<b;y++){let _=v>0?g[y-m]:0;let T=g[y]-_;w+=Math.abs(T)}return w}function l(g,v,m,w,b,y){for(let _=0;_<m;_++){let T=_>=y?g[v+_-y]:0;let $=v>0?g[v+_-m]:0;let x=g[v+_]-(T+$>>1);w[b+_]=x}}function u(g,v,m,w){let b=0;for(let y=0;y<m;y++){let _=y>=w?g[v+y-w]:0;let T=v>0?g[v+y-m]:0;let $=g[v+y]-(_+T>>1);b+=Math.abs($)}return b}function d(g,v,m,w,b,y){for(let _=0;_<m;_++){let T=_>=y?g[v+_-y]:0;let $=v>0?g[v+_-m]:0;let x=v>0&&_>=y?g[v+_-(m+y)]:0;let A=g[v+_]-t(T,$,x);w[b+_]=A}}function h(g,v,m,w){let b=0;for(let y=0;y<m;y++){let _=y>=w?g[v+y-w]:0;let T=v>0?g[v+y-m]:0;let $=v>0&&y>=w?g[v+y-(m+w)]:0;let x=g[v+y]-t(_,T,$);b+=Math.abs(x)}return b}var p={0:r,1:o,2:a,3:l,4:d};var f={0:i,1:s,2:c,3:u,4:h};n.exports=function(g,v,m,w,b){let y;if(!("filterType"in w)||w.filterType===-1){y=[0,1,2,3,4]}else if(typeof w.filterType==="number"){y=[w.filterType]}else{throw new Error("unrecognised filter types")}if(w.bitDepth===16){b*=2}let _=v*b;let T=0;let $=0;let x=Buffer.alloc((_+1)*m);let A=y[0];for(let I=0;I<m;I++){if(y.length>1){let E=Infinity;for(let k=0;k<y.length;k++){let S=f[y[k]](g,$,_,b);if(S<E){A=y[k];E=S}}}x[T]=A;T++;p[A](g,$,_,x,T,b);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 s=require("zlib");var a=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||s.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")}};a.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};a.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};a.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 p=o(d,l,u,this._options,h);return p};a.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};a.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)};a.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)};a.prototype.packIDAT=function(c){return this._packChunk(t.TYPE_IDAT,c)};a.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 s=n.exports=function(a){r.call(this);let c=a||{};this._packer=new o(c);this._deflate=this._packer.createDeflate();this.readable=true};t.inherits(s,r);s.prototype.pack=function(a,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(a,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 s(d){if(!(this instanceof s)){return new s(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 a(d){return new s(d)}function c(d,h){if(h){process.nextTick(h)}if(!d._handle){return}d._handle.close();d._handle=null}s.prototype._processChunk=function(d,h,p){if(typeof p==="function"){return r.Inflate._processChunk.call(this,d,h,p)}let f=this;let g=d&&d.length;let v=this._chunkSize-this._offset;let m=this._maxLength;let w=0;let b=[];let y=0;let _;this.on("error",function(A){_=A});function T(A,I){if(f._hadError){return}let E=v-I;t(E>=0,"have should not go down");if(E>0){let k=f._buffer.slice(f._offset,f._offset+E);f._offset+=E;if(k.length>m){k=k.slice(0,m)}b.push(k);y+=k.length;m-=k.length;if(m===0){return false}}if(I===0||f._offset>=f._chunkSize){v=f._chunkSize;f._offset=0;f._buffer=Buffer.allocUnsafe(f._chunkSize)}if(I===0){w+=g-A;g=A;return true}return false}t(this._handle,"zlib binding closed");let $;do{$=this._handle.writeSync(h,d,w,g,this._buffer,this._offset,v);$=$||this._writeState}while(!this._hadError&&T($[0],$[1]));if(this._hadError){throw _}if(y>=o){c(this);throw new RangeError("Cannot create final Buffer. It would be larger than 0x"+o.toString(16)+" bytes")}let x=Buffer.concat(b,y);c(this);return x};i.inherits(s,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 p=d._finishFlushFlag;if(p==null){p=r.Z_FINISH}return d._processChunk(h,p)}function u(d,h){return l(new s(h),d)}n.exports=e=u;e.Inflate=s;e.createInflate=a;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 s=new n(r);let a=new t(i,{read:s.read.bind(s),write:function(c){o.push(c)},complete:function(){}});a.start();s.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 s=require_filter_parse_sync();var a=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 p(M){h=M}let f;function g(M){f=M}function v(M){f.transColor=M}function m(M){f.palette=M}function w(){f.alpha=true}let b;function y(M){b=M}let _=[];function T(M){_.push(M)}let $=new o(u);let x=new a(d,{read:$.read.bind($),error:p,metadata:g,gamma:y,palette:m,transColor:v,inflateData:T,simpleTransparency:w});x.start();$.process();if(h){throw h}let A=Buffer.concat(_);_.length=0;let I;if(f.interlace){I=r.inflateSync(A)}else{let M=(f.width*f.bpp*f.depth+7>>3)+1;let D=M*f.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=s.process(I,f);A=null;let k=c.dataToBitMap(E,f);E=null;let S=l(k,f,d.skipRescale);f.data=S;f.gamma=b||0;return f}}});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(s,a){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=a||{};let l=new o(c);let u=[];u.push(Buffer.from(i.PNG_SIGNATURE));u.push(l.packIHDR(s.width,s.height));if(s.gamma){u.push(l.packGAMA(s.gamma))}let d=l.filterData(s.data,s.width,s.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 s=e.PNG=function(a){t.call(this);a=a||{};this.width=a.width|0;this.height=a.height|0;this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null;if(a.fill&&this.data){this.data.fill(0)}this.gamma=0;this.readable=this.writable=true;this._parser=new r(a);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(a);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(s,t);s.sync=o;s.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};s.prototype.parse=function(a,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(a);return this};s.prototype.write=function(a){this._parser.write(a);return true};s.prototype.end=function(a){this._parser.end(a)};s.prototype._metadata=function(a){this.width=a.width;this.height=a.height;this.emit("metadata",a)};s.prototype._gamma=function(a){this.gamma=a};s.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable){this.emit("close")}};s.bitblt=function(a,c,l,u,d,h,p,f){l|=0;u|=0;d|=0;h|=0;p|=0;f|=0;if(l>a.width||u>a.height||l+d>a.width||u+h>a.height){throw new Error("bitblt reading outside image")}if(p>c.width||f>c.height||p+d>c.width||f+h>c.height){throw new Error("bitblt writing outside image")}for(let g=0;g<h;g++){a.data.copy(c.data,(f+g)*c.width+p<<2,(u+g)*a.width+l<<2,(u+g)*a.width+l+d<<2)}};s.prototype.bitblt=function(a,c,l,u,d,h,p){s.bitblt(this,a,c,l,u,d,h,p);return this};s.adjustGamma=function(a){if(a.gamma){for(let c=0;c<a.height;c++){for(let l=0;l<a.width;l++){let u=a.width*c+l<<2;for(let d=0;d<3;d++){let h=a.data[u+d]/255;h=Math.pow(h,1/2.2/a.gamma);a.data[u+d]=Math.round(h*255)}}}a.gamma=0}};s.prototype.adjustGamma=function(){s.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_crypto4;var init_profiles=__esm({"../sim-farm/src/profiles.ts"(){"use strict";import_node_crypto4=require("crypto")}});function run(e,n,t={}){const{timeoutMs:r=3e4,maxBytes:i=4*1024*1024}=t;return new Promise(o=>{const s=(0,import_node_child_process3.spawn)(e,n,{env:t.env??process.env,stdio:[t.input==null?"ignore":"pipe","pipe","pipe"]});liveChildren.add(s);let a="";let c="";let l=false;s.stdout.on("data",d=>{if(a.length<i)a+=d.toString("utf8")});s.stderr.on("data",d=>{if(c.length<i)c+=d.toString("utf8")});if(t.input!=null)s.stdin.end(t.input);const u=setTimeout(()=>{l=true;s.kill("SIGTERM");setTimeout(()=>s.kill("SIGKILL"),2e3).unref?.()},r);s.on("error",d=>{liveChildren.delete(s);clearTimeout(u);o({code:null,stdout:a,stderr:c+String(d),timedOut:l})});s.on("close",d=>{liveChildren.delete(s);clearTimeout(u);o({code:d,stdout:a,stderr:c,timedOut:l})})})}async function pidStart(e){const n=await run("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,t=false){if(!Number.isInteger(e)||e<=0)return false;try{process.kill(e,0)}catch(i){if(i.code!=="EPERM")return false}if(!n)return true;const r=await pidStart(e);if(r===null)return t;return r===n}function bootEnv(e=process.env){return Object.fromEntries(Object.entries(e).filter(([n])=>!n.startsWith("SIMCTL_CHILD_")))}var import_node_child_process3,liveChildren,sleep;var init_proc=__esm({"../sim-farm/src/proc.ts"(){"use strict";import_node_child_process3=require("child_process");liveChildren=new Set;sleep=e=>new Promise(n=>setTimeout(n,e))}});var import_node_fs4,import_node_path5,import_node_crypto5,DISABLED_STORE_ROOT;var init_disabledStore=__esm({"../sim-farm/src/disabledStore.ts"(){"use strict";import_node_fs4=require("fs");import_node_path5=__toESM(require("path"));import_node_crypto5=require("crypto");init_proc();DISABLED_STORE_ROOT=process.env.BUOY_FARM_DISABLED_ROOT||"/private/var/tmp"}});async function findDataContainer(e,n){const t=import_node_path6.default.join(e,"Containers/Data/Application");let r;try{r=await import_node_fs5.promises.readdir(t)}catch{return null}for(const i of r){const o=import_node_path6.default.join(t,i,".com.apple.mobile_container_manager.metadata.plist");if(!(0,import_node_fs5.existsSync)(o))continue;const s=await run("plutil",["-extract","MCMMetadataIdentifier","raw","-o","-",o],{timeoutMs:5e3});if(s.code===0&&s.stdout.trim()===n)return import_node_path6.default.join(t,i)}return null}async function readBuoyInstallId(e){let n;try{n=await import_node_fs5.promises.readFile(import_node_path6.default.join(e,"Documents/react-buoy/@react_buoy_sync_device_id.json"),"utf8")}catch{return null}try{const t=JSON.parse(n);if(typeof t==="string")return t||null;if(typeof t?.value==="string")return t.value||null}catch{}return n.trim()||null}var import_node_fs5,import_node_path6,import_node_crypto6;var init_seed=__esm({"../sim-farm/src/seed.ts"(){"use strict";import_node_fs5=require("fs");import_node_path6=__toESM(require("path"));import_node_crypto6=require("crypto");init_proc()}});var KEEP_MS;var init_meter=__esm({"../sim-farm/src/meter.ts"(){"use strict";KEEP_MS=2*60*6e4}});var init_phoneProfileSource_generated=__esm({"../sim-farm/src/phoneProfileSource.generated.ts"(){"use strict"}});function farmHome(){return process.env.BUOY_FARM_HOME||import_node_path7.default.join(import_node_os5.default.homedir(),".buoy","farm")}function phoneDir(e=farmHome()){return import_node_path7.default.join(e,"phone")}function joinInsertList(...e){const n=new Set;const t=[];for(const r of e){for(const i of(r??"").split(":")){const o=i.trim();if(o&&!n.has(o)){n.add(o);t.push(o)}}}return t.join(":")}function launchFilePath(e,n=farmHome()){if(!/^[0-9A-F-]{36}$/i.test(e))throw new Error(`not a UDID: ${e}`);return import_node_path7.default.join(phoneDir(n),`${e}.launch.json`)}async function readLaunchFile(e,n=farmHome()){try{const t=JSON.parse(await import_node_fs6.promises.readFile(launchFilePath(e,n),"utf8"));if(t?.udid!==e||typeof t.dylib!=="string"||!t.vars||typeof t.vars!=="object")return null;await import_node_fs6.promises.access(t.dylib);return t}catch{return null}}async function simWideInsertList(e){try{const{stdout:n}=await execFileAsync3("xcrun",["simctl","spawn",e,"launchctl","getenv","DYLD_INSERT_LIBRARIES"],{timeout:1e4});return n.trim()}catch{return""}}async function simLaunchEnv(e,n,t,r=farmHome(),i=simWideInsertList){const o=await readLaunchFile(e,r);if(!o||o.bundleId!==n){return t?{SIMCTL_CHILD_DYLD_INSERT_LIBRARIES:joinInsertList(process.env.SIMCTL_CHILD_DYLD_INSERT_LIBRARIES,await i(e),t)}:{}}const s={};for(const[a,c]of Object.entries(o.vars))s[`SIMCTL_CHILD_${a}`]=c;s.SIMCTL_CHILD_DYLD_INSERT_LIBRARIES=joinInsertList(process.env.SIMCTL_CHILD_DYLD_INSERT_LIBRARIES,await i(e),t,o.dylib);return s}var import_node_child_process4,import_node_fs6,import_node_os5,import_node_path7,import_node_util3,execFileAsync3;var init_phoneProfile=__esm({"../sim-farm/src/phoneProfile.ts"(){"use strict";import_node_child_process4=require("child_process");import_node_fs6=require("fs");import_node_os5=__toESM(require("os"));import_node_path7=__toESM(require("path"));import_node_util3=require("util");init_phoneProfileSource_generated();execFileAsync3=(0,import_node_util3.promisify)(import_node_child_process4.execFile)}});var import_node_fs7,import_node_path8,import_node_async_hooks2,import_node_crypto7,GB,PHONE_RETRY_MS;var init_engine=__esm({"../sim-farm/src/engine.ts"(){"use strict";import_node_fs7=require("fs");import_node_path8=__toESM(require("path"));import_node_async_hooks2=require("async_hooks");import_node_crypto7=require("crypto");init_disabledStore();init_profiles();init_proc();init_seed();init_meter();init_phoneProfile();init_types();GB=1024**3;PHONE_RETRY_MS=10*6e4}});var import_node_fs8,import_node_os6,import_node_path9;var init_host=__esm({"../sim-farm/src/host.ts"(){"use strict";import_node_fs8=require("fs");import_node_os6=__toESM(require("os"));import_node_path9=__toESM(require("path"));init_disabledStore();init_meter();init_proc()}});function farmHome2(){return process.env.BUOY_FARM_HOME||import_node_path10.default.join(import_node_os7.default.homedir(),".buoy","farm")}function ensureHome(e=farmHome2()){(0,import_node_fs9.mkdirSync)(e,{recursive:true,mode:448});try{(0,import_node_fs9.chmodSync)(e,448)}catch{}}function readOrCreateToken(e=farmHome2()){const n=paths(e).token;try{const t=(0,import_node_fs9.readFileSync)(n,"utf8").trim();if(t)return t}catch{}ensureHome(e);try{(0,import_node_fs9.writeFileSync)(n,(0,import_node_crypto8.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_fs9.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=farmHome2()){try{return JSON.parse(await import_node_fs9.promises.readFile(paths(e).lockOwner,"utf8"))}catch{return null}}async function ownerAlive(e){return!!e&&await pidAlive(e.pid,e.start,true)}var import_node_fs9,import_node_os7,import_node_path10,import_node_crypto8,paths;var init_store=__esm({"../sim-farm/src/store.ts"(){"use strict";import_node_fs9=require("fs");import_node_os7=__toESM(require("os"));import_node_path10=__toESM(require("path"));import_node_crypto8=require("crypto");init_proc();init_types();paths=(e=farmHome2())=>({home:e,lock:import_node_path10.default.join(e,"owner.lock"),lockOwner:import_node_path10.default.join(e,"owner.lock","owner.json"),socket:import_node_path10.default.join(e,"farmd.sock"),token:import_node_path10.default.join(e,"token"),state:import_node_path10.default.join(e,"state.json"),journal:import_node_path10.default.join(e,"journal.ndjson"),log:import_node_path10.default.join(e,"farmd.log"),shots:import_node_path10.default.join(e,"shots")})}});var import_node_net,import_node_fs10,import_node_crypto9;var init_server=__esm({"../sim-farm/src/server.ts"(){"use strict";import_node_net=__toESM(require("net"));import_node_fs10=require("fs");import_node_crypto9=require("crypto");init_engine();init_host();init_store();init_types();init_proc()}});function nodeLauncher(e,n=["farmd"]){return()=>{const t=(0,import_node_child_process5.spawn)(process.execPath,[...process.execArgv,e,...n],{detached:true,stdio:"ignore",env:bootEnv()});t.unref()}}async function connectFarm(e){return new FarmClient(e).connect()}var import_node_net2,import_node_fs11,import_node_child_process5,import_node_crypto10,FarmClient;var init_client=__esm({"../sim-farm/src/client.ts"(){"use strict";import_node_net2=__toESM(require("net"));import_node_fs11=require("fs");import_node_child_process5=require("child_process");import_node_crypto10=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??farmHome2();this.clientIdValue=`c-${(0,import_node_crypto10.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,...this.opts.agent?{agent:this.opts.agent}:{}};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 sleep(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 sleep(500);return this.connect()}}return this}tryOpen(){const e=paths(this.home).socket;if(!(0,import_node_fs11.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,s)=>{const a=setTimeout(()=>{this.pending.delete(r);s(new FarmError("HOST_ERROR",`Farm call ${e} timed out.`,void 0,true))},t.timeoutMs??3e4);this.pending.set(r,{resolve:o,reject:s,timer:a});this.sock.write(JSON.stringify(i)+"\n")})}async acquire(e){const{requestId:n,...t}=e;const r=n??`acq-${(0,import_node_crypto10.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(s=>{if(["LEASE_EXPIRED","STALE_EPOCH","RUN_STOPPED","RUN_ENDED"].includes(s.code))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",r=false){this.stopRenew(e);return this.call("release",{leaseId:e,epoch:n,reset:t,keepRun:r},{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_path11,import_node_os8,import_node_fs12;var init_discover=__esm({"../sim-farm/src/discover.ts"(){"use strict";import_node_path11=__toESM(require("path"));import_node_os8=__toESM(require("os"));import_node_fs12=require("fs");init_proc();init_seed();init_profiles()}});async function parentOf(e){const n=await run("ps",["-o","ppid=,comm=","-p",String(e)],{timeoutMs:3e3});const t=/^\s*(\d+)\s+(.+?)\s*$/.exec(n.stdout);return n.code===0&&t?{ppid:Number(t[1]),comm:t[2]}:null}async function cwdOf(e){const n=await run("lsof",["-a","-p",String(e),"-d","cwd","-Fn"],{timeoutMs:3e3});const t=n.stdout.split("\n").find(r=>r.startsWith("n"));return t?t.slice(1):null}function fromClientName(e){if(!e)return void 0;return APPS.find(n=>e.toLowerCase().includes(n.app))}async function detectAgent(e={}){const n=e.env??process.env;let t=e.pid??process.pid;let r=null;for(let u=0;u<5&&t>1;u++){const d=await parentOf(t).catch(()=>null);if(!d)break;const h=APPS.find(p=>p.match.test(d.comm));if(u>0&&h){r={app:h,pid:t};break}t=d.ppid}const i=r?.app??fromClientName(e.clientName);const o=(r?await cwdOf(r.pid).catch(()=>null):null)??process.cwd();const s=(await run("git",["-C",o,"rev-parse","--abbrev-ref","HEAD"],{timeoutMs:3e3}).catch(()=>null))?.stdout.trim();const a=n.CLAUDE_CODE_SESSION_ID?.trim();let c;let l="none";if(a&&(i?.app??"claude")==="claude"){c=`claude:${a}`;l="claude-session"}else if(r){c=`${r.app.app}:${r.pid}:${await pidStart(r.pid)??""}`;l="parent-process"}return{app:i?.app??"other",appName:i?.name??(e.clientName||"Agent"),chatKey:c,chatKeySource:l,project:import_node_path12.default.basename(o)||void 0,projectPath:o,branch:s&&s!=="HEAD"?s:void 0,clientName:e.clientName}}function agentLabel(e){return e.project?`${e.appName} \xB7 ${e.project}`:e.appName}var import_node_path12,APPS;var init_agent=__esm({"../sim-farm/src/agent.ts"(){"use strict";import_node_path12=__toESM(require("path"));init_proc();APPS=[{app:"claude",name:"Claude",match:/(^|\/)claude$/i},{app:"codex",name:"Codex",match:/(^|\/)codex$/i},{app:"cursor",name:"Cursor",match:/cursor/i}]}});var import_node_child_process6,import_node_crypto11,import_node_fs13,import_node_os9,import_node_path13,import_node_util4,execFileAsync4,MB;var init_phoneMeasure=__esm({"../sim-farm/src/phoneMeasure.ts"(){"use strict";import_node_child_process6=require("child_process");import_node_crypto11=require("crypto");import_node_fs13=require("fs");import_node_os9=__toESM(require("os"));import_node_path13=__toESM(require("path"));import_node_util4=require("util");init_phoneProfile();init_phoneProfileSource_generated();execFileAsync4=(0,import_node_util4.promisify)(import_node_child_process6.execFile);MB=1024*1024}});function hostAbi(){return import_node_os10.default.arch()==="arm64"?"arm64-v8a":"x86_64"}var import_node_crypto12,import_node_fs14,import_node_os10,import_node_path14,import_node_stream,import_promises,DEFAULT_IMAGE;var init_sdk=__esm({"../sim-farm/src/android/sdk.ts"(){"use strict";import_node_crypto12=require("crypto");import_node_fs14=require("fs");import_node_os10=__toESM(require("os"));import_node_path14=__toESM(require("path"));import_node_stream=require("stream");import_promises=require("stream/promises");init_proc();DEFAULT_IMAGE={api:36,tag:"aosp_atd",abi:hostAbi()}}});var import_node_fs15,import_node_path15;var init_phones=__esm({"../sim-farm/src/android/phones.ts"(){"use strict";import_node_fs15=require("fs");import_node_path15=__toESM(require("path"))}});var import_node_child_process7,import_node_crypto13,import_node_fs16,import_node_net3,import_node_os11,import_node_path16,ANDROID_ADB_PORT;var init_farm=__esm({"../sim-farm/src/android/farm.ts"(){"use strict";import_node_child_process7=require("child_process");import_node_crypto13=require("crypto");import_node_fs16=require("fs");import_node_net3=__toESM(require("net"));import_node_os11=__toESM(require("os"));import_node_path16=__toESM(require("path"));init_store();init_proc();init_sdk();init_phones();ANDROID_ADB_PORT=Number(process.env.BUOY_FARM_ADB_PORT)||5137}});var import_node_os12,import_node_path17;var init_command=__esm({"../sim-farm/src/android/command.ts"(){"use strict";import_node_os12=__toESM(require("os"));import_node_path17=__toESM(require("path"));init_proc();init_types();init_farm();init_sdk();init_phones()}});var import_node_path18,import_node_fs17,import_node_os13,farmHelp,HELP;var init_command2=__esm({"../sim-farm/src/command.ts"(){"use strict";import_node_path18=__toESM(require("path"));import_node_fs17=require("fs");import_node_os13=__toESM(require("os"));init_client();init_server();init_host();init_types();init_profiles();init_seed();init_store();init_discover();init_phoneProfile();init_phoneMeasure();init_command();farmHelp=e=>`Usage: ${e} <command>
2
2
 
3
3
  status [--outside] Pool, budgets, sims, leases, recent events
4
4
  setup [options] Make a template (the sim clones are made from)
@@ -27,21 +27,23 @@
27
27
  phone measure [--device <udid>]
28
28
  Read the iPhone plugged into this Mac and add it
29
29
  doctor Check Xcode, disk, memory, the farm service
30
+ android <command> Slim Android phones from one snapshot
31
+ (see: android help)
30
32
  stop [--now] Stop the farm service and park free sims
31
33
  --now Stop even if leases are still held
32
34
  farmd Run the farm service in this process
33
- `;HELP=farmHelp("pnpm farm")}});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();init_agent();init_command();init_meter();init_seed();init_proc();init_phoneProfile();init_phoneMeasure();init_phoneProfile()}});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 s=o.match(/^\s*(?:export\s+)?([A-Z_][A-Z_0-9]*)\s*=\s*(.*)$/);if(!s)continue;const a=s[2].trim();const c=a.match(/^(['"])(.*?)\1\s*(?:#.*)?$/);i.set(s[1],c?c[2]:a.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 a=(0,import_headless.checkDevToken)(e);if(!a.ok){this.cache=null;this.removeCache()}else{const c=Math.min(Date.now(),a.claims.iat*1e3);const l=a.claims.tier==="free"?"free":"pro";this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`dev:${a.claims.sid}`,valid:true,tier:l,isPro:l==="pro",expiresAt:new Date(a.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 a=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(!a.ok){if(a.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=a.claims.exp*1e3;this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`service:${a.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 a=(0,import_headless.verifyFreeToken)(e);if(!a){this.cache=null;this.removeCache()}else{const c=Date.now();this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`token:${a.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 s=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:s,lastValidatedAt:s});this.persistCache();this.retry=0;this.nextCheck=s+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(a=>a.trim()).find(Boolean);if(!i)return null;const{stdout:o}=await execFileAsync("lsof",["-a","-p",i,"-d","cwd","-Fn"],{timeout:3e3});const s=o.split("\n").find(a=>a.startsWith("n"));return s?import_node_path2.default.resolve(s.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(s=>({deviceId:s.deviceId,score:s.root?closeness(import_node_path2.default.resolve(s.root),t):-1})).filter(s=>s.score>=0);if(r.length===0)return null;const i=Math.min(...r.map(s=>s.score));const o=r.filter(s=>s.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}var import_node_async_hooks=require("async_hooks");var FREE_TOOLS={list_devices:null,list_tool_actions:null,camera_diagnose:null,describe_screen:e=>e.includeBuoy?"includeBuoy":null,tap_element:e=>e.includeBuoy?"includeBuoy":null,native_tap:e=>e.allowBuoy?"allowBuoy":null,native_type:null,native_swipe:e=>e.allowBuoy?"allowBuoy":null,native_pinch:e=>e.allowBuoy?"allowBuoy":null,native_inspect:null,run_flow:null,screenshot_component:null,screen_recording:null,device_control:null,reload_app:null,navigate:null,get_routes:null,get_console:null,get_network_requests:e=>e.includeBodies?"includeBodies":null,get_triage:null,run_benchmark_batch:null,wait_for_automation:null,get_automation_status:null,get_batch_report:null,compare_reports:null,get_benchmark_settings:null,set_benchmark_settings:null,get_js_thread_top:null,run_web_benchmark:e=>e.traceDir?"traceDir":null,find_web_ceiling:null,screenshot_web_variants:null,start_optimize_session:null,sim_farm_status:null,sim_farm_setup:null,sim_farm_acquire:null,sim_farm_release:null,sim_farm_action:null,sim_farm_lock:null,sim_farm_report:null,sim_farm_extend:null,sim_farm_finish:null};var FREE_APP_CALLS={"highlight-updates":["describeScreen","tapElement","hitTest","readMaps","setSilentTracking"],"route-events":["@snapshot","getCurrentRoute","navigate"],app:["@snapshot","ping","reloadApp"],console:["@snapshot"],network:["@snapshot"],storage:["async.getAllKeys","secure.keys"],"perf-monitor":["@snapshot","getAutomationConfig","setAutomationConfig","acknowledgeAutomation","setEnabled","refreshIndex","startAutomation","loadReport"],"js-top":["sample"]};function isFreeAppCall(e,n){return Object.prototype.hasOwnProperty.call(FREE_APP_CALLS,e)&&FREE_APP_CALLS[e].includes(n)}var clock=()=>new Date;function isWeekendPass(e=clock()){const n=e.getDay();return n===0||n===6}function accessFor(e,n){const t=isWeekendPass();if(!Object.prototype.hasOwnProperty.call(FREE_TOOLS,e))return{tool:e,level:"pro",weekend:t};const r=FREE_TOOLS[e];const i=r?r(n&&typeof n==="object"?n:{}):null;return i?{tool:e,level:"pro",proOption:i,weekend:t}:{tool:e,level:"free",weekend:t}}function weekendNow(){return scope.getStore()?.weekend??isWeekendPass()}function hasProAccess(e){if(!e)return false;if(e.isPro===true)return true;return e.tier==="free"&&weekendNow()}function freeToolNames(){return Object.keys(FREE_TOOLS).sort()}var scope=new import_node_async_hooks.AsyncLocalStorage;function runWithAccess(e,n){return scope.run(Object.freeze({...e}),n)}function outsideCalls(e){return scope.exit(e)}function currentAccess(){return scope.getStore()??{tool:"",level:"pro"}}function meetsAccess(e,n){if(!e)return false;if(hasProAccess(e))return true;return n==="free"&&e.tier==="free"}var FREE_SUMMARY="Free covers reading the screen, taps, swipes and typing, run_flow, screenshots, screen recording, device_control, reload_app, navigate, get_routes, get_console, the request list and get_triage. It also covers Buoy Optimize and the Sim Farm: benchmark batches, reports, web benchmarks and JS thread totals, without the render names, script names and JS origins that say why. Every Saturday and Sunday a free account gets everything Pro does.";function proRequiredMessage(e,n){const t=e.proOption?`\`${e.tool}\` with \`${e.proOption}\` needs Buoy Pro.`:e.tool?`\`${e.tool}\` needs Buoy Pro.`:"This needs Buoy Pro.";return`${t}${n} ${FREE_SUMMARY} Tell the user Pro unlocks the rest (https://buoy.gg/pricing). To add a license, enter it in the app, or pass \`licenseKey\` to \`<FloatingDevTools />\` for an app with no on-device UI. No setting, argument or other tool turns Pro on, so don't try to work around it.`}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 WAIT_FOR_MAX_MS=3e4;var WAIT_FOR_MARGIN_MS=5e3;function selfTimedBudgetMs(e,n,t){if(e!=="highlight-updates"||n!=="waitFor")return 0;const r=Number(t?.timeoutMs);if(!Number.isFinite(r)||r<=0)return 0;return Math.min(r,WAIT_FOR_MAX_MS)+WAIT_FOR_MARGIN_MS}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.transportLost=false;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}
34
- `));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 outsideCalls(()=>new Promise((e,n)=>{const t=(0,import_socket.io)(this.url,{transports:["websocket"],query:{deviceName:DASHBOARD_NAME},auth:a=>{const c=this.broker?.dashboardToken??(0,import_sync_broker2.readBrokerToken)((0,import_sync_broker2.brokerTokenPath)(this.port));a(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",a=>{const c=!!a&&typeof a==="object"&&a.protocol===1&&a.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 s=a=>a.message===import_sync_broker2.DASHBOARD_TOKEN_REQUIRED;t.once("connect_error",a=>{if(r)return;r=true;clearTimeout(o);n(new Error(s(a)?`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}: ${a.message}`))});t.on("connect_error",a=>{if(!s(a)||t.active)return;setTimeout(()=>{if(this.socket===t&&!t.connected)t.connect()},1e3).unref?.()});t.on("devtool-capabilities",a=>{if(!this.admitted||this.lockedDevices.has(a.persistentDeviceId))return;this.capabilities.set(a.persistentDeviceId,a);this.trackRootLookup(this.learnDevServerOrigin(a.persistentDeviceId));if(a.tools?.some(c=>c.toolId==="console"))this.ensureWatching("console",a.persistentDeviceId)});t.on("all-devices-update",a=>{if(!this.admitted)return;if(!Array.isArray(a))return;let c=false;for(const u of a){if(u.deviceId&&(u.tier==="locked"||u.tier==="checking"))this.lockDevice(String(u.deviceId),u.tier==="checking");else if(u.deviceId&&(u.tier==="free"||u.tier==="pro")){c=this.lockedDevices.delete(String(u.deviceId))||c}}this.devices=a;const l=Date.now();for(const u of a)if(u.deviceId)this.lastSeen.set(u.deviceId,l);this.pruneStaleDevices();if(c)this.rearmWatches();else this.rearmReconnectedDevices(a)});t.on("devtool-sync",a=>{if(!this.admitted||this.lockedDevices.has(a.persistentDeviceId))return;const c=snapKey(a.persistentDeviceId,a.toolId);this.snapshots.set(c,a.payload);this.snapshotAt.set(c,Date.now());if(a.toolId==="console")this.noteCrashReport(a.persistentDeviceId,a.payload);const l=this.snapshotWaiters.get(c);if(l&&l.length){this.snapshotWaiters.set(c,[]);for(const u of l)u(a.payload)}});t.on("devtool-action-result",a=>{if(!this.admitted)return;const c=this.pendingActions.get(a.requestId);if(!c)return;this.pendingActions.delete(a.requestId);clearTimeout(c.timer);c.resolve(a)})}))}isAdmitted(){return this.admitted}requireAdmission(){if(this.transportLost)throw new Error("The broker link was lost. Wait for it to reconnect.");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.transportLost=!e&&n;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(n?"The broker link was lost during the call. Its result is unknown.":"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.devices.some(n=>n.deviceId===e&&n.tier==="checking"))throw new Error(`${NOT_READY_MARK} The new app link is still checking access.`);if(this.lockedDevices.has(e))throw new Error("The device's Buoy account access ended. Sign in and verify its key.")}lockDevice(e,n=false){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 t=`${e}::`;for(const r of this.snapshots.keys())if(r.startsWith(t)){this.snapshots.delete(r);this.snapshotAt.delete(r)}for(const[r,i]of this.snapshotWaiters)if(r.startsWith(t)){this.snapshotWaiters.delete(r);for(const o of i)o(void 0)}for(const[r,i]of this.pendingActions)if(i.target===e||i.target===ALL_DEVICES){clearTimeout(i.timer);this.pendingActions.delete(r);i.reject(new Error(n?"The app link changed during the call. Its result is unknown.":"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==="checking"?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 s=pickByProject(i.map(l=>({deviceId:l.deviceId,root:this.devServerRoots.get(l.deviceId)})),o);if(s)return this.sessionDevice=s;const a=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(a)throw n(a,"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();const n=currentAccess();if(e&&e!==ALL_DEVICES)this.sessionDevice=e;const t=s=>{if(!s)return"";return s.tier==="locked"?` The broker has not confirmed account access for "${s.deviceName}"; a locked status does not establish whether a key is configured.`:` The connected app "${s.deviceName}" is on the ${s.tier} tier.`};const r=s=>n.level==="pro"?proRequiredMessage(n,t(s)):`The Buoy MCP needs an app on a Buoy account.${t(s)} Run \`npx buoy login\` in the project (free), restart the dev server with its cache cleared, then run \`list_devices\` to check.`;if(e===ALL_DEVICES){const s=this.connectedDevices().filter(c=>c.isPro||c.tier==="free");const a=s.find(c=>!meetsAccess(c,n.level));if(s.length===0)throw new Error(r());if(a)throw new Error(r(a));return ALL_DEVICES}const i=this.resolveDevice(e);const o=this.connectedDevices().find(s=>s.deviceId===i);if(!meetsAccess(o,n.level)){const s=this.accessState(i,n.level);if(s==="offline")throw new Error(`${NOT_READY_MARK} "${i}" is not connected right now. If the app is starting or reloading, it usually takes a few seconds. Run list_devices to check.`);if(s==="pending")throw new Error(`${NOT_READY_MARK} account access for "${i}" is still being confirmed (the app just connected). Try again in a moment.`);throw new Error(r(o))}return i}checkAppCall(e,n,t){const r=currentAccess();if(!r.tool)return;const i=t===ALL_DEVICES?this.connectedDevices().find(o=>o.tier==="free"&&!hasProAccess(o)):this.listDevices().find(o=>o.deviceId===t&&!hasProAccess(o));if(!i)return;if(r.level==="free"&&isFreeAppCall(e,n))return;throw new Error(proRequiredMessage({...r,level:"pro"},` The app "${i.deviceName}" is on the ${i.tier} tier${r.level==="free"?`, and this part of \`${r.tool}\` reads its ${e} data, which is Pro`:""}.`))}refuseBuoyPanelTap(e,n,t,r){if(e!=="highlight-updates"||n!=="tapElement")return null;const i=currentAccess();if(!i.tool||i.level!=="free")return null;const o=t??{};const s=typeof o.nativeTag==="number"?o.nativeTag:null;const a=typeof o.testID==="string"&&o.testID?o.testID.toLowerCase():null;const c=s!=null||a!=null||!!o.includeBuoy;if(r===ALL_DEVICES){if(!c||!this.connectedDevices().some(d=>d.tier==="free"&&!hasProAccess(d)))return null;return Promise.reject(new Error(proRequiredMessage({...i,level:"pro"},' On a free app, tap one app at a time (not "All") when tapping by testID or nativeTag.')))}const l=this.listDevices().find(d=>d.deviceId===r);if(!l||hasProAccess(l)||!c)return null;const u=d=>new Error(proRequiredMessage({...i,level:"pro"},d));if(o.includeBuoy)return Promise.reject(u(" That reaches Buoy's own panel, not the app."));return(async()=>{let d;try{d=await this.callAction("highlight-updates","describeScreen",{includeBuoy:false,includeHidden:true},r,{timeoutMs:4e3,silent:true})}catch(p){throw new Error(`Could not check that target before tapping (${p instanceof Error?p.message:String(p)}). On a free app, tap by query, or retry once the screen settles.`)}const h=(d?.elements??[]).some(p=>s!=null?p.nativeTag===s:p.testID?.toLowerCase()===a);if(!h&&s==null&&typeof o.query==="string"){const{testID:p,...f}=o;return f}if(!h){throw new Error(`"${s??String(o.testID)}" is not on the app's screen right now. On a free app, a tap by testID or nativeTag must hit an element describe_screen lists, and Buoy's own panels are Pro. Swipe it into view first, or tap by query.`)}})()}fullResultsFor(e){if(e===ALL_DEVICES){const n=this.connectedDevices();return n.length>0&&n.every(t=>hasProAccess(t))}return hasProAccess(this.listDevices().find(n=>n.deviceId===e))}deviceWasAllowed(e){return meetsAccess(this.listDevices().find(n=>n.deviceId===e),currentAccess().level)}accessState(e,n=currentAccess().level){const t=this.devices.find(r=>r.deviceId===e);if(!t||t.isConnected===false)return"offline";if(hasProAccess(t)||n==="free"&&t.tier==="free")return"ready";return t.tier===void 0||t.tier==="checking"?"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(s=>typeof s?.timestamp==="number"?s.timestamp:-Infinity));const i=this.crashSeen.get(e)??new Set;let o=false;for(const s of t){const a=s?.fatal||/^\[(RENDER ERROR|FATAL)/.test(s?.message??"");if(!a||typeof s.timestamp!=="number")continue;const c=`${s.id??""}|${s.timestamp}|${(s.message??"").slice(0,120)}`;if(i.has(c))continue;i.add(c);if(r-s.timestamp<3e4)o=true}if(i.size>200)for(const s of[...i].slice(0,i.size-200))i.delete(s);this.crashSeen.set(e,i);if(!o)return;if(![...this.pendingActions.values()].some(s=>s.target===e&&s.expire&&!s.cut))return;void this.callAction("app","ping",{},e,{timeoutMs:1500,silent:true}).then(()=>void 0,()=>{const s=Date.now();for(const a of this.pendingActions.values()){if(a.target!==e||!a.expire||a.cut)continue;a.cut=true;if(a.deadline!==void 0&&a.deadline-s<=UNRESPONSIVE_ACTION_TIMEOUT_MS)continue;clearTimeout(a.timer);a.timer=setTimeout(a.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:s}of this.watching.values()){if(s===t)this.sendWatch(o,s)}}}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);this.checkAppCall(e,"@snapshot",n);return this.snapshots.get(snapKey(n,e))}async getSnapshot(e,n,t={}){const r=this.resolveDevice(n);this.checkAppCall(e,"@snapshot",r);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 s=this.waitForSnapshot(i,o);this.socket?.emit("request-devtool-state",{toolId:e,targetDeviceId:r});const a=await s;this.requireAdmission();this.requireDeviceAccount(r);if(a!==void 0){if(!t.silent)this.noteOk(r);return{deviceId:r,payload:a}}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){this.checkAppCall(n,"@snapshot",e);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 s=(this.snapshotWaiters.get(e)??[]).filter(a=>a!==o);this.snapshotWaiters.set(e,s);t(void 0)},n);const o=s=>{clearTimeout(i);t(s)};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);this.checkAppCall(e,n,o);const s=this.refuseBuoyPanelTap(e,n,t,o);if(s)t=await s??t;if(!this.socket)throw new Error("SyncClient is not connected");const a=(0,import_node_crypto2.randomUUID)();const c=i.timeoutMs??Math.max(this.timeoutFor(o,e,n),selfTimedBudgetMs(e,n,t));const l=await new Promise((u,d)=>{const h=Date.now();const p=()=>{this.pendingActions.delete(a);if(o!==ALL_DEVICES&&!i.silent)this.noteTimeout(o);d(new Error(`Action "${e}.${n}" got no answer in ${Date.now()-h}ms. `+(o===ALL_DEVICES?"No device responded.":this.unresponsiveNote(o))))};const f=setTimeout(p,c);this.pendingActions.set(a,{resolve:u,reject:d,timer:f,target:o,expire:p,deadline:h+c});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(!l.ok){throw new Error(l.error||`Action "${e}.${n}" failed on device`)}return l.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.71"?"7.0.71":"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(s=>Number(s)||0);const r=t(e);const i=t(n);for(let o=0;o<3;o++){const s=r[o]??0;const a=i[o]??0;if(s>a)return true;if(s<a)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 s of await listDir(import_node_path4.default.join(i,o))){const a=import_node_path4.default.join(i,o,s,"LocalStorage","localstorage.sqlite3");try{await import_node_fs3.promises.access(a);const{stdout:c}=await execFileAsync2("sqlite3",["-readonly",a,`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(s=>s.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 s of o){try{const a=(await import_node_fs3.promises.readFile(import_node_path4.default.join(i,s,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim();if(a===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 s=o&&i?.udid?n.find(c=>c.udid===i.udid):void 0;if(s)return{ok:true,udid:s.udid,how:`matched ${e} to "${s.name}" (WebView storage)`};const a=[];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))a.push(n[u])});webViewLookups.set(e,{booted:r,udid:a.length===1?a[0].udid:null,at:Date.now()})}if(a.length===1){return{ok:true,udid:a[0].udid,how:`matched ${e} to "${a[0].name}" (WebView storage)`}}if(a.length>1){return{ok:false,error:`${a.length} booted simulators (${a.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(([s])=>/iOS/.test(s)).flatMap(([,s])=>s.filter(a=>a.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 s=[];try{s=await import_node_fs3.promises.readdir(o)}catch{continue}for(const a of s){try{const c=(await import_node_fs3.promises.readFile(import_node_path4.default.join(o,a,"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 s=clamp(Math.round(t.height),1,n.height-i);const a=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(s),String(o),"--cropOffset",String(i),String(r),e,"--out",a],{timeout:1e4});const c=await import_node_fs3.promises.readFile(a);return{ok:true,buffer:c,width:o,height:s}}catch(c){const l=c;return{ok:false,error:`Crop failed: ${l?.stderr||l?.message||c}`}}finally{await import_node_fs3.promises.unlink(a).catch(()=>{});await import_node_fs3.promises.unlink(e).catch(()=>{})}}var import_node_child_process11=require("child_process");var import_node_util9=require("util");var import_node_child_process10=require("child_process");var import_node_util8=require("util");var import_node_fs17=require("fs");var import_node_os12=__toESM(require("os"));var import_node_path17=__toESM(require("path"));var import_node_crypto13=require("crypto");var import_pngjs2=__toESM(require_png());init_src();var import_node_child_process7=require("child_process");var import_node_util5=require("util");var import_node_fs15=require("fs");var import_node_os11=__toESM(require("os"));var import_node_path15=__toESM(require("path"));var import_node_crypto12=require("crypto");var import_pngjs=__toESM(require_png());var execFileAsync5=(0,import_node_util5.promisify)(import_node_child_process7.execFile);async function devicectl(e,n=3e4){const t=import_node_path15.default.join(import_node_os11.default.tmpdir(),`buoy-devicectl-${(0,import_node_crypto12.randomUUID)()}.json`);try{await execFileAsync5("xcrun",["devicectl",...e,"--quiet","--json-output",t],{timeout:n,maxBuffer:16*1024*1024});return JSON.parse(await import_node_fs15.promises.readFile(t,"utf8"))}catch(r){const i=r;let o=(i.stderr||i.stdout||i.message||"").trim();try{const s=JSON.parse(await import_node_fs15.promises.readFile(t,"utf8"));o=s.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_fs15.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(s=>s.relativePath??s.name??""));if(!i.has(t))return null;const o=import_node_path15.default.join(import_node_os11.default.tmpdir(),`buoy-devfile-${(0,import_node_crypto12.randomUUID)()}`);try{await devicectl(["device","copy","from","--device",e,"--domain-type","appDataContainer","--domain-identifier",n,"--source",t,"--destination",o],2e4);return await import_node_fs15.promises.readFile(o)}finally{await import_node_fs15.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_path15.default.join(import_node_os11.default.tmpdir(),`buoy-phone-shot-${(0,import_node_crypto12.randomUUID)()}.png`);try{await devicectl(["device","capture","screenshot","--device",e,"--destination",n],3e4);return await import_node_fs15.promises.readFile(n)}finally{await import_node_fs15.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(s=>s.bundleId===n)?.path;const i=await devicectl(["device","info","processes","--device",e]);const o=(i.result?.runningProcesses??[]).find(s=>r&&decodeURIComponent(s.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_process9=require("child_process");var import_node_util7=require("util");var import_node_fs16=require("fs");var import_node_path16=__toESM(require("path"));var import_ws=require("ws");var import_node_child_process8=require("child_process");var import_node_util6=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,s)=>{const a=n[`BUOY_SECRET_${s}`]??n[s];if(a===void 0||a===""){t.push(s);return""}if(a.length<MIN_SECRET_LENGTH){r.push(s);return""}used.set(s,a);return a});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 s of[o,JSON.stringify(o).slice(1,-1),encodeURIComponent(o)])n.set(s,i);for(let s=o.length-1;s>=MIN_SECRET_LENGTH;s--){n.set(`${o.slice(0,s)}\u2026`,i);n.set(`${o.slice(0,s)}...`,i);if(s>=8)n.set(o.slice(0,s),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,s)=>{if(/^\d+$/.test(i)){const a=s.slice(Math.max(0,o-8),o);const c=s.slice(o+i.length,o+i.length+8);if(/(\d|\d\.)$/.test(a)||/^(\d|\.\d|[eE][+-]?\d)/.test(c))return i;if(/[:[,]\s*$/.test(a)&&/^\s*([,\]}]|$)/.test(c)&&!insideJsonString(s,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 execFileAsync6=(0,import_node_util6.promisify)(import_node_child_process8.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 execFileAsync6("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 s=n[0]==="shell"?i.stderr||(i.killed?"timed out":"no error text"):i.stderr||i.message||"";const a=scrubSecrets(s.replace(/'[^']*'/g,"'\u2026'")).trim().slice(0,300);throw new Error(`adb ${o} failed: ${a}`)}}function adbShell(e,n,t=15e3){return adb(e,["shell",n],t)}async function adbBytes(e,n,t=15e3){try{const{stdout:r}=await execFileAsync6("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,s,a,c]=i.slice(1).map(Number);if(a>o&&c>s)return{x:o,y:s,width:a-o,height:c-s}}}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[s,a,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:s,y:a,width:c-s,height:l-a}})}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 s=i.filter(c=>r(c)===o);let a=s.filter((c,l)=>s.findIndex(u=>JSON.stringify(u.bounds)===JSON.stringify(c.bounds))===l);if(a.length>1){const c=a.filter(l=>[l.desc,l.text,l.id.split("/").pop()??""].some(u=>u.trim()===n.trim()));if(c.length)a=c}if(a.length>1){const c=a.filter(l=>l.clickable||/EditText|Button/.test(l.cls));if(c.length)a=c}return a}var execFileAsync7=(0,import_node_util7.promisify)(import_node_child_process9.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_fs16.promises.readdir(e).catch(()=>[])}async function containerLocalStorageFiles(e){const n=[];const t=import_node_path16.default.join(e,"Library","WebKit");for(const r of await listDir2(t)){const i=import_node_path16.default.join(t,r,"WebsiteData","Default");for(const o of await listDir2(i)){for(const s of await listDir2(import_node_path16.default.join(i,o))){const a=import_node_path16.default.join(i,o,s);const c=import_node_path16.default.join(a,"LocalStorage","localstorage.sqlite3");if(!await import_node_fs16.promises.access(c).then(()=>true,()=>false))continue;const l=await import_node_fs16.promises.readFile(import_node_path16.default.join(a,"origin")).then(u=>u.toString("hex"),()=>"");if(l)n.push({db:c,origin:l})}}}return n}var sqlite=(e,n,t=true)=>execFileAsync7("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 s=o.lastIndexOf("|");if(s<0)continue;const a=o.slice(0,s);if(WEB_KEEP_KEY.test(a))n.push({key:a,value:o.slice(s+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(a=>a.origin===i):void 0;if(!o)return false;const s=n.filter(a=>(a.origin??"")===i&&/^[0-9A-F]*$/i.test(a.value)).map(a=>`('${a.key.replace(/'/g,"''")}', X'${a.value}')`).join(",");if(s)await sqlite(o.db,`INSERT OR REPLACE INTO ItemTable (key, value) VALUES ${s};`,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 s=o.find(a=>a.type==="page"&&a.webSocketDebuggerUrl);if(!s?.webSocketDebuggerUrl)throw new Error("no debuggable WebView page (needs a debug build)");return await new Promise((a,c)=>{const l=new import_ws.WebSocket(s.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 a(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(s){o=s;await new Promise(a=>setTimeout(a,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 execFileAsync8=(0,import_node_util8.promisify)(import_node_child_process10.execFile);var hosts=new Map;function rememberedHost(e){return hosts.get(e)}async function sh(e,n,t=2e4,r){try{const{stdout:i}=await execFileAsync8(e,n,{timeout:t,maxBuffer:16*1024*1024,env:r?{...process.env,...r}:void 0});return i}catch(i){const o=i;if(o.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: ${(o.stderr||o.message||"").trim().slice(0,300)}`)}}var simctl=(e,n)=>sh("xcrun",["simctl",...e],n);async function simctlLaunch(e,n){const t=await simLaunchEnv(e,n).catch(()=>({}));return sh("xcrun",["simctl","launch",e,n],void 0,t)}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(s=>s.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_path17.default.join(t,"Containers","Data","Application");let s=[];try{s=await import_node_fs17.promises.readdir(o)}catch{return null}const a=await Promise.all(s.map(c=>iosContainerHolds(import_node_path17.default.join(o,c),i,r)));for(const[c,l]of s.entries()){const u=import_node_path17.default.join(o,l);if(!a[c])continue;let d=null;try{d=(await sh("plutil",["-extract","MCMMetadataIdentifier","raw","-o","-",import_node_path17.default.join(u,".com.apple.mobile_container_manager.metadata.plist")])).trim()||null}catch{}return{container:u,bundleId:d,kind:a[c]}}return null}async function iosContainerHolds(e,n,t=["rn","webview"]){if(t.includes("rn")){try{if((await import_node_fs17.promises.readFile(import_node_path17.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 s=await adbUserPackages(i).catch(()=>[]);const a=[n.bundleId,o,...s].filter((c,l,u)=>!!c&&u.indexOf(c)===l).slice(0,80);for(const c of a){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 s=null;if(!i){const l=await simsHolding(e);s=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 a=s?.udid===i?await iosContainerHolds(s.found.container,tailOf(e),[s.found.kind])?s.found:null:await findIosContainer(e,i);if(!a)throw new Error(`Simulator ${i} does not hold "${e}".`);const c={platform:"ios",udid:i,name:o,bundleId:t.bundleId??a?.bundleId??null,container:a?.container??null,picked:!!t.udid,idKind:a.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_fs17.promises.readFile(n.srcPath)}finally{await import_node_fs17.promises.unlink(n.srcPath).catch(()=>{})}}async function toSmallImage(e,n=1280){if(process.platform==="darwin"){const i=import_node_path17.default.join(import_node_os12.default.tmpdir(),`buoy-mcp-img-${(0,import_node_crypto13.randomUUID)()}.png`);const o=i.replace(/\.png$/,".jpg");await import_node_fs17.promises.writeFile(i,e);try{await sh("sips",["-Z",String(n),"-s","format","jpeg","-s","formatOptions","70",i,"--out",o],15e3);const s=await sh("sips",["-g","pixelWidth","-g","pixelHeight",o]);return{data:(await import_node_fs17.promises.readFile(o)).toString("base64"),mimeType:"image/jpeg",width:Number(/pixelWidth:\s*(\d+)/.exec(s)?.[1]??0),height:Number(/pixelHeight:\s*(\d+)/.exec(s)?.[1]??0)}}finally{await import_node_fs17.promises.unlink(i).catch(()=>{});await import_node_fs17.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 s=e.width/r;const a=e.height/i;for(let c=0;c<i;c++){const l=Math.floor(c*a);const u=Math.max(l+1,Math.floor((c+1)*a));for(let d=0;d<r;d++){const h=Math.floor(d*s);const p=Math.max(h+1,Math.floor((d+1)*s));const f=[0,0,0,0];let g=0;for(let m=l;m<u;m++){for(let w=h;w<p;w++){const b=(m*e.width+w)*4;for(let y=0;y<4;y++)f[y]+=e.data[b+y];g++}}const v=(c*r+d)*4;for(let m=0;m<4;m++)o.data[v+m]=Math.round(f[m]/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 simctlLaunch(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_path17.default.join(e,"Info.plist");const t=s=>sh("plutil",["-extract",s,"raw","-o","-",n]).then(a=>a.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_path17.default.join(import_node_os12.default.homedir(),"Library","Android","sdk"),import_node_path17.default.join(import_node_os12.default.homedir(),"Android","Sdk")].filter(t=>!!t);for(const t of n){const r=import_node_path17.default.join(t,"build-tools");const i=(await import_node_fs17.promises.readdir(r).catch(()=>[])).sort().reverse();for(const o of i){for(const s of["aapt2","aapt"]){const a=import_node_path17.default.join(r,o,s);try{await import_node_fs17.promises.access(a)}catch{continue}const c=await sh(a,s==="aapt2"?["dump","packagename",e]:["dump","badging",e]).catch(()=>"");const l=s==="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_path17.default.resolve(n);try{await import_node_fs17.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_path17.default.basename(i)} is ${o.bundleId}, but this app is ${r}. Nothing was changed.`);if(!o.simulator)throw new Error(`${import_node_path17.default.basename(i)} is a device build, not a simulator build. Nothing was changed.`);const s=t?await import_node_fs17.promises.mkdtemp(import_node_path17.default.join(import_node_os12.default.tmpdir(),"buoy-mcp-keep-")):null;try{let a=false;let c=[];if(s){await import_node_fs17.promises.chmod(s,448);const u=(await simctl(["get_app_container",e.udid,r,"data"]).catch(()=>"")).trim();if(u)a=await copyBuoyFiles(import_node_path17.default.join(u,"Documents"),s);if(u&&!a){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_path17.default.basename(i)} failed: ${u.message}. Install it again by hand.`)}let l="";if(s&&a){try{const u=(await simctl(["get_app_container",e.udid,r,"data"])).trim();await copyBuoyFiles(s,import_node_path17.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 simctlLaunch(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 simctlLaunch(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(s)await import_node_fs17.promises.rm(s,{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_path17.default.join(e,r);try{await import_node_fs17.promises.access(i)}catch{continue}const o=import_node_path17.default.join(n,r);await import_node_fs17.promises.mkdir(import_node_path17.default.dirname(o),{recursive:true});await import_node_fs17.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_path17.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 s=[];if(r&&!o.length&&await androidHasWebViewStorage(e.serial,n)){try{s=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 a="";if(s.length){await hostLaunch(e);try{await androidWriteWebKeep(e.serial,n,s);a=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(c){a=` 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.${a}`}if(o.length){try{for(const c of o){const l=import_node_path17.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)}`)}`)}a=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(c){a=` Buoy's sign-in could not be restored (${c.message}): sign in to Buoy again in the app.`}}else if(r){a=" 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.${a}`}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_path17.default.basename(t)} is ${i.bundleId}, but this app is ${n}. Nothing was changed.`);if(i.simulator)throw new Error(`${import_node_path17.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 s=r?await import_node_fs17.promises.mkdtemp(import_node_path17.default.join(import_node_os12.default.tmpdir(),"buoy-mcp-keep-")):null;try{const a=[];if(s){await import_node_fs17.promises.chmod(s,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_path17.default.basename(l)} from the iPhone (${h.message}). Nothing was changed.`)}if(!u)continue;const d=import_node_path17.default.join(s,l.replace(/\//g,"__"));await import_node_fs17.promises.writeFile(d,u,{mode:384});a.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_path17.default.basename(t)} failed: ${l.message}. Install it again from Xcode.`)}let c="";if(a.length){try{for(const d of a)await writeAppFile(e.udid,n,d.local,d.rel);const l=a.some(d=>d.rel.includes("buoy-license"));const u=a.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(s)await import_node_fs17.promises.rm(s,{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(([a])=>/iOS/.test(a)).flatMap(([,a])=>a);const r=e.trim().toLowerCase();const i=t.filter(a=>a.udid.toLowerCase()===r||a.name.toLowerCase()===r);const o=i.length?i:t.filter(a=>a.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(a=>`${a.name} (${a.udid})`).join(", ")}. Pass the udid.`);const s=o[0];if(s.state!=="Booted"){try{await execFileAsync8("xcrun",["simctl","boot",s.udid],{timeout:12e4,env:bootEnv()})}catch(a){const c=a;throw new Error(`xcrun simctl boot failed: ${(c.stderr||c.message||"").trim().slice(0,300)}`)}}await sh("open",["-a","Simulator","--args","-CurrentDeviceUDID",s.udid]).catch(()=>void 0);return s.state==="Booted"?`${s.name} (${s.udid}) was already booted.`:`Booted ${s.name} (${s.udid}).`}var execFileAsync9=(0,import_node_util9.promisify)(import_node_child_process11.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.deviceWasAllowed(u):false;if(!r.allowOffline||!u||!d)throw c;i=u;o=false}const s=e.listDevices().find(c=>c.deviceId===i)?.platform;let a=await findHost(i,s,t);if(r.changesApp&&rememberedHost(i)===a)a=await verifyHost(i,a);return{id:i,host:a,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,execFileAsync9("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(a=>setTimeout(()=>a(void 0),3e3))]):void 0);const s=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"],...!s?{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 p=0;i.length===0&&p<10;p++){await new Promise(f=>setTimeout(f,200));i=n.listDevices()}if(i.length===0){return json({devices:[],hint:"No devices connected. Open the app with Buoy devtools running, then retry.",...r?{updateAvailable:r}:{}})}const o=t.includeDisconnected?0:i.filter(p=>!p.isConnected).length;if(!t.includeDisconnected)i=i.filter(p=>p.isConnected);if(i.length===0){return json({devices:[],hint:`No app is connected right now${o?` (${o} seen before; pass includeDisconnected:true to list them)`:""}. Open the app with Buoy devtools running, then retry.`,...r?{updateAvailable:r}:{}})}const s=await resolveSims(i.filter(p=>p.platform==="ios").map(p=>p.deviceId)).catch(()=>new Map);const a=i.filter(p=>p.isConnected);const c=a.some(p=>hasProAccess(p));const l=a.some(p=>p.tier!=="locked");const u=a.filter(p=>p.collision);const d=await Promise.all(i.map(p=>p.isConnected?hostSummary(p,s.get(p.deviceId)).catch(()=>void 0):void 0));const h=i.map((p,f)=>{const g=s.get(p.deviceId);const v=d[f];return{deviceId:p.deviceId,deviceName:p.deviceName,platform:p.platform,isConnected:p.isConnected,isPro:p.isPro,tier:p.tier,...!p.isPro&&hasProAccess(p)?{weekendPass:true}:{},access:n.accessState(p.deviceId,"free"),...g?{simulator:g}:{},...v?{host:v}:{},...p.collision?{collision:true}:{},tools:t.details?p.tools:p.tools.map(m=>m.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(p=>`"${p.deviceId}"`).join(", ")}: more than one app is registered under this id, so actions sent to it land on an arbitrary device. Give each device its own externalSync.deviceId (or leave it unset for a per-install default) before mutating anything.`}:{},...c?{}:{hint:l?`The connected app is on the free tier, so only the free MCP tools work: ${freeToolNames().join(", ")} (get_network_requests without includeBodies; get_triage without storage values). Every other tool needs Buoy Pro (https://buoy.gg/pricing). To add a license, enter it 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")}
35
+ `;HELP=farmHelp("pnpm farm")}});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();init_agent();init_command2();init_meter();init_seed();init_proc();init_phoneProfile();init_phoneMeasure();init_phoneProfile();init_farm();init_command();init_phones()}});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 s=o.match(/^\s*(?:export\s+)?([A-Z_][A-Z_0-9]*)\s*=\s*(.*)$/);if(!s)continue;const a=s[2].trim();const c=a.match(/^(['"])(.*?)\1\s*(?:#.*)?$/);i.set(s[1],c?c[2]:a.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 a=(0,import_headless.checkDevToken)(e);if(!a.ok){this.cache=null;this.removeCache()}else{const c=Math.min(Date.now(),a.claims.iat*1e3);const l=a.claims.tier==="free"?"free":"pro";this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`dev:${a.claims.sid}`,valid:true,tier:l,isPro:l==="pro",expiresAt:new Date(a.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 a=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(!a.ok){if(a.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=a.claims.exp*1e3;this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`service:${a.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 a=(0,import_headless.verifyFreeToken)(e);if(!a){this.cache=null;this.removeCache()}else{const c=Date.now();this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`token:${a.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 s=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:s,lastValidatedAt:s});this.persistCache();this.retry=0;this.nextCheck=s+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(a=>a.trim()).find(Boolean);if(!i)return null;const{stdout:o}=await execFileAsync("lsof",["-a","-p",i,"-d","cwd","-Fn"],{timeout:3e3});const s=o.split("\n").find(a=>a.startsWith("n"));return s?import_node_path2.default.resolve(s.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(s=>({deviceId:s.deviceId,score:s.root?closeness(import_node_path2.default.resolve(s.root),t):-1})).filter(s=>s.score>=0);if(r.length===0)return null;const i=Math.min(...r.map(s=>s.score));const o=r.filter(s=>s.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}var import_node_async_hooks=require("async_hooks");var FREE_TOOLS={list_devices:null,list_tool_actions:null,camera_diagnose:null,describe_screen:e=>e.includeBuoy?"includeBuoy":null,tap_element:e=>e.includeBuoy?"includeBuoy":null,native_tap:e=>e.allowBuoy?"allowBuoy":null,native_type:null,native_swipe:e=>e.allowBuoy?"allowBuoy":null,native_pinch:e=>e.allowBuoy?"allowBuoy":null,native_inspect:null,run_flow:null,screenshot_component:null,screen_recording:null,device_control:null,reload_app:null,navigate:null,get_routes:null,get_console:null,get_network_requests:e=>e.includeBodies?"includeBodies":null,get_triage:null,run_benchmark_batch:null,wait_for_automation:null,get_automation_status:null,get_batch_report:null,compare_reports:null,get_benchmark_settings:null,set_benchmark_settings:null,get_js_thread_top:null,run_web_benchmark:e=>e.traceDir?"traceDir":null,find_web_ceiling:null,screenshot_web_variants:null,start_optimize_session:null,sim_farm_status:null,sim_farm_setup:null,sim_farm_acquire:null,sim_farm_release:null,sim_farm_action:null,sim_farm_lock:null,sim_farm_report:null,sim_farm_extend:null,sim_farm_finish:null};var FREE_APP_CALLS={"highlight-updates":["describeScreen","tapElement","hitTest","readMaps","setSilentTracking"],"route-events":["@snapshot","getCurrentRoute","navigate"],app:["@snapshot","ping","reloadApp"],console:["@snapshot"],network:["@snapshot"],storage:["async.getAllKeys","secure.keys"],"perf-monitor":["@snapshot","getAutomationConfig","setAutomationConfig","acknowledgeAutomation","setEnabled","refreshIndex","startAutomation","loadReport"],"js-top":["sample"]};function isFreeAppCall(e,n){return Object.prototype.hasOwnProperty.call(FREE_APP_CALLS,e)&&FREE_APP_CALLS[e].includes(n)}var clock=()=>new Date;function isWeekendPass(e=clock()){const n=e.getDay();return n===0||n===6}function accessFor(e,n){const t=isWeekendPass();if(!Object.prototype.hasOwnProperty.call(FREE_TOOLS,e))return{tool:e,level:"pro",weekend:t};const r=FREE_TOOLS[e];const i=r?r(n&&typeof n==="object"?n:{}):null;return i?{tool:e,level:"pro",proOption:i,weekend:t}:{tool:e,level:"free",weekend:t}}function weekendNow(){return scope.getStore()?.weekend??isWeekendPass()}function hasProAccess(e){if(!e)return false;if(e.isPro===true)return true;return e.tier==="free"&&weekendNow()}function freeToolNames(){return Object.keys(FREE_TOOLS).sort()}var scope=new import_node_async_hooks.AsyncLocalStorage;function runWithAccess(e,n){return scope.run(Object.freeze({...e}),n)}function outsideCalls(e){return scope.exit(e)}function currentAccess(){return scope.getStore()??{tool:"",level:"pro"}}function meetsAccess(e,n){if(!e)return false;if(hasProAccess(e))return true;return n==="free"&&e.tier==="free"}var FREE_SUMMARY="Free covers reading the screen, taps, swipes and typing, run_flow, screenshots, screen recording, device_control, reload_app, navigate, get_routes, get_console, the request list and get_triage. It also covers Buoy Optimize and the Sim Farm: benchmark batches, reports, web benchmarks and JS thread totals, without the render names, script names and JS origins that say why. Every Saturday and Sunday a free account gets everything Pro does.";function proRequiredMessage(e,n){const t=e.proOption?`\`${e.tool}\` with \`${e.proOption}\` needs Buoy Pro.`:e.tool?`\`${e.tool}\` needs Buoy Pro.`:"This needs Buoy Pro.";return`${t}${n} ${FREE_SUMMARY} Tell the user Pro unlocks the rest (https://buoy.gg/pricing). To add a license, enter it in the app, or pass \`licenseKey\` to \`<FloatingDevTools />\` for an app with no on-device UI. No setting, argument or other tool turns Pro on, so don't try to work around it.`}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 WAIT_FOR_MAX_MS=3e4;var WAIT_FOR_MARGIN_MS=5e3;function selfTimedBudgetMs(e,n,t){if(e!=="highlight-updates"||n!=="waitFor")return 0;const r=Number(t?.timeoutMs);if(!Number.isFinite(r)||r<=0)return 0;return Math.min(r,WAIT_FOR_MAX_MS)+WAIT_FOR_MARGIN_MS}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.transportLost=false;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}
36
+ `));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 outsideCalls(()=>new Promise((e,n)=>{const t=(0,import_socket.io)(this.url,{transports:["websocket"],query:{deviceName:DASHBOARD_NAME},auth:a=>{const c=this.broker?.dashboardToken??(0,import_sync_broker2.readBrokerToken)((0,import_sync_broker2.brokerTokenPath)(this.port));a(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",a=>{const c=!!a&&typeof a==="object"&&a.protocol===1&&a.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 s=a=>a.message===import_sync_broker2.DASHBOARD_TOKEN_REQUIRED;t.once("connect_error",a=>{if(r)return;r=true;clearTimeout(o);n(new Error(s(a)?`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}: ${a.message}`))});t.on("connect_error",a=>{if(!s(a)||t.active)return;setTimeout(()=>{if(this.socket===t&&!t.connected)t.connect()},1e3).unref?.()});t.on("devtool-capabilities",a=>{if(!this.admitted||this.lockedDevices.has(a.persistentDeviceId))return;this.capabilities.set(a.persistentDeviceId,a);this.trackRootLookup(this.learnDevServerOrigin(a.persistentDeviceId));if(a.tools?.some(c=>c.toolId==="console"))this.ensureWatching("console",a.persistentDeviceId)});t.on("all-devices-update",a=>{if(!this.admitted)return;if(!Array.isArray(a))return;let c=false;for(const u of a){if(u.deviceId&&(u.tier==="locked"||u.tier==="checking"))this.lockDevice(String(u.deviceId),u.tier==="checking");else if(u.deviceId&&(u.tier==="free"||u.tier==="pro")){c=this.lockedDevices.delete(String(u.deviceId))||c}}this.devices=a;const l=Date.now();for(const u of a)if(u.deviceId)this.lastSeen.set(u.deviceId,l);this.pruneStaleDevices();if(c)this.rearmWatches();else this.rearmReconnectedDevices(a)});t.on("devtool-sync",a=>{if(!this.admitted||this.lockedDevices.has(a.persistentDeviceId))return;const c=snapKey(a.persistentDeviceId,a.toolId);this.snapshots.set(c,a.payload);this.snapshotAt.set(c,Date.now());if(a.toolId==="console")this.noteCrashReport(a.persistentDeviceId,a.payload);const l=this.snapshotWaiters.get(c);if(l&&l.length){this.snapshotWaiters.set(c,[]);for(const u of l)u(a.payload)}});t.on("devtool-action-result",a=>{if(!this.admitted)return;const c=this.pendingActions.get(a.requestId);if(!c)return;this.pendingActions.delete(a.requestId);clearTimeout(c.timer);c.resolve(a)})}))}isAdmitted(){return this.admitted}requireAdmission(){if(this.transportLost)throw new Error("The broker link was lost. Wait for it to reconnect.");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.transportLost=!e&&n;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(n?"The broker link was lost during the call. Its result is unknown.":"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.devices.some(n=>n.deviceId===e&&n.tier==="checking"))throw new Error(`${NOT_READY_MARK} The new app link is still checking access.`);if(this.lockedDevices.has(e))throw new Error("The device's Buoy account access ended. Sign in and verify its key.")}lockDevice(e,n=false){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 t=`${e}::`;for(const r of this.snapshots.keys())if(r.startsWith(t)){this.snapshots.delete(r);this.snapshotAt.delete(r)}for(const[r,i]of this.snapshotWaiters)if(r.startsWith(t)){this.snapshotWaiters.delete(r);for(const o of i)o(void 0)}for(const[r,i]of this.pendingActions)if(i.target===e||i.target===ALL_DEVICES){clearTimeout(i.timer);this.pendingActions.delete(r);i.reject(new Error(n?"The app link changed during the call. Its result is unknown.":"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==="checking"?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 s=pickByProject(i.map(l=>({deviceId:l.deviceId,root:this.devServerRoots.get(l.deviceId)})),o);if(s)return this.sessionDevice=s;const a=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(a)throw n(a,"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();const n=currentAccess();if(e&&e!==ALL_DEVICES)this.sessionDevice=e;const t=s=>{if(!s)return"";return s.tier==="locked"?` The broker has not confirmed account access for "${s.deviceName}"; a locked status does not establish whether a key is configured.`:` The connected app "${s.deviceName}" is on the ${s.tier} tier.`};const r=s=>n.level==="pro"?proRequiredMessage(n,t(s)):`The Buoy MCP needs an app on a Buoy account.${t(s)} Run \`npx buoy login\` in the project (free), restart the dev server with its cache cleared, then run \`list_devices\` to check.`;if(e===ALL_DEVICES){const s=this.connectedDevices().filter(c=>c.isPro||c.tier==="free");const a=s.find(c=>!meetsAccess(c,n.level));if(s.length===0)throw new Error(r());if(a)throw new Error(r(a));return ALL_DEVICES}const i=this.resolveDevice(e);const o=this.connectedDevices().find(s=>s.deviceId===i);if(!meetsAccess(o,n.level)){const s=this.accessState(i,n.level);if(s==="offline")throw new Error(`${NOT_READY_MARK} "${i}" is not connected right now. If the app is starting or reloading, it usually takes a few seconds. Run list_devices to check.`);if(s==="pending")throw new Error(`${NOT_READY_MARK} account access for "${i}" is still being confirmed (the app just connected). Try again in a moment.`);throw new Error(r(o))}return i}checkAppCall(e,n,t){const r=currentAccess();if(!r.tool)return;const i=t===ALL_DEVICES?this.connectedDevices().find(o=>o.tier==="free"&&!hasProAccess(o)):this.listDevices().find(o=>o.deviceId===t&&!hasProAccess(o));if(!i)return;if(r.level==="free"&&isFreeAppCall(e,n))return;throw new Error(proRequiredMessage({...r,level:"pro"},` The app "${i.deviceName}" is on the ${i.tier} tier${r.level==="free"?`, and this part of \`${r.tool}\` reads its ${e} data, which is Pro`:""}.`))}refuseBuoyPanelTap(e,n,t,r){if(e!=="highlight-updates"||n!=="tapElement")return null;const i=currentAccess();if(!i.tool||i.level!=="free")return null;const o=t??{};const s=typeof o.nativeTag==="number"?o.nativeTag:null;const a=typeof o.testID==="string"&&o.testID?o.testID.toLowerCase():null;const c=s!=null||a!=null||!!o.includeBuoy;if(r===ALL_DEVICES){if(!c||!this.connectedDevices().some(d=>d.tier==="free"&&!hasProAccess(d)))return null;return Promise.reject(new Error(proRequiredMessage({...i,level:"pro"},' On a free app, tap one app at a time (not "All") when tapping by testID or nativeTag.')))}const l=this.listDevices().find(d=>d.deviceId===r);if(!l||hasProAccess(l)||!c)return null;const u=d=>new Error(proRequiredMessage({...i,level:"pro"},d));if(o.includeBuoy)return Promise.reject(u(" That reaches Buoy's own panel, not the app."));return(async()=>{let d;try{d=await this.callAction("highlight-updates","describeScreen",{includeBuoy:false,includeHidden:true},r,{timeoutMs:4e3,silent:true})}catch(p){throw new Error(`Could not check that target before tapping (${p instanceof Error?p.message:String(p)}). On a free app, tap by query, or retry once the screen settles.`)}const h=(d?.elements??[]).some(p=>s!=null?p.nativeTag===s:p.testID?.toLowerCase()===a);if(!h&&s==null&&typeof o.query==="string"){const{testID:p,...f}=o;return f}if(!h){throw new Error(`"${s??String(o.testID)}" is not on the app's screen right now. On a free app, a tap by testID or nativeTag must hit an element describe_screen lists, and Buoy's own panels are Pro. Swipe it into view first, or tap by query.`)}})()}fullResultsFor(e){if(e===ALL_DEVICES){const n=this.connectedDevices();return n.length>0&&n.every(t=>hasProAccess(t))}return hasProAccess(this.listDevices().find(n=>n.deviceId===e))}deviceWasAllowed(e){return meetsAccess(this.listDevices().find(n=>n.deviceId===e),currentAccess().level)}accessState(e,n=currentAccess().level){const t=this.devices.find(r=>r.deviceId===e);if(!t||t.isConnected===false)return"offline";if(hasProAccess(t)||n==="free"&&t.tier==="free")return"ready";return t.tier===void 0||t.tier==="checking"?"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(s=>typeof s?.timestamp==="number"?s.timestamp:-Infinity));const i=this.crashSeen.get(e)??new Set;let o=false;for(const s of t){const a=s?.fatal||/^\[(RENDER ERROR|FATAL)/.test(s?.message??"");if(!a||typeof s.timestamp!=="number")continue;const c=`${s.id??""}|${s.timestamp}|${(s.message??"").slice(0,120)}`;if(i.has(c))continue;i.add(c);if(r-s.timestamp<3e4)o=true}if(i.size>200)for(const s of[...i].slice(0,i.size-200))i.delete(s);this.crashSeen.set(e,i);if(!o)return;if(![...this.pendingActions.values()].some(s=>s.target===e&&s.expire&&!s.cut))return;void this.callAction("app","ping",{},e,{timeoutMs:1500,silent:true}).then(()=>void 0,()=>{const s=Date.now();for(const a of this.pendingActions.values()){if(a.target!==e||!a.expire||a.cut)continue;a.cut=true;if(a.deadline!==void 0&&a.deadline-s<=UNRESPONSIVE_ACTION_TIMEOUT_MS)continue;clearTimeout(a.timer);a.timer=setTimeout(a.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:s}of this.watching.values()){if(s===t)this.sendWatch(o,s)}}}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);this.checkAppCall(e,"@snapshot",n);return this.snapshots.get(snapKey(n,e))}async getSnapshot(e,n,t={}){const r=this.resolveDevice(n);this.checkAppCall(e,"@snapshot",r);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 s=this.waitForSnapshot(i,o);this.socket?.emit("request-devtool-state",{toolId:e,targetDeviceId:r});const a=await s;this.requireAdmission();this.requireDeviceAccount(r);if(a!==void 0){if(!t.silent)this.noteOk(r);return{deviceId:r,payload:a}}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){this.checkAppCall(n,"@snapshot",e);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 s=(this.snapshotWaiters.get(e)??[]).filter(a=>a!==o);this.snapshotWaiters.set(e,s);t(void 0)},n);const o=s=>{clearTimeout(i);t(s)};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);this.checkAppCall(e,n,o);const s=this.refuseBuoyPanelTap(e,n,t,o);if(s)t=await s??t;if(!this.socket)throw new Error("SyncClient is not connected");const a=(0,import_node_crypto2.randomUUID)();const c=i.timeoutMs??Math.max(this.timeoutFor(o,e,n),selfTimedBudgetMs(e,n,t));const l=await new Promise((u,d)=>{const h=Date.now();const p=()=>{this.pendingActions.delete(a);if(o!==ALL_DEVICES&&!i.silent)this.noteTimeout(o);d(new Error(`Action "${e}.${n}" got no answer in ${Date.now()-h}ms. `+(o===ALL_DEVICES?"No device responded.":this.unresponsiveNote(o))))};const f=setTimeout(p,c);this.pendingActions.set(a,{resolve:u,reject:d,timer:f,target:o,expire:p,deadline:h+c});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(!l.ok){throw new Error(l.error||`Action "${e}.${n}" failed on device`)}return l.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.72"?"7.0.72":"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(s=>Number(s)||0);const r=t(e);const i=t(n);for(let o=0;o<3;o++){const s=r[o]??0;const a=i[o]??0;if(s>a)return true;if(s<a)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 s of await listDir(import_node_path4.default.join(i,o))){const a=import_node_path4.default.join(i,o,s,"LocalStorage","localstorage.sqlite3");try{await import_node_fs3.promises.access(a);const{stdout:c}=await execFileAsync2("sqlite3",["-readonly",a,`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(s=>s.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 s of o){try{const a=(await import_node_fs3.promises.readFile(import_node_path4.default.join(i,s,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim();if(a===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 s=o&&i?.udid?n.find(c=>c.udid===i.udid):void 0;if(s)return{ok:true,udid:s.udid,how:`matched ${e} to "${s.name}" (WebView storage)`};const a=[];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))a.push(n[u])});webViewLookups.set(e,{booted:r,udid:a.length===1?a[0].udid:null,at:Date.now()})}if(a.length===1){return{ok:true,udid:a[0].udid,how:`matched ${e} to "${a[0].name}" (WebView storage)`}}if(a.length>1){return{ok:false,error:`${a.length} booted simulators (${a.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(([s])=>/iOS/.test(s)).flatMap(([,s])=>s.filter(a=>a.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 s=[];try{s=await import_node_fs3.promises.readdir(o)}catch{continue}for(const a of s){try{const c=(await import_node_fs3.promises.readFile(import_node_path4.default.join(o,a,"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 s=clamp(Math.round(t.height),1,n.height-i);const a=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(s),String(o),"--cropOffset",String(i),String(r),e,"--out",a],{timeout:1e4});const c=await import_node_fs3.promises.readFile(a);return{ok:true,buffer:c,width:o,height:s}}catch(c){const l=c;return{ok:false,error:`Crop failed: ${l?.stderr||l?.message||c}`}}finally{await import_node_fs3.promises.unlink(a).catch(()=>{});await import_node_fs3.promises.unlink(e).catch(()=>{})}}var import_node_child_process12=require("child_process");var import_node_util9=require("util");var import_node_child_process11=require("child_process");var import_node_util8=require("util");var import_node_fs20=require("fs");var import_node_os15=__toESM(require("os"));var import_node_path21=__toESM(require("path"));var import_node_crypto15=require("crypto");var import_pngjs2=__toESM(require_png());init_src();var import_node_child_process8=require("child_process");var import_node_util5=require("util");var import_node_fs18=require("fs");var import_node_os14=__toESM(require("os"));var import_node_path19=__toESM(require("path"));var import_node_crypto14=require("crypto");var import_pngjs=__toESM(require_png());var execFileAsync5=(0,import_node_util5.promisify)(import_node_child_process8.execFile);async function devicectl(e,n=3e4){const t=import_node_path19.default.join(import_node_os14.default.tmpdir(),`buoy-devicectl-${(0,import_node_crypto14.randomUUID)()}.json`);try{await execFileAsync5("xcrun",["devicectl",...e,"--quiet","--json-output",t],{timeout:n,maxBuffer:16*1024*1024});return JSON.parse(await import_node_fs18.promises.readFile(t,"utf8"))}catch(r){const i=r;let o=(i.stderr||i.stdout||i.message||"").trim();try{const s=JSON.parse(await import_node_fs18.promises.readFile(t,"utf8"));o=s.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_fs18.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(s=>s.relativePath??s.name??""));if(!i.has(t))return null;const o=import_node_path19.default.join(import_node_os14.default.tmpdir(),`buoy-devfile-${(0,import_node_crypto14.randomUUID)()}`);try{await devicectl(["device","copy","from","--device",e,"--domain-type","appDataContainer","--domain-identifier",n,"--source",t,"--destination",o],2e4);return await import_node_fs18.promises.readFile(o)}finally{await import_node_fs18.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_path19.default.join(import_node_os14.default.tmpdir(),`buoy-phone-shot-${(0,import_node_crypto14.randomUUID)()}.png`);try{await devicectl(["device","capture","screenshot","--device",e,"--destination",n],3e4);return await import_node_fs18.promises.readFile(n)}finally{await import_node_fs18.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(s=>s.bundleId===n)?.path;const i=await devicectl(["device","info","processes","--device",e]);const o=(i.result?.runningProcesses??[]).find(s=>r&&decodeURIComponent(s.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_process10=require("child_process");var import_node_util7=require("util");var import_node_fs19=require("fs");var import_node_path20=__toESM(require("path"));var import_ws=require("ws");var import_node_child_process9=require("child_process");var import_node_util6=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,s)=>{const a=n[`BUOY_SECRET_${s}`]??n[s];if(a===void 0||a===""){t.push(s);return""}if(a.length<MIN_SECRET_LENGTH){r.push(s);return""}used.set(s,a);return a});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 s of[o,JSON.stringify(o).slice(1,-1),encodeURIComponent(o)])n.set(s,i);for(let s=o.length-1;s>=MIN_SECRET_LENGTH;s--){n.set(`${o.slice(0,s)}\u2026`,i);n.set(`${o.slice(0,s)}...`,i);if(s>=8)n.set(o.slice(0,s),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,s)=>{if(/^\d+$/.test(i)){const a=s.slice(Math.max(0,o-8),o);const c=s.slice(o+i.length,o+i.length+8);if(/(\d|\d\.)$/.test(a)||/^(\d|\.\d|[eE][+-]?\d)/.test(c))return i;if(/[:[,]\s*$/.test(a)&&/^\s*([,\]}]|$)/.test(c)&&!insideJsonString(s,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 execFileAsync6=(0,import_node_util6.promisify)(import_node_child_process9.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 execFileAsync6("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 s=n[0]==="shell"?i.stderr||(i.killed?"timed out":"no error text"):i.stderr||i.message||"";const a=scrubSecrets(s.replace(/'[^']*'/g,"'\u2026'")).trim().slice(0,300);throw new Error(`adb ${o} failed: ${a}`)}}function adbShell(e,n,t=15e3){return adb(e,["shell",n],t)}async function adbBytes(e,n,t=15e3){try{const{stdout:r}=await execFileAsync6("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,s,a,c]=i.slice(1).map(Number);if(a>o&&c>s)return{x:o,y:s,width:a-o,height:c-s}}}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[s,a,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:s,y:a,width:c-s,height:l-a}})}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 s=i.filter(c=>r(c)===o);let a=s.filter((c,l)=>s.findIndex(u=>JSON.stringify(u.bounds)===JSON.stringify(c.bounds))===l);if(a.length>1){const c=a.filter(l=>[l.desc,l.text,l.id.split("/").pop()??""].some(u=>u.trim()===n.trim()));if(c.length)a=c}if(a.length>1){const c=a.filter(l=>l.clickable||/EditText|Button/.test(l.cls));if(c.length)a=c}return a}var execFileAsync7=(0,import_node_util7.promisify)(import_node_child_process10.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_fs19.promises.readdir(e).catch(()=>[])}async function containerLocalStorageFiles(e){const n=[];const t=import_node_path20.default.join(e,"Library","WebKit");for(const r of await listDir2(t)){const i=import_node_path20.default.join(t,r,"WebsiteData","Default");for(const o of await listDir2(i)){for(const s of await listDir2(import_node_path20.default.join(i,o))){const a=import_node_path20.default.join(i,o,s);const c=import_node_path20.default.join(a,"LocalStorage","localstorage.sqlite3");if(!await import_node_fs19.promises.access(c).then(()=>true,()=>false))continue;const l=await import_node_fs19.promises.readFile(import_node_path20.default.join(a,"origin")).then(u=>u.toString("hex"),()=>"");if(l)n.push({db:c,origin:l})}}}return n}var sqlite=(e,n,t=true)=>execFileAsync7("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 s=o.lastIndexOf("|");if(s<0)continue;const a=o.slice(0,s);if(WEB_KEEP_KEY.test(a))n.push({key:a,value:o.slice(s+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(a=>a.origin===i):void 0;if(!o)return false;const s=n.filter(a=>(a.origin??"")===i&&/^[0-9A-F]*$/i.test(a.value)).map(a=>`('${a.key.replace(/'/g,"''")}', X'${a.value}')`).join(",");if(s)await sqlite(o.db,`INSERT OR REPLACE INTO ItemTable (key, value) VALUES ${s};`,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 s=o.find(a=>a.type==="page"&&a.webSocketDebuggerUrl);if(!s?.webSocketDebuggerUrl)throw new Error("no debuggable WebView page (needs a debug build)");return await new Promise((a,c)=>{const l=new import_ws.WebSocket(s.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 a(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(s){o=s;await new Promise(a=>setTimeout(a,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 execFileAsync8=(0,import_node_util8.promisify)(import_node_child_process11.execFile);var hosts=new Map;function rememberedHost(e){return hosts.get(e)}async function sh(e,n,t=2e4,r){try{const{stdout:i}=await execFileAsync8(e,n,{timeout:t,maxBuffer:16*1024*1024,env:r?{...process.env,...r}:void 0});return i}catch(i){const o=i;if(o.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: ${(o.stderr||o.message||"").trim().slice(0,300)}`)}}var simctl=(e,n)=>sh("xcrun",["simctl",...e],n);async function simctlLaunch(e,n){const t=await simLaunchEnv(e,n).catch(()=>({}));return sh("xcrun",["simctl","launch",e,n],void 0,t)}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(s=>s.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_path21.default.join(t,"Containers","Data","Application");let s=[];try{s=await import_node_fs20.promises.readdir(o)}catch{return null}const a=await Promise.all(s.map(c=>iosContainerHolds(import_node_path21.default.join(o,c),i,r)));for(const[c,l]of s.entries()){const u=import_node_path21.default.join(o,l);if(!a[c])continue;let d=null;try{d=(await sh("plutil",["-extract","MCMMetadataIdentifier","raw","-o","-",import_node_path21.default.join(u,".com.apple.mobile_container_manager.metadata.plist")])).trim()||null}catch{}return{container:u,bundleId:d,kind:a[c]}}return null}async function iosContainerHolds(e,n,t=["rn","webview"]){if(t.includes("rn")){try{if((await import_node_fs20.promises.readFile(import_node_path21.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 s=await adbUserPackages(i).catch(()=>[]);const a=[n.bundleId,o,...s].filter((c,l,u)=>!!c&&u.indexOf(c)===l).slice(0,80);for(const c of a){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 s=null;if(!i){const l=await simsHolding(e);s=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 a=s?.udid===i?await iosContainerHolds(s.found.container,tailOf(e),[s.found.kind])?s.found:null:await findIosContainer(e,i);if(!a)throw new Error(`Simulator ${i} does not hold "${e}".`);const c={platform:"ios",udid:i,name:o,bundleId:t.bundleId??a?.bundleId??null,container:a?.container??null,picked:!!t.udid,idKind:a.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_fs20.promises.readFile(n.srcPath)}finally{await import_node_fs20.promises.unlink(n.srcPath).catch(()=>{})}}async function toSmallImage(e,n=1280){if(process.platform==="darwin"){const i=import_node_path21.default.join(import_node_os15.default.tmpdir(),`buoy-mcp-img-${(0,import_node_crypto15.randomUUID)()}.png`);const o=i.replace(/\.png$/,".jpg");await import_node_fs20.promises.writeFile(i,e);try{await sh("sips",["-Z",String(n),"-s","format","jpeg","-s","formatOptions","70",i,"--out",o],15e3);const s=await sh("sips",["-g","pixelWidth","-g","pixelHeight",o]);return{data:(await import_node_fs20.promises.readFile(o)).toString("base64"),mimeType:"image/jpeg",width:Number(/pixelWidth:\s*(\d+)/.exec(s)?.[1]??0),height:Number(/pixelHeight:\s*(\d+)/.exec(s)?.[1]??0)}}finally{await import_node_fs20.promises.unlink(i).catch(()=>{});await import_node_fs20.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 s=e.width/r;const a=e.height/i;for(let c=0;c<i;c++){const l=Math.floor(c*a);const u=Math.max(l+1,Math.floor((c+1)*a));for(let d=0;d<r;d++){const h=Math.floor(d*s);const p=Math.max(h+1,Math.floor((d+1)*s));const f=[0,0,0,0];let g=0;for(let m=l;m<u;m++){for(let w=h;w<p;w++){const b=(m*e.width+w)*4;for(let y=0;y<4;y++)f[y]+=e.data[b+y];g++}}const v=(c*r+d)*4;for(let m=0;m<4;m++)o.data[v+m]=Math.round(f[m]/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 simctlLaunch(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_path21.default.join(e,"Info.plist");const t=s=>sh("plutil",["-extract",s,"raw","-o","-",n]).then(a=>a.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_path21.default.join(import_node_os15.default.homedir(),"Library","Android","sdk"),import_node_path21.default.join(import_node_os15.default.homedir(),"Android","Sdk")].filter(t=>!!t);for(const t of n){const r=import_node_path21.default.join(t,"build-tools");const i=(await import_node_fs20.promises.readdir(r).catch(()=>[])).sort().reverse();for(const o of i){for(const s of["aapt2","aapt"]){const a=import_node_path21.default.join(r,o,s);try{await import_node_fs20.promises.access(a)}catch{continue}const c=await sh(a,s==="aapt2"?["dump","packagename",e]:["dump","badging",e]).catch(()=>"");const l=s==="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_path21.default.resolve(n);try{await import_node_fs20.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_path21.default.basename(i)} is ${o.bundleId}, but this app is ${r}. Nothing was changed.`);if(!o.simulator)throw new Error(`${import_node_path21.default.basename(i)} is a device build, not a simulator build. Nothing was changed.`);const s=t?await import_node_fs20.promises.mkdtemp(import_node_path21.default.join(import_node_os15.default.tmpdir(),"buoy-mcp-keep-")):null;try{let a=false;let c=[];if(s){await import_node_fs20.promises.chmod(s,448);const u=(await simctl(["get_app_container",e.udid,r,"data"]).catch(()=>"")).trim();if(u)a=await copyBuoyFiles(import_node_path21.default.join(u,"Documents"),s);if(u&&!a){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_path21.default.basename(i)} failed: ${u.message}. Install it again by hand.`)}let l="";if(s&&a){try{const u=(await simctl(["get_app_container",e.udid,r,"data"])).trim();await copyBuoyFiles(s,import_node_path21.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 simctlLaunch(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 simctlLaunch(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(s)await import_node_fs20.promises.rm(s,{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_path21.default.join(e,r);try{await import_node_fs20.promises.access(i)}catch{continue}const o=import_node_path21.default.join(n,r);await import_node_fs20.promises.mkdir(import_node_path21.default.dirname(o),{recursive:true});await import_node_fs20.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_path21.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 s=[];if(r&&!o.length&&await androidHasWebViewStorage(e.serial,n)){try{s=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 a="";if(s.length){await hostLaunch(e);try{await androidWriteWebKeep(e.serial,n,s);a=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(c){a=` 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.${a}`}if(o.length){try{for(const c of o){const l=import_node_path21.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)}`)}`)}a=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(c){a=` Buoy's sign-in could not be restored (${c.message}): sign in to Buoy again in the app.`}}else if(r){a=" 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.${a}`}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_path21.default.basename(t)} is ${i.bundleId}, but this app is ${n}. Nothing was changed.`);if(i.simulator)throw new Error(`${import_node_path21.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 s=r?await import_node_fs20.promises.mkdtemp(import_node_path21.default.join(import_node_os15.default.tmpdir(),"buoy-mcp-keep-")):null;try{const a=[];if(s){await import_node_fs20.promises.chmod(s,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_path21.default.basename(l)} from the iPhone (${h.message}). Nothing was changed.`)}if(!u)continue;const d=import_node_path21.default.join(s,l.replace(/\//g,"__"));await import_node_fs20.promises.writeFile(d,u,{mode:384});a.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_path21.default.basename(t)} failed: ${l.message}. Install it again from Xcode.`)}let c="";if(a.length){try{for(const d of a)await writeAppFile(e.udid,n,d.local,d.rel);const l=a.some(d=>d.rel.includes("buoy-license"));const u=a.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(s)await import_node_fs20.promises.rm(s,{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(([a])=>/iOS/.test(a)).flatMap(([,a])=>a);const r=e.trim().toLowerCase();const i=t.filter(a=>a.udid.toLowerCase()===r||a.name.toLowerCase()===r);const o=i.length?i:t.filter(a=>a.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(a=>`${a.name} (${a.udid})`).join(", ")}. Pass the udid.`);const s=o[0];if(s.state!=="Booted"){try{await execFileAsync8("xcrun",["simctl","boot",s.udid],{timeout:12e4,env:bootEnv()})}catch(a){const c=a;throw new Error(`xcrun simctl boot failed: ${(c.stderr||c.message||"").trim().slice(0,300)}`)}}await sh("open",["-a","Simulator","--args","-CurrentDeviceUDID",s.udid]).catch(()=>void 0);return s.state==="Booted"?`${s.name} (${s.udid}) was already booted.`:`Booted ${s.name} (${s.udid}).`}var execFileAsync9=(0,import_node_util9.promisify)(import_node_child_process12.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.deviceWasAllowed(u):false;if(!r.allowOffline||!u||!d)throw c;i=u;o=false}const s=e.listDevices().find(c=>c.deviceId===i)?.platform;let a=await findHost(i,s,t);if(r.changesApp&&rememberedHost(i)===a)a=await verifyHost(i,a);return{id:i,host:a,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,execFileAsync9("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(a=>setTimeout(()=>a(void 0),3e3))]):void 0);const s=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"],...!s?{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 p=0;i.length===0&&p<10;p++){await new Promise(f=>setTimeout(f,200));i=n.listDevices()}if(i.length===0){return json({devices:[],hint:"No devices connected. Open the app with Buoy devtools running, then retry.",...r?{updateAvailable:r}:{}})}const o=t.includeDisconnected?0:i.filter(p=>!p.isConnected).length;if(!t.includeDisconnected)i=i.filter(p=>p.isConnected);if(i.length===0){return json({devices:[],hint:`No app is connected right now${o?` (${o} seen before; pass includeDisconnected:true to list them)`:""}. Open the app with Buoy devtools running, then retry.`,...r?{updateAvailable:r}:{}})}const s=await resolveSims(i.filter(p=>p.platform==="ios").map(p=>p.deviceId)).catch(()=>new Map);const a=i.filter(p=>p.isConnected);const c=a.some(p=>hasProAccess(p));const l=a.some(p=>p.tier!=="locked");const u=a.filter(p=>p.collision);const d=await Promise.all(i.map(p=>p.isConnected?hostSummary(p,s.get(p.deviceId)).catch(()=>void 0):void 0));const h=i.map((p,f)=>{const g=s.get(p.deviceId);const v=d[f];return{deviceId:p.deviceId,deviceName:p.deviceName,platform:p.platform,isConnected:p.isConnected,isPro:p.isPro,tier:p.tier,...!p.isPro&&hasProAccess(p)?{weekendPass:true}:{},access:n.accessState(p.deviceId,"free"),...g?{simulator:g}:{},...v?{host:v}:{},...p.collision?{collision:true}:{},tools:t.details?p.tools:p.tools.map(m=>m.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(p=>`"${p.deviceId}"`).join(", ")}: more than one app is registered under this id, so actions sent to it land on an arbitrary device. Give each device its own externalSync.deviceId (or leave it unset for a per-install default) before mutating anything.`}:{},...c?{}:{hint:l?`The connected app is on the free tier, so only the free MCP tools work: ${freeToolNames().join(", ")} (get_network_requests without includeBodies; get_triage without storage values). Every other tool needs Buoy Pro (https://buoy.gg/pricing). To add a license, enter it 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")}
35
37
 
36
38
  Call one with call_action({toolId, action, params}).`}]}}const s=new Set(n.connectedDevices().map(c=>c.deviceId));const a=n.toolActions(o).filter(c=>s.has(c.deviceId)&&(!i||c.deviceId===i));if(a.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:a})});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 s=t??r;if(!s)return fail("get_snapshot needs toolId (see list_tool_actions).");const a=n.requireProDevice(i);const{payload:c,stale:l}=await n.getSnapshot(s,a,{timeoutMs:o});return json({toolId:s,deviceId:a,...l?{stale:l}:{},snapshot:c})}catch(s){return fail(errMsg(s))}});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:s,deviceId:a,timeoutMs:c})=>{try{const l=t??r;if(!l)return fail("call_action needs toolId (see list_tool_actions).");const u=actionParams(o??s);const d=n.requireProDevice(a);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_zod4=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}
37
39
 
38
- `:""}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.deviceWasAllowed(i))return void 0;const o=e.lastSync(i,t);if(!o)return void 0;const s=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 (${s}). 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 import_node_os14=__toESM(require("os"));var import_node_path19=__toESM(require("path"));var import_zod3=require("zod");var import_node_child_process12=require("child_process");var import_node_util10=require("util");var import_node_fs18=require("fs");var import_node_os13=__toESM(require("os"));var import_node_path18=__toESM(require("path"));var execFileAsync10=(0,import_node_util10.promisify)(import_node_child_process12.execFile);function candidates(){const e=process.env.BUOY_SIMCAM_DIR;const n=[...e?[import_node_path18.default.join(e,"buoycam")]:[],"/Applications/Buoy.app/Contents/Resources/simcam/buoycam",import_node_path18.default.join(import_node_os13.default.homedir(),"Applications/Buoy.app/Contents/Resources/simcam/buoycam")];let t=__dirname;for(let r=0;r<8;r++){n.push(import_node_path18.default.join(t,"apps/desktop/resources/simcam/buoycam"));const i=import_node_path18.default.dirname(t);if(i===t)break;t=i}return n}var resolved=null;function cliPath(){if(resolved)return resolved;resolved=candidates().find(e=>(0,import_node_fs18.existsSync)(e))??null;return resolved}async function run2(e){const n=cliPath();if(!n){return{ok:false,error:"The simulator camera components were not found. They ship with the Buoy desktop app \u2014 install it, or set BUOY_SIMCAM_DIR to the directory holding `buoycam`."}}try{const{stdout:t}=await execFileAsync10(n,[...e,"--json"],{timeout:3e4});return{ok:true,data:JSON.parse(t)}}catch(t){const r=t.stdout??"";try{return{ok:false,data:JSON.parse(r)}}catch{return{ok:false,error:t.message||"the simulator camera CLI failed"}}}}function describeDiagnosis(e){const n=e.filter(o=>o.level==="fail");const t=e.filter(o=>o.level==="warn");if(n.length===0&&t.length===0){return"The simulator camera is healthy \u2014 every check passed."}const r=[];for(const o of[...n,...t]){r.push(`- **${o.name}** (${o.level}): ${o.detail}`);if(o.fix)r.push(` ${o.fix}`)}const i=n.length>0?`${n.length} problem${n.length===1?"":"s"} found.`:`No hard failures, but ${t.length} thing${t.length===1?"":"s"} worth knowing.`;return[i,"",...r].join("\n")}function describeDevices(e,n){if(e.length===0){return"No booted simulators.\n\n_Boot one first \u2014 `xcrun simctl boot <udid>`, or open Simulator.app. The camera attaches to a simulator, so nothing else here works until one is running._"}const t=[e.length===1?"1 booted simulator:":`${e.length} booted simulators:`,...e.map(r=>`- **${r.name}** (${r.runtime}) \u2014 \`${r.udid}\``)];if(e.length>1&&n===null){t.push("","_More than one is booted, so pass `udid` to list a specific one's apps \u2014 and to every other camera tool that takes one._");return t.join("\n")}if(n===null){t.push("","_Could not read the installed apps._");return t.join("\n")}if(n.length===0){t.push("","No apps installed on it.");return t.join("\n")}t.push("",`${n.length} installed app${n.length===1?"":"s"}:`,...n.map(r=>`- ${r.name} \u2014 \`${r.bundleId}\``),"","_Pass one of these bundle ids to `camera_launch` to relaunch it with the camera attached._");return t.join("\n")}function describeInputs(e,n){const t=[];t.push(e.length?'**Mac cameras** (for `kind: "camera"`):':"**Mac cameras**: none found.");if(e.length){t.push(...e.map(r=>`- ${r.name} \u2014 \`${r.uniqueId}\``))}else{t.push("_If this Mac has a webcam, Buoy has not been granted Camera permission (System Settings \u2192 Privacy & Security \u2192 Camera)._")}t.push("");t.push(n.length?'**Capturable windows** (for `kind: "screen"`, `value: "window:<id>"`):':"**Capturable windows**: none found.");if(n.length){t.push(...n.map(r=>`- ${r.app}${r.title?` \u2014 ${r.title}`:""} \u2014 \`window:${r.id}\``))}else{t.push("_Screen Recording permission is almost certainly missing (System Settings \u2192 Privacy & Security \u2192 Screen & System Audio Recording)._")}return t.join("\n")}var testEntitlementFile=null;function entitlementPaths(){if(testEntitlementFile)return[testEntitlementFile];return[import_node_path18.default.join(import_node_os13.default.homedir(),"Library/Application Support/Buoy/entitlement.json"),import_node_path18.default.join(import_node_os13.default.homedir(),"Library/Application Support/buoy-desktop/entitlement.json")]}function readEntitlement(){for(const e of entitlementPaths()){try{if(!(0,import_node_fs18.existsSync)(e))continue;const n=JSON.parse((0,import_node_fs18.readFileSync)(e,"utf8"));const t=n.tier==="pro"||n.tier==="free"?n.tier:"locked";const r=n.hasDesktopAccess===true&&typeof n.validUntil==="number"&&Number.isFinite(n.validUntil)&&Date.now()<n.validUntil;const i=r&&n.isPro===true&&typeof n.proValidUntil==="number"&&Number.isFinite(n.proValidUntil)&&Date.now()<n.proValidUntil;return{tier:t,isPro:i,admitted:i||r&&t!=="locked"}}catch{}}return{tier:"locked",isPro:false,admitted:false}}function entitlementHasPro(e=readEntitlement()){return e.isPro||e.admitted===true&&weekendNow()}function proRequired(e){return`\`${e}\` is a Buoy Pro feature.
40
+ `:""}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.deviceWasAllowed(i))return void 0;const o=e.lastSync(i,t);if(!o)return void 0;const s=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 (${s}). 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 import_node_os17=__toESM(require("os"));var import_node_path23=__toESM(require("path"));var import_zod3=require("zod");var import_node_child_process13=require("child_process");var import_node_util10=require("util");var import_node_fs21=require("fs");var import_node_os16=__toESM(require("os"));var import_node_path22=__toESM(require("path"));var execFileAsync10=(0,import_node_util10.promisify)(import_node_child_process13.execFile);function candidates(){const e=process.env.BUOY_SIMCAM_DIR;const n=[...e?[import_node_path22.default.join(e,"buoycam")]:[],"/Applications/Buoy.app/Contents/Resources/simcam/buoycam",import_node_path22.default.join(import_node_os16.default.homedir(),"Applications/Buoy.app/Contents/Resources/simcam/buoycam")];let t=__dirname;for(let r=0;r<8;r++){n.push(import_node_path22.default.join(t,"apps/desktop/resources/simcam/buoycam"));const i=import_node_path22.default.dirname(t);if(i===t)break;t=i}return n}var resolved=null;function cliPath(){if(resolved)return resolved;resolved=candidates().find(e=>(0,import_node_fs21.existsSync)(e))??null;return resolved}async function run2(e){const n=cliPath();if(!n){return{ok:false,error:"The simulator camera components were not found. They ship with the Buoy desktop app \u2014 install it, or set BUOY_SIMCAM_DIR to the directory holding `buoycam`."}}try{const{stdout:t}=await execFileAsync10(n,[...e,"--json"],{timeout:3e4});return{ok:true,data:JSON.parse(t)}}catch(t){const r=t.stdout??"";try{return{ok:false,data:JSON.parse(r)}}catch{return{ok:false,error:t.message||"the simulator camera CLI failed"}}}}function describeDiagnosis(e){const n=e.filter(o=>o.level==="fail");const t=e.filter(o=>o.level==="warn");if(n.length===0&&t.length===0){return"The simulator camera is healthy \u2014 every check passed."}const r=[];for(const o of[...n,...t]){r.push(`- **${o.name}** (${o.level}): ${o.detail}`);if(o.fix)r.push(` ${o.fix}`)}const i=n.length>0?`${n.length} problem${n.length===1?"":"s"} found.`:`No hard failures, but ${t.length} thing${t.length===1?"":"s"} worth knowing.`;return[i,"",...r].join("\n")}function describeDevices(e,n){if(e.length===0){return"No booted simulators.\n\n_Boot one first \u2014 `xcrun simctl boot <udid>`, or open Simulator.app. The camera attaches to a simulator, so nothing else here works until one is running._"}const t=[e.length===1?"1 booted simulator:":`${e.length} booted simulators:`,...e.map(r=>`- **${r.name}** (${r.runtime}) \u2014 \`${r.udid}\``)];if(e.length>1&&n===null){t.push("","_More than one is booted, so pass `udid` to list a specific one's apps \u2014 and to every other camera tool that takes one._");return t.join("\n")}if(n===null){t.push("","_Could not read the installed apps._");return t.join("\n")}if(n.length===0){t.push("","No apps installed on it.");return t.join("\n")}t.push("",`${n.length} installed app${n.length===1?"":"s"}:`,...n.map(r=>`- ${r.name} \u2014 \`${r.bundleId}\``),"","_Pass one of these bundle ids to `camera_launch` to relaunch it with the camera attached._");return t.join("\n")}function describeInputs(e,n){const t=[];t.push(e.length?'**Mac cameras** (for `kind: "camera"`):':"**Mac cameras**: none found.");if(e.length){t.push(...e.map(r=>`- ${r.name} \u2014 \`${r.uniqueId}\``))}else{t.push("_If this Mac has a webcam, Buoy has not been granted Camera permission (System Settings \u2192 Privacy & Security \u2192 Camera)._")}t.push("");t.push(n.length?'**Capturable windows** (for `kind: "screen"`, `value: "window:<id>"`):':"**Capturable windows**: none found.");if(n.length){t.push(...n.map(r=>`- ${r.app}${r.title?` \u2014 ${r.title}`:""} \u2014 \`window:${r.id}\``))}else{t.push("_Screen Recording permission is almost certainly missing (System Settings \u2192 Privacy & Security \u2192 Screen & System Audio Recording)._")}return t.join("\n")}var testEntitlementFile=null;function entitlementPaths(){if(testEntitlementFile)return[testEntitlementFile];return[import_node_path22.default.join(import_node_os16.default.homedir(),"Library/Application Support/Buoy/entitlement.json"),import_node_path22.default.join(import_node_os16.default.homedir(),"Library/Application Support/buoy-desktop/entitlement.json")]}function readEntitlement(){for(const e of entitlementPaths()){try{if(!(0,import_node_fs21.existsSync)(e))continue;const n=JSON.parse((0,import_node_fs21.readFileSync)(e,"utf8"));const t=n.tier==="pro"||n.tier==="free"?n.tier:"locked";const r=n.hasDesktopAccess===true&&typeof n.validUntil==="number"&&Number.isFinite(n.validUntil)&&Date.now()<n.validUntil;const i=r&&n.isPro===true&&typeof n.proValidUntil==="number"&&Number.isFinite(n.proValidUntil)&&Date.now()<n.proValidUntil;return{tier:t,isPro:i,admitted:i||r&&t!=="locked"}}catch{}}return{tier:"locked",isPro:false,admitted:false}}function entitlementHasPro(e=readEntitlement()){return e.isPro||e.admitted===true&&weekendNow()}function proRequired(e){return`\`${e}\` is a Buoy Pro feature.
39
41
 
40
42
  The simulator camera itself is free \u2014 the Mac camera, image, video, test-pattern and QR sources all work in the Buoy desktop panel with a Free account. Pro adds the screen region, the non-QR symbologies (PDF417, Aztec, DataMatrix, Code 128), and driving any of it from an agent.
41
43
 
42
44
  _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._`}function hasBuoyAccount(e){if(readEntitlement().admitted)return true;if(!e)return false;if(e.isAdmitted?.())return true;return e.connectedDevices().some(n=>n.isPro===true||n.tier==="free")}function accountRequired(e){return`\`${e}\` needs a Buoy account. A free one works.
43
45
 
44
- Tell the user to sign in to Buoy Desktop, or run \`npx buoy login\` in the project. Then run this again.`}init_src();var text2=e=>({content:[{type:"text",text:e}]});var fail3=e=>({isError:true,content:[{type:"text",text:e}]});var json2=e=>text2(JSON.stringify(e,null,2));var farmApps;var gate=e=>hasBuoyAccount(farmApps)?null:fail3(accountRequired(e));var client=null;var clientName=()=>void 0;function farm(){if(!client){client=detectAgent({clientName:clientName()}).catch(()=>void 0).then(e=>connectFarm({label:process.env.BUOY_AGENT_LABEL||(e?agentLabel(e):"Buoy MCP"),agent:e,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})}var held=[];function forget(e){for(let n=held.length-1;n>=0;n--)if(e(held[n]))held.splice(n,1)}async function farmFairness(e,n){const t=()=>held.find(i=>i.buoyDeviceId&&e.endsWith(i.buoyDeviceId));let r=t();if(!r&&held.length){await learnIds().catch(()=>void 0);r=t()}if(!r)return null;try{return{checked:true,...await call("fairness",{leaseId:r.leaseId,epoch:r.epoch,windows:n},3e4)}}catch(i){if(i instanceof FarmError&&i.code==="BAD_REQUEST"&&/Unknown method/.test(i.message)){return{checked:false,why:"This farm is too old to check fairness. Restart Buoy Desktop when the farm is idle."}}return{checked:false,why:i instanceof FarmError?`${i.code}: ${i.message}`:String(i?.message??i)}}}async function learnIds(){const e=await call("status");const n=new Set(held.map(t=>t.leaseId));for(const t of e.sims){if(!t.leaseId||!n.has(t.leaseId))continue;let r=held.find(c=>c.udid===t.udid);if(!r){const c=held.find(l=>l.leaseId===t.leaseId);r={...c,udid:t.udid,buoyDeviceId:void 0};held.push(r)}if(t.buoyDeviceId){r.buoyDeviceId=t.buoyDeviceId;continue}const i=e.templates.find(c=>c.id===t.templateId)?.bundleId;const o=import_node_path19.default.join(import_node_os14.default.homedir(),"Library/Developer/CoreSimulator/Devices",t.udid,"data");const s=i?await findDataContainer(o,i):null;const a=s?await readBuoyInstallId(s):null;if(a)r.buoyDeviceId=a}}function explain(e){if(e instanceof FarmError&&e.code==="RUN_STOPPED"){return fail3('RUN_STOPPED: The person stopped this run in Buoy Desktop (reason=user). Stop work on it. Tell them: "You stopped this run in Sims." Start a new run only if they ask.')}if(e instanceof FarmError)return fail3(`${e.code}: ${e.message}${e.next?`
46
+ Tell the user to sign in to Buoy Desktop, or run \`npx buoy login\` in the project. Then run this again.`}init_src();var text2=e=>({content:[{type:"text",text:e}]});var fail3=e=>({isError:true,content:[{type:"text",text:e}]});var json2=e=>text2(JSON.stringify(e,null,2));var farmApps;var gate=e=>hasBuoyAccount(farmApps)?null:fail3(accountRequired(e));var client=null;var clientName=()=>void 0;function farm(){if(!client){client=detectAgent({clientName:clientName()}).catch(()=>void 0).then(e=>connectFarm({label:process.env.BUOY_AGENT_LABEL||(e?agentLabel(e):"Buoy MCP"),agent:e,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})}var held=[];function forget(e){for(let n=held.length-1;n>=0;n--)if(e(held[n]))held.splice(n,1)}async function farmFairness(e,n){const t=()=>held.find(i=>i.buoyDeviceId&&e.endsWith(i.buoyDeviceId));let r=t();if(!r&&held.length){await learnIds().catch(()=>void 0);r=t()}if(!r)return null;try{return{checked:true,...await call("fairness",{leaseId:r.leaseId,epoch:r.epoch,windows:n},3e4)}}catch(i){if(i instanceof FarmError&&i.code==="BAD_REQUEST"&&/Unknown method/.test(i.message)){return{checked:false,why:"This farm is too old to check fairness. Restart Buoy Desktop when the farm is idle."}}return{checked:false,why:i instanceof FarmError?`${i.code}: ${i.message}`:String(i?.message??i)}}}async function learnIds(){const e=await call("status");const n=new Set(held.map(t=>t.leaseId));for(const t of e.sims){if(!t.leaseId||!n.has(t.leaseId))continue;let r=held.find(c=>c.udid===t.udid);if(!r){const c=held.find(l=>l.leaseId===t.leaseId);r={...c,udid:t.udid,buoyDeviceId:void 0};held.push(r)}if(t.buoyDeviceId){r.buoyDeviceId=t.buoyDeviceId;continue}const i=e.templates.find(c=>c.id===t.templateId)?.bundleId;const o=import_node_path23.default.join(import_node_os17.default.homedir(),"Library/Developer/CoreSimulator/Devices",t.udid,"data");const s=i?await findDataContainer(o,i):null;const a=s?await readBuoyInstallId(s):null;if(a)r.buoyDeviceId=a}}function explain(e){if(e instanceof FarmError&&e.code==="RUN_STOPPED"){return fail3('RUN_STOPPED: The person stopped this run in Buoy Desktop (reason=user). Stop work on it. Tell them: "You stopped this run in Sims." Start a new run only if they ask.')}if(e instanceof FarmError)return fail3(`${e.code}: ${e.message}${e.next?`
45
47
  Next: ${e.next}`:""}`);return fail3(`Sim Farm error: ${e?.message??e}`)}var leaseFields={leaseId:import_zod3.z.string().describe("The lease id from sim_farm_acquire."),epoch:import_zod3.z.number().int().describe("The epoch from sim_farm_acquire. A stale epoch is refused.")};var requestId=import_zod3.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.");var runId=import_zod3.z.string().describe("The runId from sim_farm_acquire.");async function waitForApps(e,n,t){const r=new Map;const i=Date.now()+t;for(;;){for(const o of n){if(r.has(o))continue;const s=e.connectedDevices().find(a=>a.deviceId.endsWith(o)&&a.tier!=="checking");if(s)r.set(o,s.deviceId)}if(r.size===n.length||Date.now()>=i)return r;await new Promise(o=>setTimeout(o,500))}}function registerSimFarmTools(e,n){clientName=()=>e.server.getClientVersion()?.name;farmApps=n;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. Apps launch as a real phone (an iPhone SE, 2nd gen, by default): they see its RAM and cores and get its memory warnings. Each sim's `phone` shows the app's peak memory, and `overLimit: true` means a real phone would have closed the app. A safety cap closes an app that keeps growing. Start here before sim_farm_acquire. Set `outside` to also list this Mac's other simulators, which the farm never touches.",inputSchema:{outside:import_zod3.z.boolean().optional().describe("Also list simulators the farm does not own.")}},async({outside:t})=>{try{return json2(await call("status",{outside:!!t}))}catch(r){return explain(r)}});e.registerTool("sim_farm_setup",{description:"Create or resize the Sim Farm. `create` makes a template sim from an app build and, optionally, a seed folder (signed-in app data); clones are made from it in about 4 s each. Dev-client apps (Expo) need `launchUrl` so they open on Metro instead of the launcher. `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. You own the pool: Buoy Desktop has no size control. sim_farm_acquire makes sims as needed; `shrink` the ones you no longer need so they stop using disk space.",inputSchema:{mode:import_zod3.z.enum(["create","grow","shrink"]).describe("create = new template; grow/shrink = pool size."),templateId:import_zod3.z.string().optional().describe("For grow/shrink. Defaults to the newest usable template."),count:import_zod3.z.number().int().min(1).max(64).optional().describe("For grow/shrink: how many sims to add or remove."),appPath:import_zod3.z.string().optional().describe("For create: path to a simulator .app build."),seedDir:import_zod3.z.string().nullable().optional().describe("For create: seed folder (Documents/, AsyncStorage/, Preferences/, seed.json). null = no seed."),launchUrl:import_zod3.z.string().optional().describe("For create: URL opened after each launch, e.g. exp+my-app://expo-development-client/?url=http%3A%2F%2Flocalhost%3A8081."),deviceType:import_zod3.z.string().optional().describe("For create: a simctl device type id. Default iPhone 17 Pro."),runtime:import_zod3.z.string().optional().describe("For create: a simctl runtime id. Default iOS 26.3."),profile:import_zod3.z.enum(["slim","stock"]).optional().describe("For create: slim (default) or stock."),metroPort:import_zod3.z.number().int().min(1).max(65535).optional().describe("For create: the Metro port the app loads from. Default 8802."),dryRun:import_zod3.z.boolean().optional().describe("Return the plan and its cost without changing anything."),requestId}},async t=>{const r=gate("sim_farm_setup");if(r)return r;try{if(t.mode==="create"){const s={appPath:t.appPath,seedDir:t.seedDir,deviceType:t.deviceType??"com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",runtime:t.runtime??"com.apple.CoreSimulator.SimRuntime.iOS-26-3",profile:t.profile??"slim",metroPort:t.metroPort??8802,...t.launchUrl?{launchUrl:t.launchUrl}:{}};if(!s.appPath)return fail3("create needs appPath.");if(s.seedDir===void 0)return fail3("create needs seedDir, or seedDir: null for an app with no seed.");if(t.dryRun)return json2({wouldCreateTemplate:s,budget:await call("budget",{ramGB:6,diskGB:4})});return json2(await call("setup",s,15*6e4,t.requestId))}let i=t.templateId;if(!i){const s=await call("status");i=s.templates.filter(a=>a.usable).pop()?.id;if(!i)return fail3("No usable template yet. Run sim_farm_setup with mode create first.")}const o=t.count??1;if(t.dryRun){const s=await call("budget",{ramGB:0,diskGB:t.mode==="grow"?2*o:0});return json2({mode:t.mode,templateId:i,count:o,roomForMoreSims:s.roomFor,ok:s.ok,reason:s.reason})}return json2(await call(t.mode,{templateId:i,count:o},30*6e4,t.requestId))}catch(i){return explain(i)}});e.registerTool("sim_farm_acquire",{description:"Take farm simulators for your work. The person watches your work live in Buoy Desktop, so give a clear `goal` and a `labels` entry per sim. Returns a run (runId, deadlineAt), 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; with launch, also deviceId, the full id to pass to other tools). 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_finish when done. Only ever target the returned UDIDs: never `booted`, which picks a random simulator when many run. While working, send sim_farm_report when a sim starts, passes or fails. The run stops at deadlineAt unless you ask for more time with sim_farm_extend. If any call returns RUN_STOPPED, the person stopped you: stop and tell them.",inputSchema:{count:import_zod3.z.number().int().min(1).max(64).describe("How many sims. There is no fixed cap: the farm gives as many as this Mac's memory and disk allow. Use allowPartial to take what fits."),goal:import_zod3.z.string().max(200).optional().describe("One short sentence the person sees on the run card, e.g. 'Make the menu list scroll faster'. With runId, the run's goal is used if you leave this out."),labels:import_zod3.z.array(import_zod3.z.string().max(80)).optional().describe("One label per sim, in order, e.g. ['Idea 1: memo rows', 'Idea 2: flat list']."),kind:import_zod3.z.enum(["try-ideas","run-tests","reproduce-bug","explore"]).optional().describe("What sort of work this is."),runId:import_zod3.z.string().optional().describe("Add these sims to a run you already have, instead of starting a new one."),purpose:import_zod3.z.string().optional().describe("Old name for goal. Use goal."),templateId:import_zod3.z.string().optional().describe("Defaults to the newest usable template."),launch:import_zod3.z.boolean().optional().describe("Launch the app on each sim and wait (up to about 30 s) until it joins Buoy. Each sim then has deviceId for other tools."),allowPartial:import_zod3.z.boolean().optional().describe("Return fewer sims than asked instead of failing."),waitSeconds:import_zod3.z.number().int().min(0).max(1800).optional().describe("Wait this long for sims to free up."),ttlMinutes:import_zod3.z.number().int().min(1).max(1440).optional().describe("How long the run may go. Default 15. Agents are capped (1 hour by default); ask for more later with sim_farm_extend."),requestId}},async t=>{const r=gate("sim_farm_acquire");if(r)return r;try{let i=t.templateId;if(!i){const u=await call("status");i=u.templates.filter(d=>d.usable).pop()?.id;if(!i)return fail3("No usable template yet. Run sim_farm_setup with mode create first.")}let o=(t.goal??t.purpose??"").trim();if(!o&&t.runId)o=((await call("status")).runs??[]).find(u=>u.id===t.runId)?.goal??"";if(!o)return fail3("Give a goal: one short sentence about what you are doing.");const s=await farm();const a=await s.acquire({templateId:i,count:t.count,purpose:o,goal:o,labels:t.labels,kind:t.kind,runId:t.runId,launch:t.launch,allowPartial:t.allowPartial,waitMs:(t.waitSeconds??0)*1e3,ttlMs:(t.ttlMinutes??15)*6e4,requestId:t.requestId});for(const u of a.sims){const d=held.findIndex(h=>h.udid===u.udid);if(d>=0)held.splice(d,1);held.push({leaseId:a.leaseId,epoch:a.epoch,runId:a.runId,udid:u.udid,buoyDeviceId:u.buoyDeviceId??void 0})}let c=a;if(t.launch&&n){const u=a.sims.map(p=>p.buoyDeviceId).filter(p=>!!p);const d=u.length?await waitForApps(n,u,3e4):new Map;c={...a,sims:a.sims.map(p=>({...p,deviceId:p.buoyDeviceId&&d.get(p.buoyDeviceId)||null}))};const h=a.sims.filter(p=>p.buoyDeviceId&&!d.has(p.buoyDeviceId));if(h.length){c.warning=`The app started on ${h.map(p=>p.name).join(", ")} but has not joined Buoy after 30 s. Run list_devices again in a moment, or take a screenshot with sim_farm_action to see the screen.`}}const l=t.launch?a.sims.filter(u=>!u.buoyDeviceId):[];if(l.length){const u=(await call("status").catch(()=>null))?.templates?.find(h=>h.id===i);const d=u?.metroPort?` on port ${u.metroPort}`:"";return json2({...c,warning:`The app did not report a Buoy id on ${l.map(h=>h.name).join(", ")}. It may still be loading, or Metro${d} may be down or broken. Check Metro${d}, then take a screenshot with sim_farm_action to see the screen.`})}return json2(c)}catch(i){return explain(i)}});e.registerTool("sim_farm_release",{description:"Give one lease's 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. Releasing your last lease ends the run, unless `keepRun` is true. To end a run with a result, use sim_farm_finish instead.",inputSchema:{...leaseFields,reset:import_zod3.z.enum(["fast","full"]).optional(),keepRun:import_zod3.z.boolean().optional().describe("Keep the run open to take more sims into it later.")}},async t=>{try{const r=await farm();const i=await r.release(t.leaseId,t.epoch,t.reset??"fast",t.keepRun===true);forget(o=>o.leaseId===t.leaseId);return json2(i)}catch(r){return explain(r)}});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_zod3.z.array(import_zod3.z.string()).min(1).describe("UDIDs from your lease."),action:import_zod3.z.enum(["screenshot","open-url","launch","reset","rebuild"]),url:import_zod3.z.string().optional().describe("For open-url."),requestId}},async t=>{const r=gate("sim_farm_action");if(r)return r;try{return json2(await call("action",{leaseId:t.leaseId,epoch:t.epoch,udids:t.udids,action:t.action,arg:t.url},10*6e4,t.requestId))}catch(i){return explain(i)}});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, and it records how busy the Mac is every second. It waits only for farm work in flight, not for other runs to end, so other sims and other apps may still use the Mac. run_benchmark_batch on your farm sim then marks each run fair or unfair from that record; run the unfair cases again. Measure only while you hold it. Other names guard shared test fixtures (e.g. `ask-buoy-gateway`, `shop`). Locks end with the lease.",inputSchema:{...leaseFields,name:import_zod3.z.string().regex(/^[a-z0-9-]{1,40}$/).describe("Lock name, e.g. perf-slot."),hold:import_zod3.z.boolean().describe("true = take it, false = free it."),waitSeconds:import_zod3.z.number().int().min(0).max(1800).optional()}},async t=>{const r=gate("sim_farm_lock");if(r)return r;try{const i={leaseId:t.leaseId,epoch:t.epoch,name:t.name,waitMs:(t.waitSeconds??0)*1e3};return json2(await call(t.hold?"lock":"unlock",i,(t.waitSeconds??0)*1e3+3e4))}catch(i){return explain(i)}});e.registerTool("sim_farm_report",{description:"Tell the person how your run is going. They watch it live in Buoy Desktop. Send one when a sim starts work, passes, fails or needs help, with a short note. `counts` only when you know the full task list. Reports never add time. Pass an increasing `sequence` so a retry is never counted twice.",inputSchema:{runId,udid:import_zod3.z.string().optional().describe("The sim this is about. Leave out for the whole run."),state:import_zod3.z.enum(["setting-up","working","waiting","passed","failed","needs-help"]).optional(),note:import_zod3.z.string().max(200).optional().describe("Short and plain, e.g. 'Idea 3: 58 fps, best so far'."),counts:import_zod3.z.object({done:import_zod3.z.number().int().min(0),total:import_zod3.z.number().int().min(0),passed:import_zod3.z.number().int().min(0).optional(),failed:import_zod3.z.number().int().min(0).optional()}).optional(),resultSource:import_zod3.z.enum(["agent","test"]).optional().describe("'test' when a test runner decided pass or fail, 'agent' when you judged it. Default agent."),sequence:import_zod3.z.number().int().min(0).optional()}},async t=>{try{return json2(await call("report",t,3e4))}catch(r){return explain(r)}});e.registerTool("sim_farm_extend",{description:"Ask for more time on your run before deadlineAt. The farm never goes past the run's cap (capAt). It says how much you got.",inputSchema:{runId,minutes:import_zod3.z.number().int().min(1).max(1440).describe("Minutes from now.")}},async t=>{try{return json2(await call("extend",t))}catch(r){return explain(r)}});e.registerTool("sim_farm_finish",{description:"End your run with a result. Gives back every sim it still holds. The person sees the summary in Buoy Desktop, so make it one or two plain sentences, e.g. 'Idea 3 won: 52 \u2192 58 fps.'",inputSchema:{runId,outcome:import_zod3.z.enum(["passed","failed","mixed","unknown"]).optional(),summary:import_zod3.z.string().max(600).optional()}},async t=>{try{const r=await call("finish",t,6e4,`fin-${t.runId}`);forget(i=>i.runId===t.runId);return json2(r)}catch(r){return explain(r)}})}var nothingLocked=()=>({renderComponents:0,renderCauses:false,scripts:0,jsOrigins:0});function addNames(e,n){for(const t of n??[])e.add(t.name)}function freeRanking(e){const n=new Set;const t=new Set;const r=e.rows.map(i=>{addNames(n,i.topRenderers);addNames(t,i.topScripts);return{...i,topRenderers:[],...i.topScripts?{topScripts:[]}:{}}});return{ranking:{...e,rows:r},locked:{...nothingLocked(),renderComponents:n.size,scripts:t.size}}}function freeComparison(e){const n=nothingLocked();const t={...e};const r=t.topScripts;if(r){const o=new Set;addNames(o,r.a);addNames(o,r.b);n.scripts=o.size;delete t.topScripts}const i=t?.renders;if(i&&i.causes){const{causes:o,...s}=i;n.renderCauses=Object.keys(o.a??{}).length+Object.keys(o.b??{}).length>0;t.renders=s}return{comparison:t,locked:n}}function freeWebBench(e){const n=new Set;const t=i=>{addNames(n,i.topScripts);return{...i,topScripts:[]}};const r=e.results.map(i=>({...i,runs:i.runs.map(t),median:i.median?t(i.median):null}));return{result:{...e,results:r},locked:{...nothingLocked(),scripts:n.size}}}function freeJsTop(e){return{snap:{...e,rows:[]},locked:{...nothingLocked(),jsOrigins:e.rows.length}}}var TRIAL_URL="https://buoy.gg/trial";var pitched=false;function lockedLines(e){const n=[];if(e.renderComponents>0){n.push(`Render causes for ${e.renderComponents} component${e.renderComponents===1?"":"s"} (which parts re-render, and why)`)}else if(e.renderCauses){n.push("Why the components rendered (render causes)")}if(e.scripts>0)n.push(`${e.scripts} script${e.scripts===1?"":"s"} named in slow frames`);if(e.jsOrigins>0)n.push(`Which code used the JS thread (${e.jsOrigins} task origin${e.jsOrigins===1?"":"s"})`);if(!n.length)return null;if(pitched)return`\u{1F512} Pro would also show: ${n.join("; ")}.`;pitched=true;return["\u{1F512} More from this run needs Buoy Pro:",...n.map(t=>` \u2022 ${t}`),` Pro shows them. Free 14-day trial: ${TRIAL_URL}`," Tell the user this once, then keep working with the free numbers above. Don't stop or ask again."].join("\n")}function withLockedLines(e,n){const t=lockedLines(n);return t?`${e}
46
48
 
47
49
  ${t}`:e}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 p=(d.name||"").trim()||`case ${h+1}`;return{id:`case-${h}`,name:p,params:d.params??{},route:d.route}});const s=clamp2(Math.round(pick(e.runsPerCase,n.runsPerCase,FALLBACK.runsPerCase)),1,10);const a=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,s-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(s===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:s,coolDownMs:a,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 s=[`**${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 a=e.settleMs+e.perCaseDurationMs+(e.coolDownMs??0)+1800;return`${s.join(", ")}. That's ~${n(a)} 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(m=>m.batchId===n);const o=new Map(r.map(m=>[m.index,m.reason]));const s=Array.from(new Set(i.map(m=>m.batchIndex??0))).sort((m,w)=>m-w);const a=m=>{const w=i.filter(_=>(_.batchIndex??0)===m);if(w.length===0)return void 0;const b=w.filter(_=>!_.batchFailureReason&&!_.discardedWarmup);const y=b.filter(_=>_.webRun?.fps!=null);if(y.length>0&&y.length===b.length){const _=[...y].sort((T,$)=>T.webRun.fps-$.webRun.fps);return _[Math.floor((_.length-1)/2)]}if(b.length>0){return b.find(_=>_.isMedianRun===true)??b.find(_=>_.runIndex===0||_.runIndex===void 0)??b[0]}return w.find(_=>_.batchFailureReason)??w[0]};const c=m=>typeof m==="number"?m:null;const l=s.map(m=>{const w=a(m);const b=i.filter(O=>(O.batchIndex??0)===m);const y=b.length;const _=b.filter(O=>!O.batchFailureReason&&!O.discardedWarmup);const T=O=>O.webRun?O.webRun.fps??O.jsFpsAvg:O.uiFpsAvg;const $=_.map(T).filter(O=>typeof O==="number");const x=w?.name??t?.[m]?.name??`case ${m+1}`;const A=i.some(O=>(O.batchIndex??0)===m&&O.isBaseline===true);const I=o.get(m)??w?.batchFailureReason;const E=b.every(O=>O.batchFailureReason||O.discardedWarmup);const k=Boolean(I)||!w||E;const S={batchIndex:m,caseName:x,params:w?.params??{},runs:y,failed:k,...w?.route?{route:w.route}:{},...A?{isBaseline:true}:{},failureReason:k?I??(E&&w?"only warmup runs were saved":"no run recorded"):void 0,uiFps:c(w?.uiFpsAvg),jsFps:c(w?.jsFpsAvg),cpu:c(w?.cpuAvg),memMb:c(w?.memMaxMb),jsJank:c(w?.jsJankFrames),uiJank:c(w?.uiJankFrames),deviceMaxRefreshRate:c(w?.deviceMaxRefreshRate),deltaUiFps:null,deltaJsFps:null,validRuns:_.length,fpsMin:$.length?round(Math.min(...$),1):null,fpsMax:$.length?round(Math.max(...$),1):null,...w?.thermalState?{thermalState:w.thermalState}:{},renderCommits:c(w?.renderCommits),renderWasted:w?.renderWasted,topRenderers:w?.topRenderers??[]};const M=w?.webRun;if(!M)return{...S,flags:k?[]:computeFlags(S)};const D=[...M.longTasksSupported?[]:["long tasks"],...M.heapSupported?[]:["JS heap"],...M.loaf===null?["long animation frames"]:[]];const R={...S,platform:"web",uiFps:null,uiJank:null,jsJank:null,cpu:null,memMb:M.heapSupported?S.memMb:null,deviceMaxRefreshRate:Math.max(S.deviceMaxRefreshRate??0,M.refreshHz??0)||null,longTaskPct:M.longTaskPct,frameGapP95Ms:M.frameGapP95Ms,frameGapMaxMs:M.frameGapMaxMs,edgeSilenceMs:M.edgeSilenceMs??null,jsFps:M.fps??S.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(b),pageLoad:M.pageLoad??null,refreshCalibrated:M.refreshCalibrated??null};return{...R,flags:k?[]:computeWebFlags({...R,frames:M.frames})}}).filter(m=>m.caseName!==WARMUP_CASE_NAME).map((m,w)=>({...m,batchIndex:w}));const u=pickBaseline(l,t);if(u){u.isBaseline=true;for(const m of l){if(m===u)continue;if(m.uiFps!=null&&u.uiFps!=null)m.deltaUiFps=round(m.uiFps-u.uiFps,1);if(m.jsFps!=null&&u.jsFps!=null)m.deltaJsFps=round(m.jsFps-u.jsFps,1)}}const d=l.filter(m=>!m.failed);const h=(m,w)=>{let b;let y=NaN;for(const _ of d){const T=m(_);if(T==null)continue;if(b===void 0||w(T,y)){b=_;y=T}}return b?.caseName};const p=m=>m.platform==="web"?m.longFrames??null:m.jsJank==null&&m.uiJank==null?null:(m.jsJank??0)+(m.uiJank??0);const f={uiFps:h(m=>m.uiFps,(m,w)=>m>w),jsFps:h(m=>m.jsFps,(m,w)=>m>w),lowestCpu:h(m=>m.cpu,(m,w)=>m<w),lowestMem:h(m=>m.memMb,(m,w)=>m<w),fewestJank:h(p,(m,w)=>m<w),fewestLongTasks:h(m=>m.longTaskPct??null,(m,w)=>m<w)};const g=d.filter(m=>m.flags.length>0).map(m=>({caseName:m.caseName,flags:m.flags}));const v=d.filter(m=>m.flags.length===0).sort((m,w)=>(w.uiFps??w.jsFps??0)-(m.uiFps??m.jsFps??0)||(m.cpu??m.longTaskPct??Infinity)-(w.cpu??w.longTaskPct??Infinity)||(m.memMb??Infinity)-(w.memMb??Infinity)).map(m=>m.caseName);return{batchId:n,baselineName:u?.caseName??null,deviceMaxRefreshRate:d.find(m=>m.deviceMaxRefreshRate!=null)?.deviceMaxRefreshRate??null,rows:l,leaders:f,flagged:g,balanced:v}}function pageLoadLines(e){const n=e.filter(s=>!s.failed);if(n.length===0)return[];const t=n.map(s=>s.pageLoad?.navigationId);if(t.some(s=>s==null)||new Set(t).size!==t.length)return[];if(n.some(s=>(s.pageLoad?.pageAgeMs??Infinity)>3e4))return[];const r=s=>(s??"").replace(/\/+$/,"")||"/";const i=s=>{const a=s.pageLoad;if(!a?.loadPath||r(a.loadPath)!==r(s.route))return false;const c=new URLSearchParams(a.loadSearch??"");const l=[...c.keys()];if(new Set(l).size!==l.length)return false;const u=Object.entries(s.params);return l.length===u.length&&u.every(([d,h])=>c.get(d)===h)};if(n.some(s=>!i(s)))return[];const o=s=>s==null?"\u2014":String(Math.round(s));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(s=>{const a=s.pageLoad;return`| ${s.caseName} | ${o(a.ttfbMs)} | ${o(a.fcpMs)} | ${o(a.lcpMs)} | ${o(a.domContentLoadedMs)} | ${o(a.scriptKb)} | ${o(a.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,s)=>(n(s)??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,p=1)=>h==null?"\u2014":h.toFixed(p);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 s=i?"-------|":"";r.push(`| # | Case | UI FPS | JS FPS | CPU % | Mem MB | JS jank | UI jank |${o} Flags |`);r.push(`|---|------|-------:|-------:|------:|-------:|--------:|--------:|${s}-------|`);for(const h of e.rows){const p=i?` ${THERMAL_MARK[h.thermalState??"unknown"]??"\u2014"} |`:"";if(h.failed){r.push(`| ${h.batchIndex} | ${h.caseName} | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 |${p} \u274C FAILED (${h.failureReason}) |`);continue}const f=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)} |${p} ${f} |`)}const a=closeCallNote(e.rows);if(a){r.push("");r.push(a)}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 p=h.topRenderers.map(v=>`${v.name} \xD7${v.renders} (${v.totalMs}ms${v.cause?`, ${v.cause}`:""})`).join(", ");const f=h.renderCommits!=null?`${h.renderCommits} commits`:"";const g=h.renderWasted!=null?`${h.renderWasted} wasted`:"";return`- **${h.caseName}** \u2014 ${[f,g,p].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=(s,a,c)=>({a:s??null,b:a??null,delta:s!=null&&a!=null?round(a-s,1):null,better:c});const r=s=>s.webRun.heapSupported?round(s.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 s=closeCallNote(e.rows);if(s){n.push("");n.push(s)}const a=Array.from(new Set(e.rows.flatMap(u=>u.missingMetrics??[])));if(a.length){n.push("");n.push(`**Not measured in this browser:** ${a.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 json3=e=>({content:[{type:"text",text:JSON.stringify(e,null,2)}]});var caseSchema=import_zod4.z.object({name:import_zod4.z.string().describe("Display name for this variant (becomes the saved run's name)."),params:import_zod4.z.record(import_zod4.z.string()).optional().describe('Query params applied to the route for this case, e.g. { "renderer": "v2", "count": "100" }.'),route:import_zod4.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:s,coolDownMs:a,discardWarmupRuns:c,shuffleCases:l,reloadBetweenCases:u,captureRenders:d}=t;return{perCaseDurationMs:r,settleMs:i,navTimeoutMs:o,runsPerCase:s,coolDownMs:a,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:s}=t;const a=t.reloadsBetweenCases?10:3;const c=Date.now();let l="";let u=false;let d=0;while(Date.now()-c<o){let f;try{f=await readPerfSnapshot(e,n)}catch{await delay2(POLL_INTERVAL_MS);continue}const g=f.index??[];const v=f.live?.automation?.phase??"idle";const m=f.live?.automationCompleted;if(m?.phase==="cancelled"&&!r.has(m.batchId)){return{batchId:m.batchId,failures:[],cancelled:true}}if(m?.phase==="done"&&!r.has(m.batchId)){return{batchId:m.batchId,failures:m.failures??failuresFromIndex(g,m.batchId)}}if(v!=="idle")u=true;if(v!==l){l=v;s(`automation phase: ${v}`)}const w=[...batchIdsIn(g)].find(b=>!r.has(b));if(w){const b=runCountFor(g,w);if(i>0&&b>=i){await waitForRunnerSettled(e,n,s);s(`batch ${w} complete (${b}/${i} runs saved)`);return{batchId:w,failures:failuresFromIndex(g,w)}}const y=(g??[]).filter(x=>x.batchId===w&&x.name!==WARMUP_CASE_NAME).length;const _=f.live?.pendingBatchId===w;const T=Boolean(f.live&&"pendingBatchId"in f.live);const $=!t.reloadsBetweenCases||T;if(v==="idle"&&u&&y>0&&!_&&$){if(++d>=a){s(`batch ${w} settled (${b} runs, automation idle)`);return{batchId:w,failures:failuresFromIndex(g,w)}}}else{d=0}}await delay2(POLL_INTERVAL_MS)}const h=await readPerfSnapshot(e,n).catch(()=>null);const p=h?[...batchIdsIn(h.index)].find(f=>!r.has(f)):void 0;if(p&&h)return{batchId:p,failures:failuresFromIndex(h.index,p),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.`)}async function checkFairness(e,n,t,r){const i=n.filter(g=>g.batchId===t&&!g.discardedWarmup&&g.name!==WARMUP_CASE_NAME&&g.durationMs);if(!i.length)return null;const o=i.map(g=>({id:g.id,from:g.createdAt-g.durationMs,to:g.createdAt}));const s=await farmFairness(e,o);if(!s)return null;if(!s.checked)return{line:`**Fair check:** not done. ${s.why}`,detail:s};const a=new Map(i.map(g=>[g.id,g]));const c=g=>r.find(v=>v.id===g?.caseId)?.name??g?.name??"?";const l=s.runs.filter(g=>!g.fair).map(g=>{const v=a.get(g.id);return{case:c(v),run:(v?.runIndex??0)+1,median:v?.isMedianRun===true,reason:g.reason}});const u=[...new Set(l.map(g=>g.case))];const d=new Map;for(const g of l){const v=g.reason??"No reason given.";d.set(v,[...d.get(v)??[],`${g.case} run ${g.run}`])}const h=[...d].map(([g,v])=>`${g} (${v.join(", ")})`).join(" ");const p=l.length>0&&l.every(g=>/perf-slot/.test(g.reason??""));const f=!l.length?`**Fair check:** all ${s.runs.length} runs were fair. The Mac stayed calm.`:`**Fair check:** ${l.length} of ${s.runs.length} runs were not fair. ${h} Don't rank on these. `+(p?`Take perf-slot with sim_farm_lock, hold it for the whole batch, then run the batch again.`:`Run these cases again with the baseline once the Mac is calm: ${u.join(", ")}.`);return{line:f,detail:{fair:s.fair,unfair:s.unfair,rules:s.rules,unfairRuns:l,redoCases:u,runs:s.runs}}}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_zod4.z.string().describe('The screen to benchmark, e.g. "/perf-test". Reads case params to pick a variant.'),cases:import_zod4.z.array(caseSchema).min(1).describe("The variants to compare. Case #0 is the baseline for deltas."),bounceRoute:import_zod4.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_zod4.z.number().optional().describe("Runs per case; the median becomes the canonical result. Default 3 (1\u201310)."),perCaseDurationMs:import_zod4.z.number().optional().describe("How long to record each run. Default 5000."),settleMs:import_zod4.z.number().optional().describe("Idle gap after navigation before recording. Default 600."),coolDownMs:import_zod4.z.number().optional().describe("Idle between runs/cases for thermal recovery. Default 2000."),navTimeoutMs:import_zod4.z.number().optional().describe("Max wait for navigation per run. Default 5000."),discardWarmupRuns:import_zod4.z.number().optional().describe("Discard first N runs of each case before taking the median. Default 0."),shuffleCases:import_zod4.z.boolean().optional().describe("Interleave and shuffle case order to reduce order-related bias. Default on for >3 cases."),reloadBetweenCases:import_zod4.z.boolean().optional().describe("Fully reload JS between cases (needs <AutomationResumer/> mounted). Default false."),captureRenders:import_zod4.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_zod4.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_zod4.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}
@@ -138,7 +140,7 @@ ${JSON.stringify(i.state,null,2)}
138
140
  _Compact view. Pass includeValues:true for the full state tree. Dispatch with redux_dispatch({type, payload})._${s}`)}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_zod10.z.string().describe('The action type, e.g. "counter/increment" or "auth/logout".'),payload:import_zod10.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_zod11=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_zod11.z.string().optional().describe("Only keys containing this substring (case-insensitive)."),includeValues:import_zod11.z.boolean().optional().describe("Include each key's value (truncated). Default false (keys only)."),limit:import_zod11.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 s=f=>!i||f.toLowerCase().includes(i);const a=[];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(s).slice(0,o);if(l.length>0){let f;if(t.includeValues){const g=await n.callAction(STORAGE_TOOL_ID,"async.multiGet",{keys:l},r);const v=new Map((g??[]).map(([m,w])=>[m,w]));f=l.map(m=>`- \`${m}\` = ${truncate2(v.get(m)??null)}`)}else{f=l.map(g=>`- \`${g}\``)}a.push(`**AsyncStorage (${l.length}/${c.length} keys):**
139
141
  ${f.join("\n")}`)}const u=await n.callAction(STORAGE_TOOL_ID,"mmkv.snapshot",{},r).catch(()=>null);for(const f of u??[]){const g=f.entries.filter(w=>s(w.key)).slice(0,o);if(g.length===0)continue;const v=g.map(w=>t.includeValues?`- \`${w.key}\` (${w.valueType}) = ${truncate2(w.value)}`:`- \`${w.key}\``);const m=[f.encrypted&&"encrypted",f.readOnly&&"read-only"].filter(Boolean).join(", ");a.push(`**MMKV \`${f.id}\`${m?` (${m})`:""} (${g.length}/${f.entries.length} keys):**
140
142
  ${v.join("\n")}`)}const d=await n.callAction(STORAGE_TOOL_ID,"secure.keys",{},r).catch(()=>null);const h=(d??[]).filter(f=>s(f.key)).slice(0,o);if(h.length>0){const f=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 v=await n.callAction(STORAGE_TOOL_ID,"secure.get",{key:g.key},r).catch(()=>null);return`- \`${g.key}\` = ${truncate2(v)}`}));a.push(`**SecureStore (${h.length} registered keys):**
141
- ${f.join("\n")}`)}if(a.length===0){return text(`No storage keys${i?` matching "${t.pattern}"`:""} in any backend.`)}const p=t.includeValues?"":"\n\n_Keys only. Pass includeValues:true for values, or a pattern to filter. Modify AsyncStorage with storage_action._";return text(`${a.join("\n\n")}${p}`)}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_zod11.z.enum(["set","remove","clear"]).describe("set/remove a key, or clear supported app AsyncStorage keys."),key:import_zod11.z.string().optional().describe("The key (required for set and remove)."),value:import_zod11.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_zod17=require("zod");var import_zod16=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((s,a)=>[String(a),s]):Object.entries(e);for(const[s,a]of o)walk(a,n?`${n}.${s}`:s,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 s=o?`${n}, ${o}`:n;const a=e.get(i)??[];if(a.length<3)a.push(s);e.set(i,a)}}async function liveStateIndex(e,n){const t=new Set(e.connectedDevices().find(s=>s.deviceId===n)?.tools.map(s=>s.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(s=>{for(const a of s?.stores??[])indexState(o,`${a.name} store`,a.currentState)}))}if(t.has("redux")){i.push(e.callAction("redux","getState",{includeValues:true},n,r).then(s=>{const a=s;if(a?.available)indexState(o,"redux state",a.state)}))}if(t.has("jotai")){i.push(e.callAction("jotai","listAtoms",{includeValues:true},n,r).then(s=>{for(const a of s?.atoms??[])indexState(o,`atom ${a.label}`,a.currentValue)}))}if(!i.length)return null;await Promise.all(i.map(s=>s.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_zod15=require("zod");var import_node_child_process17=require("child_process");var import_node_util14=require("util");var import_node_fs24=require("fs");var import_node_os17=__toESM(require("os"));var import_node_path25=__toESM(require("path"));var import_pngjs3=__toESM(require_png());function pixelmatch(e,n,t,r,i,o={}){const{threshold:s=.1,alpha:a=.1,aaColor:c=[255,255,0],diffColor:l=[255,0,0],checkerboard:u=true,includeAA:d,diffColorAlt:h,diffMask:p}=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 f=r*i;const g=new Uint32Array(e.buffer,e.byteOffset,f);const v=new Uint32Array(n.buffer,n.byteOffset,f);let m=true;for(let S=0;S<f;S++){if(g[S]!==v[S]){m=false;break}}if(m){if(t&&!p){for(let S=0,M=0;S<f;S++,M+=4)drawGrayPixel(e,M,a,t)}return 0}const w=35215*s*s;const[b,y,_]=c;const[T,$,x]=l;const[A,I,E]=h||l;let k=0;for(let S=0,M=0;S<f;S++,M+=4){const D=g[S]===v[S]?0:colorDelta(e,n,M,M,u);if(Math.abs(D)>w){const R=S%r;const O=S/r|0;const U=!d&&(antialiased(e,R,O,r,i,g,v,u)||antialiased(n,R,O,r,i,v,g,u));if(U){if(t&&!p)drawPixel(t,M,b,y,_)}else{if(t){if(D<0){drawPixel(t,M,A,I,E)}else{drawPixel(t,M,T,$,x)}}k++}}else if(t&&!p){drawGrayPixel(e,M,a,t)}}return k}function isPixelData(e){return ArrayBuffer.isView(e)&&e.BYTES_PER_ELEMENT===1}function antialiased(e,n,t,r,i,o,s,a){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 p=e[h];const f=e[h+1];const g=e[h+2];const v=e[h+3];let m=n===c||n===u||t===l||t===d?1:0;let w=0;let b=0;let y=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,p,f,g,v,a);if(I===0){m++;if(m>2)return false}else if(I<w){w=I;y=x;_=A}else if(I>b){b=I;T=x;$=A}}}if(w===0||b===0)return false;return hasManySiblings(o,y,_,r,i)&&hasManySiblings(s,y,_,r,i)||hasManySiblings(o,T,$,r,i)&&hasManySiblings(s,T,$,r,i)}function hasManySiblings(e,n,t,r,i){const o=Math.max(n-1,0);const s=Math.max(t-1,0);const a=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===a||t===s||t===c?1:0;for(let d=o;d<=a;d++){for(let h=s;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 s=e[t+1];const a=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 p=o-l;let f=s-u;let g=a-d;const v=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)}p=(o*c-l*h-_*v)/255;f=(s*c-u*h-T*v)/255;g=(a*c-d*h-$*v)/255}const m=p*.29889531+f*.58662247+g*.11448223;const w=p*.59597799-f*.2741761-g*.32180189;const b=p*.21147017-f*.52261711+g*.31114694;const y=.5053*m*m+.299*w*w+.1957*b*b;return m>0?-y:y}function brightnessDelta(e,n,t,r,i,o,s,a){const c=e[t];const l=e[t+1];const u=e[t+2];const d=e[t+3];let h=r-c;let p=i-l;let f=o-u;const g=s-d;if(!h&&!p&&!f&&!g)return 0;if(s<255||d<255){let v=255,m=255,w=255;if(a){v=48+159*(n%2);m=48+159*((n/1.618033988749895|0)%2);w=48+159*((n/2.618033988749895|0)%2)}h=(r*s-c*d-v*g)/255;p=(i*s-l*d-m*g)/255;f=(o*s-u*d-w*g)/255}return h*.29889531+p*.58662247+f*.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:s}=r;const a=Math.round(s*(t.ignoreTop??0));for(const p of[r,i])p.data.fill(0,0,a*o*4);for(const p of t.masks??[]){const f=Math.max(0,Math.floor(p.x*o));const g=Math.min(o,Math.ceil((p.x+p.width)*o));const v=Math.max(0,Math.floor(p.y*s));const m=Math.min(s,Math.ceil((p.y+p.height)*s));for(const w of[r,i])for(let b=v;b<m;b++)w.data.fill(0,(b*o+f)*4,(b*o+g)*4)}const c=t.threshold??.1;const l=new import_pngjs3.PNG({width:o,height:s});const u=pixelmatch(r.data,i.data,l.data,o,s,{threshold:c,includeAA:false,diffMask:true});const d=new import_pngjs3.PNG({width:o,height:s});pixelmatch(r.data,i.data,d.data,o,s,{threshold:c,includeAA:false,alpha:.25,diffColor:[230,30,40]});const h=o*(s-a);return{width:o,height:s,changedPixels:u,percent:h?u/h*100:0,boxes:changedBoxes(l.data,o,s),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 s=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)s[Math.floor(u/r)*i+Math.floor(d/r)]++}}const a=1;const c=new Uint8Array(i*o);const l=[];for(let u=0;u<s.length;u++){if(c[u]||s[u]<a)continue;const d={x0:Infinity,y0:Infinity,x1:-1,y1:-1,pixels:0};const h=[u];c[u]=1;while(h.length){const p=h.pop();const f=p%i;const g=Math.floor(p/i);d.x0=Math.min(d.x0,f);d.y0=Math.min(d.y0,g);d.x1=Math.max(d.x1,f);d.y1=Math.max(d.y1,g);d.pixels+=s[p];for(let v=-2;v<=2;v++){for(let m=-2;m<=2;m++){const w=f+m;const b=g+v;if(w<0||b<0||w>=i||b>=o)continue;const y=b*i+w;if(!c[y]&&s[y]>=a){c[y]=1;h.push(y)}}}}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:s,height:a}=i;const c=Math.max(0,Math.floor(t.x*s));const l=Math.min(s,Math.ceil((t.x+t.width)*s));const u=Math.max(Math.round(a*r),Math.floor(t.y*a));const d=Math.min(a,Math.ceil((t.y+t.height)*a));const h=new Map;const p=new Map;for(let w=u;w<d;w++){for(let b=c;b<l;b++){const y=(w*s+b)*4;const _=i.data[y]<<16|i.data[y+1]<<8|i.data[y+2];const T=o.data[y]<<16|o.data[y+1]<<8|o.data[y+2];if(_===T)continue;h.set(_,(h.get(_)??0)+1);p.set(T,(p.get(T)??0)+1)}}const f=w=>[...w].sort((b,y)=>y[1]-b[1])[0]?.[0];const g=f(h);const v=f(p);if(g===void 0||v===void 0)return null;const m=w=>`#${w.toString(16).padStart(6,"0").toUpperCase()}`;return{before:m(g),after:m(v)}}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 s=Math.max(1,Math.min(t.height-i,Math.round(n.height*t.height)));const a=new import_pngjs3.PNG({width:o,height:s});import_pngjs3.PNG.bitblt(t,a,r,i,o,s,0,0);return import_pngjs3.PNG.sync.write(a)}var import_node_child_process13=require("child_process");var import_node_util11=require("util");var execFileAsync11=(0,import_node_util11.promisify)(import_node_child_process13.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 s=/digitizer detached \(sender ([0-9A-F]+)\)/i.exec(i);if(s){const a=r.indexOf(s[1]);if(a>=0)r.splice(a,1);if(n===s[1]||n===OTHER_UNSEEN&&a<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 execFileAsync11("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_process15=require("child_process");var import_node_util12=require("util");var import_node_fs19=require("fs");var import_node_os15=__toESM(require("os"));var import_node_path20=__toESM(require("path"));var HID_SWIFT=`import Foundation
143
+ ${f.join("\n")}`)}if(a.length===0){return text(`No storage keys${i?` matching "${t.pattern}"`:""} in any backend.`)}const p=t.includeValues?"":"\n\n_Keys only. Pass includeValues:true for values, or a pattern to filter. Modify AsyncStorage with storage_action._";return text(`${a.join("\n\n")}${p}`)}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_zod11.z.enum(["set","remove","clear"]).describe("set/remove a key, or clear supported app AsyncStorage keys."),key:import_zod11.z.string().optional().describe("The key (required for set and remove)."),value:import_zod11.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_zod17=require("zod");var import_zod16=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((s,a)=>[String(a),s]):Object.entries(e);for(const[s,a]of o)walk(a,n?`${n}.${s}`:s,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 s=o?`${n}, ${o}`:n;const a=e.get(i)??[];if(a.length<3)a.push(s);e.set(i,a)}}async function liveStateIndex(e,n){const t=new Set(e.connectedDevices().find(s=>s.deviceId===n)?.tools.map(s=>s.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(s=>{for(const a of s?.stores??[])indexState(o,`${a.name} store`,a.currentState)}))}if(t.has("redux")){i.push(e.callAction("redux","getState",{includeValues:true},n,r).then(s=>{const a=s;if(a?.available)indexState(o,"redux state",a.state)}))}if(t.has("jotai")){i.push(e.callAction("jotai","listAtoms",{includeValues:true},n,r).then(s=>{for(const a of s?.atoms??[])indexState(o,`atom ${a.label}`,a.currentValue)}))}if(!i.length)return null;await Promise.all(i.map(s=>s.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_zod15=require("zod");var import_node_child_process18=require("child_process");var import_node_util14=require("util");var import_node_fs27=require("fs");var import_node_os20=__toESM(require("os"));var import_node_path29=__toESM(require("path"));var import_pngjs3=__toESM(require_png());function pixelmatch(e,n,t,r,i,o={}){const{threshold:s=.1,alpha:a=.1,aaColor:c=[255,255,0],diffColor:l=[255,0,0],checkerboard:u=true,includeAA:d,diffColorAlt:h,diffMask:p}=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 f=r*i;const g=new Uint32Array(e.buffer,e.byteOffset,f);const v=new Uint32Array(n.buffer,n.byteOffset,f);let m=true;for(let S=0;S<f;S++){if(g[S]!==v[S]){m=false;break}}if(m){if(t&&!p){for(let S=0,M=0;S<f;S++,M+=4)drawGrayPixel(e,M,a,t)}return 0}const w=35215*s*s;const[b,y,_]=c;const[T,$,x]=l;const[A,I,E]=h||l;let k=0;for(let S=0,M=0;S<f;S++,M+=4){const D=g[S]===v[S]?0:colorDelta(e,n,M,M,u);if(Math.abs(D)>w){const R=S%r;const O=S/r|0;const U=!d&&(antialiased(e,R,O,r,i,g,v,u)||antialiased(n,R,O,r,i,v,g,u));if(U){if(t&&!p)drawPixel(t,M,b,y,_)}else{if(t){if(D<0){drawPixel(t,M,A,I,E)}else{drawPixel(t,M,T,$,x)}}k++}}else if(t&&!p){drawGrayPixel(e,M,a,t)}}return k}function isPixelData(e){return ArrayBuffer.isView(e)&&e.BYTES_PER_ELEMENT===1}function antialiased(e,n,t,r,i,o,s,a){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 p=e[h];const f=e[h+1];const g=e[h+2];const v=e[h+3];let m=n===c||n===u||t===l||t===d?1:0;let w=0;let b=0;let y=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,p,f,g,v,a);if(I===0){m++;if(m>2)return false}else if(I<w){w=I;y=x;_=A}else if(I>b){b=I;T=x;$=A}}}if(w===0||b===0)return false;return hasManySiblings(o,y,_,r,i)&&hasManySiblings(s,y,_,r,i)||hasManySiblings(o,T,$,r,i)&&hasManySiblings(s,T,$,r,i)}function hasManySiblings(e,n,t,r,i){const o=Math.max(n-1,0);const s=Math.max(t-1,0);const a=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===a||t===s||t===c?1:0;for(let d=o;d<=a;d++){for(let h=s;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 s=e[t+1];const a=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 p=o-l;let f=s-u;let g=a-d;const v=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)}p=(o*c-l*h-_*v)/255;f=(s*c-u*h-T*v)/255;g=(a*c-d*h-$*v)/255}const m=p*.29889531+f*.58662247+g*.11448223;const w=p*.59597799-f*.2741761-g*.32180189;const b=p*.21147017-f*.52261711+g*.31114694;const y=.5053*m*m+.299*w*w+.1957*b*b;return m>0?-y:y}function brightnessDelta(e,n,t,r,i,o,s,a){const c=e[t];const l=e[t+1];const u=e[t+2];const d=e[t+3];let h=r-c;let p=i-l;let f=o-u;const g=s-d;if(!h&&!p&&!f&&!g)return 0;if(s<255||d<255){let v=255,m=255,w=255;if(a){v=48+159*(n%2);m=48+159*((n/1.618033988749895|0)%2);w=48+159*((n/2.618033988749895|0)%2)}h=(r*s-c*d-v*g)/255;p=(i*s-l*d-m*g)/255;f=(o*s-u*d-w*g)/255}return h*.29889531+p*.58662247+f*.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:s}=r;const a=Math.round(s*(t.ignoreTop??0));for(const p of[r,i])p.data.fill(0,0,a*o*4);for(const p of t.masks??[]){const f=Math.max(0,Math.floor(p.x*o));const g=Math.min(o,Math.ceil((p.x+p.width)*o));const v=Math.max(0,Math.floor(p.y*s));const m=Math.min(s,Math.ceil((p.y+p.height)*s));for(const w of[r,i])for(let b=v;b<m;b++)w.data.fill(0,(b*o+f)*4,(b*o+g)*4)}const c=t.threshold??.1;const l=new import_pngjs3.PNG({width:o,height:s});const u=pixelmatch(r.data,i.data,l.data,o,s,{threshold:c,includeAA:false,diffMask:true});const d=new import_pngjs3.PNG({width:o,height:s});pixelmatch(r.data,i.data,d.data,o,s,{threshold:c,includeAA:false,alpha:.25,diffColor:[230,30,40]});const h=o*(s-a);return{width:o,height:s,changedPixels:u,percent:h?u/h*100:0,boxes:changedBoxes(l.data,o,s),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 s=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)s[Math.floor(u/r)*i+Math.floor(d/r)]++}}const a=1;const c=new Uint8Array(i*o);const l=[];for(let u=0;u<s.length;u++){if(c[u]||s[u]<a)continue;const d={x0:Infinity,y0:Infinity,x1:-1,y1:-1,pixels:0};const h=[u];c[u]=1;while(h.length){const p=h.pop();const f=p%i;const g=Math.floor(p/i);d.x0=Math.min(d.x0,f);d.y0=Math.min(d.y0,g);d.x1=Math.max(d.x1,f);d.y1=Math.max(d.y1,g);d.pixels+=s[p];for(let v=-2;v<=2;v++){for(let m=-2;m<=2;m++){const w=f+m;const b=g+v;if(w<0||b<0||w>=i||b>=o)continue;const y=b*i+w;if(!c[y]&&s[y]>=a){c[y]=1;h.push(y)}}}}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:s,height:a}=i;const c=Math.max(0,Math.floor(t.x*s));const l=Math.min(s,Math.ceil((t.x+t.width)*s));const u=Math.max(Math.round(a*r),Math.floor(t.y*a));const d=Math.min(a,Math.ceil((t.y+t.height)*a));const h=new Map;const p=new Map;for(let w=u;w<d;w++){for(let b=c;b<l;b++){const y=(w*s+b)*4;const _=i.data[y]<<16|i.data[y+1]<<8|i.data[y+2];const T=o.data[y]<<16|o.data[y+1]<<8|o.data[y+2];if(_===T)continue;h.set(_,(h.get(_)??0)+1);p.set(T,(p.get(T)??0)+1)}}const f=w=>[...w].sort((b,y)=>y[1]-b[1])[0]?.[0];const g=f(h);const v=f(p);if(g===void 0||v===void 0)return null;const m=w=>`#${w.toString(16).padStart(6,"0").toUpperCase()}`;return{before:m(g),after:m(v)}}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 s=Math.max(1,Math.min(t.height-i,Math.round(n.height*t.height)));const a=new import_pngjs3.PNG({width:o,height:s});import_pngjs3.PNG.bitblt(t,a,r,i,o,s,0,0);return import_pngjs3.PNG.sync.write(a)}var import_node_child_process14=require("child_process");var import_node_util11=require("util");var execFileAsync11=(0,import_node_util11.promisify)(import_node_child_process14.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 s=/digitizer detached \(sender ([0-9A-F]+)\)/i.exec(i);if(s){const a=r.indexOf(s[1]);if(a>=0)r.splice(a,1);if(n===s[1]||n===OTHER_UNSEEN&&a<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 execFileAsync11("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_process16=require("child_process");var import_node_util12=require("util");var import_node_fs22=require("fs");var import_node_os18=__toESM(require("os"));var import_node_path24=__toESM(require("path"));var HID_SWIFT=`import Foundation
142
144
  import Darwin
143
145
  import CryptoKit
144
146
 
@@ -611,10 +613,10 @@ struct Command {
611
613
  down = false
612
614
  }
613
615
  }
614
- `;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_process14=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 s=(0,import_node_child_process14.spawn)(n,["--stream"],{stdio:["pipe","pipe","pipe"]});let a;const c=new Promise(d=>{a=d});i={bin:n,child:s,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);s.ref();s.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;s.on("error",d=>{a();u(d)});s.on("exit",()=>{a();u(new Error("The touch helper closed. Try the next touch."))});s.stdin.on("error",d=>u(d));s.stdout.on("data",d=>{l.buffer+=d;let h;while((h=l.buffer.indexOf("\n"))>=0){const p=l.buffer.slice(0,h);l.buffer=l.buffer.slice(h+1);const f=l.pending;if(!f)continue;try{const g=JSON.parse(p);if(!g||typeof g.ok!=="boolean")throw new Error("Bad reply.");if(g.ok===true){clearTimeout(f.timer);l.pending=void 0;f.resolve()}else u(new Error(g.error??"The touch failed."))}catch{u(new Error("The touch helper sent a bad reply."))}}});s.stderr.resume();s.unref();for(const d of[s.stdin,s.stdout,s.stderr])d.unref?.()}const o=i;if(o.idle)clearTimeout(o.idle);return new Promise((s,a)=>{const c=setTimeout(()=>{o.stop(new Error("The touch helper timed out."))},45e3);o.pending={resolve:s,reject:a,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 execFileAsync12=(0,import_node_util12.promisify)(import_node_child_process15.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 execFileAsync12("xcode-select",["-p"],{timeout:1e4});const n=import_node_path20.default.join(process.env.DEVELOPER_DIR||e.trim(),"..","Info.plist");const{stdout:t}=await execFileAsync12("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_path20.default.join(import_node_os15.default.homedir(),".buoy","hidtouch",`${e}-${HID_HASH}`);const t=import_node_path20.default.join(n,"hidtouch");try{await import_node_fs19.promises.access(t);return t}catch{}try{await import_node_fs19.promises.access(import_node_path20.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_fs19.promises.mkdtemp(import_node_path20.default.join(import_node_os15.default.tmpdir(),"buoy-hidtouch-"));try{await import_node_fs19.promises.mkdir(import_node_path20.default.join(r,"modules"));await import_node_fs19.promises.writeFile(import_node_path20.default.join(r,"hidtouch.swift"),HID_SWIFT);await import_node_fs19.promises.writeFile(import_node_path20.default.join(r,"modules","CoreDevice.swiftinterface"),HID_INTERFACE);const i=import_node_path20.default.join(r,"hidtouch");await execFileAsync12("xcrun",["swiftc","-O","-module-cache-path",import_node_path20.default.join(r,"cache"),"-I",import_node_path20.default.join(r,"modules"),"-F",PRIVATE_FRAMEWORKS,"-framework","CoreDevice","-parse-as-library",import_node_path20.default.join(r,"hidtouch.swift"),"-o",i],{timeout:18e4,maxBuffer:8*1024*1024,env:{...process.env,TMPDIR:r}});await import_node_fs19.promises.mkdir(n,{recursive:true});const o=`${t}.${process.pid}`;await import_node_fs19.promises.copyFile(i,o);await import_node_fs19.promises.chmod(o,493);await import_node_fs19.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_fs19.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 execFileAsync12("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 execFileAsync12("xcrun",["simctl","get_app_container",e,n,"app"],{timeout:1e4});const{stdout:r}=await execFileAsync12("plutil",["-convert","json","-o","-",import_node_path20.default.join(t.trim(),"Info.plist")],{timeout:1e4});const i=JSON.parse(r);const{stdout:o}=await execFileAsync12("xcrun",["simctl","getenv",e,"SIMULATOR_MODEL_IDENTIFIER"],{timeout:1e4});const s=o.trim().startsWith("iPad")?"ipad":"iphone";const a=i[`UISupportedInterfaceOrientations~${s}`]??i.UISupportedInterfaceOrientations;if(!Array.isArray(a)||!a.every(c=>typeof c==="string"))return null;return a.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 run3(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 s=o.stderr||o.message||"";if(/HID Digitizer/i.test(s)&&/not supported/i.test(s)){console.error("[buoy:hid]",s);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: ${s.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,s){const a=t.width>t.height;const c=s!==void 0?s:await deviceOrientation(n);const l=c==="portraitUpsideDown"?await appUpsideDown(n,t.bundleId):null;const[u,d]=toDigitizer(r/t.width,i/t.height,a,c,l);await run3(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,s=0,a=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 p=toDigitizer(i[0]/t.width,i[1]/t.height,l,u,d);const f=String(Math.round(Math.min(1e4,Math.max(1,o))));const g=[frac(h[0]),frac(h[1]),frac(p[0]),frac(p[1])];const v=s>0?["--device",n,"drag",...g,String(Math.round(Math.min(1e4,s))),f]:a>0?["--device",n,"scroll",...g,f,String(Math.round(Math.min(1e4,a)))]:["--device",n,"swipe",...g,f];await run3(e,v,void 0,t.isPhone);return u}async function simHidTwo(e,n,t,r,i,o,s,a){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,s].flatMap(p=>{const[f,g]=toDigitizer(p[0]/t.width,p[1]/t.height,c,l,u);return[(clamp3(f)*d.w).toFixed(2),(clamp3(g)*d.h).toFixed(2)]});await run3(e,["--device",n,"--points",String(d.w),String(d.h),"two",...h,String(Math.round(Math.min(1e4,Math.max(1,a))))],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 run3(e,["--device",n,"type","-"],t)}var import_zod14=require("zod");var import_node_fs23=require("fs");var import_node_path24=__toESM(require("path"));var import_node_crypto14=require("crypto");var import_zod12=require("zod");function pickDescribeScreenMatch(e,n,t){if(t!=null){const o=e.find(s=>s.nativeTag===t);if(o)return o}const r=(n??"").trim().toLowerCase();if(!r)return void 0;let i;for(const o of e){const s=[o.testID,o.label,o.text,o.name].filter(Boolean).map(l=>l.toLowerCase());let a=0;for(const l of s){if(l===r)a=Math.max(a,100);else if(l.startsWith(r))a=Math.max(a,50);else if(l.includes(r))a=Math.max(a,25)}const c=o.tap;if(c&&c.x>=0&&c.x<=1&&c.y>=0&&c.y<=1)a+=20;else if(c)a-=40;if(a<=0)continue;if(!i||a>i.score)i={el:o,score:a}}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_os16=__toESM(require("os"));var import_node_fs20=require("fs");var import_node_path21=__toESM(require("path"));var import_pngjs4=__toESM(require_png());var TOOL_ID="highlight-updates";var MARGIN_PT=12;var CAPTURE_PADDING_PT=6;var fail4=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`
616
+ `;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_process15=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 s=(0,import_node_child_process15.spawn)(n,["--stream"],{stdio:["pipe","pipe","pipe"]});let a;const c=new Promise(d=>{a=d});i={bin:n,child:s,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);s.ref();s.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;s.on("error",d=>{a();u(d)});s.on("exit",()=>{a();u(new Error("The touch helper closed. Try the next touch."))});s.stdin.on("error",d=>u(d));s.stdout.on("data",d=>{l.buffer+=d;let h;while((h=l.buffer.indexOf("\n"))>=0){const p=l.buffer.slice(0,h);l.buffer=l.buffer.slice(h+1);const f=l.pending;if(!f)continue;try{const g=JSON.parse(p);if(!g||typeof g.ok!=="boolean")throw new Error("Bad reply.");if(g.ok===true){clearTimeout(f.timer);l.pending=void 0;f.resolve()}else u(new Error(g.error??"The touch failed."))}catch{u(new Error("The touch helper sent a bad reply."))}}});s.stderr.resume();s.unref();for(const d of[s.stdin,s.stdout,s.stderr])d.unref?.()}const o=i;if(o.idle)clearTimeout(o.idle);return new Promise((s,a)=>{const c=setTimeout(()=>{o.stop(new Error("The touch helper timed out."))},45e3);o.pending={resolve:s,reject:a,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 execFileAsync12=(0,import_node_util12.promisify)(import_node_child_process16.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 execFileAsync12("xcode-select",["-p"],{timeout:1e4});const n=import_node_path24.default.join(process.env.DEVELOPER_DIR||e.trim(),"..","Info.plist");const{stdout:t}=await execFileAsync12("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_path24.default.join(import_node_os18.default.homedir(),".buoy","hidtouch",`${e}-${HID_HASH}`);const t=import_node_path24.default.join(n,"hidtouch");try{await import_node_fs22.promises.access(t);return t}catch{}try{await import_node_fs22.promises.access(import_node_path24.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_fs22.promises.mkdtemp(import_node_path24.default.join(import_node_os18.default.tmpdir(),"buoy-hidtouch-"));try{await import_node_fs22.promises.mkdir(import_node_path24.default.join(r,"modules"));await import_node_fs22.promises.writeFile(import_node_path24.default.join(r,"hidtouch.swift"),HID_SWIFT);await import_node_fs22.promises.writeFile(import_node_path24.default.join(r,"modules","CoreDevice.swiftinterface"),HID_INTERFACE);const i=import_node_path24.default.join(r,"hidtouch");await execFileAsync12("xcrun",["swiftc","-O","-module-cache-path",import_node_path24.default.join(r,"cache"),"-I",import_node_path24.default.join(r,"modules"),"-F",PRIVATE_FRAMEWORKS,"-framework","CoreDevice","-parse-as-library",import_node_path24.default.join(r,"hidtouch.swift"),"-o",i],{timeout:18e4,maxBuffer:8*1024*1024,env:{...process.env,TMPDIR:r}});await import_node_fs22.promises.mkdir(n,{recursive:true});const o=`${t}.${process.pid}`;await import_node_fs22.promises.copyFile(i,o);await import_node_fs22.promises.chmod(o,493);await import_node_fs22.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_fs22.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 execFileAsync12("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 execFileAsync12("xcrun",["simctl","get_app_container",e,n,"app"],{timeout:1e4});const{stdout:r}=await execFileAsync12("plutil",["-convert","json","-o","-",import_node_path24.default.join(t.trim(),"Info.plist")],{timeout:1e4});const i=JSON.parse(r);const{stdout:o}=await execFileAsync12("xcrun",["simctl","getenv",e,"SIMULATOR_MODEL_IDENTIFIER"],{timeout:1e4});const s=o.trim().startsWith("iPad")?"ipad":"iphone";const a=i[`UISupportedInterfaceOrientations~${s}`]??i.UISupportedInterfaceOrientations;if(!Array.isArray(a)||!a.every(c=>typeof c==="string"))return null;return a.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 run3(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 s=o.stderr||o.message||"";if(/HID Digitizer/i.test(s)&&/not supported/i.test(s)){console.error("[buoy:hid]",s);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: ${s.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,s){const a=t.width>t.height;const c=s!==void 0?s:await deviceOrientation(n);const l=c==="portraitUpsideDown"?await appUpsideDown(n,t.bundleId):null;const[u,d]=toDigitizer(r/t.width,i/t.height,a,c,l);await run3(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,s=0,a=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 p=toDigitizer(i[0]/t.width,i[1]/t.height,l,u,d);const f=String(Math.round(Math.min(1e4,Math.max(1,o))));const g=[frac(h[0]),frac(h[1]),frac(p[0]),frac(p[1])];const v=s>0?["--device",n,"drag",...g,String(Math.round(Math.min(1e4,s))),f]:a>0?["--device",n,"scroll",...g,f,String(Math.round(Math.min(1e4,a)))]:["--device",n,"swipe",...g,f];await run3(e,v,void 0,t.isPhone);return u}async function simHidTwo(e,n,t,r,i,o,s,a){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,s].flatMap(p=>{const[f,g]=toDigitizer(p[0]/t.width,p[1]/t.height,c,l,u);return[(clamp3(f)*d.w).toFixed(2),(clamp3(g)*d.h).toFixed(2)]});await run3(e,["--device",n,"--points",String(d.w),String(d.h),"two",...h,String(Math.round(Math.min(1e4,Math.max(1,a))))],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 run3(e,["--device",n,"type","-"],t)}var import_zod14=require("zod");var import_node_fs26=require("fs");var import_node_path28=__toESM(require("path"));var import_node_crypto16=require("crypto");var import_zod12=require("zod");function pickDescribeScreenMatch(e,n,t){if(t!=null){const o=e.find(s=>s.nativeTag===t);if(o)return o}const r=(n??"").trim().toLowerCase();if(!r)return void 0;let i;for(const o of e){const s=[o.testID,o.label,o.text,o.name].filter(Boolean).map(l=>l.toLowerCase());let a=0;for(const l of s){if(l===r)a=Math.max(a,100);else if(l.startsWith(r))a=Math.max(a,50);else if(l.includes(r))a=Math.max(a,25)}const c=o.tap;if(c&&c.x>=0&&c.x<=1&&c.y>=0&&c.y<=1)a+=20;else if(c)a-=40;if(a<=0)continue;if(!i||a>i.score)i={el:o,score:a}}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_os19=__toESM(require("os"));var import_node_fs23=require("fs");var import_node_path25=__toESM(require("path"));var import_pngjs4=__toESM(require_png());var TOOL_ID="highlight-updates";var MARGIN_PT=12;var CAPTURE_PADDING_PT=6;var fail4=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`
615
617
 
616
618
  Closest matches (retry with a more precise query, or pass nativeTag directly):
617
- ${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_zod12.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_zod12.z.string().optional().describe('Fuzzy match against testID, nativeID, accessibilityLabel, component name, or view type \u2014 e.g. "submit-button".'),nativeTag:import_zod12.z.number().optional().describe("An exact nativeTag (from a previous call's candidates) to skip fuzzy matching."),scrollIntoView:import_zod12.z.boolean().optional().describe("Attempt to scroll an off-screen component into view before capture. Default true; inspect the result."),serial:import_zod12.z.string().optional().describe("Android: the adb serial, when several devices are connected."),baseline:import_zod12.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_zod12.z.boolean().optional().describe("With baseline: save the current screen as the new baseline instead of comparing."),steady:import_zod12.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_zod12.z.number().min(0).max(1).optional().describe("With baseline: per-pixel color tolerance, 0 to 1. Default 0.1."),ignore:import_zod12.z.array(import_zod12.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_zod12.z.array(import_zod12.z.object({x:import_zod12.z.number(),y:import_zod12.z.number(),width:import_zod12.z.number(),height:import_zod12.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 fail4("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 fail4("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 fail4("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:y,host:_,online:T}=await hostTarget(n,t.deviceId,{serial:t.serial},{allowOffline:true});let $=Buffer.alloc(0);const x=await maskSecrets(n,y,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 s=await n.callAction(TOOL_ID,"locateComponent",{query:i==null?t.query:void 0,nativeTag:i,scrollIntoView:t.scrollIntoView??true,margin:MARGIN_PT},r);let a=s;if(!a.matched&&(a.reason==="no-renders"||a.reason==="no-match")){const y=await n.callAction(TOOL_ID,"describeScreen",{},r).catch(()=>null);const _=y?.elements?pickDescribeScreenMatch(y.elements,t.query,i):void 0;if(_?.frame&&y?.screen){a={matched:true,live:true,rect:frameToRect(_.frame,y.screen),screen:y.screen,nativeTag:_.nativeTag??void 0,componentName:_.name,testID:_.testID}}else if(a.reason==="no-renders"){a={matched:false,reason:"no-match",candidates:a.candidates}}}if(!a.matched||!a.rect||!a.screen){return fail4(reasonMessage(a,t.query)+candidatesText(a.candidates))}if(i==null&&t.query){const y=t.query.toLowerCase();const _=a.candidates?.find(I=>I.nativeTag===a.nativeTag);const T=await n.callAction(TOOL_ID,"describeScreen",{},r,{timeoutMs:4e3}).catch(()=>null);const $=T?.elements?.find(I=>I.nativeTag===a.nativeTag);const x=[a.testID,a.nativeID,a.componentName,_?.testID,_?.nativeID,_?.componentName,$?.testID,$?.nativeID,$?.text,$?.label].filter(Boolean).map(I=>String(I).toLowerCase());const A=x.some(I=>I.includes(y)||I.length>3&&y.includes(I));if(!A){return fail4(`"${t.query}" is not on the current screen (the closest component was ${a.componentName??"unknown"}${a.testID?` [${a.testID}]`:""}). Navigate to it first, or pass a testID from describe_screen.`+candidatesText(a.candidates))}}const{host:c}=await hostTarget(n,r);if(c.platform!=="ios")return fail4("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_fs20.promises.readFile(l.srcPath):Buffer.alloc(0)});if(u.covered&&l.ok&&l.srcPath)await import_node_fs20.promises.writeFile(l.srcPath,u.png);if(!l.ok||!l.srcPath||!l.width||!l.height){return fail4(l.error??"Screenshot capture failed.")}const d=l.width/a.screen.width;const h=a.rect;const p=CAPTURE_PADDING_PT;const f=await cropToBuffer(l.srcPath,{width:l.width,height:l.height},{x:(h.x-p)*d,y:(h.y-p)*d,width:(h.width+p*2)*d,height:(h.height+p*2)*d});if(!f.ok||!f.buffer){return fail4(f.error??"Crop failed.")}const g=a.componentName||o?.name||"component";const v=a.testID??o?.testID;const m=v?` (testID: "${v}")`:"";const w=a.inView===false?"\n\nNote: the component is partly off-screen even after scrolling, so the crop is clamped to the screen edge.":"";const b=`Captured "${g}"${m} \u2014 ${f.width}\xD7${f.height}px.${w}`;return{content:[{type:"image",data:f.buffer.toString("base64"),mimeType:"image/png"},{type:"text",text:b}]}}catch(r){return fail4(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 s=t?await secretBoxes(e,n,o):null;const a=await i();const c=t?await secretBoxes(e,n,o):null;if(s===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:a,covered:0}}const l=[...s,...c];if(!a.length)return{png:a,covered:0};return{png:l.length?blackOut(a,l):a,covered:Math.max(s.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 s of r.elements??[]){const a=s.value;const c=[s.text,s.label,a].filter(h=>h!=null&&h!=="").map(String);const l=c.some(h=>t.some(p=>showsSecret(h,p)));const u=i&&s.control==="text"&&a===void 0;if(!l&&!u)continue;const d=s.frame?.width&&s.frame.height?fractionFrame(s,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 s=Math.max(0,Math.floor((r.y-.005)*t.height));const a=Math.min(t.height,Math.ceil((r.y+r.height+.005)*t.height));for(let c=s;c<a;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 s=i.filter(l=>l.testID===t&&l.nativeTag!=null);if(s.length===1)return o(s[0]);const a=t.trim().toLowerCase();const c=i.filter(l=>(l.text??l.label??"").trim().toLowerCase()===a&&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_fs20.promises.stat(e));const r=await import_node_fs20.promises.open(e,import_node_fs20.constants.O_RDONLY|import_node_fs20.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 s=Buffer.concat(i,o);if(s.length<24||s.subarray(0,8).toString("hex")!=="89504e470d0a1a0a")throw new Error("The saved file must be a PNG.");const a=s.readUInt32BE(16),c=s.readUInt32BE(20);if(!a||!c||a*c>32e6)throw new Error("Use a PNG with at most 32 million pixels.");return s}finally{await r.close()}}async function compareFileShot(e,n,t,r){const i=n==="~"?import_node_os16.default.homedir():n.startsWith("~/")?import_node_path21.default.join(import_node_os16.default.homedir(),n.slice(2)):n;const o=await readComparisonPng(import_node_path21.default.resolve(process.env.BUOY_PROJECT_ROOT||process.cwd(),i));const{id:s,host:a,online:c}=await hostTarget(e,t,{serial:r},{allowOffline:true});const l=await maskSecrets(e,s,c,()=>hostPng(a));const u=await toSmallImage(o);const d=await toSmallImage(l.png);const h=await measureChange(e,s,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 s;try{s=diffScreens(r,i,{ignoreTop:o})}catch{return null}if(!s.boxes.length)return"Measured: no change outside the status bar.";let a=[];if(t){try{const l=await e.callAction("highlight-updates","describeScreen",{},n,{timeoutMs:3e3,silent:true});const u=l?.screen??{width:1,height:1};a=(l?.elements??[]).map(d=>({name:d.name,words:d.text??d.label,testID:d.testID,frame:fractionFrame(d,u)}))}catch{}}const c=s.boxes.slice(0,3).map(l=>{const u=elementsIn(l,a)[0];const d=boxColors(r,i,l,o);return`- ${describeSpot(l)}${u?`, ${u}`:""}${d?`: main color ${d.before} before, ${d.after} now`:""}.`});return[`Measured: ${s.percent.toFixed(1)}% of the screen changed, in ${s.boxes.length} area${s.boxes.length===1?"":"s"}.`,...c].join("\n")}function baselinePath(e){const n=e.trim().replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"")||"screen";return import_node_path21.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 s=Math.max(0,Math.min(e.y+e.height,i.y+i.height)-Math.max(e.y,i.y));const a=i.width*i.height;if(!a||o*s/a<.5)continue;t.push({label:labelOf(r),area:a,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 s=new Set([...i.values()].map(d=>d.words));const a=[];for(const[d,h]of i){const p=r.get(d);if(p){if(p.words!==h.words)a.push(`changed: ${labelOf({...h,words:void 0})} "${p.words}" \u2192 "${h.words}"`)}else if(!o.has(h.words))a.push(`appeared: ${labelOf(h)}`)}for(const[d,h]of r)if(!i.has(d)&&!s.has(h.words))a.push(`gone: ${labelOf(h)}`);const c=[...r.entries()].filter(([d,h])=>!i.has(d)&&!s.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(f=>f.name===d.name&&u(f.frame,d.frame));if(!h)continue;c.splice(c.indexOf(h),1);const p=new Set([`appeared: ${labelOf(d)}`,`gone: ${labelOf(h)}`]);for(let f=a.length-1;f>=0;f--)if(p.has(a[f]))a.splice(f,1);a.push(`changed: ${labelOf({...d,words:void 0})} "${h.words}" \u2192 "${d.words}"`)}return a.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 s=new Set((r?.elements??[]).map(u=>u.nativeTag));const a=[];for(const u of t?.elements??[]){if(s.has(u.nativeTag))continue;const d=fractionFrame(u,o);if(d)a.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:a,route:l?scrubSecrets(l):void 0}}catch{return null}}async function withFrozenClock(e,n,t,r){let i;let o;let s;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){s=c}}const a=s?` WARNING: putting the app's clock back failed (${errMsg3(s)}); run clock_action reset.`:"";if(o)throw new Error(`${errMsg3(o)}${a}`);return{result:i,note:` The app's clock was frozen at ${new Date(t).toISOString()} for the capture.${a}`}}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 s=o.replace(/\.png$/,".json");const a=import_node_path21.default.relative(process.env.BUOY_PROJECT_ROOT||process.cwd(),o);let c=null;try{c=await import_node_fs20.promises.readFile(o)}catch{}const l=!c||!!t.update;const u=l?{}:JSON.parse(await import_node_fs20.promises.readFile(s,"utf8").catch(()=>"{}"));const d=hostLabel(i);const h=e.connectedDevices().find(P=>P.deviceId===r);const p=h?.tools.some(P=>P.toolId==="clock")??false;const f=p&&hasProAccess(h);const g=t.steady??f;let v="";const m=async()=>{const{result:P,steadied:N}=await withSteadyStatusBar(i,async()=>({png:(await maskSecrets(e,r,true,()=>hostPng(i))).png,screen:await readScreen(e,r)}));return{...P,steadied:N}};let w;if(g&&f){const P=await e.callAction("clock","getState",{},r).catch(()=>null);if(P?.mode==="real"){const N=l||!u.steadyTime?Math.floor(Date.now()/6e4)*6e4:u.steadyTime;u.steadyTime=N;const H=await withFrozenClock(e,r,N,m);w=H.result;v+=H.note}else{w=await m();v+=" The app's clock was already overridden, so it was left as it was."}}else{w=await m();if(g&&!f)v+=p?" (steady freezes the app clock, which needs Buoy Pro; times on screen may differ.)":" (steady needs the Clock tool in the app; times on screen may differ.)"}const b={width:w.png.readUInt32BE(16),height:w.png.readUInt32BE(20)};if(l){await import_node_fs20.promises.mkdir(import_node_path21.default.dirname(o),{recursive:true});await import_node_fs20.promises.writeFile(o,w.png);const P={...u,device:d,size:b,route:w.screen?.route,elements:w.screen?.elements};await import_node_fs20.promises.writeFile(s,JSON.stringify(P,null,1));const N=await toSmallImage(w.png);const H=`${c?"Replaced":"Saved"} baseline "${n}"`;return{outcome:{saved:true,changed:false,percent:0,texts:0,summary:`${H} (first run)`},result:{content:[{type:"image",data:N.data,mimeType:N.mimeType},{type:"text",text:`${c?"Replaced":"Saved"} baseline "${n}" (${a}) from ${d}${w.screen?.route?` on ${w.screen.route}`:""}. Call again with the same baseline to compare.${v}`}]}}}const y=[];if(u.device&&u.device!==d)y.push(`The baseline was saved on ${u.device}; this is ${d}.`);if(u.route&&w.screen?.route&&u.route!==w.screen.route)y.push(`The baseline was on ${u.route}; the app is now on ${w.screen.route}.`);const _=[...t.ignoreAreas??[]];const T=new Set(t.ignore??[]);const $=new Set(T);for(const P of[...u.elements??[],...w.screen?.elements??[]]){if(!P.testID||!T.has(P.testID)||!P.frame)continue;$.delete(P.testID);_.push({x:P.frame.x-.005,y:P.frame.y-.005,width:P.frame.width+.01,height:P.frame.height+.01})}if($.size)y.push(`Not on screen, so not left out: ${[...$].join(", ")}.`);const x=i.platform==="android"?[]:[{x:.28,y:0,width:.44,height:.055}];const A=diffScreens(c,w.png,{threshold:t.threshold,masks:[...w.screen?.masks??[],..._,...x],ignoreTop:w.steadied?0:.065});const I=P=>!!P&&_.some(N=>P.x+P.width/2>=N.x&&P.x+P.width/2<=N.x+N.width&&P.y+P.height/2>=N.y&&P.y+P.height/2<=N.y+N.height);const E=P=>(!P.testID||!T.has(P.testID))&&!I(P.frame);const k=u.elements&&w.screen?textChanges(u.elements.filter(E),w.screen.elements.filter(E)):[];const S=[w.steadied?"":"status bar",w.screen?.masks.length?"Buoy's overlay":"",_.length?"the parts you asked to ignore":""].filter(Boolean);const M=S.join(" and ");const D=M?`; ${M} left out`:"";const R=y.length?`
619
+ ${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_zod12.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_zod12.z.string().optional().describe('Fuzzy match against testID, nativeID, accessibilityLabel, component name, or view type \u2014 e.g. "submit-button".'),nativeTag:import_zod12.z.number().optional().describe("An exact nativeTag (from a previous call's candidates) to skip fuzzy matching."),scrollIntoView:import_zod12.z.boolean().optional().describe("Attempt to scroll an off-screen component into view before capture. Default true; inspect the result."),serial:import_zod12.z.string().optional().describe("Android: the adb serial, when several devices are connected."),baseline:import_zod12.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_zod12.z.boolean().optional().describe("With baseline: save the current screen as the new baseline instead of comparing."),steady:import_zod12.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_zod12.z.number().min(0).max(1).optional().describe("With baseline: per-pixel color tolerance, 0 to 1. Default 0.1."),ignore:import_zod12.z.array(import_zod12.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_zod12.z.array(import_zod12.z.object({x:import_zod12.z.number(),y:import_zod12.z.number(),width:import_zod12.z.number(),height:import_zod12.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 fail4("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 fail4("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 fail4("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:y,host:_,online:T}=await hostTarget(n,t.deviceId,{serial:t.serial},{allowOffline:true});let $=Buffer.alloc(0);const x=await maskSecrets(n,y,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 s=await n.callAction(TOOL_ID,"locateComponent",{query:i==null?t.query:void 0,nativeTag:i,scrollIntoView:t.scrollIntoView??true,margin:MARGIN_PT},r);let a=s;if(!a.matched&&(a.reason==="no-renders"||a.reason==="no-match")){const y=await n.callAction(TOOL_ID,"describeScreen",{},r).catch(()=>null);const _=y?.elements?pickDescribeScreenMatch(y.elements,t.query,i):void 0;if(_?.frame&&y?.screen){a={matched:true,live:true,rect:frameToRect(_.frame,y.screen),screen:y.screen,nativeTag:_.nativeTag??void 0,componentName:_.name,testID:_.testID}}else if(a.reason==="no-renders"){a={matched:false,reason:"no-match",candidates:a.candidates}}}if(!a.matched||!a.rect||!a.screen){return fail4(reasonMessage(a,t.query)+candidatesText(a.candidates))}if(i==null&&t.query){const y=t.query.toLowerCase();const _=a.candidates?.find(I=>I.nativeTag===a.nativeTag);const T=await n.callAction(TOOL_ID,"describeScreen",{},r,{timeoutMs:4e3}).catch(()=>null);const $=T?.elements?.find(I=>I.nativeTag===a.nativeTag);const x=[a.testID,a.nativeID,a.componentName,_?.testID,_?.nativeID,_?.componentName,$?.testID,$?.nativeID,$?.text,$?.label].filter(Boolean).map(I=>String(I).toLowerCase());const A=x.some(I=>I.includes(y)||I.length>3&&y.includes(I));if(!A){return fail4(`"${t.query}" is not on the current screen (the closest component was ${a.componentName??"unknown"}${a.testID?` [${a.testID}]`:""}). Navigate to it first, or pass a testID from describe_screen.`+candidatesText(a.candidates))}}const{host:c}=await hostTarget(n,r);if(c.platform!=="ios")return fail4("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_fs23.promises.readFile(l.srcPath):Buffer.alloc(0)});if(u.covered&&l.ok&&l.srcPath)await import_node_fs23.promises.writeFile(l.srcPath,u.png);if(!l.ok||!l.srcPath||!l.width||!l.height){return fail4(l.error??"Screenshot capture failed.")}const d=l.width/a.screen.width;const h=a.rect;const p=CAPTURE_PADDING_PT;const f=await cropToBuffer(l.srcPath,{width:l.width,height:l.height},{x:(h.x-p)*d,y:(h.y-p)*d,width:(h.width+p*2)*d,height:(h.height+p*2)*d});if(!f.ok||!f.buffer){return fail4(f.error??"Crop failed.")}const g=a.componentName||o?.name||"component";const v=a.testID??o?.testID;const m=v?` (testID: "${v}")`:"";const w=a.inView===false?"\n\nNote: the component is partly off-screen even after scrolling, so the crop is clamped to the screen edge.":"";const b=`Captured "${g}"${m} \u2014 ${f.width}\xD7${f.height}px.${w}`;return{content:[{type:"image",data:f.buffer.toString("base64"),mimeType:"image/png"},{type:"text",text:b}]}}catch(r){return fail4(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 s=t?await secretBoxes(e,n,o):null;const a=await i();const c=t?await secretBoxes(e,n,o):null;if(s===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:a,covered:0}}const l=[...s,...c];if(!a.length)return{png:a,covered:0};return{png:l.length?blackOut(a,l):a,covered:Math.max(s.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 s of r.elements??[]){const a=s.value;const c=[s.text,s.label,a].filter(h=>h!=null&&h!=="").map(String);const l=c.some(h=>t.some(p=>showsSecret(h,p)));const u=i&&s.control==="text"&&a===void 0;if(!l&&!u)continue;const d=s.frame?.width&&s.frame.height?fractionFrame(s,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 s=Math.max(0,Math.floor((r.y-.005)*t.height));const a=Math.min(t.height,Math.ceil((r.y+r.height+.005)*t.height));for(let c=s;c<a;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 s=i.filter(l=>l.testID===t&&l.nativeTag!=null);if(s.length===1)return o(s[0]);const a=t.trim().toLowerCase();const c=i.filter(l=>(l.text??l.label??"").trim().toLowerCase()===a&&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_fs23.promises.stat(e));const r=await import_node_fs23.promises.open(e,import_node_fs23.constants.O_RDONLY|import_node_fs23.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 s=Buffer.concat(i,o);if(s.length<24||s.subarray(0,8).toString("hex")!=="89504e470d0a1a0a")throw new Error("The saved file must be a PNG.");const a=s.readUInt32BE(16),c=s.readUInt32BE(20);if(!a||!c||a*c>32e6)throw new Error("Use a PNG with at most 32 million pixels.");return s}finally{await r.close()}}async function compareFileShot(e,n,t,r){const i=n==="~"?import_node_os19.default.homedir():n.startsWith("~/")?import_node_path25.default.join(import_node_os19.default.homedir(),n.slice(2)):n;const o=await readComparisonPng(import_node_path25.default.resolve(process.env.BUOY_PROJECT_ROOT||process.cwd(),i));const{id:s,host:a,online:c}=await hostTarget(e,t,{serial:r},{allowOffline:true});const l=await maskSecrets(e,s,c,()=>hostPng(a));const u=await toSmallImage(o);const d=await toSmallImage(l.png);const h=await measureChange(e,s,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 s;try{s=diffScreens(r,i,{ignoreTop:o})}catch{return null}if(!s.boxes.length)return"Measured: no change outside the status bar.";let a=[];if(t){try{const l=await e.callAction("highlight-updates","describeScreen",{},n,{timeoutMs:3e3,silent:true});const u=l?.screen??{width:1,height:1};a=(l?.elements??[]).map(d=>({name:d.name,words:d.text??d.label,testID:d.testID,frame:fractionFrame(d,u)}))}catch{}}const c=s.boxes.slice(0,3).map(l=>{const u=elementsIn(l,a)[0];const d=boxColors(r,i,l,o);return`- ${describeSpot(l)}${u?`, ${u}`:""}${d?`: main color ${d.before} before, ${d.after} now`:""}.`});return[`Measured: ${s.percent.toFixed(1)}% of the screen changed, in ${s.boxes.length} area${s.boxes.length===1?"":"s"}.`,...c].join("\n")}function baselinePath(e){const n=e.trim().replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"")||"screen";return import_node_path25.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 s=Math.max(0,Math.min(e.y+e.height,i.y+i.height)-Math.max(e.y,i.y));const a=i.width*i.height;if(!a||o*s/a<.5)continue;t.push({label:labelOf(r),area:a,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 s=new Set([...i.values()].map(d=>d.words));const a=[];for(const[d,h]of i){const p=r.get(d);if(p){if(p.words!==h.words)a.push(`changed: ${labelOf({...h,words:void 0})} "${p.words}" \u2192 "${h.words}"`)}else if(!o.has(h.words))a.push(`appeared: ${labelOf(h)}`)}for(const[d,h]of r)if(!i.has(d)&&!s.has(h.words))a.push(`gone: ${labelOf(h)}`);const c=[...r.entries()].filter(([d,h])=>!i.has(d)&&!s.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(f=>f.name===d.name&&u(f.frame,d.frame));if(!h)continue;c.splice(c.indexOf(h),1);const p=new Set([`appeared: ${labelOf(d)}`,`gone: ${labelOf(h)}`]);for(let f=a.length-1;f>=0;f--)if(p.has(a[f]))a.splice(f,1);a.push(`changed: ${labelOf({...d,words:void 0})} "${h.words}" \u2192 "${d.words}"`)}return a.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 s=new Set((r?.elements??[]).map(u=>u.nativeTag));const a=[];for(const u of t?.elements??[]){if(s.has(u.nativeTag))continue;const d=fractionFrame(u,o);if(d)a.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:a,route:l?scrubSecrets(l):void 0}}catch{return null}}async function withFrozenClock(e,n,t,r){let i;let o;let s;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){s=c}}const a=s?` WARNING: putting the app's clock back failed (${errMsg3(s)}); run clock_action reset.`:"";if(o)throw new Error(`${errMsg3(o)}${a}`);return{result:i,note:` The app's clock was frozen at ${new Date(t).toISOString()} for the capture.${a}`}}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 s=o.replace(/\.png$/,".json");const a=import_node_path25.default.relative(process.env.BUOY_PROJECT_ROOT||process.cwd(),o);let c=null;try{c=await import_node_fs23.promises.readFile(o)}catch{}const l=!c||!!t.update;const u=l?{}:JSON.parse(await import_node_fs23.promises.readFile(s,"utf8").catch(()=>"{}"));const d=hostLabel(i);const h=e.connectedDevices().find(P=>P.deviceId===r);const p=h?.tools.some(P=>P.toolId==="clock")??false;const f=p&&hasProAccess(h);const g=t.steady??f;let v="";const m=async()=>{const{result:P,steadied:N}=await withSteadyStatusBar(i,async()=>({png:(await maskSecrets(e,r,true,()=>hostPng(i))).png,screen:await readScreen(e,r)}));return{...P,steadied:N}};let w;if(g&&f){const P=await e.callAction("clock","getState",{},r).catch(()=>null);if(P?.mode==="real"){const N=l||!u.steadyTime?Math.floor(Date.now()/6e4)*6e4:u.steadyTime;u.steadyTime=N;const H=await withFrozenClock(e,r,N,m);w=H.result;v+=H.note}else{w=await m();v+=" The app's clock was already overridden, so it was left as it was."}}else{w=await m();if(g&&!f)v+=p?" (steady freezes the app clock, which needs Buoy Pro; times on screen may differ.)":" (steady needs the Clock tool in the app; times on screen may differ.)"}const b={width:w.png.readUInt32BE(16),height:w.png.readUInt32BE(20)};if(l){await import_node_fs23.promises.mkdir(import_node_path25.default.dirname(o),{recursive:true});await import_node_fs23.promises.writeFile(o,w.png);const P={...u,device:d,size:b,route:w.screen?.route,elements:w.screen?.elements};await import_node_fs23.promises.writeFile(s,JSON.stringify(P,null,1));const N=await toSmallImage(w.png);const H=`${c?"Replaced":"Saved"} baseline "${n}"`;return{outcome:{saved:true,changed:false,percent:0,texts:0,summary:`${H} (first run)`},result:{content:[{type:"image",data:N.data,mimeType:N.mimeType},{type:"text",text:`${c?"Replaced":"Saved"} baseline "${n}" (${a}) from ${d}${w.screen?.route?` on ${w.screen.route}`:""}. Call again with the same baseline to compare.${v}`}]}}}const y=[];if(u.device&&u.device!==d)y.push(`The baseline was saved on ${u.device}; this is ${d}.`);if(u.route&&w.screen?.route&&u.route!==w.screen.route)y.push(`The baseline was on ${u.route}; the app is now on ${w.screen.route}.`);const _=[...t.ignoreAreas??[]];const T=new Set(t.ignore??[]);const $=new Set(T);for(const P of[...u.elements??[],...w.screen?.elements??[]]){if(!P.testID||!T.has(P.testID)||!P.frame)continue;$.delete(P.testID);_.push({x:P.frame.x-.005,y:P.frame.y-.005,width:P.frame.width+.01,height:P.frame.height+.01})}if($.size)y.push(`Not on screen, so not left out: ${[...$].join(", ")}.`);const x=i.platform==="android"?[]:[{x:.28,y:0,width:.44,height:.055}];const A=diffScreens(c,w.png,{threshold:t.threshold,masks:[...w.screen?.masks??[],..._,...x],ignoreTop:w.steadied?0:.065});const I=P=>!!P&&_.some(N=>P.x+P.width/2>=N.x&&P.x+P.width/2<=N.x+N.width&&P.y+P.height/2>=N.y&&P.y+P.height/2<=N.y+N.height);const E=P=>(!P.testID||!T.has(P.testID))&&!I(P.frame);const k=u.elements&&w.screen?textChanges(u.elements.filter(E),w.screen.elements.filter(E)):[];const S=[w.steadied?"":"status bar",w.screen?.masks.length?"Buoy's overlay":"",_.length?"the parts you asked to ignore":""].filter(Boolean);const M=S.join(" and ");const D=M?`; ${M} left out`:"";const R=y.length?`
618
620
 
619
621
  \u26A0\uFE0F ${y.join(" ")}`:"";if(A.changedPixels===0&&k.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}" (${a}${D}).${v}${R}`)}}const O=A.boxes.map((P,N)=>{const H=w.screen?elementsIn(P,w.screen.elements):[];const j=`${describeSpot(P)} (x ${P.x.toFixed(2)}, y ${P.y.toFixed(2)}, ${P.width.toFixed(2)}\xD7${P.height.toFixed(2)})`;return`${N+1}. ${j}${H.length?`: ${H.join(", ")}`:""}`});const U=await toSmallImage(A.diffPng);const C=A.percent<.01&&A.changedPixels>0?"<0.01":A.percent.toFixed(2);const F=O[0]?`; ${O[0].replace(/^1\. /,"")}`:"";const z=k[0]?`; ${k[0]}`:"";const B=A.changedPixels===0?`no pixel change from baseline "${n}", but text changed`:`${C}% changed from baseline "${n}"`;const L={saved:false,changed:true,percent:A.percent,texts:k.length,summary:`${B}${F}${z}`};return{outcome:L,result:{content:[{type:"image",data:U.data,mimeType:U.mimeType},{type:"text",text:`**Changed from baseline "${n}": ${A.percent<.01&&A.changedPixels>0?"<0.01":A.percent.toFixed(2)}% of the screen** (${A.changedPixels} px${D}). Changes are red in the picture.${v}`+(O.length?`
620
622
 
@@ -624,9 +626,9 @@ ${O.join("\n")}`:"")+(k.length?`
624
626
  Text:
625
627
  ${k.map(P=>`- ${P}`).join("\n")}`:"")+`${R}
626
628
 
627
- If this change is expected, save it with updateBaseline: true.`}]}}}var import_zod13=require("zod");var import_node_fs21=require("fs");var import_node_path22=__toESM(require("path"));var FLOW_DIR=()=>import_node_path22.default.join(process.cwd(),".buoy","flows");var FLOW_NAME=/^[A-Za-z0-9_-]{1,64}$/;async function listSavedFlows(){try{return(await import_node_fs21.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 text3=e=>({content:[{type:"text",text:e}]});var fail5=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=s=>{if(!s||typeof s!=="object"||Array.isArray(s))return s;const a=s;return[a.testID,a.text,a.query,a.label,a.name].find(c=>typeof c==="string")??s};for(const s of["tap","into","waitFor","waitGone","expect","expectGone"])n[s]=t(n[s]);for(const s of Object.keys(n))if(n[s]===void 0)delete n[s];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(s=>typeof s==="string");for(const s of["query","text","target","selector","element","testID"])delete n[s];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_zod13.z.preprocess(normalizeStep,import_zod13.z.object({tap:import_zod13.z.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),longPress:import_zod13.z.boolean().optional().describe("Make `tap` a long-press instead."),type:import_zod13.z.string().optional().describe("Text to type (needs `into`)."),into:import_zod13.z.string().optional().describe("Target text input for `type`: testID or fuzzy text."),set:import_zod13.z.union([import_zod13.z.number(),import_zod13.z.boolean()]).optional().describe("Set a toggle (true/false) or slider (number) \u2014 pair with `tap` as the target."),swipe:import_zod13.z.enum(["up","down","left","right"]).optional().describe('A real swipe, the way the finger moves: "up" scrolls down the list.'),untilEnd:import_zod13.z.boolean().optional().describe("With swipe: keep swiping until the screen stops moving (the end of the list)."),real:import_zod13.z.boolean().optional().describe("Make this step's tap a real touch. Default: the flow's `real`."),reload:import_zod13.z.boolean().optional().describe("Reload the JS bundle before this step's action."),waitMs:import_zod13.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_zod13.z.string().optional().describe("Wait until an element matching this appears (default 5s)."),waitGone:import_zod13.z.string().optional().describe("Wait until no element matches this (default 5s)."),expect:import_zod13.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_zod13.z.string().optional().describe("Assert nothing matches this (waits up to 2s for it to go); fails the flow if something does."),snapshot:import_zod13.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_zod13.z.number().min(0).max(100).optional().describe("snapshot: allowed changed share of the screen, in percent. Default 0.05."),timeoutMs:import_zod13.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_zod13.z.array(stepSchema).min(1).optional().describe("Steps to run, in order. Leave out when replaying a saved flow."),flow:import_zod13.z.string().optional().describe("Replay a saved flow by name (from .buoy/flows in the project) instead of passing steps."),save:import_zod13.z.string().optional().describe('Save these steps under this name when the flow passes, so it can be replayed with flow:"name".'),include:import_zod13.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_zod13.z.boolean().optional().describe("Save every snapshot step's screen as its new baseline instead of comparing."),continueOnFailure:import_zod13.z.boolean().optional().describe("Keep going after a failed step instead of stopping. Default false."),real:import_zod13.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()=>fail5("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. Needs the app interaction integration. Works on the free tier.",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 fail5(`Flow names use letters, numbers, - and _ (got "${t.flow}").`);try{i=JSON.parse(await import_node_fs21.promises.readFile(import_node_path22.default.join(FLOW_DIR(),`${t.flow}.json`),"utf8")).steps}catch{const k=await listSavedFlows();return fail5(`No saved flow "${t.flow}". ${k.length?`Saved flows: ${k.join(", ")}.`:'No flows are saved yet; run one with save:"name" first.'}`)}}if(!i||i.length===0)return fail5('Pass steps, or flow:"name" to replay a saved flow.');if(t.save&&!FLOW_NAME.test(t.save))return fail5(`Flow names use letters, numbers, - and _ (got "${t.save}").`);const o=n.requireProDevice(t.deviceId);const s=t.include??"all";const a=nativeKit(n);let c=null;const l=()=>c??=hostTarget(n,o).then(async k=>{await a.primeScreen(o,k.host,k.online);return k});let u;const d=async(k,S,M,D)=>{const R=S?await a.buoyCover(o,k,M):null;if(R)throw new Error(R);const O=D?600:void 0;const U=await a.touch(k,M,O,u);if(U!==void 0)u=U;await a.mark(o,k,O?"hold":"tap",[[M.x,M.y]],void 0,O??150,U);await delay3(120);return`${D?"long-pressed":"tapped"} ${M.what} (real touch)`};const h=async(k,S,M)=>{const{host:D,online:R}=await l();const O=Date.now();let U=false;for(;;){let C=await a.findSpot(o,D,k,R,"app");if("miss"in C&&!C.tie&&(U||!R||Date.now()-O>=600)){if(!U){U=true;C=await a.findSpot(o,D,k,R,"native")}if("miss"in C&&!C.tie)C=await a.findSpot(o,D,k,R,"loose")}if(!("miss"in C))return d(D,R,C,S);if(C.tie||Date.now()-O>=M)throw new Error(C.miss);await delay3(POLL_MS)}};const p=async(k,S,M)=>{let D;try{D=await l()}catch{return null}if(D.host.platform==="ios-device")return null;const R=await a.findSpot(o,D.host,k,D.online,M?"nativeExact":"native").catch(()=>null);if(!R||"miss"in R)return null;return d(D.host,D.online,R,S)};const f=async()=>{const k=await n.callAction(UI_TOOL_ID,"describeScreen",{},o);return k?.elements??[]};const g=async()=>{try{const k=await n.callAction(APP_TOOL_ID,"ping",{},o,{timeoutMs:REALM_PROBE_MS,silent:true});return typeof k?.startedAt==="number"?k.startedAt:null}catch{return null}};const v=async(k,S)=>{const M=Date.now();while(Date.now()-M<S){const D=await g();if(D!==null&&D!==k)return Date.now()-M;await delay3(POLL_MS)}return null};const m=new Set;const w=new Set;const b=new Set((n.connectedDevices().find(k=>k.deviceId===o)?.tools??[]).map(k=>k.toolId));if(s==="all"){if(b.has("console")){const{payload:k}=await n.getSnapshot("console",o).catch(()=>({payload:null}));const S=k?.entries??[];for(const M of S)m.add(M.id)}if(b.has("network")){const{payload:k}=await n.getSnapshot("network",o).catch(()=>({payload:null}));const S=Array.isArray(k)?k:k?.events??[];for(const M of S)w.add(M.id)}}const y=async(k,S)=>{const M=Date.now();let D=false;for(;;){if(Date.now()-M>=S||Date.now()-r>MAX_FLOW_MS){return{ok:false,ms:Date.now()-M,unread:!D}}let R;try{R=await f();D=true}catch{await delay3(POLL_MS);continue}if(k(R))return{ok:true,ms:Date.now()-M,unread:false};await delay3(POLL_MS)}};const _=k=>`could not read the screen within ${k}ms, so this step is unknown`;const T=[];let $=null;let x=0;for(let k=0;k<i.length;k++){const S=i[k];const M=`${k+1}`;const D=S.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`);$=k;break}const R=[];const O=[];const U=S.reload||S.tap||S.swipe||S.type!==void 0||S.waitMs||S.waitFor||S.waitGone||S.expect||S.expectGone||S.snapshot;if(!U){T.push(`${k+1} \u2717 step does nothing \u2014 give it a tap/type/wait/expect${S.set!==void 0?" (`set` needs `tap` naming the control)":""}`);$=$??k;if(!t.continueOnFailure)break;continue}try{if(S.reload){const C=await g();await n.callAction(APP_TOOL_ID,"reloadApp",{strategy:"auto"},o);await delay3(TEARDOWN_GRACE_MS);const F=await v(C,Math.max(D,2e4));if(F==null){R.push("app did not come back after reload")}else{O.push(`reloaded (${F}ms)`);await y(z=>z.length>0,1e4)}}if(S.type!==void 0){const C=S.into??S.tap;if(!C){R.push("`type` needs `into` (which input to type into)")}else{const F=await n.callAction(UI_TOOL_ID,"tapElement",{...selector(C),text:fillSecrets(S.type)},o);if(!F?.tapped){R.push(F?.reason??`could not type into "${C}"`)}else if(F.matched?.via&&F.matched.via!=="onChangeText"){R.push(`"${C}" is not a text input \u2014 it ran ${F.matched.via} instead, and the text was not entered`)}else{O.push(`typed ${JSON.stringify(S.type)} into "${C}"`)}}}else if(S.tap&&(S.real??t.real)&&S.set===void 0){O.push(await h(S.tap,S.longPress,S.timeoutMs??3e3))}else if(S.tap){const C={...selector(S.tap)};if(S.longPress)C.longPress=true;if(S.set!==void 0)C.value=S.set;let F=await n.callAction(UI_TOOL_ID,"tapElement",C,o);for(let P=0;!F?.tapped&&/No element matched/.test(F?.reason??"")&&P<TAP_SETTLE_MS;P+=POLL_MS){await delay3(POLL_MS);F=await n.callAction(UI_TOOL_ID,"tapElement",C,o)}const z=/isn't showing|No element matched|no JS press handler|can't be driven in JS/;const B=/equally well/.test(F?.reason??"");const L=!F?.tapped&&S.set===void 0&&(B||z.test(F?.reason??""))?await p(S.tap,S.longPress,B):null;if(L){O.push(L)}else if(!F?.tapped){R.push(F?.reason??`no element matched "${S.tap}"`)}else{const P=F.matched;const N=P?.text??P?.label??P?.name??S.tap;if(S.set!==void 0&&P?.via&&P.via!=="onValueChange"){R.push(`"${N}" is not a toggle/slider \u2014 it ran ${P.via} instead, so it was not set to ${JSON.stringify(S.set)}`)}else{O.push(S.set!==void 0?`set "${N}" \u2192 ${JSON.stringify(P?.value??S.set)}`:`${S.longPress?"long-pressed":"tapped"} "${N}"`)}}}if(!R.length&&S.swipe){const{host:C,online:F}=await l();const z=await a.screenOf(C);const B=S.swipe;const{from:L,to:P}=swipePoints(B,!!S.untilEnd);const N=[L[0]*z.width,L[1]*z.height];const H=[P[0]*z.width,P[1]*z.height];const j=F?await a.buoyCover(o,C,{x:N[0],y:N[1]}):null;if(j)throw new Error(j);if(S.untilEnd){const{swipes:W,atEnd:V,lastRow:J}=await a.scrollToEnd(o,C,N,H,250);if(V)O.push(`swiped ${B} to the end (${W} swipes)${J?`; the last row is "${J}"`:""}`);else R.push(`swiped ${B} ${W} times and the screen was still moving`)}else{const W=await a.swipe(C,N,H,300);await a.mark(o,C,"swipe",[N],[H],300,W);await delay3(400);O.push(`swiped ${B}`)}}if(!R.length&&S.waitMs){await delay3(S.waitMs);O.push(`waited ${S.waitMs}ms`)}if(!R.length&&S.waitFor){const C=await y(F=>F.some(z=>matches(z,S.waitFor)),D);if(C.ok)O.push(`"${S.waitFor}" appeared (${C.ms}ms)`);else R.push(C.unread?_(D):`"${S.waitFor}" never appeared within ${D}ms`)}if(!R.length&&S.waitGone){const C=await y(F=>!F.some(z=>matches(z,S.waitGone)),D);if(C.ok)O.push(`"${S.waitGone}" gone (${C.ms}ms)`);else R.push(C.unread?_(D):`"${S.waitGone}" was still there after ${D}ms`)}if(!R.length&&S.expect){const C=await y(F=>F.some(z=>matches(z,S.expect)),S.timeoutMs??ASSERT_SETTLE_MS);if(C.ok)O.push(`"${S.expect}" is on screen`);else R.push(C.unread?_(S.timeoutMs??ASSERT_SETTLE_MS):`expected "${S.expect}" on screen \u2014 not found`)}if(!R.length&&S.expectGone){const C=await y(F=>!F.some(z=>matches(z,S.expectGone)),S.timeoutMs??ASSERT_SETTLE_MS);if(C.ok)O.push(`"${S.expectGone}" is gone`);else R.push(C.unread?_(S.timeoutMs??ASSERT_SETTLE_MS):`expected "${S.expectGone}" to be gone \u2014 still on screen`)}if(!R.length&&S.snapshot){const{outcome:C}=await runBaseline(n,S.snapshot,{deviceId:o,update:t.updateSnapshots});const F=S.maxChange??.05;if(C.changed&&(C.texts>0||C.percent>F)){R.push(`${C.summary}${C.texts>0?"":` (more than ${F}%)`}. Run screenshot_component with baseline "${S.snapshot}" to see the diff, or updateSnapshots: true if it is expected.`)}else O.push(C.summary)}}catch(C){R.push(errMsg4(C))}if(R.length){T.push(`${M} \u2717 ${describeStep(S)} \u2014 ${R.join("; ")}`);$=$??k;if(!t.continueOnFailure)break}else{x++;T.push(`${M} \u2713 ${O.join(", ")||describeStep(S)}`)}}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(s!=="none"){E.push(`**Screen now:**${await observeAfterAction(n,o,void 0,0)}`)}if(s==="all"){if(b.has("network")){const{payload:k}=await n.getSnapshot("network",o).catch(()=>({payload:null}));const S=Array.isArray(k)?k:k?.events??[];const M=S.filter(D=>!w.has(D.id)).slice(-15);if(M.length){E.push(`**Network during this flow (${M.length}):**
629
+ If this change is expected, save it with updateBaseline: true.`}]}}}var import_zod13=require("zod");var import_node_fs24=require("fs");var import_node_path26=__toESM(require("path"));var FLOW_DIR=()=>import_node_path26.default.join(process.cwd(),".buoy","flows");var FLOW_NAME=/^[A-Za-z0-9_-]{1,64}$/;async function listSavedFlows(){try{return(await import_node_fs24.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 text3=e=>({content:[{type:"text",text:e}]});var fail5=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=s=>{if(!s||typeof s!=="object"||Array.isArray(s))return s;const a=s;return[a.testID,a.text,a.query,a.label,a.name].find(c=>typeof c==="string")??s};for(const s of["tap","into","waitFor","waitGone","expect","expectGone"])n[s]=t(n[s]);for(const s of Object.keys(n))if(n[s]===void 0)delete n[s];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(s=>typeof s==="string");for(const s of["query","text","target","selector","element","testID"])delete n[s];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_zod13.z.preprocess(normalizeStep,import_zod13.z.object({tap:import_zod13.z.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),longPress:import_zod13.z.boolean().optional().describe("Make `tap` a long-press instead."),type:import_zod13.z.string().optional().describe("Text to type (needs `into`)."),into:import_zod13.z.string().optional().describe("Target text input for `type`: testID or fuzzy text."),set:import_zod13.z.union([import_zod13.z.number(),import_zod13.z.boolean()]).optional().describe("Set a toggle (true/false) or slider (number) \u2014 pair with `tap` as the target."),swipe:import_zod13.z.enum(["up","down","left","right"]).optional().describe('A real swipe, the way the finger moves: "up" scrolls down the list.'),untilEnd:import_zod13.z.boolean().optional().describe("With swipe: keep swiping until the screen stops moving (the end of the list)."),real:import_zod13.z.boolean().optional().describe("Make this step's tap a real touch. Default: the flow's `real`."),reload:import_zod13.z.boolean().optional().describe("Reload the JS bundle before this step's action."),waitMs:import_zod13.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_zod13.z.string().optional().describe("Wait until an element matching this appears (default 5s)."),waitGone:import_zod13.z.string().optional().describe("Wait until no element matches this (default 5s)."),expect:import_zod13.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_zod13.z.string().optional().describe("Assert nothing matches this (waits up to 2s for it to go); fails the flow if something does."),snapshot:import_zod13.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_zod13.z.number().min(0).max(100).optional().describe("snapshot: allowed changed share of the screen, in percent. Default 0.05."),timeoutMs:import_zod13.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_zod13.z.array(stepSchema).min(1).optional().describe("Steps to run, in order. Leave out when replaying a saved flow."),flow:import_zod13.z.string().optional().describe("Replay a saved flow by name (from .buoy/flows in the project) instead of passing steps."),save:import_zod13.z.string().optional().describe('Save these steps under this name when the flow passes, so it can be replayed with flow:"name".'),include:import_zod13.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_zod13.z.boolean().optional().describe("Save every snapshot step's screen as its new baseline instead of comparing."),continueOnFailure:import_zod13.z.boolean().optional().describe("Keep going after a failed step instead of stopping. Default false."),real:import_zod13.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()=>fail5("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. Needs the app interaction integration. Works on the free tier.",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 fail5(`Flow names use letters, numbers, - and _ (got "${t.flow}").`);try{i=JSON.parse(await import_node_fs24.promises.readFile(import_node_path26.default.join(FLOW_DIR(),`${t.flow}.json`),"utf8")).steps}catch{const k=await listSavedFlows();return fail5(`No saved flow "${t.flow}". ${k.length?`Saved flows: ${k.join(", ")}.`:'No flows are saved yet; run one with save:"name" first.'}`)}}if(!i||i.length===0)return fail5('Pass steps, or flow:"name" to replay a saved flow.');if(t.save&&!FLOW_NAME.test(t.save))return fail5(`Flow names use letters, numbers, - and _ (got "${t.save}").`);const o=n.requireProDevice(t.deviceId);const s=t.include??"all";const a=nativeKit(n);let c=null;const l=()=>c??=hostTarget(n,o).then(async k=>{await a.primeScreen(o,k.host,k.online);return k});let u;const d=async(k,S,M,D)=>{const R=S?await a.buoyCover(o,k,M):null;if(R)throw new Error(R);const O=D?600:void 0;const U=await a.touch(k,M,O,u);if(U!==void 0)u=U;await a.mark(o,k,O?"hold":"tap",[[M.x,M.y]],void 0,O??150,U);await delay3(120);return`${D?"long-pressed":"tapped"} ${M.what} (real touch)`};const h=async(k,S,M)=>{const{host:D,online:R}=await l();const O=Date.now();let U=false;for(;;){let C=await a.findSpot(o,D,k,R,"app");if("miss"in C&&!C.tie&&(U||!R||Date.now()-O>=600)){if(!U){U=true;C=await a.findSpot(o,D,k,R,"native")}if("miss"in C&&!C.tie)C=await a.findSpot(o,D,k,R,"loose")}if(!("miss"in C))return d(D,R,C,S);if(C.tie||Date.now()-O>=M)throw new Error(C.miss);await delay3(POLL_MS)}};const p=async(k,S,M)=>{let D;try{D=await l()}catch{return null}if(D.host.platform==="ios-device")return null;const R=await a.findSpot(o,D.host,k,D.online,M?"nativeExact":"native").catch(()=>null);if(!R||"miss"in R)return null;return d(D.host,D.online,R,S)};const f=async()=>{const k=await n.callAction(UI_TOOL_ID,"describeScreen",{},o);return k?.elements??[]};const g=async()=>{try{const k=await n.callAction(APP_TOOL_ID,"ping",{},o,{timeoutMs:REALM_PROBE_MS,silent:true});return typeof k?.startedAt==="number"?k.startedAt:null}catch{return null}};const v=async(k,S)=>{const M=Date.now();while(Date.now()-M<S){const D=await g();if(D!==null&&D!==k)return Date.now()-M;await delay3(POLL_MS)}return null};const m=new Set;const w=new Set;const b=new Set((n.connectedDevices().find(k=>k.deviceId===o)?.tools??[]).map(k=>k.toolId));if(s==="all"){if(b.has("console")){const{payload:k}=await n.getSnapshot("console",o).catch(()=>({payload:null}));const S=k?.entries??[];for(const M of S)m.add(M.id)}if(b.has("network")){const{payload:k}=await n.getSnapshot("network",o).catch(()=>({payload:null}));const S=Array.isArray(k)?k:k?.events??[];for(const M of S)w.add(M.id)}}const y=async(k,S)=>{const M=Date.now();let D=false;for(;;){if(Date.now()-M>=S||Date.now()-r>MAX_FLOW_MS){return{ok:false,ms:Date.now()-M,unread:!D}}let R;try{R=await f();D=true}catch{await delay3(POLL_MS);continue}if(k(R))return{ok:true,ms:Date.now()-M,unread:false};await delay3(POLL_MS)}};const _=k=>`could not read the screen within ${k}ms, so this step is unknown`;const T=[];let $=null;let x=0;for(let k=0;k<i.length;k++){const S=i[k];const M=`${k+1}`;const D=S.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`);$=k;break}const R=[];const O=[];const U=S.reload||S.tap||S.swipe||S.type!==void 0||S.waitMs||S.waitFor||S.waitGone||S.expect||S.expectGone||S.snapshot;if(!U){T.push(`${k+1} \u2717 step does nothing \u2014 give it a tap/type/wait/expect${S.set!==void 0?" (`set` needs `tap` naming the control)":""}`);$=$??k;if(!t.continueOnFailure)break;continue}try{if(S.reload){const C=await g();await n.callAction(APP_TOOL_ID,"reloadApp",{strategy:"auto"},o);await delay3(TEARDOWN_GRACE_MS);const F=await v(C,Math.max(D,2e4));if(F==null){R.push("app did not come back after reload")}else{O.push(`reloaded (${F}ms)`);await y(z=>z.length>0,1e4)}}if(S.type!==void 0){const C=S.into??S.tap;if(!C){R.push("`type` needs `into` (which input to type into)")}else{const F=await n.callAction(UI_TOOL_ID,"tapElement",{...selector(C),text:fillSecrets(S.type)},o);if(!F?.tapped){R.push(F?.reason??`could not type into "${C}"`)}else if(F.matched?.via&&F.matched.via!=="onChangeText"){R.push(`"${C}" is not a text input \u2014 it ran ${F.matched.via} instead, and the text was not entered`)}else{O.push(`typed ${JSON.stringify(S.type)} into "${C}"`)}}}else if(S.tap&&(S.real??t.real)&&S.set===void 0){O.push(await h(S.tap,S.longPress,S.timeoutMs??3e3))}else if(S.tap){const C={...selector(S.tap)};if(S.longPress)C.longPress=true;if(S.set!==void 0)C.value=S.set;let F=await n.callAction(UI_TOOL_ID,"tapElement",C,o);for(let P=0;!F?.tapped&&/No element matched/.test(F?.reason??"")&&P<TAP_SETTLE_MS;P+=POLL_MS){await delay3(POLL_MS);F=await n.callAction(UI_TOOL_ID,"tapElement",C,o)}const z=/isn't showing|No element matched|no JS press handler|can't be driven in JS/;const B=/equally well/.test(F?.reason??"");const L=!F?.tapped&&S.set===void 0&&(B||z.test(F?.reason??""))?await p(S.tap,S.longPress,B):null;if(L){O.push(L)}else if(!F?.tapped){R.push(F?.reason??`no element matched "${S.tap}"`)}else{const P=F.matched;const N=P?.text??P?.label??P?.name??S.tap;if(S.set!==void 0&&P?.via&&P.via!=="onValueChange"){R.push(`"${N}" is not a toggle/slider \u2014 it ran ${P.via} instead, so it was not set to ${JSON.stringify(S.set)}`)}else{O.push(S.set!==void 0?`set "${N}" \u2192 ${JSON.stringify(P?.value??S.set)}`:`${S.longPress?"long-pressed":"tapped"} "${N}"`)}}}if(!R.length&&S.swipe){const{host:C,online:F}=await l();const z=await a.screenOf(C);const B=S.swipe;const{from:L,to:P}=swipePoints(B,!!S.untilEnd);const N=[L[0]*z.width,L[1]*z.height];const H=[P[0]*z.width,P[1]*z.height];const j=F?await a.buoyCover(o,C,{x:N[0],y:N[1]}):null;if(j)throw new Error(j);if(S.untilEnd){const{swipes:W,atEnd:V,lastRow:J}=await a.scrollToEnd(o,C,N,H,250);if(V)O.push(`swiped ${B} to the end (${W} swipes)${J?`; the last row is "${J}"`:""}`);else R.push(`swiped ${B} ${W} times and the screen was still moving`)}else{const W=await a.swipe(C,N,H,300);await a.mark(o,C,"swipe",[N],[H],300,W);await delay3(400);O.push(`swiped ${B}`)}}if(!R.length&&S.waitMs){await delay3(S.waitMs);O.push(`waited ${S.waitMs}ms`)}if(!R.length&&S.waitFor){const C=await y(F=>F.some(z=>matches(z,S.waitFor)),D);if(C.ok)O.push(`"${S.waitFor}" appeared (${C.ms}ms)`);else R.push(C.unread?_(D):`"${S.waitFor}" never appeared within ${D}ms`)}if(!R.length&&S.waitGone){const C=await y(F=>!F.some(z=>matches(z,S.waitGone)),D);if(C.ok)O.push(`"${S.waitGone}" gone (${C.ms}ms)`);else R.push(C.unread?_(D):`"${S.waitGone}" was still there after ${D}ms`)}if(!R.length&&S.expect){const C=await y(F=>F.some(z=>matches(z,S.expect)),S.timeoutMs??ASSERT_SETTLE_MS);if(C.ok)O.push(`"${S.expect}" is on screen`);else R.push(C.unread?_(S.timeoutMs??ASSERT_SETTLE_MS):`expected "${S.expect}" on screen \u2014 not found`)}if(!R.length&&S.expectGone){const C=await y(F=>!F.some(z=>matches(z,S.expectGone)),S.timeoutMs??ASSERT_SETTLE_MS);if(C.ok)O.push(`"${S.expectGone}" is gone`);else R.push(C.unread?_(S.timeoutMs??ASSERT_SETTLE_MS):`expected "${S.expectGone}" to be gone \u2014 still on screen`)}if(!R.length&&S.snapshot){const{outcome:C}=await runBaseline(n,S.snapshot,{deviceId:o,update:t.updateSnapshots});const F=S.maxChange??.05;if(C.changed&&(C.texts>0||C.percent>F)){R.push(`${C.summary}${C.texts>0?"":` (more than ${F}%)`}. Run screenshot_component with baseline "${S.snapshot}" to see the diff, or updateSnapshots: true if it is expected.`)}else O.push(C.summary)}}catch(C){R.push(errMsg4(C))}if(R.length){T.push(`${M} \u2717 ${describeStep(S)} \u2014 ${R.join("; ")}`);$=$??k;if(!t.continueOnFailure)break}else{x++;T.push(`${M} \u2713 ${O.join(", ")||describeStep(S)}`)}}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(s!=="none"){E.push(`**Screen now:**${await observeAfterAction(n,o,void 0,0)}`)}if(s==="all"){if(b.has("network")){const{payload:k}=await n.getSnapshot("network",o).catch(()=>({payload:null}));const S=Array.isArray(k)?k:k?.events??[];const M=S.filter(D=>!w.has(D.id)).slice(-15);if(M.length){E.push(`**Network during this flow (${M.length}):**
628
630
  `+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(b.has("console")){const{payload:k}=await n.getSnapshot("console",o).catch(()=>({payload:null}));const S=k?.entries??[];const M=S.filter(D=>!m.has(D.id)&&(D.level==="error"||D.level==="warning")).slice(-10);if(M.length){E.push(`**Console during this flow (${M.length}):**
629
- `+M.map(D=>`[${D.level==="error"?"ERR":"warn"}] ${cap(firstLines(scrubSecrets(D.message??"")),220)}`).join("\n"))}}}if(t.save&&$===null){await import_node_fs21.promises.mkdir(FLOW_DIR(),{recursive:true});const k=import_node_path22.default.join(FLOW_DIR(),`${t.save}.json`);await import_node_fs21.promises.writeFile(k,JSON.stringify({steps:i},null,2)+"\n");E.push(`Saved as flow "${t.save}" (${import_node_path22.default.relative(process.cwd(),k)}). 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?text3(E.join("\n\n")):{...text3(E.join("\n\n")),isError:true}}catch(i){return fail5(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_process16=require("child_process");var import_node_util13=require("util");var import_node_fs22=require("fs");var import_node_path23=__toESM(require("path"));var MAX_RECORDING_MS=3*6e4;var live=new Set;async function startRecording(e,n){await import_node_fs22.promises.mkdir(import_node_path23.default.dirname(n),{recursive:true});const t=Date.now();let r;let i;if(e.platform==="ios"){r=(0,import_node_child_process16.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_process16.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_process16.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 s="";let a=t;let c;r.stderr?.on("data",d=>{s+=String(d);if(/Recording started/i.test(String(d)))a=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 p=setInterval(()=>{if(e.platform==="ios"&&a!==t||e.platform==="android"&&c!==void 0){clearTimeout(h);clearInterval(p);d(null)}},50);r.once("exit",f=>{clearTimeout(h);clearInterval(p);d(f??-1)});r.once("error",()=>{clearTimeout(h);clearInterval(p);d(-1)})});live.delete(o);if(l!==null){if(/not supported by this device/i.test(s)){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: ${s.trim().slice(0,300)||`exit ${l}`}`)}if(e.platform==="ios"&&r.pid){const d=r.pid;const h=(0,import_node_child_process16.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:a,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_fs22.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 execFileAsync13("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 s=a=>execFileAsync13("ffmpeg",["-y","-v","error","-i",e,"-vf",`tpad=stop_mode=clone:stop_duration=${i.toFixed(2)},fps=30`,"-an",...a,"-pix_fmt","yuv420p","-movflags","+faststart",o],{timeout:24e4,maxBuffer:4*1024*1024});try{await s(["-c:v","h264_videotoolbox","-b:v","6M"])}catch{await s(["-c:v","libx264","-preset","veryfast","-crf","22"])}await import_node_fs22.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 s=n.width>n.height?!o:o;return s?[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,s,a]=[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=[(s[0]+a[0])/2,(s[1]+a[1])/2];const u=Math.atan2(i[1]-c[1],i[0]-c[0]);let d=Math.atan2(s[1]-l[1],s[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(s[0]-l[0],s[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 execFileAsync13=(0,import_node_util13.promisify)(import_node_child_process16.execFile);async function burnTouchMarks(e,n,t){let r;try{r=(await execFileAsync13("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 s={width:i,height:o};const a=Math.max(8,Math.round(Math.min(i,o)*.045));const c=a*2;const l=Math.max(2,Math.round(a*.18));const u=g=>g.toFixed(3);const d=[];for(const g of n){const v=g.t/1e3;const m=Math.max(g.ms,1)/1e3;const w=`clip((t-${u(v)})/${u(m)},0,1)`;const b=`enable='between(t,${u(v)},${u(v+m+.35)})':eval=frame:shortest=1`;const y=pinchPath(g);if(y){const{width:_,height:T}=g.screen;const $=markPoint([0,0],g.screen,s,g.orientation);const x=markPoint([1,0],g.screen,s,g.orientation);const A=markPoint([0,1],g.screen,s,g.orientation);[1,-1].forEach(I=>{const E=`(${u(y.r0)}+(${u(y.r1-y.r0)})*${w})`;const k=`(${u(y.a0)}+(${u(y.turn)})*${w})`;const S=`clip((${u(y.c0[0])}+(${u(y.c1[0]-y.c0[0])})*${w}+${I}*${E}*cos(${k}))/${u(_)},0,1)`;const M=`clip((${u(y.c0[1])}+(${u(y.c1[1]-y.c0[1])})*${w}+${I}*${E}*sin(${k}))/${u(T)},0,1)`;const[D,R]=[0,1].map(O=>`(${$[O]}+(${x[O]-$[O]})*${S}+(${A[O]-$[O]})*${M})`);d.push(`overlay=x='${D}*${i}-${a}':y='${R}*${o}-${a}':${b}`)});continue}g.from.forEach((_,T)=>{const[$,x]=markPoint(_,g.screen,s,g.orientation);const[A,I]=markPoint(g.to?.[T]??_,g.screen,s,g.orientation);d.push(`overlay=x='${u($*i-a)}+(${u((A-$)*i)})*${w}':y='${u(x*o-a)}+(${u((I-x)*o)})*${w}':${b}`)})}const h=d.slice(0,MAX_BURN_DOTS);const p=["[0:v]fps=30[base]",`[1:v]split=${h.length}${h.map((g,v)=>`[c${v}]`).join("")}`,...h.map((g,v)=>`${v===0?"[base]":`[v${v-1}]`}[c${v}]${g}[v${v}]`)].join(";");const f=`color=c=white@0:s=${c}x${c},format=rgba,geq=r='255':g='255':b='255':a='if(lte(hypot(X-${a},Y-${a}),${a}),if(gte(hypot(X-${a},Y-${a}),${a-l}),235,105),0)'`;await execFileAsync13("ffmpeg",["-y","-v","error","-i",e,"-f","lavfi","-i",f,"-filter_complex",p,"-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>
631
+ `+M.map(D=>`[${D.level==="error"?"ERR":"warn"}] ${cap(firstLines(scrubSecrets(D.message??"")),220)}`).join("\n"))}}}if(t.save&&$===null){await import_node_fs24.promises.mkdir(FLOW_DIR(),{recursive:true});const k=import_node_path26.default.join(FLOW_DIR(),`${t.save}.json`);await import_node_fs24.promises.writeFile(k,JSON.stringify({steps:i},null,2)+"\n");E.push(`Saved as flow "${t.save}" (${import_node_path26.default.relative(process.cwd(),k)}). 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?text3(E.join("\n\n")):{...text3(E.join("\n\n")),isError:true}}catch(i){return fail5(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_process17=require("child_process");var import_node_util13=require("util");var import_node_fs25=require("fs");var import_node_path27=__toESM(require("path"));var MAX_RECORDING_MS=3*6e4;var live=new Set;async function startRecording(e,n){await import_node_fs25.promises.mkdir(import_node_path27.default.dirname(n),{recursive:true});const t=Date.now();let r;let i;if(e.platform==="ios"){r=(0,import_node_child_process17.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_process17.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_process17.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 s="";let a=t;let c;r.stderr?.on("data",d=>{s+=String(d);if(/Recording started/i.test(String(d)))a=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 p=setInterval(()=>{if(e.platform==="ios"&&a!==t||e.platform==="android"&&c!==void 0){clearTimeout(h);clearInterval(p);d(null)}},50);r.once("exit",f=>{clearTimeout(h);clearInterval(p);d(f??-1)});r.once("error",()=>{clearTimeout(h);clearInterval(p);d(-1)})});live.delete(o);if(l!==null){if(/not supported by this device/i.test(s)){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: ${s.trim().slice(0,300)||`exit ${l}`}`)}if(e.platform==="ios"&&r.pid){const d=r.pid;const h=(0,import_node_child_process17.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:a,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_fs25.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 execFileAsync13("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 s=a=>execFileAsync13("ffmpeg",["-y","-v","error","-i",e,"-vf",`tpad=stop_mode=clone:stop_duration=${i.toFixed(2)},fps=30`,"-an",...a,"-pix_fmt","yuv420p","-movflags","+faststart",o],{timeout:24e4,maxBuffer:4*1024*1024});try{await s(["-c:v","h264_videotoolbox","-b:v","6M"])}catch{await s(["-c:v","libx264","-preset","veryfast","-crf","22"])}await import_node_fs25.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 s=n.width>n.height?!o:o;return s?[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,s,a]=[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=[(s[0]+a[0])/2,(s[1]+a[1])/2];const u=Math.atan2(i[1]-c[1],i[0]-c[0]);let d=Math.atan2(s[1]-l[1],s[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(s[0]-l[0],s[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 execFileAsync13=(0,import_node_util13.promisify)(import_node_child_process17.execFile);async function burnTouchMarks(e,n,t){let r;try{r=(await execFileAsync13("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 s={width:i,height:o};const a=Math.max(8,Math.round(Math.min(i,o)*.045));const c=a*2;const l=Math.max(2,Math.round(a*.18));const u=g=>g.toFixed(3);const d=[];for(const g of n){const v=g.t/1e3;const m=Math.max(g.ms,1)/1e3;const w=`clip((t-${u(v)})/${u(m)},0,1)`;const b=`enable='between(t,${u(v)},${u(v+m+.35)})':eval=frame:shortest=1`;const y=pinchPath(g);if(y){const{width:_,height:T}=g.screen;const $=markPoint([0,0],g.screen,s,g.orientation);const x=markPoint([1,0],g.screen,s,g.orientation);const A=markPoint([0,1],g.screen,s,g.orientation);[1,-1].forEach(I=>{const E=`(${u(y.r0)}+(${u(y.r1-y.r0)})*${w})`;const k=`(${u(y.a0)}+(${u(y.turn)})*${w})`;const S=`clip((${u(y.c0[0])}+(${u(y.c1[0]-y.c0[0])})*${w}+${I}*${E}*cos(${k}))/${u(_)},0,1)`;const M=`clip((${u(y.c0[1])}+(${u(y.c1[1]-y.c0[1])})*${w}+${I}*${E}*sin(${k}))/${u(T)},0,1)`;const[D,R]=[0,1].map(O=>`(${$[O]}+(${x[O]-$[O]})*${S}+(${A[O]-$[O]})*${M})`);d.push(`overlay=x='${D}*${i}-${a}':y='${R}*${o}-${a}':${b}`)});continue}g.from.forEach((_,T)=>{const[$,x]=markPoint(_,g.screen,s,g.orientation);const[A,I]=markPoint(g.to?.[T]??_,g.screen,s,g.orientation);d.push(`overlay=x='${u($*i-a)}+(${u((A-$)*i)})*${w}':y='${u(x*o-a)}+(${u((I-x)*o)})*${w}':${b}`)})}const h=d.slice(0,MAX_BURN_DOTS);const p=["[0:v]fps=30[base]",`[1:v]split=${h.length}${h.map((g,v)=>`[c${v}]`).join("")}`,...h.map((g,v)=>`${v===0?"[base]":`[v${v-1}]`}[c${v}]${g}[v${v}]`)].join(";");const f=`color=c=white@0:s=${c}x${c},format=rgba,geq=r='255':g='255':b='255':a='if(lte(hypot(X-${a},Y-${a}),${a}),if(gte(hypot(X-${a},Y-${a}),${a-l}),235,105),0)'`;await execFileAsync13("ffmpeg",["-y","-v","error","-i",e,"-f","lavfi","-i",f,"-filter_complex",p,"-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>
630
632
  <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
631
633
  <title>${escapeHtml(e.title)}</title>
632
634
  <style>
@@ -678,12 +680,12 @@ const c=(n)=>Math.min(1,Math.max(0,n));for(const s of [1,-1])dot(place([c((cx+s*
678
680
  m.from.forEach((p,i)=>{const q=(m.to&&m.to[i])||p;const a=place(p,m),b=place(q,m);dot([a[0]+(b[0]-a[0])*k,a[1]+(b[1]-a[1])*k])})}}
679
681
  (function tick(){marks();requestAnimationFrame(tick)})();
680
682
  <\/script></body></html>
681
- `}function escapeHtml(e){return e.replace(/[&<>"']/g,n=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[n])}var sessions=new Map;var finished=new Map;var delay4=e=>new Promise(n=>setTimeout(n,e));function projectDir(){return process.env.BUOY_PROJECT_ROOT||process.cwd()}function stamp(e=new Date){const n=t=>String(t).padStart(2,"0");return`${e.getFullYear()}${n(e.getMonth()+1)}${n(e.getDate())}-${n(e.getHours())}${n(e.getMinutes())}${n(e.getSeconds())}`}var READ_ONLY=/^(get_|list_|describe_screen$|screenshot_component$|screen_recording$|wait_for_automation$|compare_reports$)/;function noteAgentCall(e,n,t){if(READ_ONLY.test(n)||sessions.size===0)return;let r=typeof t?.deviceId==="string"?t.deviceId:void 0;if(!r){try{r=e.resolveDevice()}catch{return}}const i=r?sessions.get(r):void 0;if(!i?.rec)return;const o=Object.entries(t??{}).filter(([s,a])=>s!=="deviceId"&&a!==void 0&&typeof a!=="object").map(([s,a])=>`${s}: ${String(a).slice(0,60)}`).join(", ");i.agent.push({at:Date.now(),t:0,source:"agent",status:"neutral",title:n,detail:o?redact(o):void 0});clearTimeout(i.afterAction);i.afterAction=setTimeout(()=>void gather(e,i),700);i.afterAction.unref?.()}function isRecording(e){return!!sessions.get(e)?.rec}function noteTouch(e,n){const t=sessions.get(e);if(t?.rec&&t.marks.length<500)t.marks.push(n)}function gather(e,n){return runWithAccess({tool:"screen_recording",level:"free"},()=>gatherNow(e,n)).catch(()=>{n.failedPolls++})}async function gatherNow(e,n){const t=e.connectedDevices().some(i=>i.deviceId===n.id);if(!t){n.failedPolls++;addConsole(n,(e.lastSync(n.id,"console")?.payload??{}).entries??[]);return}if(!e.connectedDevices().some(i=>i.deviceId===n.id&&hasProAccess(i))){n.notes.add("The events timeline needs Buoy Pro; this video shows console lines and agent steps only.")}else try{const i=await e.callAction("events","exportEvents",{settings:{format:"json",includeEventData:false},limit:500},n.id,{timeoutMs:4e3,silent:true});const o=i?.output?JSON.parse(i.output):null;const s=Array.isArray(o)?o:o?.events??[];for(const a of s){const c=a.timestamp?Date.parse(a.timestamp):NaN;if(!Number.isFinite(c))continue;const l=a.status==="error"||a.status==="success"||a.status==="pending"?a.status:"neutral";const u={at:c,t:0,source:a.source??"event",status:l,title:scrubSecrets(redact(a.title??"")),detail:a.subtitle?scrubSecrets(redact(a.subtitle)):void 0};n.events.set(`${c}|${u.source}|${u.title}|${u.detail??""}|${l}`,u)}if((i?.returned??0)>=500)n.notes.add("Busy app: some events may be missing from busy stretches.")}catch{n.failedPolls++}let r=[];try{const{payload:i}=await e.getSnapshot("console",n.id,{timeoutMs:2500,silent:true});r=i?.entries??[]}catch{r=(e.lastSync(n.id,"console")?.payload??{}).entries??[]}addConsole(n,r)}function addConsole(e,n){for(const t of n){if(typeof t.timestamp!=="number")continue;const[r,...i]=scrubSecrets(redact(t.message??"")).split("\n");const o=t.level==="error"?"error":t.level==="warning"?"warning":"neutral";e.events.set(`console|${t.timestamp}|${t.id??r}`,{at:t.timestamp,t:0,source:"console",status:o,title:r.slice(0,200),detail:i.join("\n").trim().slice(0,600)||void 0})}}async function finish(e,n){const t=n.rec;if(n.poll)clearInterval(n.poll);clearTimeout(n.afterAction);n.stopped??={durationMs:await stopRecording(t)};const{durationMs:r}=n.stopped;await gather(e,n);if(n.failedPolls)n.notes.add(`The app's events could not be read ${n.failedPolls} time(s) during the recording (the app may have been reloading or stuck), so parts of the timeline may be missing.`);const i=t.startedAt;const o=i+r;const s=[...n.events.values(),...n.agent].filter(v=>v.at>=i-500&&v.at<=o+500).map(({at:v,...m})=>({...m,title:scrubSecrets(m.title),detail:m.detail?scrubSecrets(m.detail):void 0,t:Math.max(0,v-i)})).sort((v,m)=>v.t-m.t);if(!s.some(v=>v.source!=="agent"))n.notes.add("No app events were captured. Is the Events tool installed in the app?");const a=t.file.replace(/\.mp4$/,"");const c=hostLabel(t.host);const l=n.marks.filter(v=>v.at>=i-500&&v.at<=o).map(({at:v,...m})=>({...m,t:Math.max(0,v-i)})).sort((v,m)=>v.t-m.t);let u=null;if(l.length){try{u=await burnTouchMarks(t.file,l,`${a}-taps.mp4`);if(u){const v=touchDotNote(l);if(v)n.notes.add(v)}if(!u)n.notes.add("Install ffmpeg to also get a copy of the video with the taps drawn in. The viewer shows them either way.")}catch(v){n.notes.add(`Could not draw the taps into a copy of the video: ${errMsg2(v).slice(0,160)}. The viewer shows them either way.`)}}const d=[...n.notes];await import_node_fs23.promises.writeFile(`${a}.timeline.json`,JSON.stringify({device:c,startedAt:new Date(i).toISOString(),durationMs:r,notes:d,items:s,touches:l},null,1));await import_node_fs23.promises.writeFile(`${a}.html`,viewerHtml({title:n.name,video:import_node_path24.default.basename(t.file),durationMs:r,items:s,device:c,notes:d,marks:l}));sessions.delete(n.id);const h=v=>import_node_path24.default.relative(projectDir(),v);const p=new Map;for(const v of s)p.set(v.source,(p.get(v.source)??0)+1);const f=v=>`${(v/1e3).toFixed(1)}s`;const g=s.filter(v=>v.status==="error"||v.source==="route"||v.source==="agent").slice(0,14);return[`Saved a ${f(r)} recording of ${c}.`,`- Video: ${h(t.file)}`,`- Viewer (video + timeline, click an event to jump there): ${h(`${a}.html`)}`,`- Timeline data: ${h(`${a}.timeline.json`)}`,...u?[`- Video with touch dots: ${h(u)}`]:l.length?[`- The viewer draws the ${l.length} real touch(es) on the video.`]:[],"",s.length?`Events: ${[...p].map(([v,m])=>`${v} ${m}`).join(", ")}.`:"No events in this window.",...g.length?["What happened:",...g.map(v=>`- ${f(v.t)} [${v.source}]${v.status==="error"?" ERROR":""} ${v.title}${v.detail&&v.source!=="route"?` (${v.detail.split("\n")[0].slice(0,80)})`:""}`)]:[],...d.map(v=>`Note: ${v}`),"Recordings are kept out of git (.buoy/recordings/.gitignore). Secrets in logs are hidden, but the video shows the screen as it was: check it before sharing."].join("\n")}var STEPS_HOLD_MS=1200;var STEPS_MIN_MS=3e3;function registerRecordingTools(e,n){setRecordingProbe(()=>sessions.size>0);e.registerTool("screen_recording",{_meta:coreTool(),description:"Record the screen of the iOS Simulator or Android device (start, do the steps, stop). On stop, saves an MP4 plus a viewer page that plays it beside a timeline of what the app did (web calls, query fetches, route changes, store writes, console errors) and what you did (your taps and other actions), and returns a short written summary. Real touches (native_tap, native_swipe, native_pinch) show as marks on the video, and with ffmpeg installed a copy of the MP4 has them drawn in. In .buoy/recordings. Use it to show a bug or a fix, e.g. for a pull request. Max 3 minutes. To record a set of taps or swipes, pass them as steps with start: Buoy records, runs them with real touches, stops and saves, all in one call.",inputSchema:{action:import_zod14.z.enum(["start","stop"]),name:import_zod14.z.string().optional().describe('start: a short name for the files, e.g. "checkout-timeout".'),steps:import_zod14.z.array(stepSchema).min(1).optional().describe('start: run_flow steps to record, e.g. [{tap:"One"},{tap:"Two"}]. Taps and swipes are real touches, so they show on the video. Each tap waits for its target, so no waitMs is needed between taps. The video stops and saves when they finish; no stop call needed.'),serial:import_zod14.z.string().optional().describe("Android: the adb serial, when several devices are connected."),deviceId:deviceIdInput}},async t=>{try{if(t.action==="start"){const{id:o,host:s}=await hostTarget(n,t.deviceId,{serial:t.serial});if(sessions.has(o))return fail2("A recording is already running on this device. Stop it first.");const a=(t.name??"recording").trim().replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"recording";const c={id:o,name:a,events:new Map,agent:[],notes:new Set,failedPolls:0,marks:[]};sessions.set(o,c);let l;c.starting=new Promise(d=>l=d);try{const d=import_node_path24.default.join(projectDir(),".buoy","recordings");await import_node_fs23.promises.mkdir(d,{recursive:true});await import_node_fs23.promises.writeFile(import_node_path24.default.join(d,".gitignore"),"*\n",{flag:"wx"}).catch(()=>void 0);if(n.connectedDevices().some(p=>p.deviceId===o&&hasProAccess(p)))await n.getSnapshot("events",o,{timeoutMs:2e3,silent:true}).catch(()=>void 0);const h=import_node_path24.default.join(d,`${a}-${stamp()}-${(0,import_node_crypto14.randomUUID)().slice(0,6)}.mp4`);c.rec=await startRecording(s,h)}catch(d){sessions.delete(o);throw d}finally{l()}c.poll=setInterval(()=>void gather(n,c),2e3);c.poll.unref?.();c.rec.stopTimer=setTimeout(()=>{c.finishing??=finish(n,c);c.finishing.then(d=>finished.set(o,`The recording hit the ${MAX_RECORDING_MS/6e4}-minute limit and was saved.
683
+ `}function escapeHtml(e){return e.replace(/[&<>"']/g,n=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[n])}var sessions=new Map;var finished=new Map;var delay4=e=>new Promise(n=>setTimeout(n,e));function projectDir(){return process.env.BUOY_PROJECT_ROOT||process.cwd()}function stamp(e=new Date){const n=t=>String(t).padStart(2,"0");return`${e.getFullYear()}${n(e.getMonth()+1)}${n(e.getDate())}-${n(e.getHours())}${n(e.getMinutes())}${n(e.getSeconds())}`}var READ_ONLY=/^(get_|list_|describe_screen$|screenshot_component$|screen_recording$|wait_for_automation$|compare_reports$)/;function noteAgentCall(e,n,t){if(READ_ONLY.test(n)||sessions.size===0)return;let r=typeof t?.deviceId==="string"?t.deviceId:void 0;if(!r){try{r=e.resolveDevice()}catch{return}}const i=r?sessions.get(r):void 0;if(!i?.rec)return;const o=Object.entries(t??{}).filter(([s,a])=>s!=="deviceId"&&a!==void 0&&typeof a!=="object").map(([s,a])=>`${s}: ${String(a).slice(0,60)}`).join(", ");i.agent.push({at:Date.now(),t:0,source:"agent",status:"neutral",title:n,detail:o?redact(o):void 0});clearTimeout(i.afterAction);i.afterAction=setTimeout(()=>void gather(e,i),700);i.afterAction.unref?.()}function isRecording(e){return!!sessions.get(e)?.rec}function noteTouch(e,n){const t=sessions.get(e);if(t?.rec&&t.marks.length<500)t.marks.push(n)}function gather(e,n){return runWithAccess({tool:"screen_recording",level:"free"},()=>gatherNow(e,n)).catch(()=>{n.failedPolls++})}async function gatherNow(e,n){const t=e.connectedDevices().some(i=>i.deviceId===n.id);if(!t){n.failedPolls++;addConsole(n,(e.lastSync(n.id,"console")?.payload??{}).entries??[]);return}if(!e.connectedDevices().some(i=>i.deviceId===n.id&&hasProAccess(i))){n.notes.add("The events timeline needs Buoy Pro; this video shows console lines and agent steps only.")}else try{const i=await e.callAction("events","exportEvents",{settings:{format:"json",includeEventData:false},limit:500},n.id,{timeoutMs:4e3,silent:true});const o=i?.output?JSON.parse(i.output):null;const s=Array.isArray(o)?o:o?.events??[];for(const a of s){const c=a.timestamp?Date.parse(a.timestamp):NaN;if(!Number.isFinite(c))continue;const l=a.status==="error"||a.status==="success"||a.status==="pending"?a.status:"neutral";const u={at:c,t:0,source:a.source??"event",status:l,title:scrubSecrets(redact(a.title??"")),detail:a.subtitle?scrubSecrets(redact(a.subtitle)):void 0};n.events.set(`${c}|${u.source}|${u.title}|${u.detail??""}|${l}`,u)}if((i?.returned??0)>=500)n.notes.add("Busy app: some events may be missing from busy stretches.")}catch{n.failedPolls++}let r=[];try{const{payload:i}=await e.getSnapshot("console",n.id,{timeoutMs:2500,silent:true});r=i?.entries??[]}catch{r=(e.lastSync(n.id,"console")?.payload??{}).entries??[]}addConsole(n,r)}function addConsole(e,n){for(const t of n){if(typeof t.timestamp!=="number")continue;const[r,...i]=scrubSecrets(redact(t.message??"")).split("\n");const o=t.level==="error"?"error":t.level==="warning"?"warning":"neutral";e.events.set(`console|${t.timestamp}|${t.id??r}`,{at:t.timestamp,t:0,source:"console",status:o,title:r.slice(0,200),detail:i.join("\n").trim().slice(0,600)||void 0})}}async function finish(e,n){const t=n.rec;if(n.poll)clearInterval(n.poll);clearTimeout(n.afterAction);n.stopped??={durationMs:await stopRecording(t)};const{durationMs:r}=n.stopped;await gather(e,n);if(n.failedPolls)n.notes.add(`The app's events could not be read ${n.failedPolls} time(s) during the recording (the app may have been reloading or stuck), so parts of the timeline may be missing.`);const i=t.startedAt;const o=i+r;const s=[...n.events.values(),...n.agent].filter(v=>v.at>=i-500&&v.at<=o+500).map(({at:v,...m})=>({...m,title:scrubSecrets(m.title),detail:m.detail?scrubSecrets(m.detail):void 0,t:Math.max(0,v-i)})).sort((v,m)=>v.t-m.t);if(!s.some(v=>v.source!=="agent"))n.notes.add("No app events were captured. Is the Events tool installed in the app?");const a=t.file.replace(/\.mp4$/,"");const c=hostLabel(t.host);const l=n.marks.filter(v=>v.at>=i-500&&v.at<=o).map(({at:v,...m})=>({...m,t:Math.max(0,v-i)})).sort((v,m)=>v.t-m.t);let u=null;if(l.length){try{u=await burnTouchMarks(t.file,l,`${a}-taps.mp4`);if(u){const v=touchDotNote(l);if(v)n.notes.add(v)}if(!u)n.notes.add("Install ffmpeg to also get a copy of the video with the taps drawn in. The viewer shows them either way.")}catch(v){n.notes.add(`Could not draw the taps into a copy of the video: ${errMsg2(v).slice(0,160)}. The viewer shows them either way.`)}}const d=[...n.notes];await import_node_fs26.promises.writeFile(`${a}.timeline.json`,JSON.stringify({device:c,startedAt:new Date(i).toISOString(),durationMs:r,notes:d,items:s,touches:l},null,1));await import_node_fs26.promises.writeFile(`${a}.html`,viewerHtml({title:n.name,video:import_node_path28.default.basename(t.file),durationMs:r,items:s,device:c,notes:d,marks:l}));sessions.delete(n.id);const h=v=>import_node_path28.default.relative(projectDir(),v);const p=new Map;for(const v of s)p.set(v.source,(p.get(v.source)??0)+1);const f=v=>`${(v/1e3).toFixed(1)}s`;const g=s.filter(v=>v.status==="error"||v.source==="route"||v.source==="agent").slice(0,14);return[`Saved a ${f(r)} recording of ${c}.`,`- Video: ${h(t.file)}`,`- Viewer (video + timeline, click an event to jump there): ${h(`${a}.html`)}`,`- Timeline data: ${h(`${a}.timeline.json`)}`,...u?[`- Video with touch dots: ${h(u)}`]:l.length?[`- The viewer draws the ${l.length} real touch(es) on the video.`]:[],"",s.length?`Events: ${[...p].map(([v,m])=>`${v} ${m}`).join(", ")}.`:"No events in this window.",...g.length?["What happened:",...g.map(v=>`- ${f(v.t)} [${v.source}]${v.status==="error"?" ERROR":""} ${v.title}${v.detail&&v.source!=="route"?` (${v.detail.split("\n")[0].slice(0,80)})`:""}`)]:[],...d.map(v=>`Note: ${v}`),"Recordings are kept out of git (.buoy/recordings/.gitignore). Secrets in logs are hidden, but the video shows the screen as it was: check it before sharing."].join("\n")}var STEPS_HOLD_MS=1200;var STEPS_MIN_MS=3e3;function registerRecordingTools(e,n){setRecordingProbe(()=>sessions.size>0);e.registerTool("screen_recording",{_meta:coreTool(),description:"Record the screen of the iOS Simulator or Android device (start, do the steps, stop). On stop, saves an MP4 plus a viewer page that plays it beside a timeline of what the app did (web calls, query fetches, route changes, store writes, console errors) and what you did (your taps and other actions), and returns a short written summary. Real touches (native_tap, native_swipe, native_pinch) show as marks on the video, and with ffmpeg installed a copy of the MP4 has them drawn in. In .buoy/recordings. Use it to show a bug or a fix, e.g. for a pull request. Max 3 minutes. To record a set of taps or swipes, pass them as steps with start: Buoy records, runs them with real touches, stops and saves, all in one call.",inputSchema:{action:import_zod14.z.enum(["start","stop"]),name:import_zod14.z.string().optional().describe('start: a short name for the files, e.g. "checkout-timeout".'),steps:import_zod14.z.array(stepSchema).min(1).optional().describe('start: run_flow steps to record, e.g. [{tap:"One"},{tap:"Two"}]. Taps and swipes are real touches, so they show on the video. Each tap waits for its target, so no waitMs is needed between taps. The video stops and saves when they finish; no stop call needed.'),serial:import_zod14.z.string().optional().describe("Android: the adb serial, when several devices are connected."),deviceId:deviceIdInput}},async t=>{try{if(t.action==="start"){const{id:o,host:s}=await hostTarget(n,t.deviceId,{serial:t.serial});if(sessions.has(o))return fail2("A recording is already running on this device. Stop it first.");const a=(t.name??"recording").trim().replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"recording";const c={id:o,name:a,events:new Map,agent:[],notes:new Set,failedPolls:0,marks:[]};sessions.set(o,c);let l;c.starting=new Promise(d=>l=d);try{const d=import_node_path28.default.join(projectDir(),".buoy","recordings");await import_node_fs26.promises.mkdir(d,{recursive:true});await import_node_fs26.promises.writeFile(import_node_path28.default.join(d,".gitignore"),"*\n",{flag:"wx"}).catch(()=>void 0);if(n.connectedDevices().some(p=>p.deviceId===o&&hasProAccess(p)))await n.getSnapshot("events",o,{timeoutMs:2e3,silent:true}).catch(()=>void 0);const h=import_node_path28.default.join(d,`${a}-${stamp()}-${(0,import_node_crypto16.randomUUID)().slice(0,6)}.mp4`);c.rec=await startRecording(s,h)}catch(d){sessions.delete(o);throw d}finally{l()}c.poll=setInterval(()=>void gather(n,c),2e3);c.poll.unref?.();c.rec.stopTimer=setTimeout(()=>{c.finishing??=finish(n,c);c.finishing.then(d=>finished.set(o,`The recording hit the ${MAX_RECORDING_MS/6e4}-minute limit and was saved.
682
684
  ${d}`),d=>finished.set(o,`The recording hit the time limit and could not be saved: ${errMsg2(d)}`))},MAX_RECORDING_MS);c.rec.stopTimer.unref?.();if(t.steps){const d=Date.now();const h=await runFlow({steps:t.steps,real:true,include:"none",deviceId:o});const p=Math.max(STEPS_HOLD_MS,STEPS_MIN_MS-(Date.now()-d));const[f]=await Promise.all([observeAfterAction(n,o,void 0,0).catch(()=>""),delay4(p)]);c.finishing??=finish(n,c);let g;try{g=await c.finishing}catch(m){c.finishing=void 0;return fail2(`${h.content[0]?.text??""}
683
685
 
684
686
  Could not save the recording: ${errMsg2(m)}. Call screen_recording with action "stop" to retry.`)}const v=text(`${h.content.map(m=>m.text).join("\n")}
685
687
 
686
- ${g}${f}`);return h.isError?{...v,isError:true}:v}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(s)}. 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 execFileAsync14=(0,import_node_util14.promisify)(import_node_child_process17.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 execFileAsync14("xcode-select",["-p"],{timeout:5e3}).catch(()=>({stdout:""}))).stdout.trim();if(!e.endsWith("/Contents/Developer"))return null;const n=import_node_path25.default.dirname(e);const t=import_node_path25.default.join(e,"Library","PrivateFrameworks","SimulatorKit.framework");const r=import_node_path25.default.join(n,"SharedFrameworks","SimulatorKit.framework");const i=l=>import_node_fs24.promises.access(l).then(()=>true,()=>false);if(await i(t)||!await i(r))return null;const o=(await execFileAsync14("plutil",["-extract","DTXcodeBuild","raw","-o","-",import_node_path25.default.join(n,"Info.plist")]).catch(()=>({stdout:"x"}))).stdout.trim();const s=import_node_path25.default.join(import_node_os17.default.homedir(),".buoy","xcode-shim",o.replace(/[^\w.-]/g,"_"),"Contents");const a=import_node_path25.default.join(s,"Developer");if(await i(import_node_path25.default.join(a,"Library","PrivateFrameworks","SimulatorKit.framework")))return a;await import_node_fs24.promises.mkdir(import_node_path25.default.join(a,"Library","PrivateFrameworks"),{recursive:true});const c=async(l,u,d)=>{for(const h of await import_node_fs24.promises.readdir(l)){if(h===d)continue;await import_node_fs24.promises.symlink(import_node_path25.default.join(l,h),import_node_path25.default.join(u,h)).catch(()=>void 0)}};await c(n,s,"Developer");await c(e,a,"Library");await c(import_node_path25.default.join(e,"Library"),import_node_path25.default.join(a,"Library"),"PrivateFrameworks");await c(import_node_path25.default.join(e,"Library","PrivateFrameworks"),import_node_path25.default.join(a,"Library","PrivateFrameworks"),"").catch(()=>void 0);await import_node_fs24.promises.symlink(r,import_node_path25.default.join(a,"Library","PrivateFrameworks","SimulatorKit.framework")).catch(()=>void 0);return a}async function restartCompanion(e){const n=`/tmp/idb/${e}.buoy-restart`;await import_node_fs24.promises.mkdir("/tmp/idb",{recursive:true}).catch(()=>void 0);const t=async()=>{try{await(await import_node_fs24.promises.open(n,"wx")).close();return true}catch{const r=await import_node_fs24.promises.stat(n).then(i=>Date.now()-i.mtimeMs,()=>0);if(r>15e3){const i=`${n}.stale-${process.pid}-${Date.now()}`;await import_node_fs24.promises.rename(n,i).then(()=>import_node_fs24.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_fs24.promises.stat(n).then(()=>true,()=>false))return}return}try{await execFileAsync14("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_process17.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_fs24.promises.unlink(n).catch(()=>void 0)}}async function idb(e,n=15e3,t=false){try{const{stdout:r}=await execFileAsync14("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 s=e.includes("--udid")?e[e.indexOf("--udid")+1]:void 0;if(!t&&s&&/not booted|connection refused|Failed to connect to companion/i.test(o)){await restartCompanion(s);return idb(e,n,true)}if(/SimulatorKit is required/i.test(o)){if(!t&&s&&await xcodeShimDir().catch(()=>null)){await restartCompanion(s);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}`)}}var AxShellOnlyError=class extends Error{constructor(e){super(`idb can only see an empty app shell on this simulator, so native labels and screen size can't be read. This happens after Maestro or another XCTest tool ran on it, and lasts until the simulator reboots. To fix it, reboot just this simulator: xcrun simctl shutdown ${e} && xcrun simctl boot ${e}. Until then, tap_element and taps by testID or query still work.`);this.name="AxShellOnlyError"}};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 s of o.children??[])r(s)};n.forEach(r);const i=t.find(o=>o.type==="Application"&&o.frame);if(!t.some(o=>(o.frame?.width??0)>0))throw new AxShellOnlyError(e);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_path25.default.join(import_node_os17.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_fs24.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_fs24.promises.mkdir(import_node_path25.default.dirname(BAR_FILE),{recursive:true}).then(()=>import_node_fs24.promises.writeFile(n,JSON.stringify(e))).then(()=>import_node_fs24.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 s=Math.round(i.frame.y+i.frame.height/2);const a=JSON.parse(await idb(["ui","describe-point","--udid",e,String(o),String(s),"--json"],3e3));if((a.AXLabel??"").trim().toLowerCase()===r&&a.frame)return{el:a,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 s=Date.now()+8e3;const a=f=>{const g=(f.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=f=>{if(!c||!f.frame)return true;const g=f.frame.x+f.frame.width/2;const v=f.frame.y+f.frame.height/2;return g>=0&&g<=c&&v>=0&&v<=l};let d=t.all.filter(f=>a(f)>0&&f.frame&&f.type!=="Application"&&u(f));if(!d.some(f=>a(f)===3)&&t.screen.width){const f=i.map(g=>{const v=[];for(let m=20;m<t.screen.width;m+=40)v.push([m,Math.round(t.screen.height*g)]);return v});for(const g of f){if(Date.now()>=s)break;const v=await Promise.allSettled(g.map(async([w,b])=>JSON.parse(await idb(["ui","describe-point","--udid",e,String(w),String(b),"--json"],3e3))));const m=[];for(const w of v){if(w.status==="rejected"){if(IDB_SETUP.test(String(w.reason)))throw w.reason;continue}const b=w.value;if(b?.frame&&b.AXLabel&&b.type&&b.type!=="Application")m.push(b);if(a(b)>0&&b.frame)d.push(b)}if(m.length){const w=barCache.get(e);const b=w&&w.screen.width===t.screen.width&&w.screen.height===t.screen.height;const y=[...b?w.els:[],...m].filter((_,T,$)=>$.findIndex(x=>x.AXLabel===_.AXLabel&&JSON.stringify(x.frame)===JSON.stringify(_.frame))===T);barCache.set(e,{screen:t.screen,els:y});saveBars()}if(d.some(w=>a(w)===3))break}}const h=Math.max(0,...d.map(a));if(r&&h<3)return[];d=d.filter(f=>a(f)===h);let p=d.filter((f,g)=>d.findIndex(v=>JSON.stringify(v.frame)===JSON.stringify(f.frame))===g);if(p.length>1){const f=p.filter(g=>(g.AXLabel??"").trim()===n.trim());if(f.length)p=f}if(p.length>1){const f=p.filter(g=>g.type&&!/StaticText|Text$|Other|Image/.test(g.type));if(f.length)p=f}return p}async function iosNativeElements(e){const n=await iosTree(e);const t=n.all.filter(a=>a.frame&&a.frame.width>0&&a.type!=="Application");const r=a=>`${a.AXLabel??""}|${JSON.stringify(a.frame)}`;const i=new Set(t.map(r));const{width:o,height:s}=n.screen;if(o){const a=t.filter(d=>!!d.type&&!/StaticText|Text$|Other|Image|Group|Heading/.test(d.type));const c=(d,h)=>a.some(p=>d>=p.frame.x&&d<=p.frame.x+p.frame.width&&h>=p.frame.y&&h<=p.frame.y+p.frame.height);const l=[];for(const d of[.95,.97,.09,.06])for(let h=20;h<o;h+=40){const p=Math.round(s*d);if(!c(h,p))l.push([h,p])}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(([p,f])=>idb(["ui","describe-point","--udid",e,String(p),String(f),"--json"],3e3).then(g=>JSON.parse(g),g=>{if(IDB_SETUP.test(String(g)))throw g;return null})));for(const p of h){if(!p?.type||!p.frame?.width||p.type==="Application"||i.has(r(p)))continue;i.add(r(p));t.push(p)}}}t.sort((a,c)=>a.frame.y-c.frame.y||a.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(w,b,y){if(b.platform!=="ios"||!y)return;try{const _=await e.callAction(UI_TOOL_ID2,"describeScreen",{},w,{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(b.udid,{size:{width:T,height:$},at:Date.now()})}catch{}}async function t(w,b){if(w.platform==="android")return adbScreenSize(w.serial);if(w.platform==="ios-device")return{...await phoneScreenSize(w.udid),isPhone:true};const y=simScreens.get(w.udid);if(!b&&y&&Date.now()-y.at<SCREEN_TTL_MS)return y.size;try{const _=(b??await iosTree(w.udid)).screen;if(!_.width)throw new Error("Could not read the simulator's screen size from idb.");simScreens.set(w.udid,{size:_,at:Date.now()});return _}catch(_){if(!b&&y&&_ instanceof AxShellOnlyError)return y.size;if(b||!await simHidTool())throw _;const T=import_node_path25.default.join(import_node_os17.default.tmpdir(),`buoy-size-${process.pid}-${Date.now()}.png`);try{await execFileAsync14("xcrun",["simctl","io",w.udid,"screenshot","--type=png",T],{timeout:2e4});const $=await import_node_fs24.promises.readFile(T);return{width:$.readUInt32BE(16),height:$.readUInt32BE(20)}}finally{await import_node_fs24.promises.rm(T,{force:true}).catch(()=>void 0)}}}async function r(w,b,y,_){if(w.platform==="android")await adbTap(w.serial,b.x,b.y,y);else if(w.platform==="ios-device"){const T=await simHidTool();if(!T)throw new Error(PHONE_TOUCH);return simHidTap(T,await coreDeviceId(w.udid),await t(w),b.x,b.y,y,_)}else if(await simHidTool()){return simHidTap(await simHidTool(),w.udid,{...await t(w),bundleId:w.bundleId},b.x,b.y,y,_)}else{await assertSimTouchable(w.udid);await idb(["ui","tap","--udid",w.udid,...y?["--duration",(y/1e3).toFixed(2)]:[],String(Math.round(b.x)),String(Math.round(b.y))])}}async function i(w,b){if(w.platform==="android"){const _=await adbAppFrame(w.serial,w.packageName);const T=_??{x:0,y:0,...await adbScreenSize(w.serial)};return[(b.x-T.x)/T.width,(b.y-T.y)/T.height]}const y=await t(w);return[b.x/y.width,b.y/y.height]}async function o(w,b,y){try{const[_,T]=await i(b,y);if(!(_>=0&&_<=1&&T>=0&&T<=1))return null;return await e.callAction(UI_TOOL_ID2,"hitTest",{x:_,y:T},w,{timeoutMs:2500,silent:true})}catch{return null}}async function s(w,b,y){const _=await o(w,b,y);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 a(w,b,y,_,T,$,x){if(!isRecording(w))return;try{const A=await t(b);const I=S=>[S[0]/A.width,S[1]/A.height];const E=Date.now()-$-(b.platform==="android"?50:80);const k=x!==void 0?x:b.platform==="android"?null:await deviceOrientation(b.udid);noteTouch(w,{at:E,kind:y,ms:$,from:_.map(I),to:T?.map(I),screen:A,orientation:k})}catch{}}async function c(w,b,y){const _=await e.callAction(UI_TOOL_ID2,"describeScreen",{},w);const T=(y.query??"").toLowerCase();const $=(_.elements??[]).filter(k=>y.nativeTag!=null?k.nativeTag===y.nativeTag:y.testID?k.testID===y.testID:(k.text??k.label??"").toLowerCase()===T);const x=$.filter(k=>k.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&&y.nativeTag==null)return`${x.length} elements match equally well, so nothing was tapped. Use nativeTag: ${x.map(k=>`#${k.nativeTag}`).join(", ")}.`;const A=x[0].tap;const I=`"${x[0].text??x[0].label??x[0].name}"`;if(b.platform==="android"){const k=await adbAppFrame(b.serial,b.packageName);const S=k??{x:0,y:0,...await adbScreenSize(b.serial)};return{x:S.x+A.x*S.width,y:S.y+A.y*S.height,what:I}}const E=await t(b);return{x:A.x*E.width,y:A.y*E.height,what:I}}async function l(w,b,y=false,_){if(w.platform==="android"){const I=findUiNodes(await adbUiNodes(w.serial),b).filter(k=>!y||[k.desc,k.text].some(S=>(S??"").trim().toLowerCase()===b.trim().toLowerCase()));if(I.length===0)return`No native element labeled "${b}" was found on screen.`;if(I.length>1)return`${I.length} native elements match "${b}" equally well, so nothing was tapped: ${I.map(k=>`"${k.desc||k.text||k.id}" at (${k.bounds.x}, ${k.bounds.y})`).join(", ")}. Tap one by x/y.`;const E=I[0].bounds;return{x:E.x+E.width/2,y:E.y+E.height/2,what:`"${I[0].desc||I[0].text||I[0].id}" (${I[0].cls.split(".").pop()})`}}const T=await cachedBarControl(w.udid,b);if(T){simScreens.set(w.udid,{size:T.screen,at:Date.now()});const I=T.el.frame;return{x:I.x+I.width/2,y:I.y+I.height/2,what:`"${T.el.AXLabel}" (${T.el.type})`}}let $;try{$=await iosTree(w.udid)}catch(I){if(!(I instanceof AxShellOnlyError))throw I;if(_?.online){const E=await m(_.id,w,b,true,"app");if(!("miss"in E))return{...E,what:`${E.what} (found in the app's own screen, because idb can only see an empty shell on this simulator)`};if(E.tie)return E.miss}return I.message}await t(w,$);const x=await findByLabel(w.udid,b,$,y);if(x.length===0)return`No native element labeled "${b}" was found on screen.`;if(x.length>1)return`${x.length} native elements match "${b}" equally well, so nothing was tapped: ${x.map(I=>`"${I.AXLabel}" at (${Math.round(I.frame.x)}, ${Math.round(I.frame.y)})`).join(", ")}. Tap one by x/y.`;const A=x[0].frame;return{x:A.x+A.width/2,y:A.y+A.height/2,what:`"${x[0].AXLabel}" (${x[0].type})`}}async function u(w,b,y,_,T=false,$=0,x){const A=[...b,...y].map(E=>String(Math.round(E)));const I=w.platform==="android"?null:await simHidTool();if(w.platform!=="android"&&!I)await assertSimTouchable(w.udid);if(w.platform==="android"){if(T)await adbShell(w.serial,`input draganddrop ${A.join(" ")} ${Math.round(_)}`);else await adbSwipe(w.serial,b,y,_);return void 0}if(I){const E=w.platform==="ios-device"?await coreDeviceId(w.udid):w.udid;const k=x?.screen??await t(w);return simHidSwipe(I,E,{...k,bundleId:w.platform==="ios"?w.bundleId:null},b,y,_,T?700:0,T?0:$,x?.orientation)}if(T)await idb(["ui","swipe","--udid",w.udid,...A,"--duration",(_/1e3).toFixed(2),"--delta","4"]);else await idb(["ui","swipe","--udid",w.udid,...A,"--duration",(_/1e3).toFixed(2)]);return void 0}async function d(w){try{const b=await e.callAction(UI_TOOL_ID2,"describeScreen",{},w,{timeoutMs:3e3,silent:true});const y=new Map;for(const _ of b?.elements??[]){if(!_.tap)continue;const T=`${_.name??""}|${_.text??_.label??""}|${_.nativeTag??""}`;if(y.has(T))y.set(T,{x:NaN,y:NaN});else y.set(T,_.tap)}return y}catch{return null}}function h(w,b,y,_,T=true){let $=0;let x=0;for(const[A,I]of b){const E=w.get(A);if(!E)x++;else if(Number.isFinite(E[y])&&Number.isFinite(I[y])&&Math.abs(I[y]-E[y])>_)$++}return $+(T&&x>=2?x:0)}function p(w,b,y){const _=[];for(const[T,$]of b){const x=w.get(T);if(x&&Number.isFinite(x[y])&&Number.isFinite($[y])&&Math.abs($[y]-x[y])>.002)_.push($[y]-x[y])}if(_.length<2)return 0;_.sort((T,$)=>T-$);return _[Math.floor(_.length/2)]}async function f(w,b){await delay5(120);let y=await d(w);const _=Date.now()+2500;while(y&&Date.now()<_){await delay5(100);const T=await d(w);if(!T)break;const $=h(y,T,b,.002,false)===0;y=T;if($)break}return y}async function g(w,b,y,_,T,$=15){const x=Math.abs(_[1]-y[1])>=Math.abs(_[0]-y[0])?"y":"x";let A=await d(w);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 k={screen:await t(b)};const S=x==="y"?1:0;const M=x==="y"?k.screen.height:k.screen.width;const D=Math.sign(_[S]-y[S]);const R=Math.abs(_[S]-y[S])/M;const O=new Set;const U=(L,P)=>{for(const[N,H]of P){const j=L.get(N);if(j&&Number.isFinite(j[x])&&Number.isFinite(H[x])&&Math.abs(H[x]-j[x])>.01)O.add(N)}};let C=A;while(I<$){const L=await u(b,y,_,T,false,SCROLL_REST_MS,k);if(L!==void 0)k.orientation=L;I++;await a(w,b,"swipe",[y],[_],T,L);await delay5(90);const P=await d(w);await delay5(70);const N=await d(w);if(!P||!N)throw new Error("The app stopped answering while scrolling.");const H=p(P,N,x)*D;U(A,N);C=N;if(H>.004||H>=-.004&&h(P,N,x,.002,false)===0&&h(A,N,x,.01)>0){A=N;continue}const j=await f(w,x);if(!j)throw new Error("The app stopped answering while scrolling.");U(A,j);C=j;if(h(A,j,x,.01)===0){E=true;break}const W=p(A,j,x)*D;if(W>.01&&W<R*.85){E=true;break}A=j}const F=[...C].filter(([L,P])=>O.has(L)&&P[x]>=0&&P[x]<=1&&L.split("|")[1]);const z=L=>L.sort((P,N)=>(N[1][x]-P[1][x])*-D)[0];const B=z(F.filter(([L])=>!L.startsWith("Text|")))??z(F);return{swipes:I,atEnd:E,lastRow:B?B[0].split("|")[1]:void 0}}async function v(w,b){if(w.platform==="android"){const _=await adbAppFrame(w.serial,w.packageName);const T=_??{x:0,y:0,...await adbScreenSize(w.serial)};return{x:T.x+b.x*T.width,y:T.y+b.y*T.height}}const y=await t(w);return{x:b.x*y.width,y:b.y*y.height}}async function m(w,b,y,_,T){if(_&&(T==="app"||T==="loose")){const $=await e.callAction(UI_TOOL_ID2,"describeScreen",{},w,{timeoutMs:4e3,silent:true}).catch(()=>null);const x=($?.elements??[]).filter(k=>k.tap&&k.tap.x>=0&&k.tap.x<=1&&k.tap.y>=0&&k.tap.y<=1);const A=y.trim().toLowerCase();const I=k=>(k.text??k.label??"").trim().toLowerCase();const E=T==="app"?[x.filter(k=>k.testID===y),x.filter(k=>I(k)===A)]:[x.filter(k=>!!A&&I(k).includes(A))];for(const k of E){if(!k.length)continue;const S=k.filter(O=>O.interactive);const M=S.length?S:k;const D=M.filter((O,U)=>M.findIndex(C=>Math.abs(C.tap.x-O.tap.x)<.02&&Math.abs(C.tap.y-O.tap.y)<.02)===U);if(D.length>1){return{tie:true,miss:`${D.length} elements match "${y}", so nothing was touched: ${D.slice(0,5).map(O=>O.testID?`testID ${O.testID}`:JSON.stringify(O.text??O.label??O.name)).join(", ")}. Use an exact testID.`}}const R=D[0];return{...await v(b,R.tap),what:`"${R.text??R.label??R.name}"${R.testID?` [testID=${R.testID}]`:""}`}}}if((T==="native"||T==="nativeExact")&&b.platform!=="ios-device"){const $=await l(b,y,T==="nativeExact",{id:w,online:_});if(typeof $!=="string")return $;if(/equally well/.test($))return{miss:$,tie:true};if(/empty app shell/.test($))return{miss:$}}return{miss:`Nothing on screen matches "${y}".`}}return{primeScreen:n,screenOf:t,touch:r,hitAt:o,buoyCover:s,mark:a,reactSpot:c,labelSpot:l,swipe:u,scrollToEnd:g,findSpot:m}}async function nativeLabelTap(e,n,t,r,i=false){const o=nativeKit(e);const{id:s,host:a,online:c}=await hostTarget(e,n);if(a.platform==="ios-device")return null;freshScreen(a);await o.primeScreen(s,a,c);const l=await o.findSpot(s,a,t,c,i?"nativeExact":"native");if("miss"in l)return null;if(c&&await o.buoyCover(s,a,l))return null;const u=r?600:void 0;const d=await o.touch(a,l,u);await o.mark(s,a,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 s=await simHidTool();if(s)await runHidStream(s,o.udid,["--device",o.udid,"ping"]);await deviceOrientation(o.udid);await loadBars();if(!barCache.has(o.udid)){const a=await iosTree(o.udid).catch(()=>null);if(a?.screen.width)await findByLabel(o.udid,"\0no such label",a,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:s,mark:a,reactSpot:c,labelSpot:l,swipe:u,scrollToEnd:d}=nativeKit(n);const h=import_zod15.z.string().optional().describe("Android: the adb serial, when several devices are connected.");const p=f=>f.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_zod15.z.string().optional().describe('Native accessibility label, e.g. "Rewards" for a native tab.'),query:import_zod15.z.string().optional().describe("Text of an element from describe_screen."),testID:import_zod15.z.string().optional(),nativeTag:import_zod15.z.number().optional(),x:import_zod15.z.number().min(0).max(1).optional().describe("Horizontal position, 0 to 1."),y:import_zod15.z.number().min(0).max(1).optional().describe("Vertical position, 0 to 1."),holdMs:import_zod15.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_zod15.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 f=>{try{const g=f.nativeTag!=null||!!f.testID||!!f.query;const{id:v,host:m,online:w}=await hostTarget(n,f.deviceId,{serial:f.serial},{allowOffline:!g});freshScreen(m);await t(v,m,w);if(m.platform==="ios-device"&&!await simHidTool())return fail2(PHONE_TOUCH);let b;if(f.x!=null&&f.y!=null){const T=await r(m);b={x:f.x*T.width,y:f.y*T.height,what:`(${f.x.toFixed(2)}, ${f.y.toFixed(2)})`}}else if(g){b=await c(v,m,f)}else if(f.label){if(m.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.");b=await l(m,f.label,false,{id:v,online:w})}else{return fail2("Give label, query, testID, nativeTag, or x and y.")}if(typeof b==="string")return fail2(b);if(w&&!f.allowBuoy){const T=await s(v,m,b);if(T)return fail2(T)}const y=await i(m,b,f.holdMs);await a(v,m,f.holdMs?"hold":"tap",[[b.x,b.y]],void 0,f.holdMs??150,y);const _=w?await observeAfterAction(n,v):" (The app is not connected, so its screen was not read back.)";return text(`${f.holdMs?`Long-pressed (${f.holdMs}ms)`:"Tapped"} ${b.what} with a real touch at (${Math.round(b.x)}, ${Math.round(b.y)}) ${p(m)}.${_}`)}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_zod15.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 f=>{try{const{id:g,host:v,online:m}=await hostTarget(n,f.deviceId,{serial:f.serial},{allowOffline:true});if(v.platform==="ios-device"&&!await simHidTool())return fail2(PHONE_TOUCH);const w=fillSecrets(f.text);let b=false;if(v.platform==="android")await adbText(v.serial,w);else if(v.platform==="ios-device")await simHidType(await simHidTool(),await coreDeviceId(v.udid),w);else{const _=await simHidTool();if(_){await simHidType(_,v.udid,w);b=true}else{await assertSimTouchable(v.udid);await idb(["ui","text","--udid",v.udid,w])}}if(!b)await delay5(300);const y=m?await observeAfterAction(n,g):"";return text(`Typed ${JSON.stringify(f.text)} on the keyboard.${y}`)}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_zod15.z.enum(["up","down","left","right"]).optional().describe('"up" scrolls content down the list (finger moves up).'),fromX:import_zod15.z.number().min(0).max(1).optional(),fromY:import_zod15.z.number().min(0).max(1).optional(),toX:import_zod15.z.number().min(0).max(1).optional(),toY:import_zod15.z.number().min(0).max(1).optional(),durationMs:import_zod15.z.number().min(50).max(5e3).optional().describe("Default 300 (1200 with drag)."),drag:import_zod15.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_zod15.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_zod15.z.boolean().optional().describe("Swipe even if Buoy's own panel covers the starting point."),serial:h,deviceId:deviceIdInput}},async f=>{try{const{id:g,host:v,online:m}=await hostTarget(n,f.deviceId,{serial:f.serial},{allowOffline:true});freshScreen(v);await t(g,v,m);if(v.platform==="ios-device"&&!await simHidTool())return fail2(PHONE_TOUCH);const w=await r(v);let b;let y;if(f.fromX!=null&&f.fromY!=null&&f.toX!=null&&f.toY!=null){b=[f.fromX,f.fromY];y=[f.toX,f.toY]}else{({from:b,to:y}=swipePoints(f.direction??"up",!!f.untilEnd))}const _=[b[0]*w.width,b[1]*w.height];const T=[y[0]*w.width,y[1]*w.height];let $=0;if(f.drag&&v.platform==="android"){const k=Number((await adbShell(v.serial,"settings get secure long_press_timeout").catch(()=>"")).trim())||500;$=k*1.5+600}const x=Math.max(f.durationMs??(f.drag?1200:300),$);if(m&&!f.allowBuoy){const k=await s(g,v,{x:_[0],y:_[1]});if(k)return fail2(k)}if(f.untilEnd){if(f.drag)return fail2("untilEnd scrolls with flicks. Leave out drag.");if(!m)return fail2("untilEnd needs the app connected, to see when the list stops moving.");const k=await d(g,v,_,T,f.durationMs??250);const{swipes:S,atEnd:M}=k;const D=await observeAfterAction(n,g,void 0,0);const{lastRow:R}=k;return text(`${M?`Reached the end of the list after ${S} swipe(s)${R?`. The last row is "${R}"`:""}`:`Swiped ${S} times and the screen was still moving`}.${D}`)}const A=v.platform==="android"?null:await simHidTool();const I=await u(v,_,T,x,f.drag);await a(g,v,f.drag?"drag":"swipe",[_],[T],x+(f.drag&&A?700:0),I);await delay5(400);const E=m?await observeAfterAction(n,g):"";return text(`${f.drag?"Dragged":"Swiped"} from (${_.map(Math.round).join(", ")}) to (${T.map(Math.round).join(", ")}) ${p(v)}.${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_zod15.z.number().finite().min(0).optional().describe("From the left. iOS Sims use points. Other hosts use pixels."),pointY:import_zod15.z.number().finite().min(0).optional().describe("From the top. iOS Sims use points. Other hosts use pixels."),x:import_zod15.z.number().min(0).max(1).optional().describe("Horizontal position, 0 to 1."),y:import_zod15.z.number().min(0).max(1).optional().describe("Vertical position, 0 to 1."),serial:h,deviceId:deviceIdInput}},async f=>{try{const g=f.pointX!=null||f.pointY!=null;if(g&&(f.pointX==null||f.pointY==null))return fail2("Use pointX and pointY together.");if(g&&(f.x!=null||f.y!=null))return fail2("Use pointX/pointY or x/y, not both.");if(!g&&f.x==null!==(f.y==null))return fail2("Use x and y together.");const{id:v,host:m,online:w}=await hostTarget(n,f.deviceId,{serial:f.serial},{allowOffline:true});freshScreen(m);await t(v,m,w);const b=p(m);if(!g&&(f.x==null||f.y==null)){if(m.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(m.platform==="android"){const I=await adbUiNodes(m.serial);$=I.filter(E=>E.text||E.desc||E.id||E.clickable).map(E=>{const k=E.bounds;const S=[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`${S.filter(Boolean).join(" ")} at (${k.x}, ${k.y}) ${k.width}x${k.height}`})}else{const{elements:I,screen:E}=await iosNativeElements(m.udid);const k=I.filter(S=>!E.width||S.frame.y<E.height&&S.frame.y+S.frame.height>0&&S.frame.x<E.width&&S.frame.x+S.frame.width>0);x=I.length-k.length;$=k.map(axLine)}const A=$.slice(0,150);return text([`${$.length} native element(s) on screen, top to bottom (${b}; 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 y;if(g){const $=await r(m);y={x:f.pointX,y:f.pointY};if(y.x>=$.width||y.y>=$.height){return fail2(`That point is outside the screen (${$.width} x ${$.height} ${b}).`)}}else{const $=await r(m);y={x:f.x*$.width,y:f.y*$.height}}const _=[g?`At (${Math.round(y.x)}, ${Math.round(y.y)}) ${b}:`:`At (${f.x.toFixed(2)}, ${f.y.toFixed(2)}) = (${Math.round(y.x)}, ${Math.round(y.y)}) ${b}:`];const T=w?o(v,m,y):Promise.resolve(null);if(m.platform==="android"){const $=(await adbUiNodes(m.serial)).filter(A=>{const I=A.bounds;return y.x>=I.x&&y.x<=I.x+I.width&&y.y>=I.y&&y.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(m.platform==="ios"){const $=JSON.parse(await idb(["ui","describe-point","--udid",m.udid,String(Math.round(y.x)),String(Math.round(y.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(!w)_.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_zod15.z.number().min(0).max(1).optional().describe("Center between the fingers, 0 to 1. Default 0.5."),y:import_zod15.z.number().min(0).max(1).optional().describe("Center between the fingers, 0 to 1. Default 0.5."),scale:import_zod15.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_zod15.z.number().min(-180).max(180).optional().describe("Turn the fingers this many degrees while pinching, clockwise. Default 0."),durationMs:import_zod15.z.number().min(100).max(5e3).optional().describe("Default 500."),allowBuoy:import_zod15.z.boolean().optional().describe("Pinch even if a finger starts on Buoy."),deviceId:deviceIdInput}},async f=>{try{const{id:g,host:v,online:m}=await hostTarget(n,f.deviceId,{},{allowOffline:true});freshScreen(v);await t(g,v,m);if(v.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 w=await simHidTool();if(!w)return fail2(v.platform==="ios-device"?PHONE_TOUCH:"Pinching needs Xcode's CoreDevice touch support (Xcode 26 or later); idb sends one finger only.");const b=await r(v);const y=[(f.x??.5)*b.width,(f.y??.5)*b.height];const _=f.scale??2;const T=Math.min(b.width,b.height);const $=T*.4;const x=_>=1?Math.max(T*.04,$/_):$;const A=_>=1?$:Math.max(T*.04,$*_);const I=(f.rotate??0)*Math.PI/180;const E=G=>[Math.min(b.width-1,Math.max(1,G[0])),Math.min(b.height-1,Math.max(1,G[1]))];const k=(G,K)=>[E([y[0]-G*Math.cos(K),y[1]-G*Math.sin(K)]),E([y[0]+G*Math.cos(K),y[1]+G*Math.sin(K)])];const[S,M]=k(x,0);const[D,R]=k(A,I);if(m&&!f.allowBuoy){for(const[G,K]of[S,M]){const se=await s(g,v,{x:G,y:K});if(se)return fail2(se)}}const O=f.durationMs??500;const U={x:Math.max(0,(y[0]-$)/b.width),y:Math.max(0,(y[1]-$)/b.height),width:Math.min(1,2*$/b.width),height:Math.min(1,2*$/b.height)};const C=m?await readMaps(n,g):[];const F=G=>G.find(K=>!K.frame||(f.x??.5)>=K.frame.x&&(f.x??.5)<=K.frame.x+K.frame.width&&(f.y??.5)>=K.frame.y&&(f.y??.5)<=K.frame.y+K.frame.height);const z=F(C);const B=z?null:await hostPng(v).catch(()=>null);const L=v.platform==="ios-device"?await coreDeviceId(v.udid):v.udid;const P=await simHidTwo(w,L,{...b,bundleId:v.platform==="ios"?v.bundleId:null},S,M,D,R,O);await a(g,v,"pinch",[S,M],[D,R],O,P);await delay5(400);const[N,H,j]=await Promise.all([m?observeAfterAction(n,g,void 0,0):Promise.resolve(""),B?hostPng(v).catch(()=>null):Promise.resolve(null),z?readMaps(n,g):Promise.resolve([])]);const W=A/x;const V=W>1.01?`Spread (zoom in, x${W.toFixed(2)})`:W<.99?`Pinched (zoom out, x${W.toFixed(2)})`:"Turned";const J=`${V}${f.rotate?`, turning ${f.rotate} degrees,`:""} around (${Math.round(y[0])}, ${Math.round(y[1])}) ${p(v)} with two real fingers.`;const re=z?j.find(G=>G.name===z.name&&G.testID===z.testID):void 0;const oe=z&&re?mapChange(z,re):null;if(oe)return text(`${J}
688
+ ${g}${f}`);return h.isError?{...v,isError:true}:v}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(s)}. 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 execFileAsync14=(0,import_node_util14.promisify)(import_node_child_process18.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 execFileAsync14("xcode-select",["-p"],{timeout:5e3}).catch(()=>({stdout:""}))).stdout.trim();if(!e.endsWith("/Contents/Developer"))return null;const n=import_node_path29.default.dirname(e);const t=import_node_path29.default.join(e,"Library","PrivateFrameworks","SimulatorKit.framework");const r=import_node_path29.default.join(n,"SharedFrameworks","SimulatorKit.framework");const i=l=>import_node_fs27.promises.access(l).then(()=>true,()=>false);if(await i(t)||!await i(r))return null;const o=(await execFileAsync14("plutil",["-extract","DTXcodeBuild","raw","-o","-",import_node_path29.default.join(n,"Info.plist")]).catch(()=>({stdout:"x"}))).stdout.trim();const s=import_node_path29.default.join(import_node_os20.default.homedir(),".buoy","xcode-shim",o.replace(/[^\w.-]/g,"_"),"Contents");const a=import_node_path29.default.join(s,"Developer");if(await i(import_node_path29.default.join(a,"Library","PrivateFrameworks","SimulatorKit.framework")))return a;await import_node_fs27.promises.mkdir(import_node_path29.default.join(a,"Library","PrivateFrameworks"),{recursive:true});const c=async(l,u,d)=>{for(const h of await import_node_fs27.promises.readdir(l)){if(h===d)continue;await import_node_fs27.promises.symlink(import_node_path29.default.join(l,h),import_node_path29.default.join(u,h)).catch(()=>void 0)}};await c(n,s,"Developer");await c(e,a,"Library");await c(import_node_path29.default.join(e,"Library"),import_node_path29.default.join(a,"Library"),"PrivateFrameworks");await c(import_node_path29.default.join(e,"Library","PrivateFrameworks"),import_node_path29.default.join(a,"Library","PrivateFrameworks"),"").catch(()=>void 0);await import_node_fs27.promises.symlink(r,import_node_path29.default.join(a,"Library","PrivateFrameworks","SimulatorKit.framework")).catch(()=>void 0);return a}async function restartCompanion(e){const n=`/tmp/idb/${e}.buoy-restart`;await import_node_fs27.promises.mkdir("/tmp/idb",{recursive:true}).catch(()=>void 0);const t=async()=>{try{await(await import_node_fs27.promises.open(n,"wx")).close();return true}catch{const r=await import_node_fs27.promises.stat(n).then(i=>Date.now()-i.mtimeMs,()=>0);if(r>15e3){const i=`${n}.stale-${process.pid}-${Date.now()}`;await import_node_fs27.promises.rename(n,i).then(()=>import_node_fs27.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_fs27.promises.stat(n).then(()=>true,()=>false))return}return}try{await execFileAsync14("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_process18.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_fs27.promises.unlink(n).catch(()=>void 0)}}async function idb(e,n=15e3,t=false){try{const{stdout:r}=await execFileAsync14("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 s=e.includes("--udid")?e[e.indexOf("--udid")+1]:void 0;if(!t&&s&&/not booted|connection refused|Failed to connect to companion/i.test(o)){await restartCompanion(s);return idb(e,n,true)}if(/SimulatorKit is required/i.test(o)){if(!t&&s&&await xcodeShimDir().catch(()=>null)){await restartCompanion(s);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}`)}}var AxShellOnlyError=class extends Error{constructor(e){super(`idb can only see an empty app shell on this simulator, so native labels and screen size can't be read. This happens after Maestro or another XCTest tool ran on it, and lasts until the simulator reboots. To fix it, reboot just this simulator: xcrun simctl shutdown ${e} && xcrun simctl boot ${e}. Until then, tap_element and taps by testID or query still work.`);this.name="AxShellOnlyError"}};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 s of o.children??[])r(s)};n.forEach(r);const i=t.find(o=>o.type==="Application"&&o.frame);if(!t.some(o=>(o.frame?.width??0)>0))throw new AxShellOnlyError(e);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_path29.default.join(import_node_os20.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_fs27.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_fs27.promises.mkdir(import_node_path29.default.dirname(BAR_FILE),{recursive:true}).then(()=>import_node_fs27.promises.writeFile(n,JSON.stringify(e))).then(()=>import_node_fs27.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 s=Math.round(i.frame.y+i.frame.height/2);const a=JSON.parse(await idb(["ui","describe-point","--udid",e,String(o),String(s),"--json"],3e3));if((a.AXLabel??"").trim().toLowerCase()===r&&a.frame)return{el:a,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 s=Date.now()+8e3;const a=f=>{const g=(f.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=f=>{if(!c||!f.frame)return true;const g=f.frame.x+f.frame.width/2;const v=f.frame.y+f.frame.height/2;return g>=0&&g<=c&&v>=0&&v<=l};let d=t.all.filter(f=>a(f)>0&&f.frame&&f.type!=="Application"&&u(f));if(!d.some(f=>a(f)===3)&&t.screen.width){const f=i.map(g=>{const v=[];for(let m=20;m<t.screen.width;m+=40)v.push([m,Math.round(t.screen.height*g)]);return v});for(const g of f){if(Date.now()>=s)break;const v=await Promise.allSettled(g.map(async([w,b])=>JSON.parse(await idb(["ui","describe-point","--udid",e,String(w),String(b),"--json"],3e3))));const m=[];for(const w of v){if(w.status==="rejected"){if(IDB_SETUP.test(String(w.reason)))throw w.reason;continue}const b=w.value;if(b?.frame&&b.AXLabel&&b.type&&b.type!=="Application")m.push(b);if(a(b)>0&&b.frame)d.push(b)}if(m.length){const w=barCache.get(e);const b=w&&w.screen.width===t.screen.width&&w.screen.height===t.screen.height;const y=[...b?w.els:[],...m].filter((_,T,$)=>$.findIndex(x=>x.AXLabel===_.AXLabel&&JSON.stringify(x.frame)===JSON.stringify(_.frame))===T);barCache.set(e,{screen:t.screen,els:y});saveBars()}if(d.some(w=>a(w)===3))break}}const h=Math.max(0,...d.map(a));if(r&&h<3)return[];d=d.filter(f=>a(f)===h);let p=d.filter((f,g)=>d.findIndex(v=>JSON.stringify(v.frame)===JSON.stringify(f.frame))===g);if(p.length>1){const f=p.filter(g=>(g.AXLabel??"").trim()===n.trim());if(f.length)p=f}if(p.length>1){const f=p.filter(g=>g.type&&!/StaticText|Text$|Other|Image/.test(g.type));if(f.length)p=f}return p}async function iosNativeElements(e){const n=await iosTree(e);const t=n.all.filter(a=>a.frame&&a.frame.width>0&&a.type!=="Application");const r=a=>`${a.AXLabel??""}|${JSON.stringify(a.frame)}`;const i=new Set(t.map(r));const{width:o,height:s}=n.screen;if(o){const a=t.filter(d=>!!d.type&&!/StaticText|Text$|Other|Image|Group|Heading/.test(d.type));const c=(d,h)=>a.some(p=>d>=p.frame.x&&d<=p.frame.x+p.frame.width&&h>=p.frame.y&&h<=p.frame.y+p.frame.height);const l=[];for(const d of[.95,.97,.09,.06])for(let h=20;h<o;h+=40){const p=Math.round(s*d);if(!c(h,p))l.push([h,p])}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(([p,f])=>idb(["ui","describe-point","--udid",e,String(p),String(f),"--json"],3e3).then(g=>JSON.parse(g),g=>{if(IDB_SETUP.test(String(g)))throw g;return null})));for(const p of h){if(!p?.type||!p.frame?.width||p.type==="Application"||i.has(r(p)))continue;i.add(r(p));t.push(p)}}}t.sort((a,c)=>a.frame.y-c.frame.y||a.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(w,b,y){if(b.platform!=="ios"||!y)return;try{const _=await e.callAction(UI_TOOL_ID2,"describeScreen",{},w,{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(b.udid,{size:{width:T,height:$},at:Date.now()})}catch{}}async function t(w,b){if(w.platform==="android")return adbScreenSize(w.serial);if(w.platform==="ios-device")return{...await phoneScreenSize(w.udid),isPhone:true};const y=simScreens.get(w.udid);if(!b&&y&&Date.now()-y.at<SCREEN_TTL_MS)return y.size;try{const _=(b??await iosTree(w.udid)).screen;if(!_.width)throw new Error("Could not read the simulator's screen size from idb.");simScreens.set(w.udid,{size:_,at:Date.now()});return _}catch(_){if(!b&&y&&_ instanceof AxShellOnlyError)return y.size;if(b||!await simHidTool())throw _;const T=import_node_path29.default.join(import_node_os20.default.tmpdir(),`buoy-size-${process.pid}-${Date.now()}.png`);try{await execFileAsync14("xcrun",["simctl","io",w.udid,"screenshot","--type=png",T],{timeout:2e4});const $=await import_node_fs27.promises.readFile(T);return{width:$.readUInt32BE(16),height:$.readUInt32BE(20)}}finally{await import_node_fs27.promises.rm(T,{force:true}).catch(()=>void 0)}}}async function r(w,b,y,_){if(w.platform==="android")await adbTap(w.serial,b.x,b.y,y);else if(w.platform==="ios-device"){const T=await simHidTool();if(!T)throw new Error(PHONE_TOUCH);return simHidTap(T,await coreDeviceId(w.udid),await t(w),b.x,b.y,y,_)}else if(await simHidTool()){return simHidTap(await simHidTool(),w.udid,{...await t(w),bundleId:w.bundleId},b.x,b.y,y,_)}else{await assertSimTouchable(w.udid);await idb(["ui","tap","--udid",w.udid,...y?["--duration",(y/1e3).toFixed(2)]:[],String(Math.round(b.x)),String(Math.round(b.y))])}}async function i(w,b){if(w.platform==="android"){const _=await adbAppFrame(w.serial,w.packageName);const T=_??{x:0,y:0,...await adbScreenSize(w.serial)};return[(b.x-T.x)/T.width,(b.y-T.y)/T.height]}const y=await t(w);return[b.x/y.width,b.y/y.height]}async function o(w,b,y){try{const[_,T]=await i(b,y);if(!(_>=0&&_<=1&&T>=0&&T<=1))return null;return await e.callAction(UI_TOOL_ID2,"hitTest",{x:_,y:T},w,{timeoutMs:2500,silent:true})}catch{return null}}async function s(w,b,y){const _=await o(w,b,y);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 a(w,b,y,_,T,$,x){if(!isRecording(w))return;try{const A=await t(b);const I=S=>[S[0]/A.width,S[1]/A.height];const E=Date.now()-$-(b.platform==="android"?50:80);const k=x!==void 0?x:b.platform==="android"?null:await deviceOrientation(b.udid);noteTouch(w,{at:E,kind:y,ms:$,from:_.map(I),to:T?.map(I),screen:A,orientation:k})}catch{}}async function c(w,b,y){const _=await e.callAction(UI_TOOL_ID2,"describeScreen",{},w);const T=(y.query??"").toLowerCase();const $=(_.elements??[]).filter(k=>y.nativeTag!=null?k.nativeTag===y.nativeTag:y.testID?k.testID===y.testID:(k.text??k.label??"").toLowerCase()===T);const x=$.filter(k=>k.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&&y.nativeTag==null)return`${x.length} elements match equally well, so nothing was tapped. Use nativeTag: ${x.map(k=>`#${k.nativeTag}`).join(", ")}.`;const A=x[0].tap;const I=`"${x[0].text??x[0].label??x[0].name}"`;if(b.platform==="android"){const k=await adbAppFrame(b.serial,b.packageName);const S=k??{x:0,y:0,...await adbScreenSize(b.serial)};return{x:S.x+A.x*S.width,y:S.y+A.y*S.height,what:I}}const E=await t(b);return{x:A.x*E.width,y:A.y*E.height,what:I}}async function l(w,b,y=false,_){if(w.platform==="android"){const I=findUiNodes(await adbUiNodes(w.serial),b).filter(k=>!y||[k.desc,k.text].some(S=>(S??"").trim().toLowerCase()===b.trim().toLowerCase()));if(I.length===0)return`No native element labeled "${b}" was found on screen.`;if(I.length>1)return`${I.length} native elements match "${b}" equally well, so nothing was tapped: ${I.map(k=>`"${k.desc||k.text||k.id}" at (${k.bounds.x}, ${k.bounds.y})`).join(", ")}. Tap one by x/y.`;const E=I[0].bounds;return{x:E.x+E.width/2,y:E.y+E.height/2,what:`"${I[0].desc||I[0].text||I[0].id}" (${I[0].cls.split(".").pop()})`}}const T=await cachedBarControl(w.udid,b);if(T){simScreens.set(w.udid,{size:T.screen,at:Date.now()});const I=T.el.frame;return{x:I.x+I.width/2,y:I.y+I.height/2,what:`"${T.el.AXLabel}" (${T.el.type})`}}let $;try{$=await iosTree(w.udid)}catch(I){if(!(I instanceof AxShellOnlyError))throw I;if(_?.online){const E=await m(_.id,w,b,true,"app");if(!("miss"in E))return{...E,what:`${E.what} (found in the app's own screen, because idb can only see an empty shell on this simulator)`};if(E.tie)return E.miss}return I.message}await t(w,$);const x=await findByLabel(w.udid,b,$,y);if(x.length===0)return`No native element labeled "${b}" was found on screen.`;if(x.length>1)return`${x.length} native elements match "${b}" equally well, so nothing was tapped: ${x.map(I=>`"${I.AXLabel}" at (${Math.round(I.frame.x)}, ${Math.round(I.frame.y)})`).join(", ")}. Tap one by x/y.`;const A=x[0].frame;return{x:A.x+A.width/2,y:A.y+A.height/2,what:`"${x[0].AXLabel}" (${x[0].type})`}}async function u(w,b,y,_,T=false,$=0,x){const A=[...b,...y].map(E=>String(Math.round(E)));const I=w.platform==="android"?null:await simHidTool();if(w.platform!=="android"&&!I)await assertSimTouchable(w.udid);if(w.platform==="android"){if(T)await adbShell(w.serial,`input draganddrop ${A.join(" ")} ${Math.round(_)}`);else await adbSwipe(w.serial,b,y,_);return void 0}if(I){const E=w.platform==="ios-device"?await coreDeviceId(w.udid):w.udid;const k=x?.screen??await t(w);return simHidSwipe(I,E,{...k,bundleId:w.platform==="ios"?w.bundleId:null},b,y,_,T?700:0,T?0:$,x?.orientation)}if(T)await idb(["ui","swipe","--udid",w.udid,...A,"--duration",(_/1e3).toFixed(2),"--delta","4"]);else await idb(["ui","swipe","--udid",w.udid,...A,"--duration",(_/1e3).toFixed(2)]);return void 0}async function d(w){try{const b=await e.callAction(UI_TOOL_ID2,"describeScreen",{},w,{timeoutMs:3e3,silent:true});const y=new Map;for(const _ of b?.elements??[]){if(!_.tap)continue;const T=`${_.name??""}|${_.text??_.label??""}|${_.nativeTag??""}`;if(y.has(T))y.set(T,{x:NaN,y:NaN});else y.set(T,_.tap)}return y}catch{return null}}function h(w,b,y,_,T=true){let $=0;let x=0;for(const[A,I]of b){const E=w.get(A);if(!E)x++;else if(Number.isFinite(E[y])&&Number.isFinite(I[y])&&Math.abs(I[y]-E[y])>_)$++}return $+(T&&x>=2?x:0)}function p(w,b,y){const _=[];for(const[T,$]of b){const x=w.get(T);if(x&&Number.isFinite(x[y])&&Number.isFinite($[y])&&Math.abs($[y]-x[y])>.002)_.push($[y]-x[y])}if(_.length<2)return 0;_.sort((T,$)=>T-$);return _[Math.floor(_.length/2)]}async function f(w,b){await delay5(120);let y=await d(w);const _=Date.now()+2500;while(y&&Date.now()<_){await delay5(100);const T=await d(w);if(!T)break;const $=h(y,T,b,.002,false)===0;y=T;if($)break}return y}async function g(w,b,y,_,T,$=15){const x=Math.abs(_[1]-y[1])>=Math.abs(_[0]-y[0])?"y":"x";let A=await d(w);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 k={screen:await t(b)};const S=x==="y"?1:0;const M=x==="y"?k.screen.height:k.screen.width;const D=Math.sign(_[S]-y[S]);const R=Math.abs(_[S]-y[S])/M;const O=new Set;const U=(L,P)=>{for(const[N,H]of P){const j=L.get(N);if(j&&Number.isFinite(j[x])&&Number.isFinite(H[x])&&Math.abs(H[x]-j[x])>.01)O.add(N)}};let C=A;while(I<$){const L=await u(b,y,_,T,false,SCROLL_REST_MS,k);if(L!==void 0)k.orientation=L;I++;await a(w,b,"swipe",[y],[_],T,L);await delay5(90);const P=await d(w);await delay5(70);const N=await d(w);if(!P||!N)throw new Error("The app stopped answering while scrolling.");const H=p(P,N,x)*D;U(A,N);C=N;if(H>.004||H>=-.004&&h(P,N,x,.002,false)===0&&h(A,N,x,.01)>0){A=N;continue}const j=await f(w,x);if(!j)throw new Error("The app stopped answering while scrolling.");U(A,j);C=j;if(h(A,j,x,.01)===0){E=true;break}const W=p(A,j,x)*D;if(W>.01&&W<R*.85){E=true;break}A=j}const F=[...C].filter(([L,P])=>O.has(L)&&P[x]>=0&&P[x]<=1&&L.split("|")[1]);const z=L=>L.sort((P,N)=>(N[1][x]-P[1][x])*-D)[0];const B=z(F.filter(([L])=>!L.startsWith("Text|")))??z(F);return{swipes:I,atEnd:E,lastRow:B?B[0].split("|")[1]:void 0}}async function v(w,b){if(w.platform==="android"){const _=await adbAppFrame(w.serial,w.packageName);const T=_??{x:0,y:0,...await adbScreenSize(w.serial)};return{x:T.x+b.x*T.width,y:T.y+b.y*T.height}}const y=await t(w);return{x:b.x*y.width,y:b.y*y.height}}async function m(w,b,y,_,T){if(_&&(T==="app"||T==="loose")){const $=await e.callAction(UI_TOOL_ID2,"describeScreen",{},w,{timeoutMs:4e3,silent:true}).catch(()=>null);const x=($?.elements??[]).filter(k=>k.tap&&k.tap.x>=0&&k.tap.x<=1&&k.tap.y>=0&&k.tap.y<=1);const A=y.trim().toLowerCase();const I=k=>(k.text??k.label??"").trim().toLowerCase();const E=T==="app"?[x.filter(k=>k.testID===y),x.filter(k=>I(k)===A)]:[x.filter(k=>!!A&&I(k).includes(A))];for(const k of E){if(!k.length)continue;const S=k.filter(O=>O.interactive);const M=S.length?S:k;const D=M.filter((O,U)=>M.findIndex(C=>Math.abs(C.tap.x-O.tap.x)<.02&&Math.abs(C.tap.y-O.tap.y)<.02)===U);if(D.length>1){return{tie:true,miss:`${D.length} elements match "${y}", so nothing was touched: ${D.slice(0,5).map(O=>O.testID?`testID ${O.testID}`:JSON.stringify(O.text??O.label??O.name)).join(", ")}. Use an exact testID.`}}const R=D[0];return{...await v(b,R.tap),what:`"${R.text??R.label??R.name}"${R.testID?` [testID=${R.testID}]`:""}`}}}if((T==="native"||T==="nativeExact")&&b.platform!=="ios-device"){const $=await l(b,y,T==="nativeExact",{id:w,online:_});if(typeof $!=="string")return $;if(/equally well/.test($))return{miss:$,tie:true};if(/empty app shell/.test($))return{miss:$}}return{miss:`Nothing on screen matches "${y}".`}}return{primeScreen:n,screenOf:t,touch:r,hitAt:o,buoyCover:s,mark:a,reactSpot:c,labelSpot:l,swipe:u,scrollToEnd:g,findSpot:m}}async function nativeLabelTap(e,n,t,r,i=false){const o=nativeKit(e);const{id:s,host:a,online:c}=await hostTarget(e,n);if(a.platform==="ios-device")return null;freshScreen(a);await o.primeScreen(s,a,c);const l=await o.findSpot(s,a,t,c,i?"nativeExact":"native");if("miss"in l)return null;if(c&&await o.buoyCover(s,a,l))return null;const u=r?600:void 0;const d=await o.touch(a,l,u);await o.mark(s,a,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 s=await simHidTool();if(s)await runHidStream(s,o.udid,["--device",o.udid,"ping"]);await deviceOrientation(o.udid);await loadBars();if(!barCache.has(o.udid)){const a=await iosTree(o.udid).catch(()=>null);if(a?.screen.width)await findByLabel(o.udid,"\0no such label",a,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:s,mark:a,reactSpot:c,labelSpot:l,swipe:u,scrollToEnd:d}=nativeKit(n);const h=import_zod15.z.string().optional().describe("Android: the adb serial, when several devices are connected.");const p=f=>f.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_zod15.z.string().optional().describe('Native accessibility label, e.g. "Rewards" for a native tab.'),query:import_zod15.z.string().optional().describe("Text of an element from describe_screen."),testID:import_zod15.z.string().optional(),nativeTag:import_zod15.z.number().optional(),x:import_zod15.z.number().min(0).max(1).optional().describe("Horizontal position, 0 to 1."),y:import_zod15.z.number().min(0).max(1).optional().describe("Vertical position, 0 to 1."),holdMs:import_zod15.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_zod15.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 f=>{try{const g=f.nativeTag!=null||!!f.testID||!!f.query;const{id:v,host:m,online:w}=await hostTarget(n,f.deviceId,{serial:f.serial},{allowOffline:!g});freshScreen(m);await t(v,m,w);if(m.platform==="ios-device"&&!await simHidTool())return fail2(PHONE_TOUCH);let b;if(f.x!=null&&f.y!=null){const T=await r(m);b={x:f.x*T.width,y:f.y*T.height,what:`(${f.x.toFixed(2)}, ${f.y.toFixed(2)})`}}else if(g){b=await c(v,m,f)}else if(f.label){if(m.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.");b=await l(m,f.label,false,{id:v,online:w})}else{return fail2("Give label, query, testID, nativeTag, or x and y.")}if(typeof b==="string")return fail2(b);if(w&&!f.allowBuoy){const T=await s(v,m,b);if(T)return fail2(T)}const y=await i(m,b,f.holdMs);await a(v,m,f.holdMs?"hold":"tap",[[b.x,b.y]],void 0,f.holdMs??150,y);const _=w?await observeAfterAction(n,v):" (The app is not connected, so its screen was not read back.)";return text(`${f.holdMs?`Long-pressed (${f.holdMs}ms)`:"Tapped"} ${b.what} with a real touch at (${Math.round(b.x)}, ${Math.round(b.y)}) ${p(m)}.${_}`)}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_zod15.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 f=>{try{const{id:g,host:v,online:m}=await hostTarget(n,f.deviceId,{serial:f.serial},{allowOffline:true});if(v.platform==="ios-device"&&!await simHidTool())return fail2(PHONE_TOUCH);const w=fillSecrets(f.text);let b=false;if(v.platform==="android")await adbText(v.serial,w);else if(v.platform==="ios-device")await simHidType(await simHidTool(),await coreDeviceId(v.udid),w);else{const _=await simHidTool();if(_){await simHidType(_,v.udid,w);b=true}else{await assertSimTouchable(v.udid);await idb(["ui","text","--udid",v.udid,w])}}if(!b)await delay5(300);const y=m?await observeAfterAction(n,g):"";return text(`Typed ${JSON.stringify(f.text)} on the keyboard.${y}`)}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_zod15.z.enum(["up","down","left","right"]).optional().describe('"up" scrolls content down the list (finger moves up).'),fromX:import_zod15.z.number().min(0).max(1).optional(),fromY:import_zod15.z.number().min(0).max(1).optional(),toX:import_zod15.z.number().min(0).max(1).optional(),toY:import_zod15.z.number().min(0).max(1).optional(),durationMs:import_zod15.z.number().min(50).max(5e3).optional().describe("Default 300 (1200 with drag)."),drag:import_zod15.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_zod15.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_zod15.z.boolean().optional().describe("Swipe even if Buoy's own panel covers the starting point."),serial:h,deviceId:deviceIdInput}},async f=>{try{const{id:g,host:v,online:m}=await hostTarget(n,f.deviceId,{serial:f.serial},{allowOffline:true});freshScreen(v);await t(g,v,m);if(v.platform==="ios-device"&&!await simHidTool())return fail2(PHONE_TOUCH);const w=await r(v);let b;let y;if(f.fromX!=null&&f.fromY!=null&&f.toX!=null&&f.toY!=null){b=[f.fromX,f.fromY];y=[f.toX,f.toY]}else{({from:b,to:y}=swipePoints(f.direction??"up",!!f.untilEnd))}const _=[b[0]*w.width,b[1]*w.height];const T=[y[0]*w.width,y[1]*w.height];let $=0;if(f.drag&&v.platform==="android"){const k=Number((await adbShell(v.serial,"settings get secure long_press_timeout").catch(()=>"")).trim())||500;$=k*1.5+600}const x=Math.max(f.durationMs??(f.drag?1200:300),$);if(m&&!f.allowBuoy){const k=await s(g,v,{x:_[0],y:_[1]});if(k)return fail2(k)}if(f.untilEnd){if(f.drag)return fail2("untilEnd scrolls with flicks. Leave out drag.");if(!m)return fail2("untilEnd needs the app connected, to see when the list stops moving.");const k=await d(g,v,_,T,f.durationMs??250);const{swipes:S,atEnd:M}=k;const D=await observeAfterAction(n,g,void 0,0);const{lastRow:R}=k;return text(`${M?`Reached the end of the list after ${S} swipe(s)${R?`. The last row is "${R}"`:""}`:`Swiped ${S} times and the screen was still moving`}.${D}`)}const A=v.platform==="android"?null:await simHidTool();const I=await u(v,_,T,x,f.drag);await a(g,v,f.drag?"drag":"swipe",[_],[T],x+(f.drag&&A?700:0),I);await delay5(400);const E=m?await observeAfterAction(n,g):"";return text(`${f.drag?"Dragged":"Swiped"} from (${_.map(Math.round).join(", ")}) to (${T.map(Math.round).join(", ")}) ${p(v)}.${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_zod15.z.number().finite().min(0).optional().describe("From the left. iOS Sims use points. Other hosts use pixels."),pointY:import_zod15.z.number().finite().min(0).optional().describe("From the top. iOS Sims use points. Other hosts use pixels."),x:import_zod15.z.number().min(0).max(1).optional().describe("Horizontal position, 0 to 1."),y:import_zod15.z.number().min(0).max(1).optional().describe("Vertical position, 0 to 1."),serial:h,deviceId:deviceIdInput}},async f=>{try{const g=f.pointX!=null||f.pointY!=null;if(g&&(f.pointX==null||f.pointY==null))return fail2("Use pointX and pointY together.");if(g&&(f.x!=null||f.y!=null))return fail2("Use pointX/pointY or x/y, not both.");if(!g&&f.x==null!==(f.y==null))return fail2("Use x and y together.");const{id:v,host:m,online:w}=await hostTarget(n,f.deviceId,{serial:f.serial},{allowOffline:true});freshScreen(m);await t(v,m,w);const b=p(m);if(!g&&(f.x==null||f.y==null)){if(m.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(m.platform==="android"){const I=await adbUiNodes(m.serial);$=I.filter(E=>E.text||E.desc||E.id||E.clickable).map(E=>{const k=E.bounds;const S=[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`${S.filter(Boolean).join(" ")} at (${k.x}, ${k.y}) ${k.width}x${k.height}`})}else{const{elements:I,screen:E}=await iosNativeElements(m.udid);const k=I.filter(S=>!E.width||S.frame.y<E.height&&S.frame.y+S.frame.height>0&&S.frame.x<E.width&&S.frame.x+S.frame.width>0);x=I.length-k.length;$=k.map(axLine)}const A=$.slice(0,150);return text([`${$.length} native element(s) on screen, top to bottom (${b}; 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 y;if(g){const $=await r(m);y={x:f.pointX,y:f.pointY};if(y.x>=$.width||y.y>=$.height){return fail2(`That point is outside the screen (${$.width} x ${$.height} ${b}).`)}}else{const $=await r(m);y={x:f.x*$.width,y:f.y*$.height}}const _=[g?`At (${Math.round(y.x)}, ${Math.round(y.y)}) ${b}:`:`At (${f.x.toFixed(2)}, ${f.y.toFixed(2)}) = (${Math.round(y.x)}, ${Math.round(y.y)}) ${b}:`];const T=w?o(v,m,y):Promise.resolve(null);if(m.platform==="android"){const $=(await adbUiNodes(m.serial)).filter(A=>{const I=A.bounds;return y.x>=I.x&&y.x<=I.x+I.width&&y.y>=I.y&&y.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(m.platform==="ios"){const $=JSON.parse(await idb(["ui","describe-point","--udid",m.udid,String(Math.round(y.x)),String(Math.round(y.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(!w)_.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_zod15.z.number().min(0).max(1).optional().describe("Center between the fingers, 0 to 1. Default 0.5."),y:import_zod15.z.number().min(0).max(1).optional().describe("Center between the fingers, 0 to 1. Default 0.5."),scale:import_zod15.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_zod15.z.number().min(-180).max(180).optional().describe("Turn the fingers this many degrees while pinching, clockwise. Default 0."),durationMs:import_zod15.z.number().min(100).max(5e3).optional().describe("Default 500."),allowBuoy:import_zod15.z.boolean().optional().describe("Pinch even if a finger starts on Buoy."),deviceId:deviceIdInput}},async f=>{try{const{id:g,host:v,online:m}=await hostTarget(n,f.deviceId,{},{allowOffline:true});freshScreen(v);await t(g,v,m);if(v.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 w=await simHidTool();if(!w)return fail2(v.platform==="ios-device"?PHONE_TOUCH:"Pinching needs Xcode's CoreDevice touch support (Xcode 26 or later); idb sends one finger only.");const b=await r(v);const y=[(f.x??.5)*b.width,(f.y??.5)*b.height];const _=f.scale??2;const T=Math.min(b.width,b.height);const $=T*.4;const x=_>=1?Math.max(T*.04,$/_):$;const A=_>=1?$:Math.max(T*.04,$*_);const I=(f.rotate??0)*Math.PI/180;const E=G=>[Math.min(b.width-1,Math.max(1,G[0])),Math.min(b.height-1,Math.max(1,G[1]))];const k=(G,K)=>[E([y[0]-G*Math.cos(K),y[1]-G*Math.sin(K)]),E([y[0]+G*Math.cos(K),y[1]+G*Math.sin(K)])];const[S,M]=k(x,0);const[D,R]=k(A,I);if(m&&!f.allowBuoy){for(const[G,K]of[S,M]){const se=await s(g,v,{x:G,y:K});if(se)return fail2(se)}}const O=f.durationMs??500;const U={x:Math.max(0,(y[0]-$)/b.width),y:Math.max(0,(y[1]-$)/b.height),width:Math.min(1,2*$/b.width),height:Math.min(1,2*$/b.height)};const C=m?await readMaps(n,g):[];const F=G=>G.find(K=>!K.frame||(f.x??.5)>=K.frame.x&&(f.x??.5)<=K.frame.x+K.frame.width&&(f.y??.5)>=K.frame.y&&(f.y??.5)<=K.frame.y+K.frame.height);const z=F(C);const B=z?null:await hostPng(v).catch(()=>null);const L=v.platform==="ios-device"?await coreDeviceId(v.udid):v.udid;const P=await simHidTwo(w,L,{...b,bundleId:v.platform==="ios"?v.bundleId:null},S,M,D,R,O);await a(g,v,"pinch",[S,M],[D,R],O,P);await delay5(400);const[N,H,j]=await Promise.all([m?observeAfterAction(n,g,void 0,0):Promise.resolve(""),B?hostPng(v).catch(()=>null):Promise.resolve(null),z?readMaps(n,g):Promise.resolve([])]);const W=A/x;const V=W>1.01?`Spread (zoom in, x${W.toFixed(2)})`:W<.99?`Pinched (zoom out, x${W.toFixed(2)})`:"Turned";const J=`${V}${f.rotate?`, turning ${f.rotate} degrees,`:""} around (${Math.round(y[0])}, ${Math.round(y[1])}) ${p(v)} with two real fingers.`;const re=z?j.find(G=>G.name===z.name&&G.testID===z.testID):void 0;const oe=z&&re?mapChange(z,re):null;if(oe)return text(`${J}
687
689
  ${oe}${N}`);const ee=B&&H?await pinchProof(B,H,U):null;if(!ee)return text(`${J}${N}`);return{content:[{type:"text",text:`${J}
688
690
  ${ee.line}${N}`},{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 s=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:s,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=f=>(f%360+360)%360;const h=f=>Math.round(Math.min(d(f),360-d(f)));const p=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 ${p}\xB0, now ${h(o)}\xB0 from north)`)}const s=e.camera.altitude,a=n.camera.altitude;const c=e.camera.zoom,l=n.camera.zoom;const u=typeof s==="number"&&typeof a==="number"&&s>0&&a>0?s/a: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 p=typeof s==="number"&&typeof a==="number"?` (altitude ${Math.round(s).toLocaleString("en-US")} m to ${Math.round(a).toLocaleString("en-US")} m)`:typeof c==="number"&&typeof l==="number"?` (zoom ${c.toFixed(1)} to ${l.toFixed(1)})`:"";r.push(`${h}${p}`)}return r.length?`Checked in the app: ${t} ${r.join("; ")}.`:null}var TOOL_ID2="highlight-updates";var text4=e=>({content:[{type:"text",text:e}]});var fail6=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 s=0;s<(t?6:1);s++){await delay6(s===0?r:250);try{const a=await e.callAction("route-events","getCurrentRoute",{},n,{timeoutMs:3e3,silent:true});i=String(a?.pathname??a?.path??"")}catch{break}if(!t||i.replace(/\(.*?\)\//g,"").replace(/\/$/,"")===t.replace(/\/$/,"")||i.endsWith(t))break}let o="";try{const s=await e.callAction(TOOL_ID2,"describeScreen",{},n,{timeoutMs:5e3,silent:true});const a=s?.elements??[];const c=new Set(a.filter(g=>g.name!=="Text").map(g=>g.text??g.label).filter(Boolean));const l=a.filter(g=>g.name!=="Text"&&g.tap&&(g.text??g.label));const u=(g,v)=>!!g.tap&&l.some(m=>Math.abs(m.tap.y-g.tap.y)<.06&&(m.text??m.label).includes(v));const d=a.filter(g=>{const v=g.text??g.label;if(g.name==="Text"&&(!v||/^[\s\uE000-\uF8FF]*$/.test(v)))return false;if(g.name==="Text"&&c.has(v))return false;if(g.name==="Text"&&v&&u(g,v))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 p=[...d.filter(h),...d.filter(g=>!h(g))];const f=p.slice(0,OBSERVE_MAX);o=f.map(formatElement).join("\n");if(p.length>f.length)o+=`
689
691
  \u2026 ${p.length-f.length} more (describe_screen lists everything)`}catch{o="(could not read the screen)"}return`
@@ -741,7 +743,7 @@ ${n.join("\n")}`}function registerTimeMachineTools(e,n){e.registerTool("get_time
741
743
  ${l.join("\n")||"_no providers registered_"}`];if(s.lastOutcome)d.push(`**Last restore:**
742
744
  ${formatOutcome(s.lastOutcome)}`);return text(staleHeader(o)+d.join("\n\n"))}catch(r){return fail2(errMsg2(r))}});e.registerTool("time_machine_action",{description:"Manage snapshots of supported registered state sources: capture, preview, restore, capture_baseline, delete or rename. Preview affected items before restoring. Live mode replaces supported state in place; reload mode restores supported persisted storage and requests a JS reload. Baselines clear providers that support clearing and request a reload; they do not reset backend state or reproduce a complete reinstall. restoreRoute:true requests the captured route when available. Inspect per-source applied/skipped results and reload outcomes.",inputSchema:{action:import_zod20.z.enum(["capture","capture_baseline","preview","restore","delete","rename"]).describe("What to do."),id:import_zod20.z.string().optional().describe("Snapshot id (required for restore/delete/rename; from get_time_machine)."),name:import_zod20.z.string().optional().describe("Snapshot name (for capture and rename)."),mode:import_zod20.z.enum(["live","reload"]).optional().describe("Restore mode. Default 'live'."),excludeKeys:import_zod20.z.array(import_zod20.z.string()).optional().describe('Restore only: item keys to LEAVE UNTOUCHED, as "sourceId::itemKey" (itemKey = the key shown by the preview action, e.g. "query::[\\"pokemon\\"]" or "storage::async:@cart").'),restoreRoute:import_zod20.z.boolean().optional().describe("Restore only: also navigate back to the route the snapshot was captured on (shown as `route` by get_time_machine). With mode 'reload' the navigation happens automatically on the next boot. Default false \u2014 state is restored but the app stays on the current screen."),sourceIds:import_zod20.z.array(import_zod20.z.string()).optional().describe("Capture/restore only these source ids (default all)."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=(o,s)=>n.callAction(TIME_MACHINE_TOOL_ID,o,s,r);switch(t.action){case"capture":{const o=await i("capture",{name:t.name??"",sourceIds:t.sourceIds});const s=o.snapshot;const a=Object.entries(s.sources).flatMap(([c,l])=>l.warnings.map(u=>`
743
745
  \u26A0 ${c}: ${u}`)).join("");return text(`Captured \`${s.id}\` "${s.name}" \u2014 ${kb(s.sizeBytes)} \xB7 ${Object.keys(s.sources).join(", ")}${a}`)}case"capture_baseline":{const o=await i("captureBaseline",{});return text(`Captured baseline \`${o.snapshot.id}\` \u2014 restoring it wipes app storage and reloads.`)}case"preview":{if(!t.id)return fail2("preview requires `id` (from get_time_machine).");const o=await i("preview",{id:t.id});const s=[];let a=0;for(const l of o.sources){const u={};for(const p of l.items){u[p.verdict]=(u[p.verdict]??0)+1}const d=(u.added??0)+(u.removed??0)+(u.changed??0)+(u["too-large"]??0);a+=d;const h=Object.entries(u).filter(([p])=>p!=="unchanged").map(([p,f])=>`${f} ${p}`);s.push(`- **${l.label}**: ${h.length?h.join(", "):"no changes"}${l.error?` \u2014 \u26A0 ${l.error}`:""}`);for(const p of l.items.filter(f=>f.verdict!=="unchanged").slice(0,8)){s.push(` ${p.verdict==="added"?"+":p.verdict==="removed"?"\u2212":p.verdict==="wont-apply"?"\u2298":"\u2248"} ${p.label}${p.reason?` (${p.reason})`:""}`)}for(const p of l.notes)s.push(` \xB7 ${p}`)}const c=a===0?"**Restore would change NOTHING** (states identical or nothing applicable).":`**Restore would apply ${a} change(s):**`;return text(`${c}
744
- ${s.join("\n")}`)}case"restore":{if(!t.id)return fail2("restore requires `id` (from get_time_machine).");const o=await i("restore",{id:t.id,mode:t.mode??"live",excludeKeys:t.excludeKeys,restoreRoute:t.restoreRoute});return text(formatOutcome(o))}case"delete":{if(!t.id)return fail2("delete requires `id`.");await i("delete",{id:t.id});return text(`Deleted snapshot \`${t.id}\`.`)}case"rename":{if(!t.id||!t.name)return fail2("rename requires `id` and `name`.");await i("rename",{id:t.id,name:t.name});return text(`Renamed \`${t.id}\` to "${t.name}".`)}}}catch(r){return fail2(errMsg2(r))}})}var import_zod21=require("zod");var CLOCK_TOOL_ID="clock";function duration(e){const n=e<0?"-":"+";let t=Math.abs(Math.round(e/1e3));if(t===0)return"0s";const r=[];for(const[i,o]of[["d",86400],["h",3600],["m",60],["s",1]]){if(t>=o){r.push(`${Math.floor(t/o)}${i}`);t%=o}if(r.length===2)break}return n+r.join(" ")}function describe(e){const n=[e.active?`**App clock: ${e.virtualIso}** (${e.mode}${e.rate!==1?`, ${e.rate}\xD7`:""}), ${duration(e.offsetMs)} from real time ${new Date(e.realNow).toISOString()}`:`**App clock: real time** (${e.virtualIso})`,`Time zone: ${e.timeZone} (the override never changes it)`,`Pending app timers: ${e.timers.timeouts} timeouts, ${e.timers.intervals} intervals`];if(e.lastJump){n.push(`Last change: ${duration(e.lastJump.byMs)}${e.lastJump.firedTimers?`, ran ${e.lastJump.firedTimers} due timer(s)`:""}`)}n.push(...describeTokens(e));n.push(`Settings: persist=${e.settings.persist} showChip=${e.settings.showChip} fireTimersOnJump=${e.settings.fireTimersOnJump}`);return n.join("\n")}function describeTokens(e){const n=e.tokens;if(!n)return[];if(!n.available)return["Sign-in tokens: unavailable (the app has no @buoy-gg/network)."];if(n.tokens.length===0)return["Sign-in tokens: none seen yet (they appear once the app sends a signed-in request)."];const t=["Sign-in tokens (read from captured requests; raw tokens are never shown):"];for(const i of n.tokens){const o=i.expiresAt!==void 0?i.expiresAt-e.virtualNow:void 0;const s=i.serverExpiresAt!==void 0?i.serverExpiresAt-e.realNow:void 0;const a=i.neverExpires?"never expires":o===void 0?"expiry unknown":o>0?`expires in ${duration(o).slice(1)} on the app's clock`:`expired ${duration(-o).slice(1)} ago on the app's clock`;const c=s!==void 0&&o!==void 0&&Math.abs(s-o)>2e3?s>0?`; the server accepts it for ${duration(s).slice(1)} more`:"; the server no longer accepts it":"";const l=[i.hint??i.formatLabel,i.expirySource?`expiry from ${i.expirySource}`:null,i.issuedBy?`issued by ${i.issuedBy}`:null,i.claims.sub?`sub ${i.claims.sub}`:null,`${i.uses} request(s)`,i.refreshes?`${i.refreshes} refresh(es)`:null,i.expiredSends?`SENT ${i.expiredSends}\xD7 AFTER EXPIRY`:null,i.rejected?`rejected ${i.rejected}\xD7`:null,i.looping?`REFRESH LOOP (${i.recentRefreshes} new tokens in 20s)`:null].filter(Boolean);t.push(`- [${i.id}] ${i.label} \u2192 ${i.host}: ${a}${c} (${l.join(", ")})`)}const r=n.check;if(r){const i=r.status==="refreshed"?`refreshed${r.kind==="401"&&r.forcedAt?" after the forced 401":""}${r.newIssuedBy?` via ${r.newIssuedBy}`:""}${r.newLifetimeMs?`; new token lasts ${duration(r.newLifetimeMs).slice(1)}`:""}`:r.status==="loop"?`REFRESH LOOP: ${r.newTokens} new tokens since the check started`:r.kind==="401"&&r.forcedAt===void 0?"waiting: the next request to that API will get a 401 (the app must send one)":`waiting for a new token (${duration(e.realNow-r.startedAt).slice(1)} so far)`;const o=r.staleAfterFailure?`; the app re-sent the old token ${r.staleAfterFailure}\xD7 after the 401`:"";t.push(`Refresh check (${r.kind==="401"?"forced 401":"jump to expiry"}): ${i}${o}`)}return t}function registerClockTools(e,n){e.registerTool("get_clock",{description:"Read the app's clock as the Clock tool (@buoy-gg/clock) sees it: the time the app reads now, whether it is overridden (running, frozen or sped up), how far it is from real time, and the pending app timers a jump ahead could run. Also lists the app's sign-in tokens seen in its traffic (JWT, PASETO, opaque tokens with an expiry from the login response, session cookies): time left on the app's clock and the server's, who issued them, refreshes, sends after expiry, refresh loops, and the result of a running refresh check. Check this before calling a date, countdown, expiry or sign-out a bug.",inputSchema:{deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(CLOCK_TOOL_ID,"getState",{},r);return text(describe(i))}catch(r){return fail2(errMsg2(r))}});e.registerTool("clock_action",{description:"Override the app's clock. set_time moves it to `time` (ISO 8601, 'YYYY-MM-DD HH:MM' in the device's zone, epoch ms, or relative like '+30d'), optionally frozen. shift jumps by `by` ('+1d', '-2h30m', '90s'); a forward shift also runs app setTimeout/setInterval callbacks that come due inside the jump, once each. freeze/resume stop and restart it, set_rate runs it faster (60 = a minute per second), reset returns to real time. To test token refresh: jump_to_token_expiry moves the app's clock to `leadMs` (default 10000) before a token expires, for apps that refresh before expiry; fail_next_request answers the next request to that token's API with a 401 once, for apps that refresh after a 401. Both start a refresh check; read get_clock after the app sends a request to see whether a new token arrived. stop_token_check ends it and withdraws an unfired 401. Moves Date.now(), new Date() and no-argument Intl formatting; performance.now(), animations, native timers, the time zone and the backend's clock stay real. Screens that already computed a time keep it until they re-read the clock or the app reloads; the override survives reload_app.",inputSchema:{action:import_zod21.z.enum(["set_time","shift","freeze","resume","set_rate","reset","settings","jump_to_token_expiry","fail_next_request","stop_token_check"]).describe("What to do."),time:import_zod21.z.union([import_zod21.z.string(),import_zod21.z.number()]).optional().describe("set_time (required) / freeze (optional): target time."),by:import_zod21.z.union([import_zod21.z.string(),import_zod21.z.number()]).optional().describe("shift (required): signed duration like '+1d', '-2h30m', '90s', or ms."),freeze:import_zod21.z.boolean().optional().describe("set_time: stop the clock at `time`. Default false."),fireTimers:import_zod21.z.boolean().optional().describe("shift: run app timers that come due inside a forward jump. Default on."),rate:import_zod21.z.number().optional().describe("set_rate (required): speed multiplier, 0.1-86400; 1 is normal."),persist:import_zod21.z.boolean().optional().describe("settings: keep the override across reloads."),showChip:import_zod21.z.boolean().optional().describe("settings: show the floating clock chip while overridden."),fireTimersOnJump:import_zod21.z.boolean().optional().describe("settings: default for shift's fireTimers."),token:import_zod21.z.string().optional().describe("jump_to_token_expiry / fail_next_request: token id from get_clock. Default: the most recently used token."),leadMs:import_zod21.z.number().optional().describe("jump_to_token_expiry: land this many ms before expiry. Default 10000."),status:import_zod21.z.number().optional().describe("fail_next_request: 401 (default) or 403."),times:import_zod21.z.number().optional().describe("fail_next_request: how many requests to fail, 1-10. Default 1."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=(s,a={})=>n.callAction(CLOCK_TOOL_ID,s,a,r);let o;switch(t.action){case"set_time":if(t.time===void 0)return fail2("set_time requires `time`.");o=await i("setTime",{time:t.time,freeze:t.freeze??false});break;case"shift":if(t.by===void 0)return fail2("shift requires `by`, e.g. '+1d'.");o=await i("shift",{by:t.by,...t.fireTimers!==void 0?{fireTimers:t.fireTimers}:{}});break;case"freeze":o=await i("freeze",t.time!==void 0?{time:t.time}:{});break;case"resume":o=await i("resume");break;case"set_rate":if(t.rate===void 0)return fail2("set_rate requires `rate`.");o=await i("setRate",{rate:t.rate});break;case"reset":o=await i("reset");break;case"settings":o=await i("updateSettings",{...t.persist!==void 0?{persist:t.persist}:{},...t.showChip!==void 0?{showChip:t.showChip}:{},...t.fireTimersOnJump!==void 0?{fireTimersOnJump:t.fireTimersOnJump}:{}});break;case"jump_to_token_expiry":o=await i("jumpToTokenExpiry",{...t.token?{token:t.token}:{},...t.leadMs!==void 0?{leadMs:t.leadMs}:{}});break;case"fail_next_request":o=await i("failNextRequest",{...t.token?{token:t.token}:{},...t.status!==void 0?{status:t.status}:{},...t.times!==void 0?{times:t.times}:{}});break;case"stop_token_check":o=await i("stopTokenCheck");break}return text(describe(o))}catch(r){return fail2(errMsg2(r))}})}var import_node_child_process18=require("child_process");var import_node_util15=require("util");var import_zod22=require("zod");var PERMISSIONS_TOOL_ID="permissions";var execFileAsync15=(0,import_node_util15.promisify)(import_node_child_process18.execFile);var PERMISSION_IDS=["location","locationBackground","camera","microphone","notifications","photos","contacts","calendar","reminders","tracking","motion","bluetooth"];function describe2(e,n=12){const t=[];t.push(e.overriddenCount>0?`**${e.overriddenCount} permission(s) overridden** on ${e.platform}. The app sees the override; the OS state is unchanged.`:`**No overrides** on ${e.platform}: the app sees the real OS state.`);t.push(`Libraries found: ${e.libraries.length?e.libraries.join(", "):"none yet"}`);if(e.permissions.length===0){t.push("No permission APIs found yet. Rows appear for Expo modules in the app and for anything the app asks for.")}for(const i of e.permissions){const o=[i.override?`override **${i.override}**`:"not overridden",`system ${i.real??"unknown"}`,i.calls?`asked ${i.calls}\xD7`:"not asked yet",i.sources.length?`via ${i.sources.join(", ")}`:null,`can be: ${i.states.join(", ")}`].filter(Boolean);t.push(`- ${i.id} (${i.label}): ${o.join("; ")}`);if(i.warning)t.push(` \u26A0 ${i.warning}`)}const r=e.settings;t.push(`Settings: requestAnswer=${r.requestAnswer} notifyApp=${r.notifyApp} interceptSettings=${r.interceptSettings} enforce=${r.enforce} persist=${r.persist} showChip=${r.showChip}`);if(e.log.length){t.push("Recent calls (newest first):");for(const i of e.log.slice(0,n)){const o=new Date(i.at).toISOString().slice(11,19);const s=i.error??i.returned??"no answer";t.push(`- ${o} ${i.source}.${i.method} \u2192 ${s}${i.overridden?" (override)":""}${i.real&&i.real!==i.returned?`, system ${i.real}`:""}${i.answer?`, answered ${i.answer}`:""}`)}}if(e.host.bundleId){t.push(`Host: ${e.host.isSimulator?"simulator/emulator":e.host.isSimulator===false?"physical device":"unknown device"} "${e.host.deviceName??"?"}", app ${e.host.bundleId}`)}return t.join("\n")}var SIMCTL_SERVICE={location:"location",locationBackground:"location-always",camera:"camera",microphone:"microphone",photos:"photos",contacts:"contacts",calendar:"calendar",reminders:"reminders",motion:"motion"};var ANDROID_PERMISSIONS={location:["ACCESS_FINE_LOCATION","ACCESS_COARSE_LOCATION"],locationBackground:["ACCESS_BACKGROUND_LOCATION"],camera:["CAMERA"],microphone:["RECORD_AUDIO"],notifications:["POST_NOTIFICATIONS"],photos:["READ_MEDIA_IMAGES","READ_MEDIA_VIDEO"],contacts:["READ_CONTACTS","WRITE_CONTACTS"],calendar:["READ_CALENDAR","WRITE_CALENDAR"],motion:["ACTIVITY_RECOGNITION"],bluetooth:["BLUETOOTH_SCAN","BLUETOOTH_CONNECT"]};async function run4(e,n){const{stdout:t}=await execFileAsync15(e,n,{timeout:2e4});return t}async function findSimulator(e,n){if(n)return n;const t=JSON.parse(await run4("xcrun",["simctl","list","devices","booted","-j"]));const r=Object.values(t.devices).flat();const i=r.filter(o=>o.name===e.host.deviceName);if(i.length===1)return i[0].udid;if(!e.host.deviceName&&r.length===1)return r[0].udid;throw new Error(i.length===0?`No booted simulator is named "${e.host.deviceName??"?"}". Pass \`udid\`.`:`${i.length} booted simulators are named "${e.host.deviceName}". Pass \`udid\`.`)}async function findAdbSerial(e){if(e)return e;const n=await run4("adb",["devices"]);const t=n.split("\n").slice(1).map(r=>r.trim().split(/\s+/)).filter(r=>r[1]==="device").map(r=>r[0]);if(t.length===1)return t[0];throw new Error(t.length===0?"No Android device is connected to adb.":"Several Android devices are connected. Pass `serial`.")}async function systemPermission(e,n,t,r){const i=e.host.bundleId;if(!i)throw new Error("The app did not report its bundle id (needs expo-application).");if(e.platform==="ios"){if(e.host.isSimulator===false)throw new Error("A physical iPhone can't be changed from the host. Use the app's Settings page.");const c=t==="all"?"all":SIMCTL_SERVICE[t];if(!c){throw new Error(`simctl has no privacy service for ${t}. Override it in the app instead (permission_action set).`)}const l=await findSimulator(e,r.udid);await run4("xcrun",["simctl","privacy",l,n,c,i]);return`simctl privacy ${n} ${c} for ${i} on ${l}.${n==="grant"?"":" iOS ends the app's process when a permission is revoked or reset; relaunch it."}`}const o=await findAdbSerial(r.serial);const s=t==="all"?Object.values(ANDROID_PERMISSIONS).flat():ANDROID_PERMISSIONS[t];if(!s)throw new Error(`No Android permission is known for ${t}.`);const a=[];for(const c of s){const l=`android.permission.${c}`;try{if(n==="grant")await run4("adb",["-s",o,"shell","pm","grant",i,l]);else{await run4("adb",["-s",o,"shell","pm","revoke",i,l]);if(n==="reset"){await run4("adb",["-s",o,"shell","pm","clear-permission-flags",i,l,"user-set","user-fixed"])}}a.push(c)}catch{}}if(a.length===0)throw new Error(`None of ${s.join(", ")} could be changed. Is it declared in the app's manifest?`);return`adb ${n} ${a.join(", ")} for ${i} on ${o}.${n==="grant"?"":" Android restarts the app's process when a permission is revoked."}`}function registerPermissionsTools(e,n){e.registerTool("get_permissions",{description:"Read the app's permissions as the Permissions tool (@buoy-gg/permissions) sees them: each permission the app can reach (location, camera, notifications, photos\u2026), what the OS says, any override, which libraries asked (Expo modules, PermissionsAndroid, react-native-permissions), the states this platform allows, and the recent permission calls with what each one returned. Check this before calling a permission screen, prompt or Settings flow a bug.",inputSchema:{logLimit:import_zod22.z.number().optional().describe("How many recent calls to list. Default 12."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(PERMISSIONS_TOOL_ID,"getState",{},r);return text(describe2(i,t.logLimit??12))}catch(r){return fail2(errMsg2(r))}});e.registerTool("permission_action",{description:"Override what the app sees when it asks for a permission, without changing the OS. set makes `permission` read as `state` (undetermined = not asked, granted, limited = approximate location / selected photos or contacts / provisional notifications, denied, blocked = Android 'don't ask again', restricted = iOS parental controls); iOS has no blocked (a refusal is final, so denied reads as blocked) and Android has no restricted. clear returns one permission to the OS answer, reset clears all. While overridden, the real system prompt never shows: a request from undetermined (or Android denied) is answered by `answer` (ask = Buoy shows a prompt on the device and waits for a tap; allow, limited or deny answer at once) and moves the state the way the OS would. Linking.openSettings and app-settings: open Buoy's stand-in for Settings. By default a change sends the app background \u2192 active, like a return from Settings, so screens that re-check on foreground update; permission hooks that read only on mount update on their next read. With enforce on (default), calls that need access (current position, launch camera, media library reads) fail with the native module's error while refused. request_real shows the real system prompt once so the OS grants what the override pretends. The override survives reload_app.",inputSchema:{action:import_zod22.z.enum(["set","clear","reset","answer","settings","request_real","return_from_settings","clear_log"]).describe("What to do."),permission:import_zod22.z.string().optional().describe(`set / clear / request_real (required): ${PERMISSION_IDS.join(", ")}, or android:<android.permission.NAME>.`),state:import_zod22.z.enum(["undetermined","granted","limited","denied","blocked","restricted"]).optional().describe("set (required): the state the app sees."),answer:import_zod22.z.enum(["ask","allow","limited","deny"]).optional().describe("answer (required): how a request from 'not asked' is answered while overridden."),notifyApp:import_zod22.z.boolean().optional().describe("settings: send background \u2192 active after each change. Default on."),interceptSettings:import_zod22.z.boolean().optional().describe("settings: stand in for Settings while overridden. Default on."),enforce:import_zod22.z.boolean().optional().describe("settings: fail calls that need a refused permission. Default on."),persist:import_zod22.z.boolean().optional().describe("settings: keep overrides across reloads. Default on."),showChip:import_zod22.z.boolean().optional().describe("settings: show the floating chip while overridden. Default on."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=(s,a={})=>n.callAction(PERMISSIONS_TOOL_ID,s,a,r);let o;switch(t.action){case"set":if(!t.permission||!t.state)return fail2("set requires `permission` and `state`.");o=await i("setOverride",{permission:t.permission,state:t.state});break;case"clear":if(!t.permission)return fail2("clear requires `permission`.");o=await i("clearOverride",{permission:t.permission});break;case"reset":o=await i("resetAll");break;case"answer":if(!t.answer)return fail2("answer requires `answer`: ask, allow, limited or deny.");o=await i("updateSettings",{requestAnswer:t.answer});break;case"settings":o=await i("updateSettings",{...t.notifyApp!==void 0?{notifyApp:t.notifyApp}:{},...t.interceptSettings!==void 0?{interceptSettings:t.interceptSettings}:{},...t.enforce!==void 0?{enforce:t.enforce}:{},...t.persist!==void 0?{persist:t.persist}:{},...t.showChip!==void 0?{showChip:t.showChip}:{}});break;case"request_real":if(!t.permission)return fail2("request_real requires `permission`.");o=await i("requestReal",{permission:t.permission});break;case"return_from_settings":o=await i("simulateReturnFromSettings");break;case"clear_log":o=await i("clearLog");break}return text(describe2(o))}catch(r){return fail2(errMsg2(r))}});e.registerTool("system_permission",{description:"Change the REAL OS permission for the connected app from this machine, for what an in-app override can't fake (native code that checks the OS itself, like reading a position or opening the camera). iOS Simulator uses `xcrun simctl privacy` (grant, revoke, reset; reset returns to 'not asked' so the real prompt shows again). There is no simctl service for notifications or tracking. Android uses `adb shell pm grant/revoke`; reset also clears 'don't ask again'. Revoking or resetting ends the app's process on both platforms, so relaunch it afterwards. Physical iPhones can't be changed this way.",inputSchema:{action:import_zod22.z.enum(["grant","revoke","reset"]).describe("grant, revoke, or reset to not asked."),permission:import_zod22.z.string().describe(`${PERMISSION_IDS.join(", ")}, or all.`),udid:import_zod22.z.string().optional().describe("iOS: the simulator udid, when its name is ambiguous."),serial:import_zod22.z.string().optional().describe("Android: the adb serial, when several devices are connected."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(PERMISSIONS_TOOL_ID,"getState",{},r);const o=await systemPermission(i,t.action,t.permission,{udid:t.udid,serial:t.serial});return text(o)}catch(r){return fail2(errMsg2(r))}})}var import_node_child_process19=require("child_process");var import_node_util16=require("util");var import_zod23=require("zod");var LIFECYCLE_TOOL_ID="lifecycle";var execFileAsync16=(0,import_node_util16.promisify)(import_node_child_process19.execFile);function listeners(e){if(e==null)return"can't count";return e===0?"none":String(e)}function describe3(e){const n=[];if(e.away){const r=Math.round((Date.now()-e.away.startedAt)/1e3);n.push(`**Simulated: ${e.away.kind==="background"?"in the background":"interrupted (inactive)"}** for ${r}s`+(e.away.returnAt?`, returns in ${Math.max(0,Math.round((e.away.returnAt-Date.now())/1e3))}s`:", until return")+`. Real OS state: ${e.realAppState}.`)}else{n.push(`App state: active (real OS state: ${e.realAppState}).`)}if(e.power){n.push(`Simulated battery: ${Math.round(e.power.level*100)}%, ${e.power.state}${e.power.lowPowerMode?", low power mode":""} (reached ${e.power.reached.join(", ")})`+(e.power.realGetters.length?`; still real: ${e.power.realGetters.join(", ")}`:""))}if(e.scheme)n.push(`Simulated color scheme: ${e.scheme.scheme} (${e.scheme.mode}).`);n.push(`App listeners: app state ${listeners(e.listeners.appState)}, memory warning ${listeners(e.listeners.memoryWarning)}, deep link ${listeners(e.listeners.deepLink)}`+(e.platform==="android"?`, window focus ${listeners(e.listeners.focus)}`:"")+(e.batteryLibraries.length?`, battery ${listeners(e.listeners.battery)} (${e.batteryLibraries.join(", ")})`:", battery: no battery library installed")+".");if(e.report){const r=e.report;n.push(`
746
+ ${s.join("\n")}`)}case"restore":{if(!t.id)return fail2("restore requires `id` (from get_time_machine).");const o=await i("restore",{id:t.id,mode:t.mode??"live",excludeKeys:t.excludeKeys,restoreRoute:t.restoreRoute});return text(formatOutcome(o))}case"delete":{if(!t.id)return fail2("delete requires `id`.");await i("delete",{id:t.id});return text(`Deleted snapshot \`${t.id}\`.`)}case"rename":{if(!t.id||!t.name)return fail2("rename requires `id` and `name`.");await i("rename",{id:t.id,name:t.name});return text(`Renamed \`${t.id}\` to "${t.name}".`)}}}catch(r){return fail2(errMsg2(r))}})}var import_zod21=require("zod");var CLOCK_TOOL_ID="clock";function duration(e){const n=e<0?"-":"+";let t=Math.abs(Math.round(e/1e3));if(t===0)return"0s";const r=[];for(const[i,o]of[["d",86400],["h",3600],["m",60],["s",1]]){if(t>=o){r.push(`${Math.floor(t/o)}${i}`);t%=o}if(r.length===2)break}return n+r.join(" ")}function describe(e){const n=[e.active?`**App clock: ${e.virtualIso}** (${e.mode}${e.rate!==1?`, ${e.rate}\xD7`:""}), ${duration(e.offsetMs)} from real time ${new Date(e.realNow).toISOString()}`:`**App clock: real time** (${e.virtualIso})`,`Time zone: ${e.timeZone} (the override never changes it)`,`Pending app timers: ${e.timers.timeouts} timeouts, ${e.timers.intervals} intervals`];if(e.lastJump){n.push(`Last change: ${duration(e.lastJump.byMs)}${e.lastJump.firedTimers?`, ran ${e.lastJump.firedTimers} due timer(s)`:""}`)}n.push(...describeTokens(e));n.push(`Settings: persist=${e.settings.persist} showChip=${e.settings.showChip} fireTimersOnJump=${e.settings.fireTimersOnJump}`);return n.join("\n")}function describeTokens(e){const n=e.tokens;if(!n)return[];if(!n.available)return["Sign-in tokens: unavailable (the app has no @buoy-gg/network)."];if(n.tokens.length===0)return["Sign-in tokens: none seen yet (they appear once the app sends a signed-in request)."];const t=["Sign-in tokens (read from captured requests; raw tokens are never shown):"];for(const i of n.tokens){const o=i.expiresAt!==void 0?i.expiresAt-e.virtualNow:void 0;const s=i.serverExpiresAt!==void 0?i.serverExpiresAt-e.realNow:void 0;const a=i.neverExpires?"never expires":o===void 0?"expiry unknown":o>0?`expires in ${duration(o).slice(1)} on the app's clock`:`expired ${duration(-o).slice(1)} ago on the app's clock`;const c=s!==void 0&&o!==void 0&&Math.abs(s-o)>2e3?s>0?`; the server accepts it for ${duration(s).slice(1)} more`:"; the server no longer accepts it":"";const l=[i.hint??i.formatLabel,i.expirySource?`expiry from ${i.expirySource}`:null,i.issuedBy?`issued by ${i.issuedBy}`:null,i.claims.sub?`sub ${i.claims.sub}`:null,`${i.uses} request(s)`,i.refreshes?`${i.refreshes} refresh(es)`:null,i.expiredSends?`SENT ${i.expiredSends}\xD7 AFTER EXPIRY`:null,i.rejected?`rejected ${i.rejected}\xD7`:null,i.looping?`REFRESH LOOP (${i.recentRefreshes} new tokens in 20s)`:null].filter(Boolean);t.push(`- [${i.id}] ${i.label} \u2192 ${i.host}: ${a}${c} (${l.join(", ")})`)}const r=n.check;if(r){const i=r.status==="refreshed"?`refreshed${r.kind==="401"&&r.forcedAt?" after the forced 401":""}${r.newIssuedBy?` via ${r.newIssuedBy}`:""}${r.newLifetimeMs?`; new token lasts ${duration(r.newLifetimeMs).slice(1)}`:""}`:r.status==="loop"?`REFRESH LOOP: ${r.newTokens} new tokens since the check started`:r.kind==="401"&&r.forcedAt===void 0?"waiting: the next request to that API will get a 401 (the app must send one)":`waiting for a new token (${duration(e.realNow-r.startedAt).slice(1)} so far)`;const o=r.staleAfterFailure?`; the app re-sent the old token ${r.staleAfterFailure}\xD7 after the 401`:"";t.push(`Refresh check (${r.kind==="401"?"forced 401":"jump to expiry"}): ${i}${o}`)}return t}function registerClockTools(e,n){e.registerTool("get_clock",{description:"Read the app's clock as the Clock tool (@buoy-gg/clock) sees it: the time the app reads now, whether it is overridden (running, frozen or sped up), how far it is from real time, and the pending app timers a jump ahead could run. Also lists the app's sign-in tokens seen in its traffic (JWT, PASETO, opaque tokens with an expiry from the login response, session cookies): time left on the app's clock and the server's, who issued them, refreshes, sends after expiry, refresh loops, and the result of a running refresh check. Check this before calling a date, countdown, expiry or sign-out a bug.",inputSchema:{deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(CLOCK_TOOL_ID,"getState",{},r);return text(describe(i))}catch(r){return fail2(errMsg2(r))}});e.registerTool("clock_action",{description:"Override the app's clock. set_time moves it to `time` (ISO 8601, 'YYYY-MM-DD HH:MM' in the device's zone, epoch ms, or relative like '+30d'), optionally frozen. shift jumps by `by` ('+1d', '-2h30m', '90s'); a forward shift also runs app setTimeout/setInterval callbacks that come due inside the jump, once each. freeze/resume stop and restart it, set_rate runs it faster (60 = a minute per second), reset returns to real time. To test token refresh: jump_to_token_expiry moves the app's clock to `leadMs` (default 10000) before a token expires, for apps that refresh before expiry; fail_next_request answers the next request to that token's API with a 401 once, for apps that refresh after a 401. Both start a refresh check; read get_clock after the app sends a request to see whether a new token arrived. stop_token_check ends it and withdraws an unfired 401. Moves Date.now(), new Date() and no-argument Intl formatting; performance.now(), animations, native timers, the time zone and the backend's clock stay real. Screens that already computed a time keep it until they re-read the clock or the app reloads; the override survives reload_app.",inputSchema:{action:import_zod21.z.enum(["set_time","shift","freeze","resume","set_rate","reset","settings","jump_to_token_expiry","fail_next_request","stop_token_check"]).describe("What to do."),time:import_zod21.z.union([import_zod21.z.string(),import_zod21.z.number()]).optional().describe("set_time (required) / freeze (optional): target time."),by:import_zod21.z.union([import_zod21.z.string(),import_zod21.z.number()]).optional().describe("shift (required): signed duration like '+1d', '-2h30m', '90s', or ms."),freeze:import_zod21.z.boolean().optional().describe("set_time: stop the clock at `time`. Default false."),fireTimers:import_zod21.z.boolean().optional().describe("shift: run app timers that come due inside a forward jump. Default on."),rate:import_zod21.z.number().optional().describe("set_rate (required): speed multiplier, 0.1-86400; 1 is normal."),persist:import_zod21.z.boolean().optional().describe("settings: keep the override across reloads."),showChip:import_zod21.z.boolean().optional().describe("settings: show the floating clock chip while overridden."),fireTimersOnJump:import_zod21.z.boolean().optional().describe("settings: default for shift's fireTimers."),token:import_zod21.z.string().optional().describe("jump_to_token_expiry / fail_next_request: token id from get_clock. Default: the most recently used token."),leadMs:import_zod21.z.number().optional().describe("jump_to_token_expiry: land this many ms before expiry. Default 10000."),status:import_zod21.z.number().optional().describe("fail_next_request: 401 (default) or 403."),times:import_zod21.z.number().optional().describe("fail_next_request: how many requests to fail, 1-10. Default 1."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=(s,a={})=>n.callAction(CLOCK_TOOL_ID,s,a,r);let o;switch(t.action){case"set_time":if(t.time===void 0)return fail2("set_time requires `time`.");o=await i("setTime",{time:t.time,freeze:t.freeze??false});break;case"shift":if(t.by===void 0)return fail2("shift requires `by`, e.g. '+1d'.");o=await i("shift",{by:t.by,...t.fireTimers!==void 0?{fireTimers:t.fireTimers}:{}});break;case"freeze":o=await i("freeze",t.time!==void 0?{time:t.time}:{});break;case"resume":o=await i("resume");break;case"set_rate":if(t.rate===void 0)return fail2("set_rate requires `rate`.");o=await i("setRate",{rate:t.rate});break;case"reset":o=await i("reset");break;case"settings":o=await i("updateSettings",{...t.persist!==void 0?{persist:t.persist}:{},...t.showChip!==void 0?{showChip:t.showChip}:{},...t.fireTimersOnJump!==void 0?{fireTimersOnJump:t.fireTimersOnJump}:{}});break;case"jump_to_token_expiry":o=await i("jumpToTokenExpiry",{...t.token?{token:t.token}:{},...t.leadMs!==void 0?{leadMs:t.leadMs}:{}});break;case"fail_next_request":o=await i("failNextRequest",{...t.token?{token:t.token}:{},...t.status!==void 0?{status:t.status}:{},...t.times!==void 0?{times:t.times}:{}});break;case"stop_token_check":o=await i("stopTokenCheck");break}return text(describe(o))}catch(r){return fail2(errMsg2(r))}})}var import_node_child_process19=require("child_process");var import_node_util15=require("util");var import_zod22=require("zod");var PERMISSIONS_TOOL_ID="permissions";var execFileAsync15=(0,import_node_util15.promisify)(import_node_child_process19.execFile);var PERMISSION_IDS=["location","locationBackground","camera","microphone","notifications","photos","contacts","calendar","reminders","tracking","motion","bluetooth"];function describe2(e,n=12){const t=[];t.push(e.overriddenCount>0?`**${e.overriddenCount} permission(s) overridden** on ${e.platform}. The app sees the override; the OS state is unchanged.`:`**No overrides** on ${e.platform}: the app sees the real OS state.`);t.push(`Libraries found: ${e.libraries.length?e.libraries.join(", "):"none yet"}`);if(e.permissions.length===0){t.push("No permission APIs found yet. Rows appear for Expo modules in the app and for anything the app asks for.")}for(const i of e.permissions){const o=[i.override?`override **${i.override}**`:"not overridden",`system ${i.real??"unknown"}`,i.calls?`asked ${i.calls}\xD7`:"not asked yet",i.sources.length?`via ${i.sources.join(", ")}`:null,`can be: ${i.states.join(", ")}`].filter(Boolean);t.push(`- ${i.id} (${i.label}): ${o.join("; ")}`);if(i.warning)t.push(` \u26A0 ${i.warning}`)}const r=e.settings;t.push(`Settings: requestAnswer=${r.requestAnswer} notifyApp=${r.notifyApp} interceptSettings=${r.interceptSettings} enforce=${r.enforce} persist=${r.persist} showChip=${r.showChip}`);if(e.log.length){t.push("Recent calls (newest first):");for(const i of e.log.slice(0,n)){const o=new Date(i.at).toISOString().slice(11,19);const s=i.error??i.returned??"no answer";t.push(`- ${o} ${i.source}.${i.method} \u2192 ${s}${i.overridden?" (override)":""}${i.real&&i.real!==i.returned?`, system ${i.real}`:""}${i.answer?`, answered ${i.answer}`:""}`)}}if(e.host.bundleId){t.push(`Host: ${e.host.isSimulator?"simulator/emulator":e.host.isSimulator===false?"physical device":"unknown device"} "${e.host.deviceName??"?"}", app ${e.host.bundleId}`)}return t.join("\n")}var SIMCTL_SERVICE={location:"location",locationBackground:"location-always",camera:"camera",microphone:"microphone",photos:"photos",contacts:"contacts",calendar:"calendar",reminders:"reminders",motion:"motion"};var ANDROID_PERMISSIONS={location:["ACCESS_FINE_LOCATION","ACCESS_COARSE_LOCATION"],locationBackground:["ACCESS_BACKGROUND_LOCATION"],camera:["CAMERA"],microphone:["RECORD_AUDIO"],notifications:["POST_NOTIFICATIONS"],photos:["READ_MEDIA_IMAGES","READ_MEDIA_VIDEO"],contacts:["READ_CONTACTS","WRITE_CONTACTS"],calendar:["READ_CALENDAR","WRITE_CALENDAR"],motion:["ACTIVITY_RECOGNITION"],bluetooth:["BLUETOOTH_SCAN","BLUETOOTH_CONNECT"]};async function run4(e,n){const{stdout:t}=await execFileAsync15(e,n,{timeout:2e4});return t}async function findSimulator(e,n){if(n)return n;const t=JSON.parse(await run4("xcrun",["simctl","list","devices","booted","-j"]));const r=Object.values(t.devices).flat();const i=r.filter(o=>o.name===e.host.deviceName);if(i.length===1)return i[0].udid;if(!e.host.deviceName&&r.length===1)return r[0].udid;throw new Error(i.length===0?`No booted simulator is named "${e.host.deviceName??"?"}". Pass \`udid\`.`:`${i.length} booted simulators are named "${e.host.deviceName}". Pass \`udid\`.`)}async function findAdbSerial(e){if(e)return e;const n=await run4("adb",["devices"]);const t=n.split("\n").slice(1).map(r=>r.trim().split(/\s+/)).filter(r=>r[1]==="device").map(r=>r[0]);if(t.length===1)return t[0];throw new Error(t.length===0?"No Android device is connected to adb.":"Several Android devices are connected. Pass `serial`.")}async function systemPermission(e,n,t,r){const i=e.host.bundleId;if(!i)throw new Error("The app did not report its bundle id (needs expo-application).");if(e.platform==="ios"){if(e.host.isSimulator===false)throw new Error("A physical iPhone can't be changed from the host. Use the app's Settings page.");const c=t==="all"?"all":SIMCTL_SERVICE[t];if(!c){throw new Error(`simctl has no privacy service for ${t}. Override it in the app instead (permission_action set).`)}const l=await findSimulator(e,r.udid);await run4("xcrun",["simctl","privacy",l,n,c,i]);return`simctl privacy ${n} ${c} for ${i} on ${l}.${n==="grant"?"":" iOS ends the app's process when a permission is revoked or reset; relaunch it."}`}const o=await findAdbSerial(r.serial);const s=t==="all"?Object.values(ANDROID_PERMISSIONS).flat():ANDROID_PERMISSIONS[t];if(!s)throw new Error(`No Android permission is known for ${t}.`);const a=[];for(const c of s){const l=`android.permission.${c}`;try{if(n==="grant")await run4("adb",["-s",o,"shell","pm","grant",i,l]);else{await run4("adb",["-s",o,"shell","pm","revoke",i,l]);if(n==="reset"){await run4("adb",["-s",o,"shell","pm","clear-permission-flags",i,l,"user-set","user-fixed"])}}a.push(c)}catch{}}if(a.length===0)throw new Error(`None of ${s.join(", ")} could be changed. Is it declared in the app's manifest?`);return`adb ${n} ${a.join(", ")} for ${i} on ${o}.${n==="grant"?"":" Android restarts the app's process when a permission is revoked."}`}function registerPermissionsTools(e,n){e.registerTool("get_permissions",{description:"Read the app's permissions as the Permissions tool (@buoy-gg/permissions) sees them: each permission the app can reach (location, camera, notifications, photos\u2026), what the OS says, any override, which libraries asked (Expo modules, PermissionsAndroid, react-native-permissions), the states this platform allows, and the recent permission calls with what each one returned. Check this before calling a permission screen, prompt or Settings flow a bug.",inputSchema:{logLimit:import_zod22.z.number().optional().describe("How many recent calls to list. Default 12."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(PERMISSIONS_TOOL_ID,"getState",{},r);return text(describe2(i,t.logLimit??12))}catch(r){return fail2(errMsg2(r))}});e.registerTool("permission_action",{description:"Override what the app sees when it asks for a permission, without changing the OS. set makes `permission` read as `state` (undetermined = not asked, granted, limited = approximate location / selected photos or contacts / provisional notifications, denied, blocked = Android 'don't ask again', restricted = iOS parental controls); iOS has no blocked (a refusal is final, so denied reads as blocked) and Android has no restricted. clear returns one permission to the OS answer, reset clears all. While overridden, the real system prompt never shows: a request from undetermined (or Android denied) is answered by `answer` (ask = Buoy shows a prompt on the device and waits for a tap; allow, limited or deny answer at once) and moves the state the way the OS would. Linking.openSettings and app-settings: open Buoy's stand-in for Settings. By default a change sends the app background \u2192 active, like a return from Settings, so screens that re-check on foreground update; permission hooks that read only on mount update on their next read. With enforce on (default), calls that need access (current position, launch camera, media library reads) fail with the native module's error while refused. request_real shows the real system prompt once so the OS grants what the override pretends. The override survives reload_app.",inputSchema:{action:import_zod22.z.enum(["set","clear","reset","answer","settings","request_real","return_from_settings","clear_log"]).describe("What to do."),permission:import_zod22.z.string().optional().describe(`set / clear / request_real (required): ${PERMISSION_IDS.join(", ")}, or android:<android.permission.NAME>.`),state:import_zod22.z.enum(["undetermined","granted","limited","denied","blocked","restricted"]).optional().describe("set (required): the state the app sees."),answer:import_zod22.z.enum(["ask","allow","limited","deny"]).optional().describe("answer (required): how a request from 'not asked' is answered while overridden."),notifyApp:import_zod22.z.boolean().optional().describe("settings: send background \u2192 active after each change. Default on."),interceptSettings:import_zod22.z.boolean().optional().describe("settings: stand in for Settings while overridden. Default on."),enforce:import_zod22.z.boolean().optional().describe("settings: fail calls that need a refused permission. Default on."),persist:import_zod22.z.boolean().optional().describe("settings: keep overrides across reloads. Default on."),showChip:import_zod22.z.boolean().optional().describe("settings: show the floating chip while overridden. Default on."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=(s,a={})=>n.callAction(PERMISSIONS_TOOL_ID,s,a,r);let o;switch(t.action){case"set":if(!t.permission||!t.state)return fail2("set requires `permission` and `state`.");o=await i("setOverride",{permission:t.permission,state:t.state});break;case"clear":if(!t.permission)return fail2("clear requires `permission`.");o=await i("clearOverride",{permission:t.permission});break;case"reset":o=await i("resetAll");break;case"answer":if(!t.answer)return fail2("answer requires `answer`: ask, allow, limited or deny.");o=await i("updateSettings",{requestAnswer:t.answer});break;case"settings":o=await i("updateSettings",{...t.notifyApp!==void 0?{notifyApp:t.notifyApp}:{},...t.interceptSettings!==void 0?{interceptSettings:t.interceptSettings}:{},...t.enforce!==void 0?{enforce:t.enforce}:{},...t.persist!==void 0?{persist:t.persist}:{},...t.showChip!==void 0?{showChip:t.showChip}:{}});break;case"request_real":if(!t.permission)return fail2("request_real requires `permission`.");o=await i("requestReal",{permission:t.permission});break;case"return_from_settings":o=await i("simulateReturnFromSettings");break;case"clear_log":o=await i("clearLog");break}return text(describe2(o))}catch(r){return fail2(errMsg2(r))}});e.registerTool("system_permission",{description:"Change the REAL OS permission for the connected app from this machine, for what an in-app override can't fake (native code that checks the OS itself, like reading a position or opening the camera). iOS Simulator uses `xcrun simctl privacy` (grant, revoke, reset; reset returns to 'not asked' so the real prompt shows again). There is no simctl service for notifications or tracking. Android uses `adb shell pm grant/revoke`; reset also clears 'don't ask again'. Revoking or resetting ends the app's process on both platforms, so relaunch it afterwards. Physical iPhones can't be changed this way.",inputSchema:{action:import_zod22.z.enum(["grant","revoke","reset"]).describe("grant, revoke, or reset to not asked."),permission:import_zod22.z.string().describe(`${PERMISSION_IDS.join(", ")}, or all.`),udid:import_zod22.z.string().optional().describe("iOS: the simulator udid, when its name is ambiguous."),serial:import_zod22.z.string().optional().describe("Android: the adb serial, when several devices are connected."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(PERMISSIONS_TOOL_ID,"getState",{},r);const o=await systemPermission(i,t.action,t.permission,{udid:t.udid,serial:t.serial});return text(o)}catch(r){return fail2(errMsg2(r))}})}var import_node_child_process20=require("child_process");var import_node_util16=require("util");var import_zod23=require("zod");var LIFECYCLE_TOOL_ID="lifecycle";var execFileAsync16=(0,import_node_util16.promisify)(import_node_child_process20.execFile);function listeners(e){if(e==null)return"can't count";return e===0?"none":String(e)}function describe3(e){const n=[];if(e.away){const r=Math.round((Date.now()-e.away.startedAt)/1e3);n.push(`**Simulated: ${e.away.kind==="background"?"in the background":"interrupted (inactive)"}** for ${r}s`+(e.away.returnAt?`, returns in ${Math.max(0,Math.round((e.away.returnAt-Date.now())/1e3))}s`:", until return")+`. Real OS state: ${e.realAppState}.`)}else{n.push(`App state: active (real OS state: ${e.realAppState}).`)}if(e.power){n.push(`Simulated battery: ${Math.round(e.power.level*100)}%, ${e.power.state}${e.power.lowPowerMode?", low power mode":""} (reached ${e.power.reached.join(", ")})`+(e.power.realGetters.length?`; still real: ${e.power.realGetters.join(", ")}`:""))}if(e.scheme)n.push(`Simulated color scheme: ${e.scheme.scheme} (${e.scheme.mode}).`);n.push(`App listeners: app state ${listeners(e.listeners.appState)}, memory warning ${listeners(e.listeners.memoryWarning)}, deep link ${listeners(e.listeners.deepLink)}`+(e.platform==="android"?`, window focus ${listeners(e.listeners.focus)}`:"")+(e.batteryLibraries.length?`, battery ${listeners(e.listeners.battery)} (${e.batteryLibraries.join(", ")})`:", battery: no battery library installed")+".");if(e.report){const r=e.report;n.push(`
745
747
  **Report: ${r.label}**${r.collectingUntil!=null?" (still collecting)":""}`);if(r.unavailable)n.push(r.unavailable);if(r.finding)n.push(`Finding: ${r.finding}`);if(r.note)n.push(`Note: ${r.note}`);const i=Object.entries(r.counts).map(([o,s])=>`${s} ${o}`).join(", ");if(!r.unavailable)n.push(`Counts: ${i||"nothing happened"}`);for(const o of r.events.slice(0,25)){n.push(`- +${(o.at/1e3).toFixed(1)}s ${o.whileAway?"[away] ":""}${o.source}: ${o.title}${o.subtitle?` (${o.subtitle})`:""}${o.status==="error"?" ERROR":""}`)}}if(e.relaunch){const r=e.relaunch;n.push(r.restored==null&&r.after==null?`
746
748
  Relaunch: checking where the app landed (was on ${r.before??"unknown"}).`:`
747
749
  Relaunch: ${r.restored?`restored ${r.after}`:`landed on ${r.after??"unknown"}, was on ${r.before??"unknown"}`}${r.tookMs!=null?` (${(r.tookMs/1e3).toFixed(1)}s)`:""}.`)}if(typeof e.handled==="boolean")n.push(`Back press handled by the app: ${e.handled}.`);if(e.log.length)n.push(`
@@ -749,7 +751,7 @@ Recent: ${e.log.slice(0,5).map(r=>r.text).join(" \xB7 ")}`);const t=e.recipes.fi
749
751
 
750
752
  ${describe3(w)}`:""}`)}const i=n.requireProDevice(t.deviceId);const o=(a,c={})=>n.callAction(LIFECYCLE_TOOL_ID,a,c,i);let s;switch(t.action){case"background":s=await o("background",{duration:t.duration,skipWait:t.skipWait});break;case"interrupt":s=await o("interrupt",{duration:t.duration,skipWait:t.skipWait});break;case"return":s=await o("returnToApp");break;case"memory_warning":s=await o("memoryWarning");break;case"open_url":if(!t.url)return fail2("open_url requires `url`.");s=await o("openUrl",{url:t.url});break;case"press_back":s=await o("pressBack");break;case"color_scheme":if(!t.scheme)return fail2("color_scheme requires `scheme`.");s=await o("setColorScheme",{scheme:t.scheme,mode:t.mode??"js"});break;case"battery":s=await o("setPower",{...t.level!==void 0?{level:t.level}:{},...t.lowPowerMode!==void 0?{lowPowerMode:t.lowPowerMode}:{},...t.state?{state:t.state}:{}});break;case"reset_battery":s=await o("resetPower");break;case"relaunch":s=await o("relaunch");return text(`Relaunching: the app's JS restarts now. Read get_lifecycle in a few seconds for where it landed.
751
753
 
752
- ${describe3(s)}`);case"recipe":if(!t.id)return fail2("recipe requires `id`; get_lifecycle lists them.");s=await o("runRecipe",{id:t.id});break;case"clear_report":s=await o("clearReport");break;case"reset":s=await o("reset");break;case"settings":s=await o("updateSettings",{...t.showChip!==void 0?{showChip:t.showChip}:{},...t.reportWindow!==void 0?{reportWindow:t.reportWindow}:{}});break;default:return fail2(`Unknown action ${t.action}.`)}return text(describe3(s))}catch(r){return fail2(errMsg2(r))}})}var import_node_child_process20=require("child_process");var import_node_util17=require("util");var import_zod24=require("zod");var execFileAsync17=(0,import_node_util17.promisify)(import_node_child_process20.execFile);var LOCATION_TOOL_ID="location";function meters(e){if(e==null||!Number.isFinite(e))return"?";return e<1e3?`${Math.round(e)} m`:`${(e/1e3).toFixed(e<1e4?1:0)} km`}function coord(e){return`${e.latitude.toFixed(5)}, ${e.longitude.toFixed(5)}`}function describe4(e){const n=e.override;const t=[];if(!e.active){t.push("**Location: real** (no override; the app gets the device's own location)")}else{const o=e.current.fix;const s=o?coord(o):`no fix (${e.current.reason})`;if(n.mode==="route"&&n.route&&e.progress){t.push(`**Location: route "${n.route.name??n.route.id??"custom"}"** ${n.playing?"moving":e.progress.finished?"arrived":"paused"} at ${(n.route.speed*3.6).toFixed(1)} km/h, ${meters(e.progress.along)} of ${meters(e.progress.length)}${n.route.loop?" (loops)":""} \u2192 ${s}`)}else if(n.mode==="fixed"){t.push(`**Location: pinned** ${n.place.label?`"${n.place.label}" `:""}\u2192 ${s}`)}else{t.push(`**Location: real position**, with overrides below`)}if(o){t.push(`Reported: \xB1${meters(o.accuracy)}${o.heading!=null?`, heading ${Math.round(o.heading)}\xB0`:""}${o.speed!=null?`, ${o.speed.toFixed(1)} m/s`:""}${n.jitter?`, drifting up to ${meters(n.jitter)}`:""}`)}if(!n.signal)t.push("GPS signal: OFF (updates stop, requests fail)");if(!n.services)t.push("Location services: OFF (the app is told they are disabled)")}if(e.permission){const o=e.permission;t.push(o.status==="granted"?`Permission: granted (${o.background?"always":"while in use"}, ${o.precision==="reduced"?"approximate":"precise"})`:`Permission: ${o.status.toUpperCase()} (the app's location requests fail)`)}if(e.current.precision==="reduced")t.push("Precise location is OFF in the permission: positions snap to ~3 km.");t.push(`Libraries overridden: ${e.libraries.length?e.libraries.join(", "):"none found in this app"}`);const r=e.watches.filter(o=>o.kind==="position");t.push(`Live watches: ${r.length?r.map(o=>`${o.library}#${o.id} (${o.updates} updates)`).join(", "):"none"}`);for(const o of e.tasks){if(o.kind==="geofencing"){t.push(`Geofencing task "${o.name}" (${o.intercepted?"simulated":"native"}, ${o.runs} runs):`);for(const s of o.regions){t.push(`- ${s.identifier}${s.label?` (${s.label})`:""}: ${s.state}, radius ${meters(s.radius)}${s.distance!=null?`, ${meters(s.distance)} from center`:""} (${coord(s)})`)}}else{t.push(`Background location task "${o.name}" (${o.intercepted?"simulated":"native"}, ${o.runs} runs)`)}}const i=e.log.slice(-10);if(i.length){t.push("Recent:");for(const o of i)t.push(`- [${o.kind}] ${o.text}${o.detail?` (${o.detail})`:""}`)}if(e.places.length)t.push(`App places: ${e.places.map(o=>o.label??coord(o)).join(", ")}`);if(e.routes.length)t.push(`App routes: ${e.routes.map(o=>o.id??o.name).join(", ")}`);t.push(`Presets: ${e.presets.map(o=>o.id).join(", ")}`);return t.join("\n")}async function bootedSimulators(){const{stdout:e}=await execFileAsync17("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const n=JSON.parse(e);return Object.values(n.devices).flat().filter(t=>t.state==="Booted").map(({udid:t,name:r})=>({udid:t,name:r}))}async function resolveSimulator(e){if(process.platform!=="darwin")throw new Error("sim_location needs macOS with Xcode's iOS Simulator.");const n=await bootedSimulators();if(e){if(!n.some(t=>t.udid===e))throw new Error(`Simulator ${e} is not booted.`);return e}if(n.length===1)return n[0].udid;if(n.length===0)throw new Error("No iOS Simulator is booted.");throw new Error(`${n.length} simulators are booted; pass \`udid\`: ${n.map(t=>`${t.name} (${t.udid})`).join(", ")}`)}function registerLocationTools(e,n){e.registerTool("get_location",{description:"Read where the app thinks it is, as the Location tool (@buoy-gg/location) sees it: real or overridden (pinned place, route with progress and speed), the position the app gets right now, GPS signal and location-services switches, which location libraries are overridden, the app's live location watches, its geofencing regions with inside/outside state and distance, background location tasks, and recent location events (requests, geofence enters and exits, errors). Check this before calling a distance, nearby list, geofence or location permission flow a bug.",inputSchema:{deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(LOCATION_TOOL_ID,"getState",{},r);return text(describe4(i))}catch(r){return fail2(errMsg2(r))}});e.registerTool("location_action",{description:"Override where the app thinks it is. set_location pins it to `latitude`+`longitude`, a `query` ('lat, lon' or a Google/Apple Maps link) or a `place` name from get_location. start_route moves it along `points` ([{latitude, longitude}, ...]), a `route` (a preset: walk, run, drive, highway, tunnel, loop; or an app route id), or in a straight line `to` a place, at `speed` m/s; heading and speed follow the route. pause_route / resume_route / seek_route (`meters` or `fraction`) / set_speed control it, and stop_route ends it and stays where it got to. enter_region / exit_region move just inside or outside a monitored geofence `identifier`, which runs the app's geofencing task. conditions sets the signal quality in one step: `conditions` good (\xB15 m), weak (\xB165 m, drifting up to 50 m), no-signal or off. signal (on=false) stops updates and fails requests; services (on=false) reports location services disabled. tune sets `accuracy` and `jitter` (drift) in meters. use_real returns to the real position but keeps signal/services switches; reset ends every override. Works for expo-location (including background tasks and geofencing), @react-native-community/geolocation and react-native-geolocation-service. Permission comes from the device or the Permissions tool: a denied permission still fails. Native maps' own blue dot follows the device's real location; use sim_location for that. The override survives reload_app.",inputSchema:{action:import_zod24.z.enum(["set_location","start_route","pause_route","resume_route","stop_route","seek_route","set_speed","enter_region","exit_region","conditions","signal","services","tune","use_real","reset","settings","clear_log"]).describe("What to do."),latitude:import_zod24.z.number().optional().describe("set_location: latitude, -90 to 90."),longitude:import_zod24.z.number().optional().describe("set_location: longitude, -180 to 180."),label:import_zod24.z.string().optional().describe("set_location: a name to show for the place."),query:import_zod24.z.string().optional().describe("set_location: 'lat, lon' text or a Google/Apple Maps link."),place:import_zod24.z.string().optional().describe("set_location: a place name from get_location (app places and built-ins)."),points:import_zod24.z.array(import_zod24.z.object({latitude:import_zod24.z.number(),longitude:import_zod24.z.number()})).optional().describe("start_route: two or more points to travel through."),route:import_zod24.z.string().optional().describe("start_route: a preset id (walk, run, drive, highway, tunnel, loop) or an app route id."),to:import_zod24.z.string().optional().describe("start_route: travel in a straight line to this place name or 'lat, lon'."),speed:import_zod24.z.number().optional().describe("start_route / set_speed: meters per second (1.4 walk, 13.4 city, 30 highway)."),heading:import_zod24.z.number().optional().describe("start_route with a preset: direction to head, degrees from north. tune: heading reported while pinned."),loop:import_zod24.z.boolean().optional().describe("start_route with points: start over after the last point."),meters:import_zod24.z.number().optional().describe("seek_route: meters from the route's start."),fraction:import_zod24.z.number().optional().describe("seek_route: 0 to 1 along the route."),identifier:import_zod24.z.string().optional().describe("enter_region / exit_region (required): the region's identifier from get_location."),task:import_zod24.z.string().optional().describe("enter_region / exit_region: the geofencing task name, when two tasks share an identifier."),conditions:import_zod24.z.enum(["good","weak","no-signal","off"]).optional().describe("conditions (required): good, weak, no-signal or off."),on:import_zod24.z.boolean().optional().describe("signal / services (required): true = working, false = off."),accuracy:import_zod24.z.number().optional().describe("tune: reported accuracy radius in meters."),jitter:import_zod24.z.number().optional().describe("tune: GPS drift in meters (0 = none)."),interval:import_zod24.z.number().optional().describe("tune: ms between updates to live watches (default 1000)."),persist:import_zod24.z.boolean().optional().describe("settings: keep the override across reloads."),showChip:import_zod24.z.boolean().optional().describe("settings: show the floating location chip while overridden."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=(a,c={})=>n.callAction(LOCATION_TOOL_ID,a,c,r);const o=(...a)=>{const c={};for(const l of a)if(t[l]!==void 0)c[l]=t[l];return c};let s;switch(t.action){case"set_location":s=await i("setLocation",o("latitude","longitude","label","query","place"));break;case"start_route":s=await i("startRoute",o("points","route","to","speed","heading","loop"));break;case"pause_route":s=await i("pauseRoute");break;case"resume_route":s=await i("resumeRoute");break;case"stop_route":s=await i("stopRoute");break;case"seek_route":s=await i("seekRoute",o("meters","fraction"));break;case"set_speed":if(t.speed===void 0)return fail2("set_speed requires `speed` in m/s.");s=await i("setSpeed",{speed:t.speed});break;case"enter_region":case"exit_region":if(!t.identifier)return fail2(`${t.action} requires \`identifier\`; get_location lists the regions.`);s=await i(t.action==="enter_region"?"enterRegion":"exitRegion",o("identifier","task"));break;case"conditions":if(!t.conditions)return fail2("conditions requires `conditions`: good, weak, no-signal or off.");s=await i("setConditions",{conditions:t.conditions});break;case"signal":if(t.on===void 0)return fail2("signal requires `on`.");s=await i("setSignal",{on:t.on});break;case"services":if(t.on===void 0)return fail2("services requires `on`.");s=await i("setServices",{on:t.on});break;case"tune":s=await i("tune",o("accuracy","jitter","heading","interval"));break;case"use_real":s=await i("useRealLocation");break;case"reset":s=await i("reset");break;case"settings":s=await i("updateSettings",o("persist","showChip"));break;case"clear_log":s=await i("clearLog");break}return text(describe4(s))}catch(r){return fail2(errMsg2(r))}});e.registerTool("sim_location",{description:"Set the iOS Simulator's own location with `xcrun simctl location` (runs on this Mac, not in the app). Unlike location_action, this reaches native code: map views' blue dot (react-native-maps, expo-maps, Mapbox), native geofence monitoring, other SDKs. set pins `latitude`+`longitude`; route moves through `points` at `speed` m/s (updates every `interval` s); clear stops it. Needs no Buoy in the app. The in-app Location tool, when on, still decides what the app's JS location calls return. Pass `udid` when more than one simulator is booted.",inputSchema:{action:import_zod24.z.enum(["set","route","clear"]).describe("What to do."),latitude:import_zod24.z.number().optional().describe("set: latitude."),longitude:import_zod24.z.number().optional().describe("set: longitude."),points:import_zod24.z.array(import_zod24.z.object({latitude:import_zod24.z.number(),longitude:import_zod24.z.number()})).optional().describe("route: two or more waypoints."),speed:import_zod24.z.number().optional().describe("route: meters per second. Default 20."),interval:import_zod24.z.number().optional().describe("route: seconds between updates. Default 1."),udid:import_zod24.z.string().optional().describe("The simulator's UDID. Required when several are booted.")}},async t=>{try{const r=await resolveSimulator(t.udid);const i=(...o)=>execFileAsync17("xcrun",["simctl","location",r,...o],{timeout:15e3});switch(t.action){case"set":if(t.latitude===void 0||t.longitude===void 0)return fail2("set requires `latitude` and `longitude`.");await i("set",`${t.latitude},${t.longitude}`);return text(`Simulator ${r} location set to ${t.latitude}, ${t.longitude}.`);case"route":{const o=t.points??[];if(o.length<2)return fail2("route requires two or more `points`.");const s=[`--speed=${t.speed??20}`,`--interval=${t.interval??1}`];await i("start",...s,...o.map(a=>`${a.latitude},${a.longitude}`));return text(`Simulator ${r} is moving through ${o.length} points at ${t.speed??20} m/s.`)}case"clear":await i("clear");return text(`Simulator ${r} location cleared.`)}}catch(r){return fail2(errMsg2(r))}})}var import_zod25=require("zod");var SCENARIOS_TOOL_ID="scenarios";var text6=e=>({content:[{type:"text",text:e}]});var fail8=e=>({isError:true,content:[{type:"text",text:e}]});var errMsg7=e=>e instanceof Error?e.message:String(e);function varSpec(e){const n=e.options?.length?` one of ${e.options.join("|")}`:"";const t=e.default!==void 0?` (default ${String(e.default)})`:"";return`${e.key}: ${e.type}${n}${t}`}function summarize2(e){const n=e.vars?.length?`
754
+ ${describe3(s)}`);case"recipe":if(!t.id)return fail2("recipe requires `id`; get_lifecycle lists them.");s=await o("runRecipe",{id:t.id});break;case"clear_report":s=await o("clearReport");break;case"reset":s=await o("reset");break;case"settings":s=await o("updateSettings",{...t.showChip!==void 0?{showChip:t.showChip}:{},...t.reportWindow!==void 0?{reportWindow:t.reportWindow}:{}});break;default:return fail2(`Unknown action ${t.action}.`)}return text(describe3(s))}catch(r){return fail2(errMsg2(r))}})}var import_node_child_process21=require("child_process");var import_node_util17=require("util");var import_zod24=require("zod");var execFileAsync17=(0,import_node_util17.promisify)(import_node_child_process21.execFile);var LOCATION_TOOL_ID="location";function meters(e){if(e==null||!Number.isFinite(e))return"?";return e<1e3?`${Math.round(e)} m`:`${(e/1e3).toFixed(e<1e4?1:0)} km`}function coord(e){return`${e.latitude.toFixed(5)}, ${e.longitude.toFixed(5)}`}function describe4(e){const n=e.override;const t=[];if(!e.active){t.push("**Location: real** (no override; the app gets the device's own location)")}else{const o=e.current.fix;const s=o?coord(o):`no fix (${e.current.reason})`;if(n.mode==="route"&&n.route&&e.progress){t.push(`**Location: route "${n.route.name??n.route.id??"custom"}"** ${n.playing?"moving":e.progress.finished?"arrived":"paused"} at ${(n.route.speed*3.6).toFixed(1)} km/h, ${meters(e.progress.along)} of ${meters(e.progress.length)}${n.route.loop?" (loops)":""} \u2192 ${s}`)}else if(n.mode==="fixed"){t.push(`**Location: pinned** ${n.place.label?`"${n.place.label}" `:""}\u2192 ${s}`)}else{t.push(`**Location: real position**, with overrides below`)}if(o){t.push(`Reported: \xB1${meters(o.accuracy)}${o.heading!=null?`, heading ${Math.round(o.heading)}\xB0`:""}${o.speed!=null?`, ${o.speed.toFixed(1)} m/s`:""}${n.jitter?`, drifting up to ${meters(n.jitter)}`:""}`)}if(!n.signal)t.push("GPS signal: OFF (updates stop, requests fail)");if(!n.services)t.push("Location services: OFF (the app is told they are disabled)")}if(e.permission){const o=e.permission;t.push(o.status==="granted"?`Permission: granted (${o.background?"always":"while in use"}, ${o.precision==="reduced"?"approximate":"precise"})`:`Permission: ${o.status.toUpperCase()} (the app's location requests fail)`)}if(e.current.precision==="reduced")t.push("Precise location is OFF in the permission: positions snap to ~3 km.");t.push(`Libraries overridden: ${e.libraries.length?e.libraries.join(", "):"none found in this app"}`);const r=e.watches.filter(o=>o.kind==="position");t.push(`Live watches: ${r.length?r.map(o=>`${o.library}#${o.id} (${o.updates} updates)`).join(", "):"none"}`);for(const o of e.tasks){if(o.kind==="geofencing"){t.push(`Geofencing task "${o.name}" (${o.intercepted?"simulated":"native"}, ${o.runs} runs):`);for(const s of o.regions){t.push(`- ${s.identifier}${s.label?` (${s.label})`:""}: ${s.state}, radius ${meters(s.radius)}${s.distance!=null?`, ${meters(s.distance)} from center`:""} (${coord(s)})`)}}else{t.push(`Background location task "${o.name}" (${o.intercepted?"simulated":"native"}, ${o.runs} runs)`)}}const i=e.log.slice(-10);if(i.length){t.push("Recent:");for(const o of i)t.push(`- [${o.kind}] ${o.text}${o.detail?` (${o.detail})`:""}`)}if(e.places.length)t.push(`App places: ${e.places.map(o=>o.label??coord(o)).join(", ")}`);if(e.routes.length)t.push(`App routes: ${e.routes.map(o=>o.id??o.name).join(", ")}`);t.push(`Presets: ${e.presets.map(o=>o.id).join(", ")}`);return t.join("\n")}async function bootedSimulators(){const{stdout:e}=await execFileAsync17("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const n=JSON.parse(e);return Object.values(n.devices).flat().filter(t=>t.state==="Booted").map(({udid:t,name:r})=>({udid:t,name:r}))}async function resolveSimulator(e){if(process.platform!=="darwin")throw new Error("sim_location needs macOS with Xcode's iOS Simulator.");const n=await bootedSimulators();if(e){if(!n.some(t=>t.udid===e))throw new Error(`Simulator ${e} is not booted.`);return e}if(n.length===1)return n[0].udid;if(n.length===0)throw new Error("No iOS Simulator is booted.");throw new Error(`${n.length} simulators are booted; pass \`udid\`: ${n.map(t=>`${t.name} (${t.udid})`).join(", ")}`)}function registerLocationTools(e,n){e.registerTool("get_location",{description:"Read where the app thinks it is, as the Location tool (@buoy-gg/location) sees it: real or overridden (pinned place, route with progress and speed), the position the app gets right now, GPS signal and location-services switches, which location libraries are overridden, the app's live location watches, its geofencing regions with inside/outside state and distance, background location tasks, and recent location events (requests, geofence enters and exits, errors). Check this before calling a distance, nearby list, geofence or location permission flow a bug.",inputSchema:{deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(LOCATION_TOOL_ID,"getState",{},r);return text(describe4(i))}catch(r){return fail2(errMsg2(r))}});e.registerTool("location_action",{description:"Override where the app thinks it is. set_location pins it to `latitude`+`longitude`, a `query` ('lat, lon' or a Google/Apple Maps link) or a `place` name from get_location. start_route moves it along `points` ([{latitude, longitude}, ...]), a `route` (a preset: walk, run, drive, highway, tunnel, loop; or an app route id), or in a straight line `to` a place, at `speed` m/s; heading and speed follow the route. pause_route / resume_route / seek_route (`meters` or `fraction`) / set_speed control it, and stop_route ends it and stays where it got to. enter_region / exit_region move just inside or outside a monitored geofence `identifier`, which runs the app's geofencing task. conditions sets the signal quality in one step: `conditions` good (\xB15 m), weak (\xB165 m, drifting up to 50 m), no-signal or off. signal (on=false) stops updates and fails requests; services (on=false) reports location services disabled. tune sets `accuracy` and `jitter` (drift) in meters. use_real returns to the real position but keeps signal/services switches; reset ends every override. Works for expo-location (including background tasks and geofencing), @react-native-community/geolocation and react-native-geolocation-service. Permission comes from the device or the Permissions tool: a denied permission still fails. Native maps' own blue dot follows the device's real location; use sim_location for that. The override survives reload_app.",inputSchema:{action:import_zod24.z.enum(["set_location","start_route","pause_route","resume_route","stop_route","seek_route","set_speed","enter_region","exit_region","conditions","signal","services","tune","use_real","reset","settings","clear_log"]).describe("What to do."),latitude:import_zod24.z.number().optional().describe("set_location: latitude, -90 to 90."),longitude:import_zod24.z.number().optional().describe("set_location: longitude, -180 to 180."),label:import_zod24.z.string().optional().describe("set_location: a name to show for the place."),query:import_zod24.z.string().optional().describe("set_location: 'lat, lon' text or a Google/Apple Maps link."),place:import_zod24.z.string().optional().describe("set_location: a place name from get_location (app places and built-ins)."),points:import_zod24.z.array(import_zod24.z.object({latitude:import_zod24.z.number(),longitude:import_zod24.z.number()})).optional().describe("start_route: two or more points to travel through."),route:import_zod24.z.string().optional().describe("start_route: a preset id (walk, run, drive, highway, tunnel, loop) or an app route id."),to:import_zod24.z.string().optional().describe("start_route: travel in a straight line to this place name or 'lat, lon'."),speed:import_zod24.z.number().optional().describe("start_route / set_speed: meters per second (1.4 walk, 13.4 city, 30 highway)."),heading:import_zod24.z.number().optional().describe("start_route with a preset: direction to head, degrees from north. tune: heading reported while pinned."),loop:import_zod24.z.boolean().optional().describe("start_route with points: start over after the last point."),meters:import_zod24.z.number().optional().describe("seek_route: meters from the route's start."),fraction:import_zod24.z.number().optional().describe("seek_route: 0 to 1 along the route."),identifier:import_zod24.z.string().optional().describe("enter_region / exit_region (required): the region's identifier from get_location."),task:import_zod24.z.string().optional().describe("enter_region / exit_region: the geofencing task name, when two tasks share an identifier."),conditions:import_zod24.z.enum(["good","weak","no-signal","off"]).optional().describe("conditions (required): good, weak, no-signal or off."),on:import_zod24.z.boolean().optional().describe("signal / services (required): true = working, false = off."),accuracy:import_zod24.z.number().optional().describe("tune: reported accuracy radius in meters."),jitter:import_zod24.z.number().optional().describe("tune: GPS drift in meters (0 = none)."),interval:import_zod24.z.number().optional().describe("tune: ms between updates to live watches (default 1000)."),persist:import_zod24.z.boolean().optional().describe("settings: keep the override across reloads."),showChip:import_zod24.z.boolean().optional().describe("settings: show the floating location chip while overridden."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=(a,c={})=>n.callAction(LOCATION_TOOL_ID,a,c,r);const o=(...a)=>{const c={};for(const l of a)if(t[l]!==void 0)c[l]=t[l];return c};let s;switch(t.action){case"set_location":s=await i("setLocation",o("latitude","longitude","label","query","place"));break;case"start_route":s=await i("startRoute",o("points","route","to","speed","heading","loop"));break;case"pause_route":s=await i("pauseRoute");break;case"resume_route":s=await i("resumeRoute");break;case"stop_route":s=await i("stopRoute");break;case"seek_route":s=await i("seekRoute",o("meters","fraction"));break;case"set_speed":if(t.speed===void 0)return fail2("set_speed requires `speed` in m/s.");s=await i("setSpeed",{speed:t.speed});break;case"enter_region":case"exit_region":if(!t.identifier)return fail2(`${t.action} requires \`identifier\`; get_location lists the regions.`);s=await i(t.action==="enter_region"?"enterRegion":"exitRegion",o("identifier","task"));break;case"conditions":if(!t.conditions)return fail2("conditions requires `conditions`: good, weak, no-signal or off.");s=await i("setConditions",{conditions:t.conditions});break;case"signal":if(t.on===void 0)return fail2("signal requires `on`.");s=await i("setSignal",{on:t.on});break;case"services":if(t.on===void 0)return fail2("services requires `on`.");s=await i("setServices",{on:t.on});break;case"tune":s=await i("tune",o("accuracy","jitter","heading","interval"));break;case"use_real":s=await i("useRealLocation");break;case"reset":s=await i("reset");break;case"settings":s=await i("updateSettings",o("persist","showChip"));break;case"clear_log":s=await i("clearLog");break}return text(describe4(s))}catch(r){return fail2(errMsg2(r))}});e.registerTool("sim_location",{description:"Set the iOS Simulator's own location with `xcrun simctl location` (runs on this Mac, not in the app). Unlike location_action, this reaches native code: map views' blue dot (react-native-maps, expo-maps, Mapbox), native geofence monitoring, other SDKs. set pins `latitude`+`longitude`; route moves through `points` at `speed` m/s (updates every `interval` s); clear stops it. Needs no Buoy in the app. The in-app Location tool, when on, still decides what the app's JS location calls return. Pass `udid` when more than one simulator is booted.",inputSchema:{action:import_zod24.z.enum(["set","route","clear"]).describe("What to do."),latitude:import_zod24.z.number().optional().describe("set: latitude."),longitude:import_zod24.z.number().optional().describe("set: longitude."),points:import_zod24.z.array(import_zod24.z.object({latitude:import_zod24.z.number(),longitude:import_zod24.z.number()})).optional().describe("route: two or more waypoints."),speed:import_zod24.z.number().optional().describe("route: meters per second. Default 20."),interval:import_zod24.z.number().optional().describe("route: seconds between updates. Default 1."),udid:import_zod24.z.string().optional().describe("The simulator's UDID. Required when several are booted.")}},async t=>{try{const r=await resolveSimulator(t.udid);const i=(...o)=>execFileAsync17("xcrun",["simctl","location",r,...o],{timeout:15e3});switch(t.action){case"set":if(t.latitude===void 0||t.longitude===void 0)return fail2("set requires `latitude` and `longitude`.");await i("set",`${t.latitude},${t.longitude}`);return text(`Simulator ${r} location set to ${t.latitude}, ${t.longitude}.`);case"route":{const o=t.points??[];if(o.length<2)return fail2("route requires two or more `points`.");const s=[`--speed=${t.speed??20}`,`--interval=${t.interval??1}`];await i("start",...s,...o.map(a=>`${a.latitude},${a.longitude}`));return text(`Simulator ${r} is moving through ${o.length} points at ${t.speed??20} m/s.`)}case"clear":await i("clear");return text(`Simulator ${r} location cleared.`)}}catch(r){return fail2(errMsg2(r))}})}var import_zod25=require("zod");var SCENARIOS_TOOL_ID="scenarios";var text6=e=>({content:[{type:"text",text:e}]});var fail8=e=>({isError:true,content:[{type:"text",text:e}]});var errMsg7=e=>e instanceof Error?e.message:String(e);function varSpec(e){const n=e.options?.length?` one of ${e.options.join("|")}`:"";const t=e.default!==void 0?` (default ${String(e.default)})`:"";return`${e.key}: ${e.type}${n}${t}`}function summarize2(e){const n=e.vars?.length?`
753
755
  variables: ${e.vars.map(varSpec).join("; ")}`:"";const t=e.stepLines?.length?`
754
756
  ${e.stepLines.map(o=>` \xB7 ${o.label} [${o.durability}]`).join("\n")}`:"";const r=[`v${e.version}`,e.author,e.usage?.runs?`${e.usage.runs} run(s)`:null,e.authoredAgainst?`authored against ${e.authoredAgainst}`:null,e.unsavedToRepo?"unsaved to repo":null].filter(Boolean).join(" \xB7 ");const i=e.expectedOutcome?`
755
757
  expected: ${e.expectedOutcome}`:"";return`- \`${e.id}\` **${e.name}** \u2014 ${r}${n}${i}${t}`}function renderSection(e,n,t){if(!n.length)return`**${e} (0):**
@@ -780,7 +782,7 @@ ${(o.errors??[o.error??"unknown error"]).map(s=>` \xB7 ${s}`).join("\n")}`)}ret
780
782
 
781
783
  It is INERT and cannot run yet. Ask the user to open Scenarios on the device, review what it will do, and tap **Accept to library** \u2014 a scenario never becomes runnable on someone's device without them seeing it first.`)}case"setFolder":{if(!t.id)return fail8("setFolder requires `id` (from get_scenarios).");const o=await i("setFolder",{id:t.id,folder:t.folder});return text6(o.folder?`Filed \`${o.id}\` under **${o.folder}**.`:`Removed \`${o.id}\` from its folder \u2014 it now shows under Ungrouped.`)}case"delete":{if(!t.id)return fail8("delete requires `id`.");await i("delete",{id:t.id});return text6(`Deleted \`${t.id}\` from the device library.`)}}}catch(r){return fail8(errMsg7(r))}})}var import_zod26=require("zod");var text7=e=>({content:[{type:"text",text:e}]});var gate2=e=>entitlementHasPro()?null:fail9(proRequired(e));var fail9=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_zod26.z.enum(["barcode","image","video","camera","screen","pattern"]).describe("What the camera should show."),value:import_zod26.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_zod26.z.enum(["qr","pdf417","aztec","code128"]).optional().describe("Barcode symbology; defaults to qr.")}},async n=>{const t=gate2("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 run2(r);if(!i.ok){return fail9(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 text7(`The simulator camera is now showing ${o}, at ${i.data?.fps??0} fps.
782
784
 
783
- _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=gate2("camera_status");if(n)return n;const t=await run2(["status"]);if(!t.ok||!t.data){return fail9(t.error??"could not read the simulator camera status")}const{publishing:r,fps:i,codes:o}=t.data;if(!r){return text7("The simulator camera is not publishing anything.\n\n_Set a source with `camera_source` first._")}return text7([`Publishing at ${i} fps.`,o.length?`Currently decoding: ${o.map(s=>`\`${s}\``).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_zod26.z.string().describe("The app's bundle identifier."),udid:import_zod26.z.string().optional().describe("Simulator udid, if more than one is booted.")}},async n=>{const t=gate2("camera_launch");if(t)return t;const r=["launch",n.bundleId];if(n.udid)r.push("--udid",n.udid);const i=await run2(r);if(!i.ok){return fail9(i.error??i.data?.error??"could not launch the app")}return text7(`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_zod26.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 run2(t);if(!r.data?.checks){return fail9(r.error??"could not run the simulator camera diagnosis")}const i=readEntitlement();const o=entitlementHasPro(i)?"":"\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 text7(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=gate2("camera_stop");if(n)return n;const t=await run2(["stop"]);if(!t.ok){return fail9(t.error??t.data?.error??"could not stop the camera")}return text7("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_zod26.z.string().optional().describe("Which simulator's apps to list. Only needed when several are booted.")}},async n=>{const t=gate2("camera_devices");if(t)return t;const r=await run2(["devices"]);if(!r.ok||!r.data){return fail9(r.error??"could not list booted simulators")}const i=r.data.devices??[];let o=null;if(i.length===1||n.udid){const s=await run2(["apps",...n.udid?["--udid",n.udid]:[]]);o=s.ok?s.data?.apps??[]:null}return text7(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=gate2("camera_inputs");if(n)return n;const[t,r]=await Promise.all([run2(["cameras"]),run2(["windows"])]);if(!t.ok&&!r.ok){return fail9(t.error??r.error??"could not list the Mac's cameras or windows")}return text7(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_zod26.z.enum(["on","off","status"]).describe("Turn it on, off, or report the current state."),udid:import_zod26.z.string().optional().describe("Which simulator. Only needed when several are booted.")}},async n=>{const t=gate2("camera_zero_setup");if(t)return t;const r=await run2(["zero-setup",n.action,...n.udid?["--udid",n.udid]:[]]);if(!r.ok){return fail9(r.error??r.data?.error??"could not change zero-setup mode")}const i=r.data??{};if(n.action==="status"){if(!i.enabled)return text7("Zero-setup mode is **off**.");return text7(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 text7("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 text7("Zero-setup mode is **off**.")})}var import_zod27=require("zod");var import_node_module=require("module");var import_node_child_process21=require("child_process");var import_node_path26=require("path");var import_node_fs25=require("fs");var import_node_os18=require("os");var import_node_url=require("url");var START_PROBE_JS=`(() => {
785
+ _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=gate2("camera_status");if(n)return n;const t=await run2(["status"]);if(!t.ok||!t.data){return fail9(t.error??"could not read the simulator camera status")}const{publishing:r,fps:i,codes:o}=t.data;if(!r){return text7("The simulator camera is not publishing anything.\n\n_Set a source with `camera_source` first._")}return text7([`Publishing at ${i} fps.`,o.length?`Currently decoding: ${o.map(s=>`\`${s}\``).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_zod26.z.string().describe("The app's bundle identifier."),udid:import_zod26.z.string().optional().describe("Simulator udid, if more than one is booted.")}},async n=>{const t=gate2("camera_launch");if(t)return t;const r=["launch",n.bundleId];if(n.udid)r.push("--udid",n.udid);const i=await run2(r);if(!i.ok){return fail9(i.error??i.data?.error??"could not launch the app")}return text7(`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_zod26.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 run2(t);if(!r.data?.checks){return fail9(r.error??"could not run the simulator camera diagnosis")}const i=readEntitlement();const o=entitlementHasPro(i)?"":"\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 text7(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=gate2("camera_stop");if(n)return n;const t=await run2(["stop"]);if(!t.ok){return fail9(t.error??t.data?.error??"could not stop the camera")}return text7("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_zod26.z.string().optional().describe("Which simulator's apps to list. Only needed when several are booted.")}},async n=>{const t=gate2("camera_devices");if(t)return t;const r=await run2(["devices"]);if(!r.ok||!r.data){return fail9(r.error??"could not list booted simulators")}const i=r.data.devices??[];let o=null;if(i.length===1||n.udid){const s=await run2(["apps",...n.udid?["--udid",n.udid]:[]]);o=s.ok?s.data?.apps??[]:null}return text7(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=gate2("camera_inputs");if(n)return n;const[t,r]=await Promise.all([run2(["cameras"]),run2(["windows"])]);if(!t.ok&&!r.ok){return fail9(t.error??r.error??"could not list the Mac's cameras or windows")}return text7(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_zod26.z.enum(["on","off","status"]).describe("Turn it on, off, or report the current state."),udid:import_zod26.z.string().optional().describe("Which simulator. Only needed when several are booted.")}},async n=>{const t=gate2("camera_zero_setup");if(t)return t;const r=await run2(["zero-setup",n.action,...n.udid?["--udid",n.udid]:[]]);if(!r.ok){return fail9(r.error??r.data?.error??"could not change zero-setup mode")}const i=r.data??{};if(n.action==="status"){if(!i.enabled)return text7("Zero-setup mode is **off**.");return text7(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 text7("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 text7("Zero-setup mode is **off**.")})}var import_zod27=require("zod");var import_node_module=require("module");var import_node_child_process22=require("child_process");var import_node_path30=require("path");var import_node_fs28=require("fs");var import_node_os21=require("os");var import_node_url=require("url");var START_PROBE_JS=`(() => {
784
786
  const supported = (t) => {
785
787
  try { return (PerformanceObserver.supportedEntryTypes || []).includes(t); } catch { return false; }
786
788
  };
@@ -924,8 +926,8 @@ _Apps already running do not pick up a camera they started without \u2014 use \`
924
926
  const ext = gl.getExtension("WEBGL_debug_renderer_info");
925
927
  return String(gl.getParameter(ext ? ext.UNMASKED_RENDERER_WEBGL : gl.RENDERER));
926
928
  } catch { return null; }
927
- })()`;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 s=Math.floor(r()*(o+1));[i[o],i[s]]=[i[s],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,s]of Object.entries(n.params??{}))r.searchParams.set(o,s);return r.toString()}var FRAME_STATES=["STATE_PRESENTED_ALL","STATE_PRESENTED_PARTIAL","STATE_DROPPED"];function summarizeFrameTrace(e){const n=p=>e.find(f=>f.name===p&&f.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 s=new Map;for(const p of e){if(p.name!=="PipelineReporter"||p.ph!=="b")continue;if(i!=null&&p.pid!==i)continue;if(p.ts==null||p.ts<t.ts||p.ts>r.ts)continue;const f=p.args?.frame_reporter;if(!f||f.frame_sequence==null)continue;const g=f.state;if(!FRAME_STATES.includes(g))continue;const v=`${f.layer_tree_host_id??""}:${f.frame_source??""}:${f.frame_sequence}`;const m=Boolean(f.affects_smoothness)&&g!=="STATE_PRESENTED_ALL";const w=s.get(v);if(!w)s.set(v,{state:g,fault:m});else{if(o[g]>o[w.state])w.state=g;w.fault=w.fault||m}}let a=0;let c=0;let l=0;let u=0;for(const p of s.values()){if(p.state==="STATE_PRESENTED_ALL")a++;else if(p.state==="STATE_PRESENTED_PARTIAL")c++;else l++;if(p.fault)u++}const d=a+c+l;if(d===0)return null;const h=(r.ts-t.ts)/1e6;return{full:a,partial:c,dropped:l,faults:u,shownFps:r1((a+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(a=>a.toLowerCase()));if(n.key!==r)return false;const o=r.toLowerCase();const s={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)!==s.ctrl||Boolean(n.alt)!==s.alt||Boolean(n.meta)!==s.meta)return false;if(!s.shift&&n.shift&&r.length!==1)return false;if(s.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(s=>s.interactionId===t.interactionId&&Math.abs(s.startTime+s.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 s=1e3/n;const a=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 p=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)p++;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 k of E.scripts){A+=k.forced;const S=I.get(k.name)??{ms:0,count:0};S.ms+=k.duration;S.count++;I.set(k.name,S)}}l=r1($);u=r1(x);d=r1(A);h=[...I.entries()].map(([E,k])=>({name:E,ms:r1(k.ms),count:k.count})).sort((E,k)=>k.ms-E.ms).slice(0,5)}let f=null;if(e.shifts){let $=0;for(const x of e.shifts)if(!x.hadRecentInput&&x.startTime>=t&&x.startTime<=r)$+=x.value;f=Math.round($*1e3)/1e3}let g=null;let v=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(!v||x.duration>v.duration)v=x}const m=v;const w=e.frames;const b=[...(e.clicks??[]).map($=>$.t),...(e.keys??[]).map($=>$.t)];const y=b.length?Math.max(...b):null;const _=y==null||w.filter($=>$>y).length>=2;const T=w.length===0?i:Math.max(0,w[0]-t,r-w[w.length-1]);return{edgeSilenceMs:r1(T),frameGapCount:o.length,inputCaptureComplete:_,resized:Boolean(e.resized),interactions:g,worstInteractionMs:m?r1(m.duration):null,worstInputDelayMs:m?r1(Math.max(0,m.processingStart-m.startTime)):null,worstProcessingMs:m?r1(Math.max(0,m.processingEnd-m.processingStart)):null,worstPresentationMs:m?r1(Math.max(0,m.startTime+m.duration-m.processingEnd)):null,fps:r1(e.frames.length/i*1e3),frameGapP95Ms:a==null?null:r1(a),frameGapMaxMs:o.length?r1(Math.max(...o)):null,longFrames:o.filter($=>$>s*1.5).length,longTaskPct:c,loafBlockingMs:l,styleLayoutMs:u,forcedLayoutMs:d,topScripts:h,loafCutOff:p,layoutShift:f,domNodesStart:e.domStart,domNodesEnd:e.domEnd}}function cdpDeltas(e,n,t){const r=a=>a in e&&a in n?n[a]-e[a]:null;const i=a=>{const c=r(a);return c==null?null:r1(c*1e3)};const o=i("TaskDuration");const s=i("Timestamp")??t;return{mainThreadPct:o==null?null:r1(o/Math.max(1,s)*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 s=o?[...t].sort((c,l)=>c.droppedPct-l.droppedPct):r;const a=s.length?s[Math.floor((s.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:a,fpsMin:r.length?r[0].fps:null,fpsMax:r.length?r[r.length-1].fps:null,flags:a?webBenchFlags(o?a:{...a,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_path26.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}
928
- (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_process21.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_process21.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 s of e.cases){if(!s.name?.trim())throw new Error("Every case needs a name.");if(n.has(s.name))throw new Error(`Two cases are named "${s.name}". Give each case its own name.`);n.add(s.name)}const t=(s,a,c,l)=>{if(s==null)return;if(!Number.isInteger(s)||s<c||s>l)throw new Error(`${a} must be a whole number from ${c} to ${l}.`)};const r=(s,a,c)=>{if(s==null)return;if(!Number.isFinite(s)||s<c)throw new Error(`${a} must be a number of at least ${c}.`)};const i=(s,a,c,l)=>{if(s==null)return;if(!Number.isFinite(s)||s<c||s>l)throw new Error(`${a} 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 s of o)i(s,"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[s,a]of Object.entries(e.budgets??{}))i(a,`budgets.${s}`,0,1e9);for(const s of e.steps??[]){if("wait"in s)i(s.wait,"a wait step",0,6e4);if("scroll"in s)i(s.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 s=o?await o.boundingBox():null;if(!s)throw new Error(`step target ${i} isn't on the page (or isn't visible)`);t.set(i,{x:s.x+s.width/2,y:s.y+s.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 s=0;let a=-Infinity;const c=u=>{while(o<r.length){const d=r[o++];if(d.t>=a&&d.hit.includes(u)){a=d.t;return true}}return false};const l=u=>{while(s<i.length){const d=i[s++];if(d.t>=a&&keyMatches(u,d)){a=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 s=o.x+o.width/2;const a=o.y+o.height/2;if(Math.abs(s-r.x)>4||Math.abs(a-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 s=o?.message??String(o);const a=/Another web benchmark|already running/.test(s);if(!a||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_path26.join)((0,import_node_os18.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_fs25.writeFileSync)(o,n);(0,import_node_fs25.linkSync)(o,LOCK_FILE);return true}catch{return false}finally{try{(0,import_node_fs25.unlinkSync)(o)}catch{}}};const r=()=>{try{return JSON.parse((0,import_node_fs25.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 s=`${LOCK_FILE}.cleanup`;let a=null;try{if(Date.now()-(0,import_node_fs25.statSync)(s).mtimeMs>3e4){const c=`${s}.${e.replace(/[^\w]/g,"")}.old`;(0,import_node_fs25.renameSync)(s,c);if(Date.now()-(0,import_node_fs25.statSync)(c).mtimeMs>3e4)(0,import_node_fs25.unlinkSync)(c);else{try{(0,import_node_fs25.linkSync)(c,s)}catch{}(0,import_node_fs25.unlinkSync)(c)}}}catch{}try{a=(0,import_node_fs25.openSync)(s,"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_fs25.unlinkSync)(LOCK_FILE);if(!t())throw new Error("Another web benchmark just started. Wait for it to finish.")}finally{(0,import_node_fs25.closeSync)(a);try{(0,import_node_fs25.unlinkSync)(s)}catch{}}}lockedHere=true;return(o=false)=>{if(o)return;lockedHere=false;if(r()?.token===e){try{(0,import_node_fs25.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 s=e.frameTrace!==false;const a=(e.cpuSlowdown?.length?e.cpuSlowdown:[1]).map(M=>Math.max(1,M));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 p=await loadChromium(e.projectRoot??process.cwd());const f=await p.launch({headless:!e.headed,args:["--enable-gpu"]});const g=[];const v=[];const m=Date.now();const w=new Date(m).toISOString();const b=e.maxBatchMs??30*6e4;let y=false;let _=false;const T={commit:gitCommit(e.projectRoot??process.cwd()),dirty:gitDirty(e.projectRoot??process.cwd())};try{const M={viewport:{width:l.width,height:l.height},deviceScaleFactor:l.deviceScaleFactor};const D=await withDeadline(f.newContext(M),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 R=3e4+15e3+o+i+6e4;const O=async(z,B,L,P)=>{const N={};return withDeadline(C(N,z,B,L,P),R,async()=>{N.cancelled=true;if(!N.ctx)y=true;else if(!await closeWithin(N.ctx,1e4))y=true;return{...U(z.name,B,L),failed:`run took over ${Math.round(R/1e3)} s (the page may be stuck in a loop)`}})};const U=(z,B,L)=>({caseName:z,cpu:B,round:L,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 C=async(z,B,L,P,N)=>{const H=await f.newContext(M);z.ctx=H;if(z.cancelled){await closeWithin(H,1e4);throw new Error("run was cancelled during setup")}const j=await H.newPage();const W=[];j.on("pageerror",J=>W.push(String(J?.message??J)));const V={...U(B.name,L,P),pageErrors:W};try{const J=await H.newCDPSession(j);await J.send("Performance.enable",{timeDomain:"timeTicks"});if(L>1)await J.send("Emulation.setCPUThrottlingRate",{rate:L});const re=await j.goto(caseUrl(e.url,B,e.path),{waitUntil:"load",timeout:3e4});if(re&&re.status()>=400)return{...V,failed:`HTTP ${re.status()}`};if(e.readySelector)await j.waitForSelector(e.readySelector,{state:"attached",timeout:15e3});await sleep3(o);const oe=N||s;if(oe){await J.send("Tracing.start",{transferMode:"ReturnAsStream",categories:(N?FULL_TRACE_CATEGORIES:FRAME_TRACE_CATEGORIES).join(",")})}const ee=e.steps?.length?await locateStepTargets(j,e.steps):new Map;if(e.steps?.length){const te=await expectsAlreadyTrue(j,e.steps);if(te)return{...V,failed:`expect ${te} already held before the steps, so it can't prove they worked`};const ne=[...ee.keys()];const Z=e.steps.flatMap(ie=>"expect"in ie?[ie.expect]:[]);await j.evaluate(`window.__buoyBenchClickTargets = ${JSON.stringify(ne)}; window.__buoyBenchExpects = ${JSON.stringify(Z)}; true`)}const G=await readMetrics(J);await j.evaluate(START_PROBE_JS);const K=Date.now();if(e.steps?.length)await runSteps(j,e.steps,ee);const se=i-(Date.now()-K);if(se>0)await sleep3(se);await j.evaluate(END_PROBE_JS);const ce=await readMetrics(J);const ue=Date.now()-K;const Q=await j.evaluate(COLLECT_PROBE_JS);let Y=null;if(oe){const te=new Promise(X=>J.on("Tracing.tracingComplete",ae=>X(ae.stream)));await J.send("Tracing.end");const ne=await te;const Z=N?(0,import_node_fs25.openSync)(N,"w"):null;const ie=[];let le=0;try{for(;;){const X=await J.send("IO.read",{handle:ne});const ae=X.base64Encoded?Buffer.from(X.data,"base64").toString("utf8"):X.data;le+=ae.length;if(Z!=null)(0,import_node_fs25.writeSync)(Z,ae);if(le<=MAX_TRACE_CHARS)ie.push(ae);else ie.length=0;if(X.eof)break}}finally{await J.send("IO.close",{handle:ne}).catch(()=>{});if(Z!=null)(0,import_node_fs25.closeSync)(Z)}if(N)d.push(N);if(le>MAX_TRACE_CHARS){u.push(`Trace for ${B.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(ie.join(""));Y=summarizeFrameTrace(Array.isArray(X)?X:X.traceEvents??[])}catch{Y=null}}}if(!Q)return{...V,failed:"probe returned nothing (page navigated away?)"};if(Q.hidden)return{...V,failed:"page was hidden during the run"};if(Q.resized)return{...V,failed:"the window size or zoom changed during the run"};if(W.length&&!e.allowPageErrors){return{...V,failed:`page error: ${oneLine(W[0])}`}}if(e.steps?.length){const te=missedInput(e.steps,Q.clicks??[],Q.keys??[]);if(te)return{...V,failed:te};const ne=expectFailureFrom(Q.expectResults??[]);if(ne)return{...V,failed:ne};const Z=await checkTargetsStill(j,ee);if(Z)return{...V,failed:Z}}const de="Timestamp"in G&&"Timestamp"in ce?r1((ce.Timestamp-G.Timestamp)*1e3):null;return{...V,...summarizeProbe(Q,c),...cdpDeltas(G,ce,ue),probeSpanMs:r1(Q.end-Q.start),cdpSpanMs:de,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{...V,failed:oneLine(J?.message??String(J))}}finally{await closeWithin(j,5e3);if(!await closeWithin(H,1e4))y=true}};{const z=await withDeadline(D.newPage(),15e3,async()=>{throw new Error("Chromium didn't open the GPU check page in 15 s.")});try{h=await withDeadline(z.evaluate(GPU_RENDERER_JS),5e3,async()=>null)??null}catch{h=null}finally{await closeWithin(z,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 z=await withDeadline(D.newPage(),15e3,async()=>{throw new Error("Chromium didn't open the calibration page in 15 s.")});try{await withDeadline(z.goto("about:blank"),15e3,async()=>null);const B=await withDeadline(z.evaluate(MEASURE_REFRESH_JS),5e3,async()=>{throw new Error("idle rate check timed out")});c=snapRefreshRate(B);n(`idle frame rate ${B.toFixed(1)} \u2192 ${c} Hz`)}catch{u.push("Couldn't measure the idle frame rate; frame budgets assume 60 Hz.")}finally{await closeWithin(z,5e3)}}n("warmup load");await O(e.cases[0],1,-1);const F=async(z,B,L,P)=>{if(y){g.push({...U(z.name,B,L),failed:"an earlier run left the browser stuck; batch stopped"});return}if(Date.now()-m>b){g.push({...U(z.name,B,L),failed:"batch time limit reached; run skipped"});return}n(P);v.push({cpu:B,round:L,caseName:z.name});g.push(await O(z,B,L))};for(const z of a){for(let B=0;B<r;B++){const L=shuffled(e.cases,2654435769^B*7919+z);for(const P of L)await F(P,z,B,`cpu ${z}x \xB7 round ${B+1}/${r} \xB7 ${P.name}`)}for(let B=0;B<(e.extraRoundsWhenClose??0);B++){const L=e.cases.map(j=>aggregateCase(g.filter(W=>W.cpu===z&&W.caseName===j.name),c));for(const j of L)j.control=e.cases.find(W=>W.name===j.caseName)?.control===true;const P=new Set([...tiedPairs(L).flat(),...L.filter(j=>!j.control&&j.validRuns<2&&j.plannedRuns>0).map(j=>j.caseName)]);if(P.size===0)break;const N=r+B;const H=shuffled(e.cases.filter(j=>P.has(j.name)),20973^N*7919+z);for(const j of H)await F(j,z,N,`cpu ${z}x \xB7 extra round ${B+1} (close call) \xB7 ${j.name}`)}}if(e.traceDir){(0,import_node_fs25.mkdirSync)(e.traceDir,{recursive:true});for(const[z,B]of e.cases.entries()){const L=(0,import_node_path26.join)(e.traceDir,`${String(z+1).padStart(2,"0")}-${B.name.replace(/[^\w.-]+/g,"_")}.json`);if(y||Date.now()-m>b){u.push(`Trace run for ${B.name} skipped (batch time limit or a stuck browser).`);continue}n(`trace \xB7 ${B.name}`);const P=await O(B,a[0],-1,L);if(P.failed)u.push(`Trace run for ${B.name} failed: ${P.failed}`)}}await closeWithin(D,1e4)}finally{const M=await closeWithin(f,15e3);t.browserLeftRunning=!M;if(!M){_=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 M of a){for(const D of e.cases){$.push(aggregateCase(g.filter(R=>R.cpu===M&&R.caseName===D.name),c))}}for(const M of $)M.control=e.cases.find(D=>D.name===M.caseName)?.control===true;for(const M of a){const D=$.filter(C=>C.cpu===M);const R=D.find(C=>!C.control);if(!R)continue;R.isBaseline=true;const O=C=>C.droppedMin!=null?C.median?.droppedPct??null:null;const U=O(R);for(const C of D.filter(F=>F!==R&&!F.control)){const F=O(C);C.deltaDroppedPct=U!=null&&F!=null?r1(F-U):null}}if(e.allowPageErrors&&g.some(M=>M.pageErrors.length)){u.push("Some runs threw page errors (kept because allowPageErrors is on).")}if(y)u.push("A browser context wouldn't close, so the batch stopped early. Restart and run again.");if(e.budgets)for(const M of $)M.budget=checkBudgets(M,e.budgets,e.steps??[]);const x=$.filter(M=>M.median).length;const A=$.every(M=>M.validRuns===M.plannedRuns);const I=x===0?"failed":x<$.length||!A?"partial":"ok";const E=$.filter(M=>M.median&&M.validRuns>0&&M.validRuns<M.plannedRuns);for(const M of E){const D=Array.from(new Set(M.runs.filter(R=>R.failed).map(R=>R.failed)));u.push(`${M.caseName} (CPU ${M.cpu}x): ${M.plannedRuns-M.validRuns} of ${M.plannedRuns} runs failed: ${D.join("; ")}`)}for(const M of $){const D=M.median;if(D?.probeSpanMs&&D.cdpSpanMs&&Math.abs(D.cdpSpanMs-D.probeSpanMs)/D.probeSpanMs>.15){u.push(`${M.caseName} (CPU ${M.cpu}x): Chrome's counters cover ${Math.round(D.cdpSpanMs)} ms but frames cover ${Math.round(D.probeSpanMs)} ms, so its cost columns include extra time.`)}if(D?.probeSpanMs!=null&&D.probeSpanMs<i*.8){u.push(`${M.caseName} (CPU ${M.cpu}x) recorded ${Math.round(D.probeSpanMs)} ms, not the ${i} ms asked for.`)}}const k={status:I,hasSteps:Boolean(e.steps?.length),browserLeftRunning:_,replay:{startedAt:w,...T,runOrder:v},url:e.url,browser:`Chromium ${f.version()}${e.headed?"":" (headless)"}`,gpu:h,viewport:l,refreshHz:c,durationMs:i,runsPerCase:r,results:$,traces:d,warnings:u};const S=e.redact?e.redact(k):k;if(e.outFile){try{const{redact:M,...D}=e;(0,import_node_fs25.writeFileSync)(e.outFile,JSON.stringify({options:D,result:S},null,2))}catch(M){S.warnings.push(`Couldn't write outFile ${e.outFile}: ${oneLine(M?.message??String(M))}`)}}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((s,a)=>s.median.droppedPct-a.median.droppedPct);for(let s=1;s<o.length;s++){const[a,c]=[o[s-1],o[s]];const l=c.median.droppedPct-a.median.droppedPct<=MIN_DROPPED_GAP_PP;if(c.droppedMin<=a.droppedMax||l)r.push([a.caseName,c.caseName])}return r}if(t.length>0)return r;const i=n.filter(o=>o.median.fps!=null).sort((o,s)=>s.median.fps-o.median.fps);for(let o=1;o<i.length;o++){const[s,a]=[i[o-1],i[o]];const c=s.median.fps-a.median.fps<=MIN_FPS_GAP;if((a.fpsMax??0)>=(s.fpsMin??0)||c)r.push([s.caseName,a.caseName])}return r}function closeCall(e){const n=e.filter(a=>!a.control&&a.median);const t=[];const r=n.filter(a=>a.validRuns<2);if(r.length)t.push(`**Too few runs to rank:** ${r.map(a=>a.caseName).join(", ")} (need 2 or more valid runs).`);const i=n.filter(a=>a.validRuns>1);const o=i.filter(a=>a.droppedMin!=null);if(o.length>0&&o.length<i.length){t.push(`**Not enough traced runs to compare smoothness:** ${i.filter(a=>!o.includes(a)).map(a=>`${a.caseName} (${a.tracedRuns}/${a.validRuns} traced)`).join(", ")}.`);return t.join("\n")}const s=new Map(i.map(a=>[a.caseName,a]));for(const[a,c]of tiedPairs(e)){const l=s.get(a);const u=s.get(c);t.push(o.length?`**Too close to call:** ${a} (${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:** ${a} 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=(a,c=1)=>a==null?"\u2014":a.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(a=>a.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(a=>a.median?.probeSpanMs).filter(a=>a!=null);const i=e.results.map(a=>a.median?.cdpSpanMs).filter(a=>a!=null);const o=a=>`${(Math.min(...a)/1e3).toFixed(2)}\u2013${(Math.max(...a)/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 s=Array.from(new Set(e.results.map(a=>a.cpu)));for(const a of s){t.push("");t.push(a===1?`#### No CPU slowdown`:`#### CPU slowed ${a}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(p=>p.cpu===a)){const p=h.median;if(!p){const v=h.runs.find(m=>m.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 (${v}) |`);continue}const f=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(p.shownFps)} | ${h.droppedMin==null&&h.tracedRuns>0?`\u2014 (${h.tracedRuns}/${h.validRuns} traced)`:n(h.droppedMin==null?null:p.droppedPct)}${h.droppedMin!=null&&h.validRuns>1?` [${h.droppedMin}\u2013${h.droppedMax}]`:""}${h.deltaDroppedPct!=null?` (${h.deltaDroppedPct>0?"+":""}${h.deltaDroppedPct} pp)`:""} | ${n(p.fps)}${f} | ${n(p.frameGapP95Ms)} | ${n(p.frameGapMaxMs)} | ${n(p.mainThreadPct)} | ${n(p.scriptMs,0)} | ${n(p.styleMs,0)} | ${n(p.layoutMs,0)} | ${n(p.layoutCount,0)} | ${n(p.domNodesEnd,0)} | ${n(p.heapMb)} | ${g} |`)}const c=closeCall(e.results.filter(h=>h.cpu===a));if(c){t.push("");t.push(c)}const l=e.results.filter(h=>h.cpu===a&&h.budget);if(l.length){t.push("");t.push(`Budget:`);for(const h of l){const p=h.budget;const f=[...p.over,...p.unknown.map(v=>`${v} not measured`)].join("; ");const g=h.control?`${h.caseName} (control)`:h.caseName;t.push(`- **${g}**: ${p.meets?"meets every limit":`misses (${f||"no result"})`}`)}}const u=e.results.filter(h=>h.cpu===a&&h.median?.interactions!=null&&(e.hasSteps||h.median.interactions>0)).map(h=>{const p=h.median;const f=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(m=>!m.failed&&m.fps!=null&&m.inputCaptureComplete===false).length;const v=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(!p.interactions)return`- **${h.caseName}**: middle run had no input entry (inputs under 16 ms aren't reported)${f}${v}`;return`- **${h.caseName}**: middle run: ${p.interactions} reported (16 ms or more), slowest ${p.worstInteractionMs} ms (waiting ${p.worstInputDelayMs} \xB7 handlers ${p.worstProcessingMs} \xB7 to paint ${p.worstPresentationMs})${f}${v}`});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===a&&h.median&&h.median.topScripts.length).map(h=>`- **${h.caseName}**: ${h.median.topScripts.slice(0,3).map(p=>`${p.name} ${p.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(a=>`\u26A0\uFE0F ${a}`))}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) => {
929
+ })()`;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 s=Math.floor(r()*(o+1));[i[o],i[s]]=[i[s],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,s]of Object.entries(n.params??{}))r.searchParams.set(o,s);return r.toString()}var FRAME_STATES=["STATE_PRESENTED_ALL","STATE_PRESENTED_PARTIAL","STATE_DROPPED"];function summarizeFrameTrace(e){const n=p=>e.find(f=>f.name===p&&f.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 s=new Map;for(const p of e){if(p.name!=="PipelineReporter"||p.ph!=="b")continue;if(i!=null&&p.pid!==i)continue;if(p.ts==null||p.ts<t.ts||p.ts>r.ts)continue;const f=p.args?.frame_reporter;if(!f||f.frame_sequence==null)continue;const g=f.state;if(!FRAME_STATES.includes(g))continue;const v=`${f.layer_tree_host_id??""}:${f.frame_source??""}:${f.frame_sequence}`;const m=Boolean(f.affects_smoothness)&&g!=="STATE_PRESENTED_ALL";const w=s.get(v);if(!w)s.set(v,{state:g,fault:m});else{if(o[g]>o[w.state])w.state=g;w.fault=w.fault||m}}let a=0;let c=0;let l=0;let u=0;for(const p of s.values()){if(p.state==="STATE_PRESENTED_ALL")a++;else if(p.state==="STATE_PRESENTED_PARTIAL")c++;else l++;if(p.fault)u++}const d=a+c+l;if(d===0)return null;const h=(r.ts-t.ts)/1e6;return{full:a,partial:c,dropped:l,faults:u,shownFps:r1((a+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(a=>a.toLowerCase()));if(n.key!==r)return false;const o=r.toLowerCase();const s={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)!==s.ctrl||Boolean(n.alt)!==s.alt||Boolean(n.meta)!==s.meta)return false;if(!s.shift&&n.shift&&r.length!==1)return false;if(s.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(s=>s.interactionId===t.interactionId&&Math.abs(s.startTime+s.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 s=1e3/n;const a=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 p=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)p++;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 k of E.scripts){A+=k.forced;const S=I.get(k.name)??{ms:0,count:0};S.ms+=k.duration;S.count++;I.set(k.name,S)}}l=r1($);u=r1(x);d=r1(A);h=[...I.entries()].map(([E,k])=>({name:E,ms:r1(k.ms),count:k.count})).sort((E,k)=>k.ms-E.ms).slice(0,5)}let f=null;if(e.shifts){let $=0;for(const x of e.shifts)if(!x.hadRecentInput&&x.startTime>=t&&x.startTime<=r)$+=x.value;f=Math.round($*1e3)/1e3}let g=null;let v=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(!v||x.duration>v.duration)v=x}const m=v;const w=e.frames;const b=[...(e.clicks??[]).map($=>$.t),...(e.keys??[]).map($=>$.t)];const y=b.length?Math.max(...b):null;const _=y==null||w.filter($=>$>y).length>=2;const T=w.length===0?i:Math.max(0,w[0]-t,r-w[w.length-1]);return{edgeSilenceMs:r1(T),frameGapCount:o.length,inputCaptureComplete:_,resized:Boolean(e.resized),interactions:g,worstInteractionMs:m?r1(m.duration):null,worstInputDelayMs:m?r1(Math.max(0,m.processingStart-m.startTime)):null,worstProcessingMs:m?r1(Math.max(0,m.processingEnd-m.processingStart)):null,worstPresentationMs:m?r1(Math.max(0,m.startTime+m.duration-m.processingEnd)):null,fps:r1(e.frames.length/i*1e3),frameGapP95Ms:a==null?null:r1(a),frameGapMaxMs:o.length?r1(Math.max(...o)):null,longFrames:o.filter($=>$>s*1.5).length,longTaskPct:c,loafBlockingMs:l,styleLayoutMs:u,forcedLayoutMs:d,topScripts:h,loafCutOff:p,layoutShift:f,domNodesStart:e.domStart,domNodesEnd:e.domEnd}}function cdpDeltas(e,n,t){const r=a=>a in e&&a in n?n[a]-e[a]:null;const i=a=>{const c=r(a);return c==null?null:r1(c*1e3)};const o=i("TaskDuration");const s=i("Timestamp")??t;return{mainThreadPct:o==null?null:r1(o/Math.max(1,s)*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 s=o?[...t].sort((c,l)=>c.droppedPct-l.droppedPct):r;const a=s.length?s[Math.floor((s.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:a,fpsMin:r.length?r[0].fps:null,fpsMax:r.length?r[r.length-1].fps:null,flags:a?webBenchFlags(o?a:{...a,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_path30.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}
930
+ (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_process22.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_process22.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 s of e.cases){if(!s.name?.trim())throw new Error("Every case needs a name.");if(n.has(s.name))throw new Error(`Two cases are named "${s.name}". Give each case its own name.`);n.add(s.name)}const t=(s,a,c,l)=>{if(s==null)return;if(!Number.isInteger(s)||s<c||s>l)throw new Error(`${a} must be a whole number from ${c} to ${l}.`)};const r=(s,a,c)=>{if(s==null)return;if(!Number.isFinite(s)||s<c)throw new Error(`${a} must be a number of at least ${c}.`)};const i=(s,a,c,l)=>{if(s==null)return;if(!Number.isFinite(s)||s<c||s>l)throw new Error(`${a} 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 s of o)i(s,"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[s,a]of Object.entries(e.budgets??{}))i(a,`budgets.${s}`,0,1e9);for(const s of e.steps??[]){if("wait"in s)i(s.wait,"a wait step",0,6e4);if("scroll"in s)i(s.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 s=o?await o.boundingBox():null;if(!s)throw new Error(`step target ${i} isn't on the page (or isn't visible)`);t.set(i,{x:s.x+s.width/2,y:s.y+s.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 s=0;let a=-Infinity;const c=u=>{while(o<r.length){const d=r[o++];if(d.t>=a&&d.hit.includes(u)){a=d.t;return true}}return false};const l=u=>{while(s<i.length){const d=i[s++];if(d.t>=a&&keyMatches(u,d)){a=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 s=o.x+o.width/2;const a=o.y+o.height/2;if(Math.abs(s-r.x)>4||Math.abs(a-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 s=o?.message??String(o);const a=/Another web benchmark|already running/.test(s);if(!a||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_path30.join)((0,import_node_os21.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_fs28.writeFileSync)(o,n);(0,import_node_fs28.linkSync)(o,LOCK_FILE);return true}catch{return false}finally{try{(0,import_node_fs28.unlinkSync)(o)}catch{}}};const r=()=>{try{return JSON.parse((0,import_node_fs28.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 s=`${LOCK_FILE}.cleanup`;let a=null;try{if(Date.now()-(0,import_node_fs28.statSync)(s).mtimeMs>3e4){const c=`${s}.${e.replace(/[^\w]/g,"")}.old`;(0,import_node_fs28.renameSync)(s,c);if(Date.now()-(0,import_node_fs28.statSync)(c).mtimeMs>3e4)(0,import_node_fs28.unlinkSync)(c);else{try{(0,import_node_fs28.linkSync)(c,s)}catch{}(0,import_node_fs28.unlinkSync)(c)}}}catch{}try{a=(0,import_node_fs28.openSync)(s,"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_fs28.unlinkSync)(LOCK_FILE);if(!t())throw new Error("Another web benchmark just started. Wait for it to finish.")}finally{(0,import_node_fs28.closeSync)(a);try{(0,import_node_fs28.unlinkSync)(s)}catch{}}}lockedHere=true;return(o=false)=>{if(o)return;lockedHere=false;if(r()?.token===e){try{(0,import_node_fs28.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 s=e.frameTrace!==false;const a=(e.cpuSlowdown?.length?e.cpuSlowdown:[1]).map(M=>Math.max(1,M));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 p=await loadChromium(e.projectRoot??process.cwd());const f=await p.launch({headless:!e.headed,args:["--enable-gpu"]});const g=[];const v=[];const m=Date.now();const w=new Date(m).toISOString();const b=e.maxBatchMs??30*6e4;let y=false;let _=false;const T={commit:gitCommit(e.projectRoot??process.cwd()),dirty:gitDirty(e.projectRoot??process.cwd())};try{const M={viewport:{width:l.width,height:l.height},deviceScaleFactor:l.deviceScaleFactor};const D=await withDeadline(f.newContext(M),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 R=3e4+15e3+o+i+6e4;const O=async(z,B,L,P)=>{const N={};return withDeadline(C(N,z,B,L,P),R,async()=>{N.cancelled=true;if(!N.ctx)y=true;else if(!await closeWithin(N.ctx,1e4))y=true;return{...U(z.name,B,L),failed:`run took over ${Math.round(R/1e3)} s (the page may be stuck in a loop)`}})};const U=(z,B,L)=>({caseName:z,cpu:B,round:L,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 C=async(z,B,L,P,N)=>{const H=await f.newContext(M);z.ctx=H;if(z.cancelled){await closeWithin(H,1e4);throw new Error("run was cancelled during setup")}const j=await H.newPage();const W=[];j.on("pageerror",J=>W.push(String(J?.message??J)));const V={...U(B.name,L,P),pageErrors:W};try{const J=await H.newCDPSession(j);await J.send("Performance.enable",{timeDomain:"timeTicks"});if(L>1)await J.send("Emulation.setCPUThrottlingRate",{rate:L});const re=await j.goto(caseUrl(e.url,B,e.path),{waitUntil:"load",timeout:3e4});if(re&&re.status()>=400)return{...V,failed:`HTTP ${re.status()}`};if(e.readySelector)await j.waitForSelector(e.readySelector,{state:"attached",timeout:15e3});await sleep3(o);const oe=N||s;if(oe){await J.send("Tracing.start",{transferMode:"ReturnAsStream",categories:(N?FULL_TRACE_CATEGORIES:FRAME_TRACE_CATEGORIES).join(",")})}const ee=e.steps?.length?await locateStepTargets(j,e.steps):new Map;if(e.steps?.length){const te=await expectsAlreadyTrue(j,e.steps);if(te)return{...V,failed:`expect ${te} already held before the steps, so it can't prove they worked`};const ne=[...ee.keys()];const Z=e.steps.flatMap(ie=>"expect"in ie?[ie.expect]:[]);await j.evaluate(`window.__buoyBenchClickTargets = ${JSON.stringify(ne)}; window.__buoyBenchExpects = ${JSON.stringify(Z)}; true`)}const G=await readMetrics(J);await j.evaluate(START_PROBE_JS);const K=Date.now();if(e.steps?.length)await runSteps(j,e.steps,ee);const se=i-(Date.now()-K);if(se>0)await sleep3(se);await j.evaluate(END_PROBE_JS);const ce=await readMetrics(J);const ue=Date.now()-K;const Q=await j.evaluate(COLLECT_PROBE_JS);let Y=null;if(oe){const te=new Promise(X=>J.on("Tracing.tracingComplete",ae=>X(ae.stream)));await J.send("Tracing.end");const ne=await te;const Z=N?(0,import_node_fs28.openSync)(N,"w"):null;const ie=[];let le=0;try{for(;;){const X=await J.send("IO.read",{handle:ne});const ae=X.base64Encoded?Buffer.from(X.data,"base64").toString("utf8"):X.data;le+=ae.length;if(Z!=null)(0,import_node_fs28.writeSync)(Z,ae);if(le<=MAX_TRACE_CHARS)ie.push(ae);else ie.length=0;if(X.eof)break}}finally{await J.send("IO.close",{handle:ne}).catch(()=>{});if(Z!=null)(0,import_node_fs28.closeSync)(Z)}if(N)d.push(N);if(le>MAX_TRACE_CHARS){u.push(`Trace for ${B.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(ie.join(""));Y=summarizeFrameTrace(Array.isArray(X)?X:X.traceEvents??[])}catch{Y=null}}}if(!Q)return{...V,failed:"probe returned nothing (page navigated away?)"};if(Q.hidden)return{...V,failed:"page was hidden during the run"};if(Q.resized)return{...V,failed:"the window size or zoom changed during the run"};if(W.length&&!e.allowPageErrors){return{...V,failed:`page error: ${oneLine(W[0])}`}}if(e.steps?.length){const te=missedInput(e.steps,Q.clicks??[],Q.keys??[]);if(te)return{...V,failed:te};const ne=expectFailureFrom(Q.expectResults??[]);if(ne)return{...V,failed:ne};const Z=await checkTargetsStill(j,ee);if(Z)return{...V,failed:Z}}const de="Timestamp"in G&&"Timestamp"in ce?r1((ce.Timestamp-G.Timestamp)*1e3):null;return{...V,...summarizeProbe(Q,c),...cdpDeltas(G,ce,ue),probeSpanMs:r1(Q.end-Q.start),cdpSpanMs:de,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{...V,failed:oneLine(J?.message??String(J))}}finally{await closeWithin(j,5e3);if(!await closeWithin(H,1e4))y=true}};{const z=await withDeadline(D.newPage(),15e3,async()=>{throw new Error("Chromium didn't open the GPU check page in 15 s.")});try{h=await withDeadline(z.evaluate(GPU_RENDERER_JS),5e3,async()=>null)??null}catch{h=null}finally{await closeWithin(z,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 z=await withDeadline(D.newPage(),15e3,async()=>{throw new Error("Chromium didn't open the calibration page in 15 s.")});try{await withDeadline(z.goto("about:blank"),15e3,async()=>null);const B=await withDeadline(z.evaluate(MEASURE_REFRESH_JS),5e3,async()=>{throw new Error("idle rate check timed out")});c=snapRefreshRate(B);n(`idle frame rate ${B.toFixed(1)} \u2192 ${c} Hz`)}catch{u.push("Couldn't measure the idle frame rate; frame budgets assume 60 Hz.")}finally{await closeWithin(z,5e3)}}n("warmup load");await O(e.cases[0],1,-1);const F=async(z,B,L,P)=>{if(y){g.push({...U(z.name,B,L),failed:"an earlier run left the browser stuck; batch stopped"});return}if(Date.now()-m>b){g.push({...U(z.name,B,L),failed:"batch time limit reached; run skipped"});return}n(P);v.push({cpu:B,round:L,caseName:z.name});g.push(await O(z,B,L))};for(const z of a){for(let B=0;B<r;B++){const L=shuffled(e.cases,2654435769^B*7919+z);for(const P of L)await F(P,z,B,`cpu ${z}x \xB7 round ${B+1}/${r} \xB7 ${P.name}`)}for(let B=0;B<(e.extraRoundsWhenClose??0);B++){const L=e.cases.map(j=>aggregateCase(g.filter(W=>W.cpu===z&&W.caseName===j.name),c));for(const j of L)j.control=e.cases.find(W=>W.name===j.caseName)?.control===true;const P=new Set([...tiedPairs(L).flat(),...L.filter(j=>!j.control&&j.validRuns<2&&j.plannedRuns>0).map(j=>j.caseName)]);if(P.size===0)break;const N=r+B;const H=shuffled(e.cases.filter(j=>P.has(j.name)),20973^N*7919+z);for(const j of H)await F(j,z,N,`cpu ${z}x \xB7 extra round ${B+1} (close call) \xB7 ${j.name}`)}}if(e.traceDir){(0,import_node_fs28.mkdirSync)(e.traceDir,{recursive:true});for(const[z,B]of e.cases.entries()){const L=(0,import_node_path30.join)(e.traceDir,`${String(z+1).padStart(2,"0")}-${B.name.replace(/[^\w.-]+/g,"_")}.json`);if(y||Date.now()-m>b){u.push(`Trace run for ${B.name} skipped (batch time limit or a stuck browser).`);continue}n(`trace \xB7 ${B.name}`);const P=await O(B,a[0],-1,L);if(P.failed)u.push(`Trace run for ${B.name} failed: ${P.failed}`)}}await closeWithin(D,1e4)}finally{const M=await closeWithin(f,15e3);t.browserLeftRunning=!M;if(!M){_=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 M of a){for(const D of e.cases){$.push(aggregateCase(g.filter(R=>R.cpu===M&&R.caseName===D.name),c))}}for(const M of $)M.control=e.cases.find(D=>D.name===M.caseName)?.control===true;for(const M of a){const D=$.filter(C=>C.cpu===M);const R=D.find(C=>!C.control);if(!R)continue;R.isBaseline=true;const O=C=>C.droppedMin!=null?C.median?.droppedPct??null:null;const U=O(R);for(const C of D.filter(F=>F!==R&&!F.control)){const F=O(C);C.deltaDroppedPct=U!=null&&F!=null?r1(F-U):null}}if(e.allowPageErrors&&g.some(M=>M.pageErrors.length)){u.push("Some runs threw page errors (kept because allowPageErrors is on).")}if(y)u.push("A browser context wouldn't close, so the batch stopped early. Restart and run again.");if(e.budgets)for(const M of $)M.budget=checkBudgets(M,e.budgets,e.steps??[]);const x=$.filter(M=>M.median).length;const A=$.every(M=>M.validRuns===M.plannedRuns);const I=x===0?"failed":x<$.length||!A?"partial":"ok";const E=$.filter(M=>M.median&&M.validRuns>0&&M.validRuns<M.plannedRuns);for(const M of E){const D=Array.from(new Set(M.runs.filter(R=>R.failed).map(R=>R.failed)));u.push(`${M.caseName} (CPU ${M.cpu}x): ${M.plannedRuns-M.validRuns} of ${M.plannedRuns} runs failed: ${D.join("; ")}`)}for(const M of $){const D=M.median;if(D?.probeSpanMs&&D.cdpSpanMs&&Math.abs(D.cdpSpanMs-D.probeSpanMs)/D.probeSpanMs>.15){u.push(`${M.caseName} (CPU ${M.cpu}x): Chrome's counters cover ${Math.round(D.cdpSpanMs)} ms but frames cover ${Math.round(D.probeSpanMs)} ms, so its cost columns include extra time.`)}if(D?.probeSpanMs!=null&&D.probeSpanMs<i*.8){u.push(`${M.caseName} (CPU ${M.cpu}x) recorded ${Math.round(D.probeSpanMs)} ms, not the ${i} ms asked for.`)}}const k={status:I,hasSteps:Boolean(e.steps?.length),browserLeftRunning:_,replay:{startedAt:w,...T,runOrder:v},url:e.url,browser:`Chromium ${f.version()}${e.headed?"":" (headless)"}`,gpu:h,viewport:l,refreshHz:c,durationMs:i,runsPerCase:r,results:$,traces:d,warnings:u};const S=e.redact?e.redact(k):k;if(e.outFile){try{const{redact:M,...D}=e;(0,import_node_fs28.writeFileSync)(e.outFile,JSON.stringify({options:D,result:S},null,2))}catch(M){S.warnings.push(`Couldn't write outFile ${e.outFile}: ${oneLine(M?.message??String(M))}`)}}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((s,a)=>s.median.droppedPct-a.median.droppedPct);for(let s=1;s<o.length;s++){const[a,c]=[o[s-1],o[s]];const l=c.median.droppedPct-a.median.droppedPct<=MIN_DROPPED_GAP_PP;if(c.droppedMin<=a.droppedMax||l)r.push([a.caseName,c.caseName])}return r}if(t.length>0)return r;const i=n.filter(o=>o.median.fps!=null).sort((o,s)=>s.median.fps-o.median.fps);for(let o=1;o<i.length;o++){const[s,a]=[i[o-1],i[o]];const c=s.median.fps-a.median.fps<=MIN_FPS_GAP;if((a.fpsMax??0)>=(s.fpsMin??0)||c)r.push([s.caseName,a.caseName])}return r}function closeCall(e){const n=e.filter(a=>!a.control&&a.median);const t=[];const r=n.filter(a=>a.validRuns<2);if(r.length)t.push(`**Too few runs to rank:** ${r.map(a=>a.caseName).join(", ")} (need 2 or more valid runs).`);const i=n.filter(a=>a.validRuns>1);const o=i.filter(a=>a.droppedMin!=null);if(o.length>0&&o.length<i.length){t.push(`**Not enough traced runs to compare smoothness:** ${i.filter(a=>!o.includes(a)).map(a=>`${a.caseName} (${a.tracedRuns}/${a.validRuns} traced)`).join(", ")}.`);return t.join("\n")}const s=new Map(i.map(a=>[a.caseName,a]));for(const[a,c]of tiedPairs(e)){const l=s.get(a);const u=s.get(c);t.push(o.length?`**Too close to call:** ${a} (${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:** ${a} 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=(a,c=1)=>a==null?"\u2014":a.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(a=>a.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(a=>a.median?.probeSpanMs).filter(a=>a!=null);const i=e.results.map(a=>a.median?.cdpSpanMs).filter(a=>a!=null);const o=a=>`${(Math.min(...a)/1e3).toFixed(2)}\u2013${(Math.max(...a)/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 s=Array.from(new Set(e.results.map(a=>a.cpu)));for(const a of s){t.push("");t.push(a===1?`#### No CPU slowdown`:`#### CPU slowed ${a}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(p=>p.cpu===a)){const p=h.median;if(!p){const v=h.runs.find(m=>m.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 (${v}) |`);continue}const f=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(p.shownFps)} | ${h.droppedMin==null&&h.tracedRuns>0?`\u2014 (${h.tracedRuns}/${h.validRuns} traced)`:n(h.droppedMin==null?null:p.droppedPct)}${h.droppedMin!=null&&h.validRuns>1?` [${h.droppedMin}\u2013${h.droppedMax}]`:""}${h.deltaDroppedPct!=null?` (${h.deltaDroppedPct>0?"+":""}${h.deltaDroppedPct} pp)`:""} | ${n(p.fps)}${f} | ${n(p.frameGapP95Ms)} | ${n(p.frameGapMaxMs)} | ${n(p.mainThreadPct)} | ${n(p.scriptMs,0)} | ${n(p.styleMs,0)} | ${n(p.layoutMs,0)} | ${n(p.layoutCount,0)} | ${n(p.domNodesEnd,0)} | ${n(p.heapMb)} | ${g} |`)}const c=closeCall(e.results.filter(h=>h.cpu===a));if(c){t.push("");t.push(c)}const l=e.results.filter(h=>h.cpu===a&&h.budget);if(l.length){t.push("");t.push(`Budget:`);for(const h of l){const p=h.budget;const f=[...p.over,...p.unknown.map(v=>`${v} not measured`)].join("; ");const g=h.control?`${h.caseName} (control)`:h.caseName;t.push(`- **${g}**: ${p.meets?"meets every limit":`misses (${f||"no result"})`}`)}}const u=e.results.filter(h=>h.cpu===a&&h.median?.interactions!=null&&(e.hasSteps||h.median.interactions>0)).map(h=>{const p=h.median;const f=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(m=>!m.failed&&m.fps!=null&&m.inputCaptureComplete===false).length;const v=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(!p.interactions)return`- **${h.caseName}**: middle run had no input entry (inputs under 16 ms aren't reported)${f}${v}`;return`- **${h.caseName}**: middle run: ${p.interactions} reported (16 ms or more), slowest ${p.worstInteractionMs} ms (waiting ${p.worstInputDelayMs} \xB7 handlers ${p.worstProcessingMs} \xB7 to paint ${p.worstPresentationMs})${f}${v}`});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===a&&h.median&&h.median.topScripts.length).map(h=>`- **${h.caseName}**: ${h.median.topScripts.slice(0,3).map(p=>`${p.name} ${p.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(a=>`\u26A0\uFE0F ${a}`))}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) => {
929
931
  setTimeout(() => {
930
932
  const deltas = [];
931
933
  let start;
@@ -992,7 +994,7 @@ ${i.join("\n")}${o.length?`
992
994
  **Page errors**
993
995
  ${o.join("\n")}`:""}${a}
994
996
 
995
- 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_process22=require("child_process");var import_node_util18=require("util");var import_node_fs26=require("fs");var import_node_os19=__toESM(require("os"));var import_node_path27=__toESM(require("path"));var import_node_crypto15=require("crypto");var execFileAsync18=(0,import_node_util18.promisify)(import_node_child_process22.execFile);async function run5(e,n,t=2e4){try{const{stdout:r}=await execFileAsync18(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_process22.spawn)("xcrun",["simctl","pbcopy",e.udid],{stdio:["pipe","ignore","pipe"]});let o="";i.stderr.on("data",s=>o+=s);i.on("error",r);i.on("exit",s=>s===0?t():r(new Error(`simctl pbcopy failed: ${o.trim()}`)));i.stdin.end(n)})}else if(e.platform==="ios-device"){const t=import_node_path27.default.join(import_node_os19.default.tmpdir(),`buoy-clip-${(0,import_node_crypto15.randomUUID)()}.txt`);await import_node_fs26.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_fs26.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 s;switch(t.action){case"rotate":if(!t.orientation)return fail2("rotate requires `orientation`.");s=await rotate(i,t.orientation);if(i.platform!=="android")forgetScreenSize(i.udid);break;case"shake":s=await shake(i);break;case"clipboard":if(t.text===void 0)return fail2("clipboard requires `text`.");s=await setClipboard(i,fillSecrets(t.text));break;case"biometrics":s=await biometrics(i,t.match!==false,t.fingerId);break}if(t.action!=="rotate"||i.platform!=="ios")await new Promise(c=>setTimeout(c,700));const a=o&&t.action!=="clipboard"?await observeAfterAction(n,r):"";return text(`${s} (${hostLabel(i)})${a}`)}catch(r){return fail2(errMsg2(r))}})}var import_node_path28=__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 s;let a;if(o){s=i.slice(o.index+2);a=o.index}else{const d=/(?:^at\s+|@)((?:https?:\/\/|file:\/\/|\/|[A-Za-z]:[\\/]).*)$/.exec(i);if(!d)continue;s=d[1];a=d.index}const c=Object.assign([t,s,r[1],r[2]],{index:a});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_path28.default.win32:import_node_path28.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 s=typeof o==="string"&&o?` Metro said: ${o.slice(0,200)}`:"";const a=/serialized source map/i.test(s)?" Its cache looks stale; restarting Metro with --clear usually fixes this.":"";throw new Error(`Metro could not map these frames (HTTP ${r.status}).${s}${a}`)}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 s;if(o){s=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")){s=i.reason}else{const a=i.reason??"React gave no source frame. Use a dev build.";s=a===t?"no source (same reason as above).":`no source. ${a}`;t=a}return`${i.name}: ${s} [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 s=await n.callAction("highlight-updates","getComponentSource",{query:t,nativeTag:r},o);if(!s)return fail2("The app gave no source result. Turn on highlight-updates or update Buoy.");if(!s.found)return text(s.reason);const a=n.devServerOrigin(o);const c=await Promise.all([s.component,...s.owners.slice(0,6)].map(d=>resolveEntry(d,a)));const l=s.component.definedIn?await resolveEntry({name:s.component.name,memo:false,forwardRef:false,source:s.component.definedIn.source,rawStack:s.component.definedIn.rawStack},a):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)
997
+ 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_process23=require("child_process");var import_node_util18=require("util");var import_node_fs29=require("fs");var import_node_os22=__toESM(require("os"));var import_node_path31=__toESM(require("path"));var import_node_crypto17=require("crypto");var execFileAsync18=(0,import_node_util18.promisify)(import_node_child_process23.execFile);async function run5(e,n,t=2e4){try{const{stdout:r}=await execFileAsync18(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_process23.spawn)("xcrun",["simctl","pbcopy",e.udid],{stdio:["pipe","ignore","pipe"]});let o="";i.stderr.on("data",s=>o+=s);i.on("error",r);i.on("exit",s=>s===0?t():r(new Error(`simctl pbcopy failed: ${o.trim()}`)));i.stdin.end(n)})}else if(e.platform==="ios-device"){const t=import_node_path31.default.join(import_node_os22.default.tmpdir(),`buoy-clip-${(0,import_node_crypto17.randomUUID)()}.txt`);await import_node_fs29.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_fs29.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 s;switch(t.action){case"rotate":if(!t.orientation)return fail2("rotate requires `orientation`.");s=await rotate(i,t.orientation);if(i.platform!=="android")forgetScreenSize(i.udid);break;case"shake":s=await shake(i);break;case"clipboard":if(t.text===void 0)return fail2("clipboard requires `text`.");s=await setClipboard(i,fillSecrets(t.text));break;case"biometrics":s=await biometrics(i,t.match!==false,t.fingerId);break}if(t.action!=="rotate"||i.platform!=="ios")await new Promise(c=>setTimeout(c,700));const a=o&&t.action!=="clipboard"?await observeAfterAction(n,r):"";return text(`${s} (${hostLabel(i)})${a}`)}catch(r){return fail2(errMsg2(r))}})}var import_node_path32=__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 s;let a;if(o){s=i.slice(o.index+2);a=o.index}else{const d=/(?:^at\s+|@)((?:https?:\/\/|file:\/\/|\/|[A-Za-z]:[\\/]).*)$/.exec(i);if(!d)continue;s=d[1];a=d.index}const c=Object.assign([t,s,r[1],r[2]],{index:a});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_path32.default.win32:import_node_path32.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 s=typeof o==="string"&&o?` Metro said: ${o.slice(0,200)}`:"";const a=/serialized source map/i.test(s)?" Its cache looks stale; restarting Metro with --clear usually fixes this.":"";throw new Error(`Metro could not map these frames (HTTP ${r.status}).${s}${a}`)}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 s;if(o){s=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")){s=i.reason}else{const a=i.reason??"React gave no source frame. Use a dev build.";s=a===t?"no source (same reason as above).":`no source. ${a}`;t=a}return`${i.name}: ${s} [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 s=await n.callAction("highlight-updates","getComponentSource",{query:t,nativeTag:r},o);if(!s)return fail2("The app gave no source result. Turn on highlight-updates or update Buoy.");if(!s.found)return text(s.reason);const a=n.devServerOrigin(o);const c=await Promise.all([s.component,...s.owners.slice(0,6)].map(d=>resolveEntry(d,a)));const l=s.component.definedIn?await resolveEntry({name:s.component.name,memo:false,forwardRef:false,source:s.component.definedIn.source,rawStack:s.component.definedIn.rawStack},a):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)
996
998
  `:"";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 formatTotalsMarkdown(e,n){const t=[];t.push(`## JS thread (${(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.`)}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. On a free account it returns the totals only (busy %, freezes); the table of origins needs 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 s=Math.min(Math.max(r??3e3,250),3e4);const a=await n.callAction(JS_TOP_TOOL_ID,"sample",{durationMs:s,clearFirst:i===true},o);if(!a)return fail2("Device returned no snapshot \u2014 is @buoy-gg/js-top installed in the app?");if(!n.fullResultsFor(o)){const{snap:u,locked:d}=freeJsTop(a);const h={busyPct:Math.round(u.busyPct*10)/10,freezeSummary:u.freezeSummary,tiers:u.tiers};return text(withLockedLines(`${formatTotalsMarkdown(u,s)}
997
999
 
998
1000
  \`\`\`json
@@ -1026,7 +1028,7 @@ _Values: get_storage includeValues:true_`}const w=new Map(m);let b=STORAGE_VALUE
1026
1028
 
1027
1029
  ${f}
1028
1030
 
1029
- _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 s=t.totalRenderMs??0;o.push(`**${t.totalRenders} component renders across ${t.totalCommits} commits in ${(e.windowMs/1e3).toFixed(1)}s**`+(s>0?` \xB7 ${s.toFixed(1)}ms of render work`:"")+` \xB7 ${r} wasted (${i}%)`);const a=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(a)o.push(`causes: ${a}`);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 s=new Map(r.topComponents.map(u=>[u.name,u.renders]));const a=[];for(const u of i.topComponents.slice(0,20)){const d=s.get(u.name)??0;if(d!==u.renders)a.push(`${u.name} ${t(d,u.renders)}`);s.delete(u.name)}for(const[u,d]of s){if(d>0)a.push(`${u} ${t(d,0)}`)}if(a.length)o.push(`- per component: ${a.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(v=>v.deviceId===r);const o=(i?.tools??[]).find(v=>v.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 s=await n.callAction(UI_TOOL_ID3,"beginMeasurement",{},r);if(s&&s.ok===false){return fail12(`Can't measure renders: ${s.reason??"capture unavailable"}`)}await delay8(SETTLE_MS);const a=Date.now();const c=[];if(t.steps?.length){for(const v of t.steps){const m=v.repeat??1;for(let w=0;w<m;w++){if(v.type!==void 0){const b=v.into??v.tap;if(!b){c.push("a `type` step needs `into`");continue}const y=await n.callAction(UI_TOOL_ID3,"tapElement",{...selector2(b),text:v.type},r);if(!y?.tapped)c.push(y?.reason??`could not type into "${b}"`);else if(y.matched?.via&&y.matched.via!=="onChangeText"){c.push(`"${b}" is not a text input \u2014 it ran ${y.matched.via}, nothing was typed`)}}else if(v.tap){const b=await n.callAction(UI_TOOL_ID3,"tapElement",selector2(v.tap),r);if(!b?.tapped)c.push(b?.reason??`no element matched "${v.tap}"`)}if(v.waitMs)await delay8(v.waitMs)}}await delay8(SETTLE_MS)}else{await delay8(t.idleMs??DEFAULT_IDLE_MS)}const l=Date.now()-a;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 p=lastCapture.get(r);lastCapture.set(r,h);const f=t.steps?.length?t.steps.map(v=>(v.type!==void 0?`type "${v.type}"`:`tap "${v.tap}"`)+(v.repeat?` \xD7${v.repeat}`:"")).join(", "):`idle ${(l/1e3).toFixed(1)}s`;const g=[`**measure_renders \u2014 ${f}**`,"",formatCapture(h,t.top??DEFAULT_TOP)];if(t.compareToPrevious){g.push("",p?formatDelta(p,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_fs27=__toESM(require("fs"));var import_node_path29=__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_fs27.default.watch(e,{recursive:true},(t,r)=>{if(!r)return;const i=String(r);if(i.split(import_node_path29.default.sep).some(o=>IGNORED_DIRS.has(o)))return;if(!WATCHED_EXT.has(import_node_path29.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`
1031
+ _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 s=t.totalRenderMs??0;o.push(`**${t.totalRenders} component renders across ${t.totalCommits} commits in ${(e.windowMs/1e3).toFixed(1)}s**`+(s>0?` \xB7 ${s.toFixed(1)}ms of render work`:"")+` \xB7 ${r} wasted (${i}%)`);const a=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(a)o.push(`causes: ${a}`);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 s=new Map(r.topComponents.map(u=>[u.name,u.renders]));const a=[];for(const u of i.topComponents.slice(0,20)){const d=s.get(u.name)??0;if(d!==u.renders)a.push(`${u.name} ${t(d,u.renders)}`);s.delete(u.name)}for(const[u,d]of s){if(d>0)a.push(`${u} ${t(d,0)}`)}if(a.length)o.push(`- per component: ${a.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(v=>v.deviceId===r);const o=(i?.tools??[]).find(v=>v.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 s=await n.callAction(UI_TOOL_ID3,"beginMeasurement",{},r);if(s&&s.ok===false){return fail12(`Can't measure renders: ${s.reason??"capture unavailable"}`)}await delay8(SETTLE_MS);const a=Date.now();const c=[];if(t.steps?.length){for(const v of t.steps){const m=v.repeat??1;for(let w=0;w<m;w++){if(v.type!==void 0){const b=v.into??v.tap;if(!b){c.push("a `type` step needs `into`");continue}const y=await n.callAction(UI_TOOL_ID3,"tapElement",{...selector2(b),text:v.type},r);if(!y?.tapped)c.push(y?.reason??`could not type into "${b}"`);else if(y.matched?.via&&y.matched.via!=="onChangeText"){c.push(`"${b}" is not a text input \u2014 it ran ${y.matched.via}, nothing was typed`)}}else if(v.tap){const b=await n.callAction(UI_TOOL_ID3,"tapElement",selector2(v.tap),r);if(!b?.tapped)c.push(b?.reason??`no element matched "${v.tap}"`)}if(v.waitMs)await delay8(v.waitMs)}}await delay8(SETTLE_MS)}else{await delay8(t.idleMs??DEFAULT_IDLE_MS)}const l=Date.now()-a;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 p=lastCapture.get(r);lastCapture.set(r,h);const f=t.steps?.length?t.steps.map(v=>(v.type!==void 0?`type "${v.type}"`:`tap "${v.tap}"`)+(v.repeat?` \xD7${v.repeat}`:"")).join(", "):`idle ${(l/1e3).toFixed(1)}s`;const g=[`**measure_renders \u2014 ${f}**`,"",formatCapture(h,t.top??DEFAULT_TOP)];if(t.compareToPrevious){g.push("",p?formatDelta(p,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_fs30=__toESM(require("fs"));var import_node_path33=__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_fs30.default.watch(e,{recursive:true},(t,r)=>{if(!r)return;const i=String(r);if(i.split(import_node_path33.default.sep).some(o=>IGNORED_DIRS.has(o)))return;if(!WATCHED_EXT.has(import_node_path33.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`
1030
1032
 
1031
1033
  ---
1032
1034
  \u26A0\uFE0F **${e.length} source file${e.length===1?"":"s"} changed since anything was last checked on the device** (${n}${t}).
@@ -1138,7 +1140,7 @@ After a behavior change, repeat the affected interaction and check the expected
1138
1140
  Include restart or persistence checks when relevant to the change. Use appropriate static
1139
1141
  checks for documentation-only work. Report actual checks, observations and remaining limits.
1140
1142
  BUOY_VERIFY reminders track selected edits and tool calls; clearing a reminder is not a
1141
- 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(...s)=>runWithAccess(accessFor(r,i?.inputSchema?s[0]:{}),async()=>{const a=s[0];if(r==="list_devices"){}else if(a?.deviceId)await e.awaitBroker();else await e.settleDeviceChoice();const c=currentAccess();if(c.level==="pro"&&!hasProProof(e)){const m=Date.now()+NOT_READY_WAIT_MS;while(!hasProProof(e)&&Date.now()<m&&e.connectedDevices().some(w=>e.accessState(w.deviceId,"pro")==="pending")){await new Promise(w=>setTimeout(w,250))}if(!hasProProof(e)){const w=e.connectedDevices().find(_=>e.accessState(_.deviceId,"pro")==="pending");if(w){return{isError:true,content:[{type:"text",text:`${NOT_READY_MARK} account access for "${w.deviceId}" is still being confirmed (the app just connected). Try again in a moment.`}]}}if(!e.isAdmitted()){return{isError:true,content:[{type:"text",text:"A verified Buoy account and an updated broker are required. Sign in to Buoy Desktop, or run npx buoy login for standalone MCP."}]}}const b=e.connectedDevices();const y=b.length?` The connected app${b.length>1?"s are":" is"} on ${[...new Set(b.map(_=>_.tier))].join(" / ")}.`:" No app on Buoy Pro has connected in this session.";return{isError:true,content:[{type:"text",text:proRequiredMessage(c,y)}]}}}noteAgentCall(e,r,a);const l=async()=>{const m=await o(...s);for(const w of m?.content??[]){if(w.type==="text"&&typeof w.text==="string")w.text=scrubSecrets(w.text)}return m};let u=await l();const d=m=>{const w=m;return w?.isError===true&&(w.content?.[0]?.text??"").startsWith(NOT_READY_MARK)};if(d(u)){const m=u.content[0].text;const w=/"([^"]+)"/.exec(m)?.[1];const b=Date.now()+NOT_READY_WAIT_MS;while(Date.now()<b){await new Promise(y=>setTimeout(y,250));if(w?e.accessState(w)==="ready":e.connectedDevices().some(y=>meetsAccess(y,currentAccess().level)))break}u=await l()}const h=u?.isError===true;let p=null;if(VERIFYING_TOOLS.has(r)&&!h)editWatcher.markVerified();else p=editWatcher.nudge();const f=optimizeNote();const g=[p,f].filter(m=>!!m);if(!g.length)return u;const v=u;if(Array.isArray(v?.content)){return{...v,content:[...v.content,...g.map(m=>({type:"text",text:m}))]}}return u}))));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,e);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_process23=require("child_process");var import_node_fs28=__toESM(require("fs"));var import_node_os20=__toESM(require("os"));var import_node_path30=__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_path30.default.resolve(__dirname,"../skill");const r=e.log??(s=>process.stdout.write(s+"\n"));const i=resolveEntry2(e,r);const o=[];upsertMcpConfig(import_node_path30.default.join(n,".mcp.json"),"mcpServers",i,n,o);import_node_fs28.default.mkdirSync(import_node_path30.default.join(n,".cursor"),{recursive:true});upsertMcpConfig(import_node_path30.default.join(n,".cursor","mcp.json"),"mcpServers",i,n,o);if(import_node_fs28.default.existsSync(import_node_path30.default.join(n,".vscode"))){upsertMcpConfig(import_node_path30.default.join(n,".vscode","mcp.json"),"servers",i,n,o)}installSkills(t,n,o);appendDebuggingGuide(import_node_path30.default.join(n,"CLAUDE.md"),n,o);appendDebuggingGuide(import_node_path30.default.join(n,"AGENTS.md"),n,o);r("Buoy MCP configuration written:");for(const s of o)r(" \u2022 "+s);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. Free accounts get the basic MCP tools; Pro adds the rest.");r("");r(`Want your AI to use the web too? Run \`npx -y ${PACKAGE_NAME}@latest init --web\` for Buoy Web (free, no account).`);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_path30.default.join(import_node_os20.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_fs28.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_process23.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 s=import_node_path30.default.join(e,"node_modules",PACKAGE_NAME,"dist","cli.js");if(!import_node_fs28.default.existsSync(s)){t(`\u26A0 install finished but ${s} is missing.`);return null}return s}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_process23.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_process23.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=`
1143
+ 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(...s)=>runWithAccess(accessFor(r,i?.inputSchema?s[0]:{}),async()=>{const a=s[0];if(r==="list_devices"){}else if(a?.deviceId)await e.awaitBroker();else await e.settleDeviceChoice();const c=currentAccess();if(c.level==="pro"&&!hasProProof(e)){const m=Date.now()+NOT_READY_WAIT_MS;while(!hasProProof(e)&&Date.now()<m&&e.connectedDevices().some(w=>e.accessState(w.deviceId,"pro")==="pending")){await new Promise(w=>setTimeout(w,250))}if(!hasProProof(e)){const w=e.connectedDevices().find(_=>e.accessState(_.deviceId,"pro")==="pending");if(w){return{isError:true,content:[{type:"text",text:`${NOT_READY_MARK} account access for "${w.deviceId}" is still being confirmed (the app just connected). Try again in a moment.`}]}}if(!e.isAdmitted()){return{isError:true,content:[{type:"text",text:"A verified Buoy account and an updated broker are required. Sign in to Buoy Desktop, or run npx buoy login for standalone MCP."}]}}const b=e.connectedDevices();const y=b.length?` The connected app${b.length>1?"s are":" is"} on ${[...new Set(b.map(_=>_.tier))].join(" / ")}.`:" No app on Buoy Pro has connected in this session.";return{isError:true,content:[{type:"text",text:proRequiredMessage(c,y)}]}}}noteAgentCall(e,r,a);const l=async()=>{const m=await o(...s);for(const w of m?.content??[]){if(w.type==="text"&&typeof w.text==="string")w.text=scrubSecrets(w.text)}return m};let u=await l();const d=m=>{const w=m;return w?.isError===true&&(w.content?.[0]?.text??"").startsWith(NOT_READY_MARK)};if(d(u)){const m=u.content[0].text;const w=/"([^"]+)"/.exec(m)?.[1];const b=Date.now()+NOT_READY_WAIT_MS;while(Date.now()<b){await new Promise(y=>setTimeout(y,250));if(w?e.accessState(w)==="ready":e.connectedDevices().some(y=>meetsAccess(y,currentAccess().level)))break}u=await l()}const h=u?.isError===true;let p=null;if(VERIFYING_TOOLS.has(r)&&!h)editWatcher.markVerified();else p=editWatcher.nudge();const f=optimizeNote();const g=[p,f].filter(m=>!!m);if(!g.length)return u;const v=u;if(Array.isArray(v?.content)){return{...v,content:[...v.content,...g.map(m=>({type:"text",text:m}))]}}return u}))));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,e);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_process24=require("child_process");var import_node_fs31=__toESM(require("fs"));var import_node_os23=__toESM(require("os"));var import_node_path34=__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_path34.default.resolve(__dirname,"../skill");const r=e.log??(s=>process.stdout.write(s+"\n"));const i=resolveEntry2(e,r);const o=[];upsertMcpConfig(import_node_path34.default.join(n,".mcp.json"),"mcpServers",i,n,o);import_node_fs31.default.mkdirSync(import_node_path34.default.join(n,".cursor"),{recursive:true});upsertMcpConfig(import_node_path34.default.join(n,".cursor","mcp.json"),"mcpServers",i,n,o);if(import_node_fs31.default.existsSync(import_node_path34.default.join(n,".vscode"))){upsertMcpConfig(import_node_path34.default.join(n,".vscode","mcp.json"),"servers",i,n,o)}installSkills(t,n,o);appendDebuggingGuide(import_node_path34.default.join(n,"CLAUDE.md"),n,o);appendDebuggingGuide(import_node_path34.default.join(n,"AGENTS.md"),n,o);r("Buoy MCP configuration written:");for(const s of o)r(" \u2022 "+s);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. Free accounts get the basic MCP tools; Pro adds the rest.");r("");r(`Want your AI to use the web too? Run \`npx -y ${PACKAGE_NAME}@latest init --web\` for Buoy Web (free, no account).`);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_path34.default.join(import_node_os23.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_fs31.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_process24.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 s=import_node_path34.default.join(e,"node_modules",PACKAGE_NAME,"dist","cli.js");if(!import_node_fs31.default.existsSync(s)){t(`\u26A0 install finished but ${s} is missing.`);return null}return s}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_process24.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_process24.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=`
1142
1144
  const url = process.argv[1];
1143
1145
  const ms = Number(process.argv[2]) || 3000;
1144
1146
  const c = new AbortController();
@@ -1151,7 +1153,7 @@ fetch(url, { method: 'HEAD', signal: c.signal })
1151
1153
  clearTimeout(t);
1152
1154
  process.exit(1);
1153
1155
  });
1154
- `;function upsertMcpConfig(e,n,t,r,i,o="buoy"){let s={};if(import_node_fs28.default.existsSync(e)){try{s=JSON.parse(import_node_fs28.default.readFileSync(e,"utf8"))}catch{const l=import_node_fs28.default.existsSync(e+".bak")?`${e}.${Date.now()}.bak`:`${e}.bak`;import_node_fs28.default.copyFileSync(e,l);i.push(`existing ${rel(e,r)} was invalid JSON \u2014 backed up to ${rel(l,r)}`);s={}}}else{import_node_fs28.default.mkdirSync(import_node_path30.default.dirname(e),{recursive:true})}const a=s[n]&&typeof s[n]==="object"?s[n]:{};const c=o in a;a[o]=t;s[n]=a;import_node_fs28.default.writeFileSync(e,JSON.stringify(s,null,2)+"\n");i.push(`${c?"updated":"added"} \`${o}\` in ${rel(e,r)}`)}var GUIDE_HEADING="# Debugging with Buoy";var DEBUGGING_GUIDE=`${GUIDE_HEADING}
1156
+ `;function upsertMcpConfig(e,n,t,r,i,o="buoy"){let s={};if(import_node_fs31.default.existsSync(e)){try{s=JSON.parse(import_node_fs31.default.readFileSync(e,"utf8"))}catch{const l=import_node_fs31.default.existsSync(e+".bak")?`${e}.${Date.now()}.bak`:`${e}.bak`;import_node_fs31.default.copyFileSync(e,l);i.push(`existing ${rel(e,r)} was invalid JSON \u2014 backed up to ${rel(l,r)}`);s={}}}else{import_node_fs31.default.mkdirSync(import_node_path34.default.dirname(e),{recursive:true})}const a=s[n]&&typeof s[n]==="object"?s[n]:{};const c=o in a;a[o]=t;s[n]=a;import_node_fs31.default.writeFileSync(e,JSON.stringify(s,null,2)+"\n");i.push(`${c?"updated":"added"} \`${o}\` in ${rel(e,r)}`)}var GUIDE_HEADING="# Debugging with Buoy";var DEBUGGING_GUIDE=`${GUIDE_HEADING}
1155
1157
 
1156
1158
  Use Buoy to inspect a connected app when runtime evidence helps the task.
1157
1159
  Complete account, tool integration and connection setup first. A free app gets
@@ -1185,4 +1187,4 @@ only source review or a build was performed.
1185
1187
  reminders, \`always\` repeats until checked, and \`never\` disables them.
1186
1188
  A reminder is not a test result. Choose checks appropriate to the change;
1187
1189
  prose-only edits do not require running device actions.
1188
- `;function appendDebuggingGuide(e,n,t){let r="";if(import_node_fs28.default.existsSync(e)){try{r=import_node_fs28.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_fs28.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_fs28.default.existsSync(e)){t.push("\u26A0 no bundled skills found \u2014 skipped");return}const r=import_node_fs28.default.readdirSync(e,{withFileTypes:true}).filter(i=>i.isDirectory()&&import_node_fs28.default.existsSync(import_node_path30.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_path30.default.join(e,i.name);const s=import_node_path30.default.join(n,".claude","skills",i.name);copyDir(o,s);t.push(`installed the ${i.name} skill \u2192 ${rel(import_node_path30.default.join(s,"SKILL.md"),n)}`)}}function copyDir(e,n){import_node_fs28.default.mkdirSync(n,{recursive:true});for(const t of import_node_fs28.default.readdirSync(e,{withFileTypes:true})){const r=import_node_path30.default.join(e,t.name);const i=import_node_path30.default.join(n,t.name);if(t.isDirectory())copyDir(r,i);else import_node_fs28.default.copyFileSync(r,i)}}function rel(e,n){const t=import_node_path30.default.relative(n,e);return t&&!t.startsWith("..")?t:e}
1190
+ `;function appendDebuggingGuide(e,n,t){let r="";if(import_node_fs31.default.existsSync(e)){try{r=import_node_fs31.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_fs31.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_fs31.default.existsSync(e)){t.push("\u26A0 no bundled skills found \u2014 skipped");return}const r=import_node_fs31.default.readdirSync(e,{withFileTypes:true}).filter(i=>i.isDirectory()&&import_node_fs31.default.existsSync(import_node_path34.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_path34.default.join(e,i.name);const s=import_node_path34.default.join(n,".claude","skills",i.name);copyDir(o,s);t.push(`installed the ${i.name} skill \u2192 ${rel(import_node_path34.default.join(s,"SKILL.md"),n)}`)}}function copyDir(e,n){import_node_fs31.default.mkdirSync(n,{recursive:true});for(const t of import_node_fs31.default.readdirSync(e,{withFileTypes:true})){const r=import_node_path34.default.join(e,t.name);const i=import_node_path34.default.join(n,t.name);if(t.isDirectory())copyDir(r,i);else import_node_fs31.default.copyFileSync(r,i)}}function rel(e,n){const t=import_node_path34.default.relative(n,e);return t&&!t.startsWith("..")?t:e}