@buoy-gg/mcp 7.0.61 → 7.0.62

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.
@@ -1,4 +1,4 @@
1
- import{createRequire as x}from"module";const B=x(import.meta.url);import{PACKAGE_NAME as l,VERSION as y}from"./chunk-CRYV6OHD.mjs";import{spawnSync as p}from"child_process";import i from"fs";import _ from"os";import a from"path";function h(){return{BUOY_VERIFY:"auto"}}var v="https://registry.npmjs.org";var m=3e3;function j(e={}){const t=e.cwd??process.cwd();const r=e.skillSrcDir??a.resolve(__dirname,"../skill");const n=e.log??(c=>process.stdout.write(c+"\n"));const o=E(e,n);const s=[];f(a.join(t,".mcp.json"),"mcpServers",o,t,s);i.mkdirSync(a.join(t,".cursor"),{recursive:true});f(a.join(t,".cursor","mcp.json"),"mcpServers",o,t,s);if(i.existsSync(a.join(t,".vscode"))){f(a.join(t,".vscode","mcp.json"),"servers",o,t,s)}F(r,t,s);k(a.join(t,"CLAUDE.md"),t,s);k(a.join(t,"AGENTS.md"),t,s);n("Buoy MCP configuration written:");for(const c of s)n(" \u2022 "+c);n("");n("Next steps:");n(" 1. Restart your editor (or reconnect the MCP server) to load `buoy`.");n(" 2. Complete account setup, then open an app with the required Buoy tools and sync integration.");n(" 3. Confirm the device and tools are available. MCP data/action access requires Pro.");if(o.command==="npx"){n("");n(`The editor launches the server with \`npx -y ${l}@latest\`, so it stays`);n(`Registry access may be needed. Re-run \`npx -y ${l}@latest init\` to refresh configuration.`)}else if(!e.cliPath){n("");n(`This uses a pinned local install (no network on startup). To update it later,`);n(`To update the local package, run: npx -y ${o.args[0]?.replace(/dist[/\\]cli\.js$/,"")??""}@latest init --local`)}}function E(e,t){if(e.cliPath){return{type:"stdio",command:"node",args:[e.cliPath],env:h()}}const r=e.mode??"auto";if(r==="npx"){return g()}if(r==="local"){return b(e,t)}const n=C();if(n.reachable){return g()}t(`\u26A0 npm registry ${n.registry?`(${n.registry}) `:""}looks unreachable \u2014 \`npx @latest\` would hang your editor at startup. Falling back to a pinned local install.`);return b(e,t)}function g(){return{type:"stdio",command:"npx",args:["-y",`${l}@latest`],env:h()}}function b(e,t){const r=e.installDir??process.env.BUOY_MCP_HOME??a.join(_.homedir(),".buoy-mcp");const n=e.registry??v;const o=A(r,n,t);if(o){return{type:"stdio",command:"node",args:[o],env:h()}}t("\u26A0 local install failed \u2014 writing the npx entry instead (see the error above).");return g()}function A(e,t,r){const n=`${l}@${y==="0.0.0-dev"?"latest":y}`;i.mkdirSync(e,{recursive:true});const o=process.platform==="win32"?"npm.cmd":"npm";r(`Installing ${n} into ${e} from ${t} \u2026`);const s=p(o,["install",n,"--prefix",e,"--registry",t,`--@buoy-gg:registry=${t}`,"--no-audit","--no-fund","--loglevel=error"],{stdio:["ignore","ignore","inherit"],encoding:"utf8"});if(s.status!==0){r(`\u26A0 npm install exited with code ${s.status??"?"}${s.error?` (${s.error.message})`:""}.`);return null}const c=a.join(e,"node_modules",l,"dist","cli.js");if(!i.existsSync(c)){r(`\u26A0 install finished but ${c} is missing.`);return null}return c}function C(){const e=P();if(!e)return{reachable:false,registry:null};if(/^https?:\/\/registry\.npmjs\.org\/?$/i.test(e)){return{reachable:true,registry:e}}return{reachable:R(e),registry:e}}function P(){const e=w("@buoy-gg:registry");if(e)return e;const t=w("registry");return t??v}function w(e){const t=process.platform==="win32"?"npm.cmd":"npm";const r=p(t,["config","get",e],{encoding:"utf8",timeout:m});if(r.status!==0||typeof r.stdout!=="string")return null;const n=r.stdout.trim();if(!n||n==="undefined"||n==="null")return null;return n}function R(e){const t=p(process.execPath,["-e",I,e,String(m)],{encoding:"utf8",timeout:m+2e3});return t.status===0}var I=`
1
+ import{createRequire as x}from"module";const B=x(import.meta.url);import{PACKAGE_NAME as l,VERSION as y}from"./chunk-ZPZBUGGW.mjs";import{spawnSync as p}from"child_process";import i from"fs";import _ from"os";import a from"path";function h(){return{BUOY_VERIFY:"auto"}}var v="https://registry.npmjs.org";var m=3e3;function j(e={}){const t=e.cwd??process.cwd();const r=e.skillSrcDir??a.resolve(__dirname,"../skill");const n=e.log??(c=>process.stdout.write(c+"\n"));const o=E(e,n);const s=[];f(a.join(t,".mcp.json"),"mcpServers",o,t,s);i.mkdirSync(a.join(t,".cursor"),{recursive:true});f(a.join(t,".cursor","mcp.json"),"mcpServers",o,t,s);if(i.existsSync(a.join(t,".vscode"))){f(a.join(t,".vscode","mcp.json"),"servers",o,t,s)}F(r,t,s);k(a.join(t,"CLAUDE.md"),t,s);k(a.join(t,"AGENTS.md"),t,s);n("Buoy MCP configuration written:");for(const c of s)n(" \u2022 "+c);n("");n("Next steps:");n(" 1. Restart your editor (or reconnect the MCP server) to load `buoy`.");n(" 2. Complete account setup, then open an app with the required Buoy tools and sync integration.");n(" 3. Confirm the device and tools are available. MCP data/action access requires Pro.");if(o.command==="npx"){n("");n(`The editor launches the server with \`npx -y ${l}@latest\`, so it stays`);n(`Registry access may be needed. Re-run \`npx -y ${l}@latest init\` to refresh configuration.`)}else if(!e.cliPath){n("");n(`This uses a pinned local install (no network on startup). To update it later,`);n(`To update the local package, run: npx -y ${o.args[0]?.replace(/dist[/\\]cli\.js$/,"")??""}@latest init --local`)}}function E(e,t){if(e.cliPath){return{type:"stdio",command:"node",args:[e.cliPath],env:h()}}const r=e.mode??"auto";if(r==="npx"){return g()}if(r==="local"){return b(e,t)}const n=C();if(n.reachable){return g()}t(`\u26A0 npm registry ${n.registry?`(${n.registry}) `:""}looks unreachable \u2014 \`npx @latest\` would hang your editor at startup. Falling back to a pinned local install.`);return b(e,t)}function g(){return{type:"stdio",command:"npx",args:["-y",`${l}@latest`],env:h()}}function b(e,t){const r=e.installDir??process.env.BUOY_MCP_HOME??a.join(_.homedir(),".buoy-mcp");const n=e.registry??v;const o=A(r,n,t);if(o){return{type:"stdio",command:"node",args:[o],env:h()}}t("\u26A0 local install failed \u2014 writing the npx entry instead (see the error above).");return g()}function A(e,t,r){const n=`${l}@${y==="0.0.0-dev"?"latest":y}`;i.mkdirSync(e,{recursive:true});const o=process.platform==="win32"?"npm.cmd":"npm";r(`Installing ${n} into ${e} from ${t} \u2026`);const s=p(o,["install",n,"--prefix",e,"--registry",t,`--@buoy-gg:registry=${t}`,"--no-audit","--no-fund","--loglevel=error"],{stdio:["ignore","ignore","inherit"],encoding:"utf8"});if(s.status!==0){r(`\u26A0 npm install exited with code ${s.status??"?"}${s.error?` (${s.error.message})`:""}.`);return null}const c=a.join(e,"node_modules",l,"dist","cli.js");if(!i.existsSync(c)){r(`\u26A0 install finished but ${c} is missing.`);return null}return c}function C(){const e=P();if(!e)return{reachable:false,registry:null};if(/^https?:\/\/registry\.npmjs\.org\/?$/i.test(e)){return{reachable:true,registry:e}}return{reachable:R(e),registry:e}}function P(){const e=w("@buoy-gg:registry");if(e)return e;const t=w("registry");return t??v}function w(e){const t=process.platform==="win32"?"npm.cmd":"npm";const r=p(t,["config","get",e],{encoding:"utf8",timeout:m});if(r.status!==0||typeof r.stdout!=="string")return null;const n=r.stdout.trim();if(!n||n==="undefined"||n==="null")return null;return n}function R(e){const t=p(process.execPath,["-e",I,e,String(m)],{encoding:"utf8",timeout:m+2e3});return t.status===0}var I=`
2
2
  const url = process.argv[1];
3
3
  const ms = Number(process.argv[2]) || 3000;
4
4
  const c = new AbortController();
@@ -1,5 +1,5 @@
1
1
  import{createRequire as vs}from"module";const wf=vs(import.meta.url);import{describeDevices as ys,describeDiagnosis as $s,describeInputs as ks,proRequired as _s,readEntitlement as Pn,run as _e}from"./chunk-6EOB4FHJ.mjs";import{GPU_RENDERER_JS as Ss,caseUrl as Hr,closeWithin as ct,formatWebBenchMarkdown as xs,isSoftwareGpu as Jr,loadChromium as Gr,runWebBench as Ts,shuffled as Is,snapRefreshRate as As,waitForHostLock as Kr,withDeadline as Vr}from"./chunk-OPHPYPJD.mjs";import{__commonJS as J,__require as ie,__toESM as Vt}from"./chunk-MTTWR4T7.mjs";var Yr=J({"../../node_modules/pngjs/lib/chunkstream.js"(e,n){"use strict";var t=ie("util");var r=ie("stream");var i=n.exports=function(){r.call(this);this._buffers=[];this._buffered=0;this._reads=[];this._paused=false;this._encoding="utf8";this.writable=true};t.inherits(i,r);i.prototype.read=function(o,a){this._reads.push({length:Math.abs(o),allowLess:o<0,func:a});process.nextTick(function(){this._process();if(this._paused&&this._reads&&this._reads.length>0){this._paused=false;this.emit("drain")}}.bind(this))};i.prototype.write=function(o,a){if(!this.writable){this.emit("error",new Error("Stream not writable"));return false}let s;if(Buffer.isBuffer(o)){s=o}else{s=Buffer.from(o,a||this._encoding)}this._buffers.push(s);this._buffered+=s.length;this._process();if(this._reads&&this._reads.length===0){this._paused=true}return this.writable&&!this._paused};i.prototype.end=function(o,a){if(o){this.write(o,a)}this.writable=false;if(!this._buffers){return}if(this._buffers.length===0){this._end()}else{this._buffers.push(null);this._process()}};i.prototype.destroySoon=i.prototype.end;i.prototype._end=function(){if(this._reads.length>0){this.emit("error",new Error("Unexpected end of input"))}this.destroy()};i.prototype.destroy=function(){if(!this._buffers){return}this.writable=false;this._reads=null;this._buffers=null;this.emit("close")};i.prototype._processReadAllowingLess=function(o){this._reads.shift();let a=this._buffers[0];if(a.length>o.length){this._buffered-=o.length;this._buffers[0]=a.slice(o.length);o.func.call(this,a.slice(0,o.length))}else{this._buffered-=a.length;this._buffers.shift();o.func.call(this,a)}};i.prototype._processRead=function(o){this._reads.shift();let a=0;let s=0;let c=Buffer.alloc(o.length);while(a<o.length){let l=this._buffers[s++];let d=Math.min(l.length,o.length-a);l.copy(c,a,0,d);a+=d;if(d!==l.length){this._buffers[--s]=l.slice(d)}}if(s>0){this._buffers.splice(0,s)}this._buffered-=o.length;o.func.call(this,c)};i.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let o=this._reads[0];if(o.allowLess){this._processReadAllowingLess(o)}else if(this._buffered>=o.length){this._processRead(o)}else{break}}if(this._buffers&&!this.writable){this._end()}}catch(o){this.emit("error",o)}}}});var Xr=J({"../../node_modules/pngjs/lib/interlace.js"(e){"use strict";var n=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];e.getImagePasses=function(t,r){let i=[];let o=t%8;let a=r%8;let s=(t-o)/8;let c=(r-a)/8;for(let l=0;l<n.length;l++){let d=n[l];let u=s*d.x.length;let h=c*d.y.length;for(let p=0;p<d.x.length;p++){if(d.x[p]<o){u++}else{break}}for(let p=0;p<d.y.length;p++){if(d.y[p]<a){h++}else{break}}if(u>0&&h>0){i.push({width:u,height:h,index:l})}}return i};e.getInterlaceIterator=function(t){return function(r,i,o){let a=r%n[o].x.length;let s=(r-a)/n[o].x.length*8+n[o].x[a];let c=i%n[o].y.length;let l=(i-c)/n[o].y.length*8+n[o].y[c];return s*4+l*t*4}}}});var Zr=J({"../../node_modules/pngjs/lib/paeth-predictor.js"(e,n){"use strict";n.exports=function t(r,i,o){let a=r+i-o;let s=Math.abs(a-r);let c=Math.abs(a-i);let l=Math.abs(a-o);if(s<=c&&s<=l){return r}if(c<=l){return i}return o}}});var Qr=J({"../../node_modules/pngjs/lib/filter-parse.js"(e,n){"use strict";var t=Xr();var r=Zr();function i(a,s,c){let l=a*s;if(c!==8){l=Math.ceil(l/(8/c))}return l}var o=n.exports=function(a,s){let c=a.width;let l=a.height;let d=a.interlace;let u=a.bpp;let h=a.depth;this.read=s.read;this.write=s.write;this.complete=s.complete;this._imageIndex=0;this._images=[];if(d){let p=t.getImagePasses(c,l);for(let m=0;m<p.length;m++){this._images.push({byteWidth:i(p[m].width,u,h),height:p[m].height,lineIndex:0})}}else{this._images.push({byteWidth:i(c,u,h),height:l,lineIndex:0})}if(h===8){this._xComparison=u}else if(h===16){this._xComparison=u*2}else{this._xComparison=1}};o.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};o.prototype._unFilterType1=function(a,s,c){let l=this._xComparison;let d=l-1;for(let u=0;u<c;u++){let h=a[1+u];let p=u>d?s[u-l]:0;s[u]=h+p}};o.prototype._unFilterType2=function(a,s,c){let l=this._lastLine;for(let d=0;d<c;d++){let u=a[1+d];let h=l?l[d]:0;s[d]=u+h}};o.prototype._unFilterType3=function(a,s,c){let l=this._xComparison;let d=l-1;let u=this._lastLine;for(let h=0;h<c;h++){let p=a[1+h];let m=u?u[h]:0;let g=h>d?s[h-l]:0;let w=Math.floor((g+m)/2);s[h]=p+w}};o.prototype._unFilterType4=function(a,s,c){let l=this._xComparison;let d=l-1;let u=this._lastLine;for(let h=0;h<c;h++){let p=a[1+h];let m=u?u[h]:0;let g=h>d?s[h-l]:0;let w=h>d&&u?u[h-l]:0;let f=r(g,m,w);s[h]=p+f}};o.prototype._reverseFilterLine=function(a){let s=a[0];let c;let l=this._images[this._imageIndex];let d=l.byteWidth;if(s===0){c=a.slice(1,d+1)}else{c=Buffer.alloc(d);switch(s){case 1:this._unFilterType1(a,c,d);break;case 2:this._unFilterType2(a,c,d);break;case 3:this._unFilterType3(a,c,d);break;case 4:this._unFilterType4(a,c,d);break;default:throw new Error("Unrecognised filter type - "+s)}}this.write(c);l.lineIndex++;if(l.lineIndex>=l.height){this._lastLine=null;this._imageIndex++;l=this._images[this._imageIndex]}else{this._lastLine=c}if(l){this.read(l.byteWidth+1,this._reverseFilterLine.bind(this))}else{this._lastLine=null;this.complete()}}}});var Ds=J({"../../node_modules/pngjs/lib/filter-parse-async.js"(e,n){"use strict";var t=ie("util");var r=Yr();var i=Qr();var o=n.exports=function(a){r.call(this);let s=[];let c=this;this._filter=new i(a,{read:this.read.bind(this),write:function(l){s.push(l)},complete:function(){c.emit("complete",Buffer.concat(s))}});this._filter.start()};t.inherits(o,r)}});var Tt=J({"../../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 ei=J({"../../node_modules/pngjs/lib/crc.js"(e,n){"use strict";var t=[];(function(){for(let i=0;i<256;i++){let o=i;for(let a=0;a<8;a++){if(o&1){o=3988292384^o>>>1}else{o=o>>>1}}t[i]=o}})();var r=n.exports=function(){this._crc=-1};r.prototype.write=function(i){for(let o=0;o<i.length;o++){this._crc=t[(this._crc^i[o])&255]^this._crc>>>8}return true};r.prototype.crc32=function(){return this._crc^-1};r.crc32=function(i){let o=-1;for(let a=0;a<i.length;a++){o=t[(o^i[a])&255]^o>>>8}return o^-1}}});var ti=J({"../../node_modules/pngjs/lib/parser.js"(e,n){"use strict";var t=Tt();var r=ei();var i=n.exports=function(o,a){this._options=o;o.checkCRC=o.checkCRC!==false;this._hasIHDR=false;this._hasIEND=false;this._emittedHeadersFinished=false;this._palette=[];this._colorType=0;this._chunks={};this._chunks[t.TYPE_IHDR]=this._handleIHDR.bind(this);this._chunks[t.TYPE_IEND]=this._handleIEND.bind(this);this._chunks[t.TYPE_IDAT]=this._handleIDAT.bind(this);this._chunks[t.TYPE_PLTE]=this._handlePLTE.bind(this);this._chunks[t.TYPE_tRNS]=this._handleTRNS.bind(this);this._chunks[t.TYPE_gAMA]=this._handleGAMA.bind(this);this.read=a.read;this.error=a.error;this.metadata=a.metadata;this.gamma=a.gamma;this.transColor=a.transColor;this.palette=a.palette;this.parsed=a.parsed;this.inflateData=a.inflateData;this.finished=a.finished;this.simpleTransparency=a.simpleTransparency;this.headersFinished=a.headersFinished||function(){}};i.prototype.start=function(){this.read(t.PNG_SIGNATURE.length,this._parseSignature.bind(this))};i.prototype._parseSignature=function(o){let a=t.PNG_SIGNATURE;for(let s=0;s<a.length;s++){if(o[s]!==a[s]){this.error(new Error("Invalid file signature"));return}}this.read(8,this._parseChunkBegin.bind(this))};i.prototype._parseChunkBegin=function(o){let a=o.readUInt32BE(0);let s=o.readUInt32BE(4);let c="";for(let d=4;d<8;d++){c+=String.fromCharCode(o[d])}let l=Boolean(o[4]&32);if(!this._hasIHDR&&s!==t.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}this._crc=new r;this._crc.write(Buffer.from(c));if(this._chunks[s]){return this._chunks[s](a)}if(!l){this.error(new Error("Unsupported critical chunk type "+c));return}this.read(a+4,this._skipChunk.bind(this))};i.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};i.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};i.prototype._parseChunkEnd=function(o){let a=o.readInt32BE(0);let s=this._crc.crc32();if(this._options.checkCRC&&s!==a){this.error(new Error("Crc error - "+a+" - "+s));return}if(!this._hasIEND){this.read(8,this._parseChunkBegin.bind(this))}};i.prototype._handleIHDR=function(o){this.read(o,this._parseIHDR.bind(this))};i.prototype._parseIHDR=function(o){this._crc.write(o);let a=o.readUInt32BE(0);let s=o.readUInt32BE(4);let c=o[8];let l=o[9];let d=o[10];let u=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(d!==0){this.error(new Error("Unsupported compression method"));return}if(u!==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:a,height:s,depth:c,interlace:Boolean(h),palette:Boolean(l&t.COLORTYPE_PALETTE),color:Boolean(l&t.COLORTYPE_COLOR),alpha:Boolean(l&t.COLORTYPE_ALPHA),bpp: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 a=Math.floor(o.length/3);for(let s=0;s<a;s++){this._palette.push([o[s*3],o[s*3+1],o[s*3+2],255])}this.palette(this._palette);this._handleChunkEnd()};i.prototype._handleTRNS=function(o){this.simpleTransparency();this.read(o,this._parseTRNS.bind(this))};i.prototype._parseTRNS=function(o){this._crc.write(o);if(this._colorType===t.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(o.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let a=0;a<o.length;a++){this._palette[a][3]=o[a]}this.palette(this._palette)}if(this._colorType===t.COLORTYPE_GRAYSCALE){this.transColor([o.readUInt16BE(0)])}if(this._colorType===t.COLORTYPE_COLOR){this.transColor([o.readUInt16BE(0),o.readUInt16BE(2),o.readUInt16BE(4)])}this._handleChunkEnd()};i.prototype._handleGAMA=function(o){this.read(o,this._parseGAMA.bind(this))};i.prototype._parseGAMA=function(o){this._crc.write(o);this.gamma(o.readUInt32BE(0)/t.GAMMA_DIVISION);this._handleChunkEnd()};i.prototype._handleIDAT=function(o){if(!this._emittedHeadersFinished){this._emittedHeadersFinished=true;this.headersFinished()}this.read(-o,this._parseIDAT.bind(this,o))};i.prototype._parseIDAT=function(o,a){this._crc.write(a);if(this._colorType===t.COLORTYPE_PALETTE_COLOR&&this._palette.length===0){throw new Error("Expected palette not found")}this.inflateData(a);let s=o-a.length;if(s>0){this._handleIDAT(s)}else{this._handleChunkEnd()}};i.prototype._handleIEND=function(o){this.read(o,this._parseIEND.bind(this))};i.prototype._parseIEND=function(o){this._crc.write(o);this._hasIEND=true;this._handleChunkEnd();if(this.finished){this.finished()}}}});var ni=J({"../../node_modules/pngjs/lib/bitmapper.js"(e){"use strict";var n=Xr();var t=[function(){},function(s,c,l,d){if(d===c.length){throw new Error("Ran out of data")}let u=c[d];s[l]=u;s[l+1]=u;s[l+2]=u;s[l+3]=255},function(s,c,l,d){if(d+1>=c.length){throw new Error("Ran out of data")}let u=c[d];s[l]=u;s[l+1]=u;s[l+2]=u;s[l+3]=c[d+1]},function(s,c,l,d){if(d+2>=c.length){throw new Error("Ran out of data")}s[l]=c[d];s[l+1]=c[d+1];s[l+2]=c[d+2];s[l+3]=255},function(s,c,l,d){if(d+3>=c.length){throw new Error("Ran out of data")}s[l]=c[d];s[l+1]=c[d+1];s[l+2]=c[d+2];s[l+3]=c[d+3]}];var r=[function(){},function(s,c,l,d){let u=c[0];s[l]=u;s[l+1]=u;s[l+2]=u;s[l+3]=d},function(s,c,l){let d=c[0];s[l]=d;s[l+1]=d;s[l+2]=d;s[l+3]=c[1]},function(s,c,l,d){s[l]=c[0];s[l+1]=c[1];s[l+2]=c[2];s[l+3]=d},function(s,c,l){s[l]=c[0];s[l+1]=c[1];s[l+2]=c[2];s[l+3]=c[3]}];function i(s,c){let l=[];let d=0;function u(){if(d===s.length){throw new Error("Ran out of data")}let h=s[d];d++;let p,m,g,w,f,b,y,v;switch(c){default:throw new Error("unrecognised depth");case 16:y=s[d];d++;l.push((h<<8)+y);break;case 4:y=h&15;v=h>>4;l.push(v,y);break;case 2:f=h&3;b=h>>2&3;y=h>>4&3;v=h>>6&3;l.push(v,y,b,f);break;case 1:p=h&1;m=h>>1&1;g=h>>2&1;w=h>>3&1;f=h>>4&1;b=h>>5&1;y=h>>6&1;v=h>>7&1;l.push(v,y,b,f,w,g,m,p);break}}return{get:function(h){while(l.length<h){u()}let p=l.slice(0,h);l=l.slice(h);return p},resetAfterLine:function(){l.length=0},end:function(){if(d!==s.length){throw new Error("extra data found")}}}}function o(s,c,l,d,u,h){let p=s.width;let m=s.height;let g=s.index;for(let w=0;w<m;w++){for(let f=0;f<p;f++){let b=l(f,w,g);t[d](c,u,b,h);h+=d}}return h}function a(s,c,l,d,u,h){let p=s.width;let m=s.height;let g=s.index;for(let w=0;w<m;w++){for(let f=0;f<p;f++){let b=u.get(d);let y=l(f,w,g);r[d](c,b,y,h)}u.resetAfterLine()}}e.dataToBitMap=function(s,c){let l=c.width;let d=c.height;let u=c.depth;let h=c.bpp;let p=c.interlace;let m;if(u!==8){m=i(s,u)}let g;if(u<=8){g=Buffer.alloc(l*d*4)}else{g=new Uint16Array(l*d*4)}let w=Math.pow(2,u)-1;let f=0;let b;let y;if(p){b=n.getImagePasses(l,d);y=n.getInterlaceIterator(l,d)}else{let v=0;y=function(){let $=v;v+=4;return $};b=[{width:l,height:d}]}for(let v=0;v<b.length;v++){if(u===8){f=o(b[v],g,y,h,s,f)}else{a(b[v],g,y,h,m,w)}}if(u===8){if(f!==s.length){throw new Error("extra data found")}}else{m.end()}return g}}});var ri=J({"../../node_modules/pngjs/lib/format-normaliser.js"(e,n){"use strict";function t(o,a,s,c,l){let d=0;for(let u=0;u<c;u++){for(let h=0;h<s;h++){let p=l[o[d]];if(!p){throw new Error("index "+o[d]+" not in palette")}for(let m=0;m<4;m++){a[d+m]=p[m]}d+=4}}}function r(o,a,s,c,l){let d=0;for(let u=0;u<c;u++){for(let h=0;h<s;h++){let p=false;if(l.length===1){if(l[0]===o[d]){p=true}}else if(l[0]===o[d]&&l[1]===o[d+1]&&l[2]===o[d+2]){p=true}if(p){for(let m=0;m<4;m++){a[d+m]=0}}d+=4}}}function i(o,a,s,c,l){let d=255;let u=Math.pow(2,l)-1;let h=0;for(let p=0;p<c;p++){for(let m=0;m<s;m++){for(let g=0;g<4;g++){a[h+g]=Math.floor(o[h+g]*d/u+.5)}h+=4}}}n.exports=function(o,a,s=false){let c=a.depth;let l=a.width;let d=a.height;let u=a.colorType;let h=a.transColor;let p=a.palette;let m=o;if(u===3){t(o,m,l,d,p)}else{if(h){r(o,m,l,d,h)}if(c!==8&&!s){if(c===16){m=Buffer.alloc(l*d*4)}i(o,m,l,d,c)}}return m}}});var Ms=J({"../../node_modules/pngjs/lib/parser-async.js"(e,n){"use strict";var t=ie("util");var r=ie("zlib");var i=Yr();var o=Ds();var a=ti();var s=ni();var c=ri();var l=n.exports=function(d){i.call(this);this._parser=new a(d,{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=d;this.writable=true;this._parser.start()};t.inherits(l,i);l.prototype._handleError=function(d){this.emit("error",d);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(d){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 u=(this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1;let h=u*this._bitmapInfo.height;let p=Math.max(h,r.Z_MIN_CHUNK);this._inflate=r.createInflate({chunkSize:p});let m=h;let g=this.emit.bind(this,"error");this._inflate.on("error",function(f){if(!m){return}g(f)});this._filter.on("complete",this._complete.bind(this));let w=this._filter.write.bind(this._filter);this._inflate.on("data",function(f){if(!m){return}if(f.length>m){f=f.slice(0,m)}m-=f.length;w(f)});this._inflate.on("end",this._filter.end.bind(this._filter))}}this._inflate.write(d)};l.prototype._handleMetaData=function(d){this._metaData=d;this._bitmapInfo=Object.create(d);this._filter=new o(this._bitmapInfo)};l.prototype._handleTransColor=function(d){this._bitmapInfo.transColor=d};l.prototype._handlePalette=function(d){this._bitmapInfo.palette=d};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(d){if(this.errord){return}let u;try{let h=s.dataToBitMap(d,this._bitmapInfo);u=c(h,this._bitmapInfo,this._options.skipRescale);h=null}catch(h){this._handleError(h);return}this.emit("parsed",u)}}});var Cs=J({"../../node_modules/pngjs/lib/bitpacker.js"(e,n){"use strict";var t=Tt();n.exports=function(r,i,o,a){let s=[t.COLORTYPE_COLOR_ALPHA,t.COLORTYPE_ALPHA].indexOf(a.colorType)!==-1;if(a.colorType===a.inputColorType){let f=(function(){let b=new ArrayBuffer(2);new DataView(b).setInt16(0,256,true);return new Int16Array(b)[0]!==256})();if(a.bitDepth===8||a.bitDepth===16&&f){return r}}let c=a.bitDepth!==16?r:new Uint16Array(r.buffer);let l=255;let d=t.COLORTYPE_TO_BPP_MAP[a.inputColorType];if(d===4&&!a.inputHasAlpha){d=3}let u=t.COLORTYPE_TO_BPP_MAP[a.colorType];if(a.bitDepth===16){l=65535;u*=2}let h=Buffer.alloc(i*o*u);let p=0;let m=0;let g=a.bgColor||{};if(g.red===void 0){g.red=l}if(g.green===void 0){g.green=l}if(g.blue===void 0){g.blue=l}function w(){let f;let b;let y;let v=l;switch(a.inputColorType){case t.COLORTYPE_COLOR_ALPHA:v=c[p+3];f=c[p];b=c[p+1];y=c[p+2];break;case t.COLORTYPE_COLOR:f=c[p];b=c[p+1];y=c[p+2];break;case t.COLORTYPE_ALPHA:v=c[p+1];f=c[p];b=f;y=f;break;case t.COLORTYPE_GRAYSCALE:f=c[p];b=f;y=f;break;default:throw new Error("input color type:"+a.inputColorType+" is not supported at present")}if(a.inputHasAlpha){if(!s){v/=l;f=Math.min(Math.max(Math.round((1-v)*g.red+v*f),0),l);b=Math.min(Math.max(Math.round((1-v)*g.green+v*b),0),l);y=Math.min(Math.max(Math.round((1-v)*g.blue+v*y),0),l)}}return{red:f,green:b,blue:y,alpha:v}}for(let f=0;f<o;f++){for(let b=0;b<i;b++){let y=w(c,p);switch(a.colorType){case t.COLORTYPE_COLOR_ALPHA:case t.COLORTYPE_COLOR:if(a.bitDepth===8){h[m]=y.red;h[m+1]=y.green;h[m+2]=y.blue;if(s){h[m+3]=y.alpha}}else{h.writeUInt16BE(y.red,m);h.writeUInt16BE(y.green,m+2);h.writeUInt16BE(y.blue,m+4);if(s){h.writeUInt16BE(y.alpha,m+6)}}break;case t.COLORTYPE_ALPHA:case t.COLORTYPE_GRAYSCALE:{let v=(y.red+y.green+y.blue)/3;if(a.bitDepth===8){h[m]=v;if(s){h[m+1]=y.alpha}}else{h.writeUInt16BE(v,m);if(s){h.writeUInt16BE(y.alpha,m+2)}}break}default:throw new Error("unrecognised color Type "+a.colorType)}p+=d;m+=u}}return h}}});var Es=J({"../../node_modules/pngjs/lib/filter-pack.js"(e,n){"use strict";var t=Zr();function r(g,w,f,b,y){for(let v=0;v<f;v++){b[y+v]=g[w+v]}}function i(g,w,f){let b=0;let y=w+f;for(let v=w;v<y;v++){b+=Math.abs(g[v])}return b}function o(g,w,f,b,y,v){for(let $=0;$<f;$++){let _=$>=v?g[w+$-v]:0;let S=g[w+$]-_;b[y+$]=S}}function a(g,w,f,b){let y=0;for(let v=0;v<f;v++){let $=v>=b?g[w+v-b]:0;let _=g[w+v]-$;y+=Math.abs(_)}return y}function s(g,w,f,b,y){for(let v=0;v<f;v++){let $=w>0?g[w+v-f]:0;let _=g[w+v]-$;b[y+v]=_}}function c(g,w,f){let b=0;let y=w+f;for(let v=w;v<y;v++){let $=w>0?g[v-f]:0;let _=g[v]-$;b+=Math.abs(_)}return b}function l(g,w,f,b,y,v){for(let $=0;$<f;$++){let _=$>=v?g[w+$-v]:0;let S=w>0?g[w+$-f]:0;let A=g[w+$]-(_+S>>1);b[y+$]=A}}function d(g,w,f,b){let y=0;for(let v=0;v<f;v++){let $=v>=b?g[w+v-b]:0;let _=w>0?g[w+v-f]:0;let S=g[w+v]-($+_>>1);y+=Math.abs(S)}return y}function u(g,w,f,b,y,v){for(let $=0;$<f;$++){let _=$>=v?g[w+$-v]:0;let S=w>0?g[w+$-f]:0;let A=w>0&&$>=v?g[w+$-(f+v)]:0;let M=g[w+$]-t(_,S,A);b[y+$]=M}}function h(g,w,f,b){let y=0;for(let v=0;v<f;v++){let $=v>=b?g[w+v-b]:0;let _=w>0?g[w+v-f]:0;let S=w>0&&v>=b?g[w+v-(f+b)]:0;let A=g[w+v]-t($,_,S);y+=Math.abs(A)}return y}var p={0:r,1:o,2:s,3:l,4:u};var m={0:i,1:a,2:c,3:d,4:h};n.exports=function(g,w,f,b,y){let v;if(!("filterType"in b)||b.filterType===-1){v=[0,1,2,3,4]}else if(typeof b.filterType==="number"){v=[b.filterType]}else{throw new Error("unrecognised filter types")}if(b.bitDepth===16){y*=2}let $=w*y;let _=0;let S=0;let A=Buffer.alloc(($+1)*f);let M=v[0];for(let E=0;E<f;E++){if(v.length>1){let W=Infinity;for(let D=0;D<v.length;D++){let C=m[v[D]](g,S,$,y);if(C<W){M=v[D];W=C}}}A[_]=M;_++;p[M](g,S,$,A,_,y);_+=$;S+=$}return A}}});var ii=J({"../../node_modules/pngjs/lib/packer.js"(e,n){"use strict";var t=Tt();var r=ei();var i=Cs();var o=Es();var a=ie("zlib");var s=n.exports=function(c){this._options=c;c.deflateChunkSize=c.deflateChunkSize||32*1024;c.deflateLevel=c.deflateLevel!=null?c.deflateLevel:9;c.deflateStrategy=c.deflateStrategy!=null?c.deflateStrategy:3;c.inputHasAlpha=c.inputHasAlpha!=null?c.inputHasAlpha:true;c.deflateFactory=c.deflateFactory||a.createDeflate;c.bitDepth=c.bitDepth||8;c.colorType=typeof c.colorType==="number"?c.colorType:t.COLORTYPE_COLOR_ALPHA;c.inputColorType=typeof c.inputColorType==="number"?c.inputColorType:t.COLORTYPE_COLOR_ALPHA;if([t.COLORTYPE_GRAYSCALE,t.COLORTYPE_COLOR,t.COLORTYPE_COLOR_ALPHA,t.COLORTYPE_ALPHA].indexOf(c.colorType)===-1){throw new Error("option color type:"+c.colorType+" is not supported at present")}if([t.COLORTYPE_GRAYSCALE,t.COLORTYPE_COLOR,t.COLORTYPE_COLOR_ALPHA,t.COLORTYPE_ALPHA].indexOf(c.inputColorType)===-1){throw new Error("option input color type:"+c.inputColorType+" is not supported at present")}if(c.bitDepth!==8&&c.bitDepth!==16){throw new Error("option bit depth:"+c.bitDepth+" is not supported at present")}};s.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};s.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};s.prototype.filterData=function(c,l,d){let u=i(c,l,d,this._options);let h=t.COLORTYPE_TO_BPP_MAP[this._options.colorType];let p=o(u,l,d,this._options,h);return p};s.prototype._packChunk=function(c,l){let d=l?l.length:0;let u=Buffer.alloc(d+12);u.writeUInt32BE(d,0);u.writeUInt32BE(c,4);if(l){l.copy(u,8)}u.writeInt32BE(r.crc32(u.slice(4,u.length-4)),u.length-4);return u};s.prototype.packGAMA=function(c){let l=Buffer.alloc(4);l.writeUInt32BE(Math.floor(c*t.GAMMA_DIVISION),0);return this._packChunk(t.TYPE_gAMA,l)};s.prototype.packIHDR=function(c,l){let d=Buffer.alloc(13);d.writeUInt32BE(c,0);d.writeUInt32BE(l,4);d[8]=this._options.bitDepth;d[9]=this._options.colorType;d[10]=0;d[11]=0;d[12]=0;return this._packChunk(t.TYPE_IHDR,d)};s.prototype.packIDAT=function(c){return this._packChunk(t.TYPE_IDAT,c)};s.prototype.packIEND=function(){return this._packChunk(t.TYPE_IEND,null)}}});var Os=J({"../../node_modules/pngjs/lib/packer-async.js"(e,n){"use strict";var t=ie("util");var r=ie("stream");var i=Tt();var o=ii();var a=n.exports=function(s){r.call(this);let c=s||{};this._packer=new o(c);this._deflate=this._packer.createDeflate();this.readable=true};t.inherits(a,r);a.prototype.pack=function(s,c,l,d){this.emit("data",Buffer.from(i.PNG_SIGNATURE));this.emit("data",this._packer.packIHDR(c,l));if(d){this.emit("data",this._packer.packGAMA(d))}let u=this._packer.filterData(s,c,l);this._deflate.on("error",this.emit.bind(this,"error"));this._deflate.on("data",function(h){this.emit("data",this._packer.packIDAT(h))}.bind(this));this._deflate.on("end",function(){this.emit("data",this._packer.packIEND());this.emit("end")}.bind(this));this._deflate.end(u)}}});var Rs=J({"../../node_modules/pngjs/lib/sync-inflate.js"(e,n){"use strict";var t=ie("assert").ok;var r=ie("zlib");var i=ie("util");var o=ie("buffer").kMaxLength;function a(u){if(!(this instanceof a)){return new a(u)}if(u&&u.chunkSize<r.Z_MIN_CHUNK){u.chunkSize=r.Z_MIN_CHUNK}r.Inflate.call(this,u);this._offset=this._offset===void 0?this._outOffset:this._offset;this._buffer=this._buffer||this._outBuffer;if(u&&u.maxLength!=null){this._maxLength=u.maxLength}}function s(u){return new a(u)}function c(u,h){if(h){process.nextTick(h)}if(!u._handle){return}u._handle.close();u._handle=null}a.prototype._processChunk=function(u,h,p){if(typeof p==="function"){return r.Inflate._processChunk.call(this,u,h,p)}let m=this;let g=u&&u.length;let w=this._chunkSize-this._offset;let f=this._maxLength;let b=0;let y=[];let v=0;let $;this.on("error",function(M){$=M});function _(M,E){if(m._hadError){return}let W=w-E;t(W>=0,"have should not go down");if(W>0){let D=m._buffer.slice(m._offset,m._offset+W);m._offset+=W;if(D.length>f){D=D.slice(0,f)}y.push(D);v+=D.length;f-=D.length;if(f===0){return false}}if(E===0||m._offset>=m._chunkSize){w=m._chunkSize;m._offset=0;m._buffer=Buffer.allocUnsafe(m._chunkSize)}if(E===0){b+=g-M;g=M;return true}return false}t(this._handle,"zlib binding closed");let S;do{S=this._handle.writeSync(h,u,b,g,this._buffer,this._offset,w);S=S||this._writeState}while(!this._hadError&&_(S[0],S[1]));if(this._hadError){throw $}if(v>=o){c(this);throw new RangeError("Cannot create final Buffer. It would be larger than 0x"+o.toString(16)+" bytes")}let A=Buffer.concat(y,v);c(this);return A};i.inherits(a,r.Inflate);function l(u,h){if(typeof h==="string"){h=Buffer.from(h)}if(!(h instanceof Buffer)){throw new TypeError("Not a string or buffer")}let p=u._finishFlushFlag;if(p==null){p=r.Z_FINISH}return u._processChunk(h,p)}function d(u,h){return l(new a(h),u)}n.exports=e=d;e.Inflate=a;e.createInflate=s;e.inflateSync=d}});var oi=J({"../../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 Ps=J({"../../node_modules/pngjs/lib/filter-parse-sync.js"(e){"use strict";var n=oi();var t=Qr();e.process=function(r,i){let o=[];let a=new n(r);let s=new t(i,{read:a.read.bind(a),write:function(c){o.push(c)},complete:function(){}});s.start();a.process();return Buffer.concat(o)}}});var Fs=J({"../../node_modules/pngjs/lib/parser-sync.js"(e,n){"use strict";var t=true;var r=ie("zlib");var i=Rs();if(!r.deflateSync){t=false}var o=oi();var a=Ps();var s=ti();var c=ni();var l=ri();n.exports=function(d,u){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(I){h=I}let m;function g(I){m=I}function w(I){m.transColor=I}function f(I){m.palette=I}function b(){m.alpha=true}let y;function v(I){y=I}let $=[];function _(I){$.push(I)}let S=new o(d);let A=new s(u,{read:S.read.bind(S),error:p,metadata:g,gamma:v,palette:f,transColor:w,inflateData:_,simpleTransparency:b});A.start();S.process();if(h){throw h}let M=Buffer.concat($);$.length=0;let E;if(m.interlace){E=r.inflateSync(M)}else{let I=(m.width*m.bpp*m.depth+7>>3)+1;let N=I*m.height;E=i(M,{chunkSize:N,maxLength:N})}M=null;if(!E||!E.length){throw new Error("bad png - invalid inflate data response")}let W=a.process(E,m);M=null;let D=c.dataToBitMap(W,m);W=null;let C=l(D,m,u.skipRescale);m.data=C;m.gamma=y||0;return m}}});var Bs=J({"../../node_modules/pngjs/lib/packer-sync.js"(e,n){"use strict";var t=true;var r=ie("zlib");if(!r.deflateSync){t=false}var i=Tt();var o=ii();n.exports=function(a,s){if(!t){throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0")}let c=s||{};let l=new o(c);let d=[];d.push(Buffer.from(i.PNG_SIGNATURE));d.push(l.packIHDR(a.width,a.height));if(a.gamma){d.push(l.packGAMA(a.gamma))}let u=l.filterData(a.data,a.width,a.height);let h=r.deflateSync(u,l.getDeflateOptions());u=null;if(!h||!h.length){throw new Error("bad png - invalid compressed data response")}d.push(l.packIDAT(h));d.push(l.packIEND());return Buffer.concat(d)}}});var Ns=J({"../../node_modules/pngjs/lib/png-sync.js"(e){"use strict";var n=Fs();var t=Bs();e.read=function(r,i){return n(r,i||{})};e.write=function(r,i){return t(r,i)}}});var Yt=J({"../../node_modules/pngjs/lib/png.js"(e){"use strict";var n=ie("util");var t=ie("stream");var r=Ms();var i=Os();var o=Ns();var a=e.PNG=function(s){t.call(this);s=s||{};this.width=s.width|0;this.height=s.height|0;this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null;if(s.fill&&this.data){this.data.fill(0)}this.gamma=0;this.readable=this.writable=true;this._parser=new r(s);this._parser.on("error",this.emit.bind(this,"error"));this._parser.on("close",this._handleClose.bind(this));this._parser.on("metadata",this._metadata.bind(this));this._parser.on("gamma",this._gamma.bind(this));this._parser.on("parsed",function(c){this.data=c;this.emit("parsed",c)}.bind(this));this._packer=new i(s);this._packer.on("data",this.emit.bind(this,"data"));this._packer.on("end",this.emit.bind(this,"end"));this._parser.on("close",this._handleClose.bind(this));this._packer.on("error",this.emit.bind(this,"error"))};n.inherits(a,t);a.sync=o;a.prototype.pack=function(){if(!this.data||!this.data.length){this.emit("error","No data provided");return this}process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this));return this};a.prototype.parse=function(s,c){if(c){let l,d;l=function(u){this.removeListener("error",d);this.data=u;c(null,this)}.bind(this);d=function(u){this.removeListener("parsed",l);c(u,null)}.bind(this);this.once("parsed",l);this.once("error",d)}this.end(s);return this};a.prototype.write=function(s){this._parser.write(s);return true};a.prototype.end=function(s){this._parser.end(s)};a.prototype._metadata=function(s){this.width=s.width;this.height=s.height;this.emit("metadata",s)};a.prototype._gamma=function(s){this.gamma=s};a.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable){this.emit("close")}};a.bitblt=function(s,c,l,d,u,h,p,m){l|=0;d|=0;u|=0;h|=0;p|=0;m|=0;if(l>s.width||d>s.height||l+u>s.width||d+h>s.height){throw new Error("bitblt reading outside image")}if(p>c.width||m>c.height||p+u>c.width||m+h>c.height){throw new Error("bitblt writing outside image")}for(let g=0;g<h;g++){s.data.copy(c.data,(m+g)*c.width+p<<2,(d+g)*s.width+l<<2,(d+g)*s.width+l+u<<2)}};a.prototype.bitblt=function(s,c,l,d,u,h,p){a.bitblt(this,s,c,l,d,u,h,p);return this};a.adjustGamma=function(s){if(s.gamma){for(let c=0;c<s.height;c++){for(let l=0;l<s.width;l++){let d=s.width*c+l<<2;for(let u=0;u<3;u++){let h=s.data[d+u]/255;h=Math.pow(h,1/2.2/s.gamma);s.data[d+u]=Math.round(h*255)}}}s.gamma=0}};a.prototype.adjustGamma=function(){a.adjustGamma(this)}}});import{DEFAULT_BROKER_PORT as js}from"@buoy-gg/sync-broker";var Fn=js;var ai=`http://localhost:${Fn}`;var si=15e3;var Bn=2500;var Ls=1200;var ci=2e4;var qs=3e4;var li=5e3;var Us=15*6e4;var Nn="Dashboard";var ve="All";import{readFileSync as di,writeFileSync as zs,mkdirSync as Ws,renameSync as Hs,unlinkSync as Js}from"fs";import{dirname as Gs,join as ui,resolve as Ks}from"path";import{homedir as Vs}from"os";import{createHash as Ys}from"crypto";import{validateLicense as Xs,isAcceptedValidation as Zs,isTransientLicenseError as Qs,resolveTier as ec,isRecognizedAccount as tc,isBuoyToken as nc,verifyFreeToken as rc,resolveAccountAccess as ic,signCache as Xt,verifyCacheSignature as oc,LICENSE_LAUNCH_VALIDATION_TTL as hi,LICENSE_REVALIDATION_INTERVAL as Ke,LICENSE_TRANSIENT_RETRY_DELAYS as pi,KEYGEN_CONFIG as ac,createNodeSession as sc,CLI_AUDIENCE as cc,exchangeServiceKey as lc,isServiceKey as dc,normalizeLicenseKey as fi,checkDevToken as uc,isDevToken as hc}from"@buoy-gg/license/headless";var mi=["BUOY_LICENSE_KEY","BUOY_KEY","EXPO_PUBLIC_BUOY_KEY","VITE_BUOY_KEY","NEXT_PUBLIC_BUOY_KEY","REACT_APP_BUOY_KEY"];function jn(e,n=process.env){for(const t of mi)if(n[t]!==void 0)return fi(n[t])||null;for(const t of[".env.development.local",".env.local",".env"]){let r;try{r=di(ui(e,t),"utf8")}catch{continue}const i=new Map;for(const o of r.split(/\r?\n/)){const a=o.match(/^\s*(?:export\s+)?([A-Z_][A-Z_0-9]*)\s*=\s*(.*)$/);if(!a)continue;const s=a[2].trim();const c=s.match(/^(['"])(.*?)\1\s*(?:#.*)?$/);i.set(a[1],c?c[2]:s.split("#")[0].trim())}for(const o of mi)if(i.has(o))return fi(i.get(o))||null}return null}var pc=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=Ks(n.projectDir??process.env.BUOY_PROJECT_DIR??process.cwd());const t=Ys("sha256").update(this.projectDir).digest("hex").slice(0,20);this.cacheFile=n.cacheFile??ui(Vs(),".buoy",`account-${t}.json`);this.session=n.session!==void 0?n.session:sc({audience:cc,openBrowser:()=>{throw new Error("The MCP does not open a browser. Run `npx buoy login`.")}})}hasKeyAccess(){return ic({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(di(this.cacheFile,"utf8"));if(e.valid&&oc(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=jn(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<hi&&this.nextCheck===0){this.nextCheck=this.cache.lastValidatedAt+hi;return}this.busy=true;const n=this.generation;try{if(hc(e)){const s=uc(e);if(!s.ok){this.cache=null;this.removeCache()}else{const c=Math.min(Date.now(),s.claims.iat*1e3);const l=s.claims.tier==="free"?"free":"pro";this.cache=Xt({licenseKey:e,licenseId:`dev:${s.claims.sid}`,valid:true,tier:l,isPro:l==="pro",expiresAt:new Date(s.claims.exp*1e3).toISOString(),cachedAt:c,lastValidatedAt:Date.now()});this.persistCache()}this.nextCheck=Date.now()+Ke;return}if(dc(e)){const s=await lc(e,{origin:process.env.BUOY_SITE_URL||"https://buoy.gg"});if(n!==this.generation||jn(this.projectDir)!==e)return;if(!s.ok){if(s.reason==="rejected"){this.cache=null;this.removeCache();this.nextCheck=Date.now()+Ke}else{this.nextCheck=Date.now()+(pi[this.retry++]??Ke)}return}const c=Date.now();const l=s.claims.exp*1e3;this.cache=Xt({licenseKey:e,licenseId:`service:${s.claims.sid}`,valid:true,tier:"pro",isPro:true,expiresAt:new Date(l).toISOString(),cachedAt:c,lastValidatedAt:c});this.persistCache();this.retry=0;this.nextCheck=Math.max(c+6e4,l-60*60*1e3);return}if(nc(e)){const s=rc(e);if(!s){this.cache=null;this.removeCache()}else{const c=Date.now();this.cache=Xt({licenseKey:e,licenseId:`token:${s.accountHash}`,valid:true,tier:"free",isPro:false,expiresAt:null,cachedAt:c,lastValidatedAt:c});this.persistCache()}this.nextCheck=Date.now()+Ke;return}const t=await Xs(e);if(n!==this.generation||jn(this.projectDir)!==e)return;const r=t.data?.relationships?.product?.data?.id;const i=t.meta.code==="EXPIRED"&&(tc(t.data)||this.cache?.licenseKey===e);if(r&&r!==ac.productId||!i&&!Zs(t)){this.cache=null;this.removeCache();this.nextCheck=Date.now()+Ke;return}const o=i?"free":ec(t.data);const a=Date.now();this.cache=Xt({licenseKey:e,licenseId:t.data?.id??"",valid:true,tier:o,isPro:o==="pro",expiresAt:i?null:t.data.attributes.expiry,cachedAt:a,lastValidatedAt:a});this.persistCache();this.retry=0;this.nextCheck=a+Ke}catch(t){if(n!==this.generation)return;const r=Qs(t)?pi[this.retry++]:void 0;this.nextCheck=Date.now()+(r??Ke)}finally{this.busy=false;this.notify()}}persistCache(){try{Ws(Gs(this.cacheFile),{recursive:true,mode:448});zs(`${this.cacheFile}.tmp`,JSON.stringify(this.cache),{mode:384});Hs(`${this.cacheFile}.tmp`,this.cacheFile)}catch{}}removeCache(){try{Js(this.cacheFile)}catch{}}};import fc from"http";import{randomUUID as mc}from"crypto";import{io as wc}from"socket.io-client";import{createBroker as gc,brokerTokenPath as Ln,readBrokerToken as bc,writeBrokerToken as vc,DASHBOARD_TOKEN_REQUIRED as yc}from"@buoy-gg/sync-broker";import{execFile as $c}from"child_process";import{promisify as kc}from"util";import je from"path";import _c from"os";var wi=kc($c);async function Sc(e){let n;try{n=new URL(e)}catch{return null}if(!xc(n.hostname))return null;const t=n.port||(n.protocol==="https:"?"443":"80");try{const{stdout:r}=await wi("lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"],{timeout:3e3});const i=r.split("\n").map(s=>s.trim()).find(Boolean);if(!i)return null;const{stdout:o}=await wi("lsof",["-a","-p",i,"-d","cwd","-Fn"],{timeout:3e3});const a=o.split("\n").find(s=>s.startsWith("n"));return a?je.resolve(a.slice(1)):null}catch{return null}}function xc(e,n=_c.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 gi(e,n){const t=je.resolve(n);const r=e.map(a=>({deviceId:a.deviceId,score:a.root?Tc(je.resolve(a.root),t):-1})).filter(a=>a.score>=0);if(r.length===0)return null;const i=Math.min(...r.map(a=>a.score));const o=r.filter(a=>a.score===i);return o.length===1?o[0].deviceId:null}function Tc(e,n){if(e===n)return 0;const t=je.relative(e,n);const r=je.relative(n,e);const i=o=>o&&!o.startsWith("..")&&!je.isAbsolute(o);if(i(t))return t.split(je.sep).length;if(i(r))return r.split(je.sep).length;return-1}function Ic(e,n){return e==="app"&&(n==="ping"||n==="reloadApp")}function bi(e){return e>=2}function Ac(e){if(Ic(e.toolId,e.action)){return{timeoutMs:e.fullMs,usedFullBudget:false}}if(!bi(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 Dc(e){if(e.consecutiveTimeouts>=2)return true;if(e.lastOkAt>0&&e.now-e.lastOkAt>e.unresponsiveAfterMs){return true}return false}var It="Not ready:";var Mc=class{constructor(e={}){this.socket=null;this.admitted=false;this.createdAt=Date.now();this.lockedDevices=new Set;this.hostAccount=null;this.broker=null;this.capabilities=new Map;this.devices=[];this.sessionDevice=null;this.snapshots=new Map;this.watching=new Map;this.pendingActions=new Map;this.snapshotWaiters=new Map;this.snapshotAt=new Map;this.health=new Map;this.devServerOrigins=new Map;this.crashSeen=new Map;this.rootLookups=new Set;this.devServerRoots=new Map;this.originProbed=new Set;this.lastSeen=new Map;this.deviceConnections=new Map;this.port=e.port??Fn;this.url=e.url??(e.port?`http://localhost:${e.port}`:ai);this.actionTimeoutMs=e.actionTimeoutMs??si;this.log=e.log??(n=>process.stderr.write(`[buoy-mcp] ${n}
2
- `));this.autoSpawn=e.autoSpawnBroker??true}async start(){const e=await qn(this.url)||await qn(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 pc(()=>this.broker?.refreshAccess());this.hostAccount.start();let t=false;this.broker=gc({canUseDesktop:this.hostAccount.hasAccess,port:this.port,onError:r=>{if(r.code==="EADDRINUSE")t=true;this.log(`broker error: ${r.code??r.message}`)}});await Cc(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{vc(this.broker.dashboardToken,Ln(this.port))}catch(r){this.log(`could not write the broker token file: ${r.message}`)}n="spawned"}else{this.log(`found a running broker at ${this.url} \u2014 connecting as a dashboard`)}await this.connectSocket();return n}connectSocket(){return new Promise((e,n)=>{const t=wc(this.url,{transports:["websocket"],query:{deviceName:Nn},auth:s=>{const c=this.broker?.dashboardToken??bc(Ln(this.port));s(c?{dashboardToken:c}:{})},reconnection:true,reconnectionDelay:500,timeout:4e3});this.socket=t;let r=false;const i=()=>{if(r)return;r=true;this.log("connected to broker");e()};const o=setTimeout(()=>{if(r)return;r=true;n(new Error("Broker account is locked or the broker needs an update. Sign in to Buoy Desktop or run npx buoy login for standalone MCP."))},5e3);t.on("buoy:access",s=>{const c=!!s&&typeof s==="object"&&s.protocol===1&&s.ready===true;this.setAdmission(c);if(c){clearTimeout(o);this.rearmWatches();i()}});t.on("connect",()=>{t.emit("buoy:access:request")});t.on("disconnect",()=>this.setAdmission(false,true));const a=s=>s.message===yc;t.once("connect_error",s=>{if(r)return;r=true;clearTimeout(o);n(new Error(a(s)?`The broker at ${this.url} refused this MCP as a dashboard: the token in ${Ln(this.port)} is missing or stale. Update Buoy Desktop, or restart it so it writes the file.`:`failed to connect to broker at ${this.url}: ${s.message}`))});t.on("connect_error",s=>{if(!a(s)||t.active)return;setTimeout(()=>{if(this.socket===t&&!t.connected)t.connect()},1e3).unref?.()});t.on("devtool-capabilities",s=>{if(!this.admitted||this.lockedDevices.has(s.persistentDeviceId))return;this.capabilities.set(s.persistentDeviceId,s);this.trackRootLookup(this.learnDevServerOrigin(s.persistentDeviceId));if(s.tools?.some(c=>c.toolId==="console"))this.ensureWatching("console",s.persistentDeviceId)});t.on("all-devices-update",s=>{if(!this.admitted)return;if(!Array.isArray(s))return;let c=false;for(const d of s){if(d.deviceId&&d.tier==="locked")this.lockDevice(String(d.deviceId));else if(d.deviceId&&(d.tier==="free"||d.tier==="pro")){c=this.lockedDevices.delete(String(d.deviceId))||c}}this.devices=s;const l=Date.now();for(const d of s)if(d.deviceId)this.lastSeen.set(d.deviceId,l);this.pruneStaleDevices();if(c)this.rearmWatches();else this.rearmReconnectedDevices(s)});t.on("devtool-sync",s=>{if(!this.admitted||this.lockedDevices.has(s.persistentDeviceId))return;const c=De(s.persistentDeviceId,s.toolId);this.snapshots.set(c,s.payload);this.snapshotAt.set(c,Date.now());if(s.toolId==="console")this.noteCrashReport(s.persistentDeviceId,s.payload);const l=this.snapshotWaiters.get(c);if(l&&l.length){this.snapshotWaiters.set(c,[]);for(const d of l)d(s.payload)}});t.on("devtool-action-result",s=>{if(!this.admitted)return;const c=this.pendingActions.get(s.requestId);if(!c)return;this.pendingActions.delete(s.requestId);clearTimeout(c.timer);c.resolve(s)})})}requireAdmission(){if(!this.admitted)throw new Error("A verified Buoy account and an updated broker are required. Sign in to Buoy Desktop, or run npx buoy login for standalone MCP.")}setAdmission(e,n=false){this.admitted=e;if(e)return;this.devices=[];this.lockedDevices.clear();this.capabilities.clear();this.snapshots.clear();this.snapshotAt.clear();this.devServerOrigins.clear();this.devServerRoots.clear();this.crashSeen.clear();this.originProbed.clear();this.health.clear();this.lastSeen.clear();if(!n)this.watching.clear();for(const t of this.pendingActions.values()){clearTimeout(t.timer);t.reject(new Error("Buoy account access ended while the action was pending."))}this.pendingActions.clear();for(const t of this.snapshotWaiters.values())for(const r of t)r(void 0);this.snapshotWaiters.clear();if(this.socket)this.socket.sendBuffer=[]}requireDeviceAccount(e){if(this.lockedDevices.has(e))throw new Error("The device's Buoy account access ended. Sign in and verify its key.")}lockDevice(e){this.lockedDevices.add(e);this.capabilities.delete(e);this.health.delete(e);this.devServerOrigins.delete(e);this.devServerRoots.delete(e);this.originProbed.delete(e);const n=`${e}::`;for(const t of this.snapshots.keys())if(t.startsWith(n)){this.snapshots.delete(t);this.snapshotAt.delete(t)}for(const[t,r]of this.snapshotWaiters)if(t.startsWith(n)){this.snapshotWaiters.delete(t);for(const i of r)i(void 0)}for(const[t,r]of this.pendingActions)if(r.target===e||r.target===ve){clearTimeout(r.timer);this.pendingActions.delete(t);r.reject(new Error("Device account access ended while the action was pending."))}}pruneStaleDevices(){const e=Date.now()-Us;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!==Nn&&e.deviceId).map(e=>{const n=this.capabilities.get(e.deviceId);return{deviceId:e.deviceId,deviceName:e.deviceName,platform:e.platform,isConnected:e.isConnected!==false,isPro:e.isPro===true,tier:e.tier==="free"||e.tier==="pro"?e.tier:e.tier===void 0&&e.isPro===true?"pro":"locked",collision:e.collision===true,tools:n?.tools??[]}})}connectedDevices(){return this.listDevices().filter(e=>e.isConnected)}toolActions(e){return this.listDevices().map(n=>{const t=n.tools.find(r=>r.toolId===e);return t?{deviceId:n.deviceId,deviceName:n.deviceName,actions:t.actions}:null}).filter(n=>n!==null)}resolveDevice(e){this.requireAdmission();if(e){this.requireDeviceAccount(e);return e}const n=(l,d)=>new Error(`${It} "${l}" (${d}) 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(d=>d.deviceId===this.sessionDevice);if(l&&l.isConnected!==false)return this.sessionDevice;throw n(this.sessionDevice,"the device this session was using")}const t=this.connectedDevices();const r=t.filter(l=>!this.lockedDevices.has(l.deviceId));const i=r.filter(l=>l.tools.length>0);const o=process.env.BUOY_PROJECT_ROOT||process.cwd();const a=gi(i.map(l=>({deviceId:l.deviceId,root:this.devServerRoots.get(l.deviceId)})),o);if(a)return this.sessionDevice=a;const s=gi(this.devices.filter(l=>l.deviceId&&l.isConnected===false&&!this.lockedDevices.has(l.deviceId)).map(l=>({deviceId:l.deviceId,root:this.devServerRoots.get(l.deviceId)})),o);if(s)throw n(s,"this project's app");if(r.length===0){if(t.length>0){throw new Error(`Devices are connected (${t.map(l=>l.deviceName).join(", ")}), but the broker has not admitted their accounts. Check app account validation and the account announcement after reconnect; this does not prove the user is signed out.`)}throw new Error("No devices are connected to the broker. Open the app with Buoy devtools running.")}if(r.length===1)return this.sessionDevice=r[0].deviceId;if(i.length===1)return this.sessionDevice=i[0].deviceId;if(i.length===0){const l=r.map(d=>d.deviceName).join(", ");throw new Error(`Connected devices (${l}) are not exposing any Buoy tools yet. Make sure the app is in the foreground with devtools mounted, then retry.`)}const c=i.map(l=>`${l.deviceName} (${l.deviceId})`).join(", ");throw new Error(`Multiple devices connected \u2014 specify deviceId. Connected: ${c}`)}requireProDevice(e){this.requireAdmission();if(e&&e!==ve)this.sessionDevice=e;const n=o=>{if(!o)return"";return o.tier==="locked"?` The broker has not confirmed account access for "${o.deviceName}"; a locked status does not establish whether a key is configured.`:` The connected app "${o.deviceName}" is on the ${o.tier} tier.`};const t=o=>`Buoy Pro is required to use the MCP.${n(o)} Enter a license in the app, or \u2014 if it runs headless (no on-device UI) \u2014 pass \`licenseKey\` to \`<FloatingDevTools />\`. Run \`list_devices\` to check status.`;if(e===ve){if(!this.connectedDevices().some(o=>o.isPro))throw new Error(t());return ve}const r=this.resolveDevice(e);const i=this.connectedDevices().find(o=>o.deviceId===r);if(!i?.isPro){const o=this.accessState(r);if(o==="offline")throw new Error(`${It} "${r}" is not connected right now. If the app is starting or reloading, it usually takes a few seconds. Run list_devices to check.`);if(o==="pending")throw new Error(`${It} account access for "${r}" is still being confirmed (the app just connected). Try again in a moment.`);throw new Error(t(i))}return r}accessState(e){const n=this.devices.find(t=>t.deviceId===e);if(!n||n.isConnected===false)return"offline";if(n.isPro===true)return"ready";return n.tier===void 0?"pending":"denied"}healthOf(e){let n=this.health.get(e);if(!n){n={consecutiveTimeouts:0,lastOkAt:0,lastFullBudgetAt:0};this.health.set(e,n)}return n}noteOk(e){const n=this.healthOf(e);n.consecutiveTimeouts=0;n.lastOkAt=Date.now()}noteTimeout(e){this.healthOf(e).consecutiveTimeouts+=1}isUnresponsive(e){return bi(this.healthOf(e).consecutiveTimeouts)}timeoutFor(e,n,t){const r=this.healthOf(e);const{timeoutMs:i,usedFullBudget:o}=Ac({consecutiveTimeouts:r.consecutiveTimeouts,lastFullBudgetAt:r.lastFullBudgetAt,now:Date.now(),fullMs:this.actionTimeoutMs,shortMs:Bn,recoveryProbeMs:ci,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=Dc({consecutiveTimeouts:n.consecutiveTimeouts,lastOkAt:n.lastOkAt,now:Date.now(),unresponsiveAfterMs:qs});const i=[`The app on "${e}" is not responding (${n.consecutiveTimeouts} call${n.consecutiveTimeouts===1?"":"s"} unanswered${t!=null?`, last answered ${t}s ago`:""}).`,r?"It is most likely CRASHED \u2014 a fatal render error unmounts the React tree, and the dev tools live in that tree, so nothing on-device can answer until the app is reloaded.":"It may be busy, mid-reload, or crashing."];const o=this.lastFatalFor(e);if(o)i.push(`Last captured error: ${o}`);i.push(o?"Read the crash state with get_console / get_storage (served from the last sync), then reload_app to recover.":"Try get_console (served from the last sync) for the app's last words, then reload_app to recover.");return i.join(" ")}noteCrashReport(e,n){const t=n?.entries;if(!Array.isArray(t)||t.length===0)return;const r=Math.max(...t.map(a=>typeof a?.timestamp==="number"?a.timestamp:-Infinity));const i=this.crashSeen.get(e)??new Set;let o=false;for(const a of t){const s=a?.fatal||/^\[(RENDER ERROR|FATAL)/.test(a?.message??"");if(!s||typeof a.timestamp!=="number")continue;const c=`${a.id??""}|${a.timestamp}|${(a.message??"").slice(0,120)}`;if(i.has(c))continue;i.add(c);if(r-a.timestamp<3e4)o=true}if(i.size>200)for(const a of[...i].slice(0,i.size-200))i.delete(a);this.crashSeen.set(e,i);if(!o)return;if(![...this.pendingActions.values()].some(a=>a.target===e&&a.expire&&!a.cut))return;void this.callAction("app","ping",{},e,{timeoutMs:1500,silent:true}).then(()=>void 0,()=>{const a=Date.now();for(const s of this.pendingActions.values()){if(s.target!==e||!s.expire||s.cut)continue;s.cut=true;if(s.deadline!==void 0&&s.deadline-a<=Bn)continue;clearTimeout(s.timer);s.timer=setTimeout(s.expire,Bn)}})}lastFatalFor(e){const n=this.snapshots.get(De(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(De(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=Sc(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(De(e,"app"));if(typeof t?.devServerOrigin==="string")return t.devServerOrigin;return null}ensureWatching(e,n){const t=De(n,e);if(this.watching.has(t))return;this.watching.set(t,{toolId:e,targetDeviceId:n});this.sendWatch(e,n)}sendWatch(e,n){if(!this.admitted||!this.socket?.connected||this.lockedDevices.has(n))return;this.socket?.emit("devtool-watch",{toolId:e,targetDeviceId:n,watching:true,stream:false})}rearmWatches(){for(const{toolId:e,targetDeviceId:n}of this.watching.values()){this.sendWatch(e,n)}}rearmReconnectedDevices(e){for(const n of e){if(!n.deviceId||n.isConnected===false)continue;const t=String(n.deviceId);const r=`${n.id}|${n.connectionNonce??""}`;const i=this.deviceConnections.get(t);this.deviceConnections.set(t,r);if(i===void 0||i===r)continue;for(const{toolId:o,targetDeviceId:a}of this.watching.values()){if(a===t)this.sendWatch(o,a)}}}unwatch(e,n){const t=De(n,e);if(!this.watching.delete(t))return;if(this.admitted&&this.socket?.connected)this.socket.emit("devtool-watch",{toolId:e,targetDeviceId:n,watching:false})}cachedSnapshot(e,n){this.requireAdmission();this.requireDeviceAccount(n);return this.snapshots.get(De(n,e))}async getSnapshot(e,n,t={}){const r=this.resolveDevice(n);const i=De(r,e);this.ensureWatching(e,r);let o=t.timeoutMs??li;if(t.timeoutMs===void 0&&this.isUnresponsive(r)){const l=this.healthOf(r);if(Date.now()-l.lastFullBudgetAt>ci){l.lastFullBudgetAt=Date.now()}else{o=Ls}}const a=this.waitForSnapshot(i,o);this.socket?.emit("request-devtool-state",{toolId:e,targetDeviceId:r});const s=await a;this.requireAdmission();this.requireDeviceAccount(r);if(s!==void 0){if(!t.silent)this.noteOk(r);return{deviceId:r,payload:s}}if(!t.silent)this.noteTimeout(r);const c=this.snapshots.get(i);if(c!==void 0){return{deviceId:r,payload:c,stale:this.staleNote(e,r)}}throw new Error(`Timed out waiting for "${e}" state from ${r} (is the tool active?). ${this.unresponsiveNote(r)}`)}lastSync(e,n){const t=this.snapshots.get(De(e,n));return t===void 0?void 0:{payload:t,ageMs:this.snapshotAgeMs(n,e)}}staleNote(e,n){const t=this.snapshotAgeMs(e,n);const r=t==null?"an earlier sync":`${Math.round(t/1e3)}s ago`;return`\u26A0\uFE0F Served from the last sync (${r}) \u2014 ${this.unresponsiveNote(n)}`}waitForSnapshot(e,n){return new Promise(t=>{const r=this.snapshotWaiters.get(e)??[];const i=setTimeout(()=>{const a=(this.snapshotWaiters.get(e)??[]).filter(s=>s!==o);this.snapshotWaiters.set(e,a);t(void 0)},n);const o=a=>{clearTimeout(i);t(a)};r.push(o);this.snapshotWaiters.set(e,r)})}async callAction(e,n,t,r,i={}){this.requireAdmission();const o=r===ve?ve:this.resolveDevice(r);if(!this.socket)throw new Error("SyncClient is not connected");const a=mc();const s=i.timeoutMs??this.timeoutFor(o,e,n);const c=await new Promise((l,d)=>{const u=Date.now();const h=()=>{this.pendingActions.delete(a);if(o!==ve&&!i.silent)this.noteTimeout(o);d(new Error(`Action "${e}.${n}" got no answer in ${Date.now()-u}ms. `+(o===ve?"No device responded.":this.unresponsiveNote(o))))};const p=setTimeout(h,s);this.pendingActions.set(a,{resolve:l,reject:d,timer:p,target:o,expire:h,deadline:u+s});this.socket.emit("devtool-action",{requestId:a,toolId:e,targetDeviceId:o,action:n,params:t??{}})});if(o!==ve&&!i.silent)this.noteOk(o);if(!c.ok){throw new Error(c.error||`Action "${e}.${n}" failed on device`)}return c.result}};var De=(e,n)=>`${e}::${n}`;function qn(e,n=800){return new Promise(t=>{const r=fc.get(e,i=>{i.resume();t((i.statusCode??0)>0)});r.setTimeout(n,()=>{r.destroy();t(false)});r.on("error",()=>t(false))})}async function Cc(e,n=20){for(let t=0;t<n;t++){if(await qn(e,300))return;await Ec(50)}throw new Error(`Spawned broker never became reachable at ${e}`)}var Ec=e=>new Promise(n=>setTimeout(n,e));var At="7.0.61"?"7.0.61":"0.0.0-dev";var Un="@buoy-gg/mcp";import{promises as vi}from"fs";import Oc from"os";import Rc from"path";var Pc=24*60*60*1e3;var Fc=1500;var Bc=`https://registry.npmjs.org/${Un}/latest`;var yi=Rc.join(Oc.tmpdir(),"buoy-mcp-update-check.json");function Nc(e,n){const t=o=>o.split("-")[0].split(".").map(a=>Number(a)||0);const r=t(e);const i=t(n);for(let o=0;o<3;o++){const a=r[o]??0;const s=i[o]??0;if(a>s)return true;if(a<s)return false}return false}async function jc(){try{const e=await vi.readFile(yi,"utf8");const n=JSON.parse(e);if(typeof n.checkedAt==="number"&&typeof n.latest==="string"){return n}}catch{}return null}async function Lc(e){const n=new AbortController;const t=setTimeout(()=>n.abort(),Fc);try{const r=await fetch(Bc,{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 vi.writeFile(yi,JSON.stringify({checkedAt:e,latest:o})).catch(()=>{})}return o}catch{return null}finally{clearTimeout(t)}}async function qc(e){const n=await jc();if(n&&e-n.checkedAt<Pc)return n.latest;return Lc(e)}async function $i(e=Date.now()){if(At==="0.0.0-dev")return null;try{const n=await qc(e);if(n&&Nc(n,At)){return`A newer buoy-mcp is available (${n}; you're on ${At}). Update by re-running: npx -y ${Un}@latest init \u2014 then restart your editor.`}}catch{}return null}import{z as G}from"zod";import{execFile as Uc}from"child_process";import{promisify as zc}from"util";import{promises as Se}from"fs";import ki from"os";import fe from"path";import{randomUUID as _i}from"crypto";var Dt=zc(Uc);var Zt=(e,n,t)=>Math.min(Math.max(e,n),t);function Si(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 Wc(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 Hc="@react_buoy_sync_device_id";async function Qt(e){try{return await Se.readdir(e)}catch{return[]}}async function Jc(e){const n=[];for(const t of await Qt(e))n.push(...await xi(fe.join(e,t)));return n}async function xi(e){const n=[];const t=fe.join(e,"Library","WebKit");for(const r of await Qt(t)){const i=fe.join(t,r,"WebsiteData","Default");for(const o of await Qt(i)){for(const a of await Qt(fe.join(i,o))){const s=fe.join(i,o,a,"LocalStorage","localstorage.sqlite3");try{await Se.access(s);const{stdout:c}=await Dt("sqlite3",["-readonly",s,`SELECT hex(value) FROM ItemTable WHERE key='${Hc}' LIMIT 1;`],{timeout:1500});const l=c.trim();if(l)n.push(Buffer.from(l,"hex").toString("utf16le").trim())}catch{}}}}return n}var Ti=new Map;var Gc=3e4;async function Ii(e){if(process.platform!=="darwin")return{ok:false,error:"Simulator lookup needs macOS."};let n=[];try{const{stdout:r}=await Dt("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const i=JSON.parse(r).devices;n=Object.entries(i).filter(([o])=>/iOS/.test(o)).flatMap(([,o])=>o.filter(a=>a.state==="Booted"))}catch(r){return{ok:false,error:Si(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=fe.join(r.dataPath,"Containers","Data","Application");let o=[];try{o=await Se.readdir(i)}catch{continue}for(const a of o){try{const s=(await Se.readFile(fe.join(i,a,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim();if(s===t)return{ok:true,udid:r.udid,how:`matched ${e} to "${r.name}"`}}catch{}}}}if(t&&e){const r=n.map(c=>c.udid).sort().join(",");const i=Ti.get(e);const o=i?.booted===r&&(i.udid!==null||Date.now()-i.at<Gc);const a=o&&i?.udid?n.find(c=>c.udid===i.udid):void 0;if(a)return{ok:true,udid:a.udid,how:`matched ${e} to "${a.name}" (WebView storage)`};const s=[];if(!o){const c=await Promise.all(n.map(l=>l.dataPath?Jc(fe.join(l.dataPath,"Containers","Data","Application")):Promise.resolve([])));c.forEach((l,d)=>{if(l.includes(t))s.push(n[d])});Ti.set(e,{booted:r,udid:s.length===1?s[0].udid:null,at:Date.now()})}if(s.length===1){return{ok:true,udid:s[0].udid,how:`matched ${e} to "${s[0].name}" (WebView storage)`}}if(s.length>1){return{ok:false,error:`${s.length} booted simulators (${s.map(c=>c.name).join(", ")}) hold ${e}. Pass the udid, or shut one down.`}}}if(n.length===1)return{ok:true,udid:n[0].udid,how:`only booted simulator "${n[0].name}"`};return{ok:false,error:`${n.length} iOS Simulators are booted (${n.map(r=>r.name).join(", ")}) and none could be matched to ${e??"this device"}. Shut down the others, or capture from a single booted simulator.`}}async function Kc(e){const n=new Map;if(process.platform!=="darwin"||e.length===0)return n;let t=[];try{const{stdout:i}=await Dt("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const o=JSON.parse(i).devices;t=Object.entries(o).filter(([a])=>/iOS/.test(a)).flatMap(([,a])=>a.filter(s=>s.state==="Booted"))}catch{return n}const r=new Map;for(const i of t){if(!i.dataPath)continue;const o=fe.join(i.dataPath,"Containers","Data","Application");let a=[];try{a=await Se.readdir(o)}catch{continue}for(const s of a){try{const c=(await Se.readFile(fe.join(o,s,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim();if(c)r.set(c,{name:i.name,udid:i.udid})}catch{}}}for(const i of e){const o=r.get(i.split("-").pop()??"");if(o)n.set(i,o)}return n}async function Ai(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=fe.join(ki.tmpdir(),`buoy-mcp-sim-${_i()}.png`);try{await Dt("xcrun",["simctl","io",e,"screenshot","--type=png",n],{timeout:15e3})}catch(t){return{ok:false,error:Si(t)}}try{const t=await Se.readFile(n);const r=Wc(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 Vc(e,n,t){const r=Zt(Math.round(t.x),0,Math.max(0,n.width-1));const i=Zt(Math.round(t.y),0,Math.max(0,n.height-1));const o=Zt(Math.round(t.width),1,n.width-r);const a=Zt(Math.round(t.height),1,n.height-i);const s=fe.join(ki.tmpdir(),`buoy-mcp-crop-${_i()}.png`);try{await Dt("sips",["-c",String(a),String(o),"--cropOffset",String(i),String(r),e,"--out",s],{timeout:1e4});const c=await Se.readFile(s);return{ok:true,buffer:c,width:o,height:a}}catch(c){const l=c;return{ok:false,error:`Crop failed: ${l?.stderr||l?.message||c}`}}finally{await Se.unlink(s).catch(()=>{});await Se.unlink(e).catch(()=>{})}}import{execFile as Yc}from"child_process";import{promisify as Xc}from"util";var zn=Vt(Yt());import{execFile as Zc}from"child_process";import{promisify as Qc}from"util";import{promises as V}from"fs";import Mt from"os";import z from"path";import{randomUUID as el}from"crypto";var tl=Vt(Yt());import{execFile as nl}from"child_process";import{promisify as rl}from"util";import{promises as Ve}from"fs";import Wn from"os";import Hn from"path";import{randomUUID as Jn}from"crypto";var il=rl(nl);async function he(e,n=3e4){const t=Hn.join(Wn.tmpdir(),`buoy-devicectl-${Jn()}.json`);try{await il("xcrun",["devicectl",...e,"--quiet","--json-output",t],{timeout:n,maxBuffer:16*1024*1024});return JSON.parse(await Ve.readFile(t,"utf8"))}catch(r){const i=r;let o=(i.stderr||i.stdout||i.message||"").trim();try{const a=JSON.parse(await Ve.readFile(t,"utf8"));o=a.error?.userInfo?.NSLocalizedDescription?.string??o}catch{}if(/locked/i.test(o))throw new Error("The iPhone is locked. Unlock it and try again.");throw new Error(`devicectl ${e.slice(0,2).join(" ")} failed: ${o.split("\n").slice(-3).join(" ").slice(0,300)}`)}finally{await Ve.unlink(t).catch(()=>void 0)}}async function ol(){if(process.platform!=="darwin")return[];return al(await he(["list","devices"],15e3).catch(()=>null))}function al(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 Di(e){const n=await he(["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 Mi(e,n,t){const r=await he(["device","info","files","--device",e,"--domain-type","appDataContainer","--domain-identifier",n],2e4);const i=new Set((r.result?.files??[]).map(a=>a.relativePath??a.name??""));if(!i.has(t))return null;const o=Hn.join(Wn.tmpdir(),`buoy-devfile-${Jn()}`);try{await he(["device","copy","from","--device",e,"--domain-type","appDataContainer","--domain-identifier",n,"--source",t,"--destination",o],2e4);return await Ve.readFile(o)}finally{await Ve.rm(o,{recursive:true,force:true}).catch(()=>void 0)}}async function Ci(e,n){const t=await Mi(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 Ei(e){const n=Hn.join(Wn.tmpdir(),`buoy-phone-shot-${Jn()}.png`);try{await he(["device","capture","screenshot","--device",e,"--destination",n],3e4);return await Ve.readFile(n)}finally{await Ve.unlink(n).catch(()=>void 0)}}var sl="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 cl(e){try{const n=tl.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 Gn(e,n,t={}){await he(["device","process","launch","--device",e,...t.terminateExisting?["--terminate-existing"]:[],...t.url?["--payload-url",t.url]:[],n])}async function ll(e,n){await he(["device","process","openURL","--device",e,n])}async function Oi(e,n){const t=await Di(e);const r=t.find(a=>a.bundleId===n)?.path;const i=await he(["device","info","processes","--device",e]);const o=(i.result?.runningProcesses??[]).find(a=>r&&decodeURIComponent(a.executable??"").replace(/^file:\/\//,"").startsWith(r.replace(/\/$/,"")));if(!o?.processIdentifier)return false;await he(["device","process","terminate","--device",e,"--pid",String(o.processIdentifier)]);return true}async function dl(e,n){await he(["device","uninstall","app","--device",e,n],12e4)}async function ul(e,n){await he(["device","install","app","--device",e,n],3e5)}async function hl(e,n,t,r){await he(["device","copy","to","--device",e,"--domain-type","appDataContainer","--domain-identifier",n,"--source",t,"--destination",r],3e4)}function pl(e,n,t){return["devicectl","device","capture","screen-record","--device",e,"--destination",n,"--duration",String(t)]}var Ri=new Map;async function Kn(e){const n=Ri.get(e);if(n)return n;const t=await he(["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.");Ri.set(e,r);return r}import{execFile as fl}from"child_process";import{promisify as ml}from"util";import{promises as Vn}from"fs";import lt from"path";import{WebSocket as wl}from"ws";import{execFile as gl}from"child_process";import{promisify as bl}from"util";var Yn=/\{\{\s*secret:([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;var dt=6;var Xn=new Map;var Pi=()=>false;function vl(e){Pi=e}function yl(e){Yn.lastIndex=0;return Yn.test(e)}function en(e,n=process.env){if(!yl(e))return e;if(Pi()){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(Yn,(o,a)=>{const s=n[`BUOY_SECRET_${a}`]??n[a];if(s===void 0||s===""){t.push(a);return""}if(s.length<dt){r.push(a);return""}Xn.set(a,s);return s});if(t.length){throw new Error(`No value for ${t.map(o=>`{{secret:${o}}}`).join(", ")}. Set ${t.map(o=>`BUOY_SECRET_${o}`).join(", ")} in the environment the MCP server runs in (for example in your editor's MCP config "env").`)}if(r.length){throw new Error(`${r.map(o=>`{{secret:${o}}}`).join(", ")} is shorter than ${dt} 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 Fi(e=process.env){const n=new Map(Xn);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 $l=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function pe(e){const n=new Map;for(const[i,o]of Fi()){if(o.length<dt)continue;for(const a of[o,JSON.stringify(o).slice(1,-1),encodeURIComponent(o)])n.set(a,i);for(let a=o.length-1;a>=dt;a--){n.set(`${o.slice(0,a)}\u2026`,i);n.set(`${o.slice(0,a)}...`,i);if(a>=8)n.set(o.slice(0,a),i)}}if(n.size===0)return e;const t=[...n.keys()].sort((i,o)=>o.length-i.length);const r=new RegExp(t.map($l).join("|"),"g");return e.replace(r,(i,o,a)=>{if(/^\d+$/.test(i)){const s=a.slice(Math.max(0,o-8),o);const c=a.slice(o+i.length,o+i.length+8);if(/(\d|\d\.)$/.test(s)||/^(\d|\.\d|[eE][+-]?\d)/.test(c))return i;if(/[:[,]\s*$/.test(s)&&/^\s*([,\]}]|$)/.test(c)&&!kl(a,o))return`"{{secret:${n.get(i)}}}"`}return`{{secret:${n.get(i)}}}`})}function kl(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 Zn(){return[...Xn.values()]}function _l(){return[...Fi().values()].filter(e=>e.length>=dt)}var Bi=bl(gl);var Ni="Android control needs adb on this computer (Android SDK platform-tools). Install it, or add it to PATH.";function ee(e){return`'${e.replace(/'/g,`'\\''`)}'`}function ji(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 xe(e,n,t=15e3){try{const{stdout:r}=await Bi("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(Ni);const o=n[0]==="shell"?`shell ${(n[1]??"").split(" ")[0]}`:n.slice(0,2).join(" ");const a=n[0]==="shell"?i.stderr||(i.killed?"timed out":"no error text"):i.stderr||i.message||"";const s=pe(a.replace(/'[^']*'/g,"'\u2026'")).trim().slice(0,300);throw new Error(`adb ${o} failed: ${s}`)}}function L(e,n,t=15e3){return xe(e,["shell",n],t)}async function Li(e,n,t=15e3){try{const{stdout:r}=await Bi("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(Ni);throw new Error(`adb ${n.slice(0,2).join(" ")} failed: ${i.message.slice(0,300)}`)}}async function Sl(){return xl(await xe(null,["devices"]))}function xl(e){return e.split("\n").slice(1).map(n=>n.trim().split(/\s+/)).filter(n=>n[1]==="device").map(n=>n[0])}async function qi(e){const n=Tl(await L(e,"wm size"));const t=Il(await L(e,"dumpsys input").catch(()=>""));return t%2===1?{width:n.height,height:n.width}:n}function Tl(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 Il(e){const n=/SurfaceOrientation:\s*(\d)/.exec(e);return n?Number(n[1]):0}async function Al(e,n){const t=await L(e,"dumpsys window windows").catch(()=>"");return Dl(t,n)}function Dl(e,n){const t=e.split(/\n(?=\s*Window #\d+)/);for(const r of t){if(!r.includes(`${n}/`))continue;const i=/mFrame=\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(r)??/\bframe=\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(r);if(i){const[o,a,s,c]=i.slice(1).map(Number);if(s>o&&c>a)return{x:o,y:a,width:s-o,height:c-a}}}return null}async function Ml(e){return Cl(await L(e,"dumpsys activity activities"))}function Cl(e){const n=/(?:topResumedActivity|mResumedActivity|ResumedActivity)[^\n]*?\s([a-zA-Z][\w.]*)\/[\w.$]+/.exec(e);return n?n[1]:null}async function El(e){const n=await L(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 Ui(e,n){ji(n);const t=await L(e,`run-as ${ee(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 Li(e,["exec-out",`run-as ${ee(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?Ol(i):null}function Ol(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 Rl(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 ee(e.replace(/ /g,"%s"))}async function Pl(e,n,t,r){const[i,o]=[Math.round(n),Math.round(t)];if(r)await L(e,`input swipe ${i} ${o} ${i} ${o} ${Math.round(r)}`);else await L(e,`input tap ${i} ${o}`)}async function Fl(e,n,t,r){const i=[...n,...t].map(o=>Math.round(o)).join(" ");await L(e,`input swipe ${i} ${Math.round(r)}`)}async function Bl(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 L(e,`input text ${Rl(i)}`)}}async function Nl(e){const n=await Li(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 zi(e,n){if(n){await L(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 L(e,`am broadcast -a com.android.systemui.demo ${t}`).catch(()=>void 0)}}else{await L(e,"am broadcast -a com.android.systemui.demo -e command exit").catch(()=>void 0)}}async function jl(e){const n=await xe(e,["exec-out","uiautomator","dump","/dev/tty"],2e4);return Ll(n)}function Ll(e){const n=[];const t=(r,i)=>{const o=new RegExp(`\\s${i}="([^"]*)"`).exec(r);return o?ql(o[1]):""};for(const r of e.matchAll(/<node\b[^>]*>/g)){const i=r[0];const o=/\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(t(i,"bounds"));if(!o)continue;const[a,s,c,l]=o.slice(1).map(Number);n.push({text:t(i,"text"),desc:t(i,"content-desc"),id:t(i,"resource-id"),cls:t(i,"class"),clickable:t(i,"clickable")==="true",bounds:{x:a,y:s,width:c-a,height:l-s}})}return n}function ql(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 Ul(e,n){const t=n.trim().toLowerCase();const r=c=>{let l=0;for(const d of[c.desc,c.text,c.id.split("/").pop()??""]){const u=d.trim().toLowerCase();if(!u)continue;if(u===t)l=Math.max(l,3);else if(u.startsWith(t))l=Math.max(l,2);else if(u.includes(t))l=Math.max(l,1)}return l};const i=e.filter(c=>c.bounds.width>0&&c.bounds.height>0&&r(c)>0);const o=Math.max(0,...i.map(r));const a=i.filter(c=>r(c)===o);let s=a.filter((c,l)=>a.findIndex(d=>JSON.stringify(d.bounds)===JSON.stringify(c.bounds))===l);if(s.length>1){const c=s.filter(l=>[l.desc,l.text,l.id.split("/").pop()??""].some(d=>d.trim()===n.trim()));if(c.length)s=c}if(s.length>1){const c=s.filter(l=>l.clickable||/EditText|Button/.test(l.cls));if(c.length)s=c}return s}var zl=ml(fl);var Wi=/^(@buoy\/session:|buoy-gg-license|buoy-gg-device-fingerprint$|@react_buoy_sync_device_id$|@react_buoy_install)/;async function Qn(e){return Vn.readdir(e).catch(()=>[])}async function er(e){const n=[];const t=lt.join(e,"Library","WebKit");for(const r of await Qn(t)){const i=lt.join(t,r,"WebsiteData","Default");for(const o of await Qn(i)){for(const a of await Qn(lt.join(i,o))){const s=lt.join(i,o,a);const c=lt.join(s,"LocalStorage","localstorage.sqlite3");if(!await Vn.access(c).then(()=>true,()=>false))continue;const l=await Vn.readFile(lt.join(s,"origin")).then(d=>d.toString("hex"),()=>"");if(l)n.push({db:c,origin:l})}}}return n}var Hi=(e,n,t=true)=>zl("sqlite3",[...t?["-readonly"]:[],e,n],{timeout:5e3}).then(r=>r.stdout);async function Wl(e){const n=[];for(const{db:t,origin:r}of await er(e)){const i=await Hi(t,"SELECT key, hex(value) FROM ItemTable;");for(const o of i.split("\n")){const a=o.lastIndexOf("|");if(a<0)continue;const s=o.slice(0,a);if(Wi.test(s))n.push({key:s,value:o.slice(a+1),origin:r})}}return n}async function Hl(e,n){if(!n.length)return false;const t=await er(e);const r=new Set(n.map(i=>i.origin??""));for(const i of r){const o=i?t.find(s=>s.origin===i):void 0;if(!o)return false;const a=n.filter(s=>(s.origin??"")===i&&/^[0-9A-F]*$/i.test(s.value)).map(s=>`('${s.key.replace(/'/g,"''")}', X'${s.value}')`).join(",");if(a)await Hi(o.db,`INSERT OR REPLACE INTO ItemTable (key, value) VALUES ${a};`,false)}return true}async function Jl(e,n=15e3){const t=Date.now()+n;while(Date.now()<t){if((await er(e)).length)return true;await new Promise(r=>setTimeout(r,500))}return false}async function Gl(e,n,t){const r=(await L(e,`pidof ${n}`).catch(()=>"")).trim().split(/\s+/)[0];if(!r)throw new Error("the app is not running");const i=(await xe(e,["forward","tcp:0",`localabstract:webview_devtools_remote_${r}`])).trim();try{const o=await(await fetch(`http://127.0.0.1:${i}/json`)).json();const a=o.find(s=>s.type==="page"&&s.webSocketDebuggerUrl);if(!a?.webSocketDebuggerUrl)throw new Error("no debuggable WebView page (needs a debug build)");return await new Promise((s,c)=>{const l=new wl(a.webSocketDebuggerUrl);const d=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",u=>{const h=JSON.parse(String(u));if(h.id!==1)return;clearTimeout(d);l.close();if(h.result?.exceptionDetails)c(new Error("the WebView script failed"));else s(h.result?.result?.value)});l.on("error",u=>{clearTimeout(d);c(u)})})}finally{await xe(e,["forward","--remove",`tcp:${i}`]).catch(()=>void 0)}}async function Ji(e,n,t,r=15e3){const i=Date.now()+r;let o;while(Date.now()<i){try{return await Gl(e,n,t)}catch(a){o=a;await new Promise(s=>setTimeout(s,700))}}throw o instanceof Error?o:new Error("the WebView did not open")}async function Kl(e,n){const t=await L(e,`run-as ${n} sh -c 'ls app_webview/Default/"Local Storage"/leveldb 2>/dev/null'`).catch(()=>"");return/CURRENT|\.log/.test(t)}async function Vl(e,n){if(!(await L(e,`pidof ${n}`).catch(()=>"")).trim()){await L(e,`monkey -p ${n} -c android.intent.category.LAUNCHER 1`)}const t=await Ji(e,n,`(() => { const re = ${Wi}; 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 Yl(e,n,t){await Ji(e,n,`(() => { for (const r of ${JSON.stringify(t)}) localStorage.setItem(r.key, r.value); setTimeout(() => location.reload(), 50); return true; })()`)}var Xl=Qc(Zc);var Ye=new Map;function tn(e){return Ye.get(e)}async function Le(e,n,t=2e4){try{const{stdout:r}=await Xl(e,n,{timeout:t,maxBuffer:16*1024*1024});return r}catch(r){const i=r;if(i.code==="ENOENT")throw new Error(e==="xcrun"?"This needs macOS with Xcode (xcrun simctl).":`${e} is not installed.`);throw new Error(`${e} ${n.slice(0,2).join(" ")} failed: ${(i.stderr||i.message||"").trim().slice(0,300)}`)}}var Y=(e,n)=>Le("xcrun",["simctl",...e],n);var nn=e=>e.split("-").pop()??"";async function tr(e){let n=[];try{const r=JSON.parse(await Y(["list","devices","booted","-j"])).devices;n=Object.entries(r).filter(([i])=>/iOS/.test(i)).flatMap(([,i])=>i.filter(o=>o.state==="Booted"))}catch{return[]}const t=[];for(const r of n)if(await Gi(e,r.udid))t.push(r);return t}function nr(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 Gi(e,n){const t=nn(e);if(!t)return null;let r;try{const a=JSON.parse(await Y(["list","devices","-j"])).devices;r=Object.values(a).flat().find(s=>s.udid===n)?.dataPath}catch{return null}if(!r)return null;const i=z.join(r,"Containers","Data","Application");let o=[];try{o=await V.readdir(i)}catch{return null}for(const a of o){const s=z.join(i,a);if(!await Ki(s,t))continue;let c=null;try{c=(await Le("plutil",["-extract","MCMMetadataIdentifier","raw","-o","-",z.join(s,".com.apple.mobile_container_manager.metadata.plist")])).trim()||null}catch{}return{container:s,bundleId:c}}return null}async function Ki(e,n){try{if((await V.readFile(z.join(e,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim()===n)return true}catch{}return(await xi(e).catch(()=>[])).includes(n)}async function Zl(e,n){const t=nn(e);const r=n.serial?[n.serial]:await Sl();if(r.length===0)throw new Error("No Android device or emulator is connected to adb.");for(const i of r){const o=await Ml(i).catch(()=>null);const a=await El(i).catch(()=>[]);const s=[n.bundleId,o,...a].filter((c,l,d)=>!!c&&d.indexOf(c)===l).slice(0,80);for(const c of s){if(await Ui(i,c).catch(()=>null)===t)return{platform:"android",serial:i,packageName:c}}}return null}async function Ql(e){const n=nn(e);for(const t of await ol()){for(const r of await Di(t.udid).catch(()=>[])){if(await Ci(t.udid,r.bundleId)===n)return{platform:"ios-device",udid:t.udid,name:t.name,bundleId:r.bundleId}}}return null}async function Ct(e,n,t={}){if(e==="All")throw new Error('Device control acts on one app. Pass its deviceId, not "All".');const r=Ye.get(e);if(r&&!t.udid&&!t.serial&&await Yi(e,r)){if(r.platform==="ios"&&!r.picked){const c=await tr(e);if(c.length>1)throw nr(e,c)}return r}if(r)Ye.delete(e);if(n==="android"){const c=await Zl(e,t);if(!c){throw new Error(`Could not prove which Android device and app run "${e}". Buoy checks the app's install id with run-as, which needs a debug build of the app on a device adb can reach${t.serial?` (looked on ${t.serial})`:""}.`)}Ye.set(e,c);return c}if(n&&n!=="ios")throw new Error(`Device control works on iOS Simulators and Android. This app runs on "${n}".`);if(process.platform!=="darwin")throw new Error("iOS control needs macOS with Xcode.");let i=t.udid;let o=i??"";if(!i){const c=await tr(e);if(c.length>1)throw nr(e,c);const l=c.length===1?{ok:true,udid:c[0].udid,how:`matched ${e} to "${c[0].name}"`}:await Ii(e);if(!l.ok||!/^matched /.test(l.how)){const d=await Ql(e).catch(()=>null);if(d){Ye.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=l.udid;o=/"([^"]+)"/.exec(l.how)?.[1]??i}const a=await Gi(e,i);if(!a&&t.udid)throw new Error(`Simulator ${t.udid} does not hold "${e}".`);const s={platform:"ios",udid:i,name:o,bundleId:t.bundleId??a?.bundleId??null,container:a?.container??null,picked:!!t.udid};Ye.set(e,s);return s}async function Vi(e,n){if(n.platform==="ios"&&!n.picked){const t=await tr(e);if(t.length>1)throw nr(e,t)}if(await Yi(e,n))return n;Ye.delete(e);return Ct(e,n.platform==="android"?"android":"ios",n.platform==="ios"&&n.picked?{udid:n.udid}:{})}async function Yi(e,n){const t=nn(e);if(n.platform==="android")return await Ui(n.serial,n.packageName).catch(()=>null)===t;if(n.platform==="ios-device")return await Ci(n.udid,n.bundleId).catch(()=>null)===t;if(n.container)return Ki(n.container,t);const r=await Ii(e);return r.ok&&r.udid===n.udid&&/^matched /.test(r.how)}function rr(e){if(e.platform==="android")return ji(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 Xi(e){if(e.platform==="android")return Nl(e.serial);if(e.platform==="ios-device")return Ei(e.udid);const n=await Ai(e.udid);if(!n.ok||!n.srcPath)throw new Error(n.error??"Screenshot failed.");try{return await V.readFile(n.srcPath)}finally{await V.unlink(n.srcPath).catch(()=>{})}}async function ir(e,n=1280){if(process.platform==="darwin"){const i=z.join(Mt.tmpdir(),`buoy-mcp-img-${el()}.png`);const o=i.replace(/\.png$/,".jpg");await V.writeFile(i,e);try{await Le("sips",["-Z",String(n),"-s","format","jpeg","-s","formatOptions","70",i,"--out",o],15e3);const a=await Le("sips",["-g","pixelWidth","-g","pixelHeight",o]);return{data:(await V.readFile(o)).toString("base64"),mimeType:"image/jpeg",width:Number(/pixelWidth:\s*(\d+)/.exec(a)?.[1]??0),height:Number(/pixelHeight:\s*(\d+)/.exec(a)?.[1]??0)}}finally{await V.unlink(i).catch(()=>{});await V.unlink(o).catch(()=>{})}}const t=ed(zn.PNG.sync.read(e),Math.min(n,1024));const r=zn.PNG.sync.write(t,{colorType:2,deflateLevel:9});return{data:r.toString("base64"),mimeType:"image/png",width:t.width,height:t.height}}function ed(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 zn.PNG({width:r,height:i});const a=e.width/r;const s=e.height/i;for(let c=0;c<i;c++){const l=Math.floor(c*s);const d=Math.max(l+1,Math.floor((c+1)*s));for(let u=0;u<r;u++){const h=Math.floor(u*a);const p=Math.max(h+1,Math.floor((u+1)*a));const m=[0,0,0,0];let g=0;for(let f=l;f<d;f++){for(let b=h;b<p;b++){const y=(f*e.width+b)*4;for(let v=0;v<4;v++)m[v]+=e.data[y+v];g++}}const w=(c*r+u)*4;for(let f=0;f<4;f++)o.data[w+f]=Math.round(m[f]/g)}}return o}var or=new Set;async function td(e,n){let t=false;try{if(e.platform==="ios"){const r=await Y(["status_bar",e.udid,"list"]).catch(()=>"");const i=r.split(/^=+$/m).slice(1).join("").trim();if(!i){await Y(["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 L(e.serial,"settings get global sysui_demo_allowed").catch(()=>"")).trim();if(r!=="1"&&!or.has(e.serial)){or.add(e.serial);await zi(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 Y(["status_bar",e.udid,"clear"]).catch(()=>void 0);else if(e.platform==="android"){await zi(e.serial,false);await L(e.serial,"settings put global sysui_demo_allowed 0").catch(()=>void 0);or.delete(e.serial)}}}}async function ar(e){const n=rr(e);if(e.platform==="ios-device"){const t=await Oi(e.udid,n);return t?`Quit ${n}.`:`${n} was not running.`}if(e.platform==="ios"){await Y(["terminate",e.udid,n]).catch(t=>{if(!/found nothing to terminate|not running/i.test(String(t)))throw t})}else{await L(e.serial,`am force-stop ${ee(n)}`)}return`Quit ${n}.`}async function ut(e){const n=rr(e);if(e.platform==="ios")await Y(["launch",e.udid,n]);else if(e.platform==="ios-device")await Gn(e.udid,n);else await L(e.serial,`monkey -p ${ee(n)} -c android.intent.category.LAUNCHER 1`);return`Launched ${n}.`}async function nd(e){if(e.platform==="ios-device"){await Gn(e.udid,"com.apple.Preferences");return"Sent to the background for real (Settings opened on top)."}if(e.platform==="ios"){await Y(["launch",e.udid,"com.apple.Preferences"]);return"Sent to the background for real (Settings opened on top)."}await L(e.serial,"input keyevent 3");return"Sent to the background for real (pressed Home)."}async function rd(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 ll(e.udid,n);return"Opened through the OS on the iPhone."}if(e.platform==="ios"){await Y(["openurl",e.udid,n]);return'Opened through the OS. A custom scheme may first show an "Open in" prompt on the simulator.'}await L(e.serial,`am start -a android.intent.action.VIEW -d ${ee(n)}`);return"Opened through the OS (an Android VIEW intent)."}var id=["buoy-license","react-buoy/@react_buoy_sync_device_id.json","react-buoy/@react_buoy_install.json"];async function Zi(e){const n=z.join(e,"Info.plist");const t=a=>Le("plutil",["-extract",a,"raw","-o","-",n]).then(s=>s.trim()).catch(()=>"");const r=await t("CFBundleIdentifier");if(!r)throw new Error(`${e} has no Info.plist with a bundle id. Pass a built .app folder.`);const i=(await Le("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 od(e){const n=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT,z.join(Mt.homedir(),"Library","Android","sdk"),z.join(Mt.homedir(),"Android","Sdk")].filter(t=>!!t);for(const t of n){const r=z.join(t,"build-tools");const i=(await V.readdir(r).catch(()=>[])).sort().reverse();for(const o of i){for(const a of["aapt2","aapt"]){const s=z.join(r,o,a);try{await V.access(s)}catch{continue}const c=await Le(s,a==="aapt2"?["dump","packagename",e]:["dump","badging",e]).catch(()=>"");const l=a==="aapt2"?c.trim().split("\n")[0]:/package: name='([^']+)'/.exec(c)?.[1]??"";if(l)return l}}}throw new Error("Could not read the APK's package name (needs aapt2 from the Android SDK build-tools). Nothing was changed.")}async function ad(e,n,t=true){const r=rr(e);const i=z.resolve(n);try{await V.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 sd(e,r,i,t);if(e.platform==="ios-device")return cd(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 Zi(i);if(o.bundleId!==r)throw new Error(`${z.basename(i)} is ${o.bundleId}, but this app is ${r}. Nothing was changed.`);if(!o.simulator)throw new Error(`${z.basename(i)} is a device build, not a simulator build. Nothing was changed.`);const a=t?await V.mkdtemp(z.join(Mt.tmpdir(),"buoy-mcp-keep-")):null;try{let s=false;let c=[];if(a){await V.chmod(a,448);const d=(await Y(["get_app_container",e.udid,r,"data"]).catch(()=>"")).trim();if(d)s=await Qi(z.join(d,"Documents"),a);if(d&&!s){try{c=await Wl(d)}catch(u){throw new Error(`Couldn't read Buoy's sign-in from the app's WebView storage (${u.message}). Nothing was changed. Pass keepBuoy: false to reinstall anyway.`)}}}await Y(["terminate",e.udid,r]).catch(()=>void 0);await Y(["uninstall",e.udid,r]);try{await Y(["install",e.udid,i],18e4)}catch(d){throw new Error(`The app was removed, but installing ${z.basename(i)} failed: ${d.message}. Install it again by hand.`)}let l="";if(a&&s){try{const d=(await Y(["get_app_container",e.udid,r,"data"])).trim();await Qi(a,z.join(d,"Documents"));e.container=d;l=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(d){l=` Buoy's sign-in could not be restored (${d.message}): sign in to Buoy again in the app.`}}else if(c.length){try{const d=(await Y(["get_app_container",e.udid,r,"data"])).trim();await Y(["launch",e.udid,r]);const u=await Jl(d);await Y(["terminate",e.udid,r]).catch(()=>void 0);if(!u||!await Hl(d,c))throw new Error("the app made no WebView storage");e.container=d;l=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(d){l=` Buoy's sign-in could not be restored (${d.message}): sign in to Buoy again in the app.`}}else if(t){l=" The old install had no Buoy sign-in to keep."}await Y(["launch",e.udid,r]);return`Reinstalled ${r} from ${i} and launched it. The app's own data is gone, like a new user.${l}`}finally{if(a)await V.rm(a,{recursive:true,force:true}).catch(()=>void 0)}}async function Qi(e,n){let t=false;for(const r of id){const i=z.join(e,r);try{await V.access(i)}catch{continue}const o=z.join(n,r);await V.mkdir(z.dirname(o),{recursive:true});await V.cp(i,o,{recursive:true,force:true});t=true}return t}async function sd(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 od(t);if(i!==n)throw new Error(`${z.basename(t)} is ${i}, but this app is ${n}. Nothing was changed.`);const o=[];if(r){const c=await L(e.serial,`run-as ${ee(n)} find files/buoy-license files/react-buoy -maxdepth 1 -type f 2>/dev/null`).catch(()=>"");const l=c.split("\n").map(d=>d.trim()).filter(d=>d.startsWith("files/buoy-license/")||/react-buoy\/@react_buoy_(sync_device_id|install)\.json$/.test(d));for(const d of l){const u=await L(e.serial,`run-as ${ee(n)} base64 ${ee(d)}`).catch(()=>"");if(u.trim())o.push({rel:d,data:u.replace(/\s+/g,"")})}}let a=[];if(r&&!o.length&&await Kl(e.serial,n)){try{a=await Vl(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 xe(e.serial,["install","-r","-d",t],18e4);await L(e.serial,`pm clear ${ee(n)}`);let s="";if(a.length){await ut(e);try{await Yl(e.serial,n,a);s=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(c){s=` Buoy's sign-in could not be restored (${c.message}): sign in to Buoy again in the app.`}return`Reinstalled ${n} from ${t} and launched it. The app's data is gone, like a new user.${s}`}if(o.length){try{for(const c of o){const l=z.posix.dirname(c.rel);await L(e.serial,`echo ${ee(c.data)} | run-as ${ee(n)} sh -c ${ee(`mkdir -p ${ee(l)} && base64 -d > ${ee(c.rel)}`)}`)}s=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(c){s=` Buoy's sign-in could not be restored (${c.message}): sign in to Buoy again in the app.`}}else if(r){s=" No Buoy sign-in could be read to keep (needs a debug build): sign in to Buoy again in the app."}await ut(e);return`Reinstalled ${n} from ${t} and launched it. The app's data is gone, like a new user.${s}`}async function cd(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 Zi(t);if(i.bundleId!==n)throw new Error(`${z.basename(t)} is ${i.bundleId}, but this app is ${n}. Nothing was changed.`);if(i.simulator)throw new Error(`${z.basename(t)} is a simulator build, not a device build. Nothing was changed.`);const o=["Documents/buoy-license/buoy-gg-license.json","Documents/react-buoy/@react_buoy_sync_device_id.json","Documents/react-buoy/@react_buoy_install.json"];const a=r?await V.mkdtemp(z.join(Mt.tmpdir(),"buoy-mcp-keep-")):null;try{const s=[];if(a){await V.chmod(a,448);for(const l of o){let d;try{d=await Mi(e.udid,n,l)}catch(h){throw new Error(`Could not back up Buoy's ${z.basename(l)} from the iPhone (${h.message}). Nothing was changed.`)}if(!d)continue;const u=z.join(a,l.replace(/\//g,"__"));await V.writeFile(u,d,{mode:384});s.push({rel:l,local:u})}}await Oi(e.udid,n).catch(()=>false);await dl(e.udid,n);try{await ul(e.udid,t)}catch(l){throw new Error(`The app was removed, but installing ${z.basename(t)} failed: ${l.message}. Install it again from Xcode.`)}let c="";if(s.length){try{for(const u of s)await hl(e.udid,n,u.local,u.rel);const l=s.some(u=>u.rel.includes("buoy-license"));const d=s.some(u=>u.rel.includes("sync_device_id"));c=l?` Kept Buoy's sign-in${d?" 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 Gn(e.udid,n);return`Reinstalled ${n} on the iPhone and launched it. The app's own data is gone, like a new user.${c}`}finally{if(a)await V.rm(a,{recursive:true,force:true}).catch(()=>void 0)}}async function ld(e){const n=JSON.parse(await Y(["list","devices","available","-j"])).devices;const t=Object.entries(n).filter(([s])=>/iOS/.test(s)).flatMap(([,s])=>s);const r=e.trim().toLowerCase();const i=t.filter(s=>s.udid.toLowerCase()===r||s.name.toLowerCase()===r);const o=i.length?i:t.filter(s=>s.name.toLowerCase().includes(r));if(o.length===0)throw new Error(`No iOS Simulator matches "${e}". Run \`xcrun simctl list devices available\` to see them.`);if(o.length>1)throw new Error(`${o.length} simulators match "${e}": ${o.map(s=>`${s.name} (${s.udid})`).join(", ")}. Pass the udid.`);const a=o[0];if(a.state!=="Booted")await Y(["boot",a.udid],12e4);await Le("open",["-a","Simulator","--args","-CurrentDeviceUDID",a.udid]).catch(()=>void 0);return a.state==="Booted"?`${a.name} (${a.udid}) was already booted.`:`Booted ${a.name} (${a.udid}).`}var dd=Xc(Yc);async function Me(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 d=l.startsWith(It)&&/is not connected right now/.test(l)?/"([^"]+)"/.exec(l)?.[1]:void 0;const u=d?e.listDevices().some(h=>h.deviceId===d&&h.isPro):false;if(!r.allowOffline||!d||!u)throw c;i=d;o=false}const a=e.listDevices().find(c=>c.deviceId===i)?.platform;let s=await Ct(i,a,t);if(r.changesApp&&tn(i)===s)s=await Vi(i,s);return{id:i,host:s,online:o}}function ht(e){if(e.platform==="ios")return`simulator "${e.name}"`;if(e.platform==="ios-device")return`iPhone "${e.name}"`;return`Android device ${e.serial}`}var sr=new Map;function eo(e){if(!sr.has(e))sr.set(e,dd("which",[e],{timeout:3e3}).then(()=>true,()=>false));return sr.get(e)}async function ud(e,n){let t=n;if(e.platform==="android"){const i=tn(e.deviceId);const o=i??(e.isConnected?await Promise.race([Ct(e.deviceId,"android").catch(()=>void 0),new Promise(s=>setTimeout(()=>s(void 0),3e3))]):void 0);const a=await eo("adb");return{kind:"android",...o&&o.platform==="android"?{id:o.serial,name:o.packageName}:{},can:["screenshot","screen_recording","baseline diffs","quit/launch/reinstall","real lifecycle events","native_tap/type/swipe"],...!a?{missing:["adb (Android SDK platform-tools)"]}:!o?{missing:["proof of which phone runs it (needs a debug build reachable by adb)"]}:{}}}if(e.platform!=="ios")return{kind:e.platform??"unknown",can:[],missing:["host control works on iOS and Android apps"]};let r=tn(e.deviceId);if(!r&&!t&&e.isConnected){r=await Promise.race([Ct(e.deviceId,"ios").catch(()=>void 0),new Promise(i=>setTimeout(()=>i(void 0),4e3))])}if(!t&&r?.platform==="ios")t={name:r.name,udid:r.udid};if(r?.platform==="ios-device"){return{kind:"physical iPhone",id:r.udid,name:r.name,can:["screenshot","screen_recording (if this iPhone supports it)","baseline diffs","quit/launch/reinstall","open_url","native_tap/type/swipe (by query, testID, nativeTag or x/y; not label)"]}}if(t){const i=await eo("idb");return{kind:"ios simulator",id:t.udid,name:t.name,can:["screenshot","screen_recording","baseline diffs","quit/launch/reinstall/boot","real lifecycle events",...i?["native_tap/type/swipe"]:[]],...i?{}:{missing:["idb for real touches (brew install facebook/fb/idb-companion && pipx install fb-idb)"]}}}return void 0}function pt(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function ft(e){return{isError:true,content:[{type:"text",text:e}]}}function to(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:G.boolean().optional().describe("Also list every action of every tool. Default false (tool names only); list_tool_actions gives one tool's actions."),includeDisconnected:G.boolean().optional().describe("Also list apps that were seen before but are not connected now. Default false.")}},async(t={})=>{const r=await $i();let i=n.listDevices();for(let p=0;i.length===0&&p<10;p++){await new Promise(m=>setTimeout(m,200));i=n.listDevices()}if(i.length===0){return pt({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 pt({devices:[],hint:`No app is connected right now${o?` (${o} seen before; pass includeDisconnected:true to list them)`:""}. Open the app with Buoy devtools running, then retry.`,...r?{updateAvailable:r}:{}})}const a=await Kc(i.filter(p=>p.platform==="ios").map(p=>p.deviceId)).catch(()=>new Map);const s=i.filter(p=>p.isConnected);const c=s.some(p=>p.isPro);const l=s.some(p=>p.tier!=="locked");const d=s.filter(p=>p.collision);const u=await Promise.all(i.map(p=>p.isConnected?ud(p,a.get(p.deviceId)).catch(()=>void 0):void 0));const h=i.map((p,m)=>{const g=a.get(p.deviceId);const w=u[m];return{deviceId:p.deviceId,deviceName:p.deviceName,platform:p.platform,isConnected:p.isConnected,isPro:p.isPro,tier:p.tier,access:n.accessState(p.deviceId),...g?{simulator:g}:{},...w?{host:w}:{},...p.collision?{collision:true}:{},tools:t.details?p.tools:p.tools.map(f=>f.toolId)}});return pt({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).`:""}`},...d.length>0?{warning:`${d.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 Buoy MCP is a Pro feature \u2014 the connected device is signed in on the free tier, so data/action tools are blocked. Upgrade to Buoy Pro in the app, or pass `licenseKey` to `<FloatingDevTools />` if it runs headless.":"The broker has not confirmed account access for the connected devices, so data/action tools are blocked. A locked status can mean missing configuration, pending/failed validation, or a missing account announcement after reconnect; it does not prove the user is signed out. Check app account status and broker compatibility."},...r?{updateAvailable:r}:{}})});e.registerTool("list_tool_actions",{description:"List the actions a tool exposes, and which connected devices offer it. Leave toolId out to list every tool's actions. Use the action names with call_action.",inputSchema:{toolId:G.string().optional().describe('The tool id, e.g. "perf-monitor", "network", "react-query". Leave out for every tool.'),tool:G.string().optional().describe("Same as toolId."),deviceId:G.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(d=>!i||d.deviceId===i);if(c.length===0)return ft(i?`No connected device "${i}". Call list_devices.`:"No devices are connected. Call list_devices.");const l=c.map(d=>[`**${d.deviceName}** (${d.deviceId})`,...d.tools.map(u=>`- ${u.toolId}: ${u.actions.join(", ")}`)].join("\n"));return{content:[{type:"text",text:`${l.join("\n\n")}
2
+ `));this.autoSpawn=e.autoSpawnBroker??true}async start(){const e=await qn(this.url)||await qn(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 pc(()=>this.broker?.refreshAccess());this.hostAccount.start();let t=false;this.broker=gc({canUseDesktop:this.hostAccount.hasAccess,port:this.port,onError:r=>{if(r.code==="EADDRINUSE")t=true;this.log(`broker error: ${r.code??r.message}`)}});await Cc(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{vc(this.broker.dashboardToken,Ln(this.port))}catch(r){this.log(`could not write the broker token file: ${r.message}`)}n="spawned"}else{this.log(`found a running broker at ${this.url} \u2014 connecting as a dashboard`)}await this.connectSocket();return n}connectSocket(){return new Promise((e,n)=>{const t=wc(this.url,{transports:["websocket"],query:{deviceName:Nn},auth:s=>{const c=this.broker?.dashboardToken??bc(Ln(this.port));s(c?{dashboardToken:c}:{})},reconnection:true,reconnectionDelay:500,timeout:4e3});this.socket=t;let r=false;const i=()=>{if(r)return;r=true;this.log("connected to broker");e()};const o=setTimeout(()=>{if(r)return;r=true;n(new Error("Broker account is locked or the broker needs an update. Sign in to Buoy Desktop or run npx buoy login for standalone MCP."))},5e3);t.on("buoy:access",s=>{const c=!!s&&typeof s==="object"&&s.protocol===1&&s.ready===true;this.setAdmission(c);if(c){clearTimeout(o);this.rearmWatches();i()}});t.on("connect",()=>{t.emit("buoy:access:request")});t.on("disconnect",()=>this.setAdmission(false,true));const a=s=>s.message===yc;t.once("connect_error",s=>{if(r)return;r=true;clearTimeout(o);n(new Error(a(s)?`The broker at ${this.url} refused this MCP as a dashboard: the token in ${Ln(this.port)} is missing or stale. Update Buoy Desktop, or restart it so it writes the file.`:`failed to connect to broker at ${this.url}: ${s.message}`))});t.on("connect_error",s=>{if(!a(s)||t.active)return;setTimeout(()=>{if(this.socket===t&&!t.connected)t.connect()},1e3).unref?.()});t.on("devtool-capabilities",s=>{if(!this.admitted||this.lockedDevices.has(s.persistentDeviceId))return;this.capabilities.set(s.persistentDeviceId,s);this.trackRootLookup(this.learnDevServerOrigin(s.persistentDeviceId));if(s.tools?.some(c=>c.toolId==="console"))this.ensureWatching("console",s.persistentDeviceId)});t.on("all-devices-update",s=>{if(!this.admitted)return;if(!Array.isArray(s))return;let c=false;for(const d of s){if(d.deviceId&&d.tier==="locked")this.lockDevice(String(d.deviceId));else if(d.deviceId&&(d.tier==="free"||d.tier==="pro")){c=this.lockedDevices.delete(String(d.deviceId))||c}}this.devices=s;const l=Date.now();for(const d of s)if(d.deviceId)this.lastSeen.set(d.deviceId,l);this.pruneStaleDevices();if(c)this.rearmWatches();else this.rearmReconnectedDevices(s)});t.on("devtool-sync",s=>{if(!this.admitted||this.lockedDevices.has(s.persistentDeviceId))return;const c=De(s.persistentDeviceId,s.toolId);this.snapshots.set(c,s.payload);this.snapshotAt.set(c,Date.now());if(s.toolId==="console")this.noteCrashReport(s.persistentDeviceId,s.payload);const l=this.snapshotWaiters.get(c);if(l&&l.length){this.snapshotWaiters.set(c,[]);for(const d of l)d(s.payload)}});t.on("devtool-action-result",s=>{if(!this.admitted)return;const c=this.pendingActions.get(s.requestId);if(!c)return;this.pendingActions.delete(s.requestId);clearTimeout(c.timer);c.resolve(s)})})}requireAdmission(){if(!this.admitted)throw new Error("A verified Buoy account and an updated broker are required. Sign in to Buoy Desktop, or run npx buoy login for standalone MCP.")}setAdmission(e,n=false){this.admitted=e;if(e)return;this.devices=[];this.lockedDevices.clear();this.capabilities.clear();this.snapshots.clear();this.snapshotAt.clear();this.devServerOrigins.clear();this.devServerRoots.clear();this.crashSeen.clear();this.originProbed.clear();this.health.clear();this.lastSeen.clear();if(!n)this.watching.clear();for(const t of this.pendingActions.values()){clearTimeout(t.timer);t.reject(new Error("Buoy account access ended while the action was pending."))}this.pendingActions.clear();for(const t of this.snapshotWaiters.values())for(const r of t)r(void 0);this.snapshotWaiters.clear();if(this.socket)this.socket.sendBuffer=[]}requireDeviceAccount(e){if(this.lockedDevices.has(e))throw new Error("The device's Buoy account access ended. Sign in and verify its key.")}lockDevice(e){this.lockedDevices.add(e);this.capabilities.delete(e);this.health.delete(e);this.devServerOrigins.delete(e);this.devServerRoots.delete(e);this.originProbed.delete(e);const n=`${e}::`;for(const t of this.snapshots.keys())if(t.startsWith(n)){this.snapshots.delete(t);this.snapshotAt.delete(t)}for(const[t,r]of this.snapshotWaiters)if(t.startsWith(n)){this.snapshotWaiters.delete(t);for(const i of r)i(void 0)}for(const[t,r]of this.pendingActions)if(r.target===e||r.target===ve){clearTimeout(r.timer);this.pendingActions.delete(t);r.reject(new Error("Device account access ended while the action was pending."))}}pruneStaleDevices(){const e=Date.now()-Us;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!==Nn&&e.deviceId).map(e=>{const n=this.capabilities.get(e.deviceId);return{deviceId:e.deviceId,deviceName:e.deviceName,platform:e.platform,isConnected:e.isConnected!==false,isPro:e.isPro===true,tier:e.tier==="free"||e.tier==="pro"?e.tier:e.tier===void 0&&e.isPro===true?"pro":"locked",collision:e.collision===true,tools:n?.tools??[]}})}connectedDevices(){return this.listDevices().filter(e=>e.isConnected)}toolActions(e){return this.listDevices().map(n=>{const t=n.tools.find(r=>r.toolId===e);return t?{deviceId:n.deviceId,deviceName:n.deviceName,actions:t.actions}:null}).filter(n=>n!==null)}resolveDevice(e){this.requireAdmission();if(e){this.requireDeviceAccount(e);return e}const n=(l,d)=>new Error(`${It} "${l}" (${d}) 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(d=>d.deviceId===this.sessionDevice);if(l&&l.isConnected!==false)return this.sessionDevice;throw n(this.sessionDevice,"the device this session was using")}const t=this.connectedDevices();const r=t.filter(l=>!this.lockedDevices.has(l.deviceId));const i=r.filter(l=>l.tools.length>0);const o=process.env.BUOY_PROJECT_ROOT||process.cwd();const a=gi(i.map(l=>({deviceId:l.deviceId,root:this.devServerRoots.get(l.deviceId)})),o);if(a)return this.sessionDevice=a;const s=gi(this.devices.filter(l=>l.deviceId&&l.isConnected===false&&!this.lockedDevices.has(l.deviceId)).map(l=>({deviceId:l.deviceId,root:this.devServerRoots.get(l.deviceId)})),o);if(s)throw n(s,"this project's app");if(r.length===0){if(t.length>0){throw new Error(`Devices are connected (${t.map(l=>l.deviceName).join(", ")}), but the broker has not admitted their accounts. Check app account validation and the account announcement after reconnect; this does not prove the user is signed out.`)}throw new Error("No devices are connected to the broker. Open the app with Buoy devtools running.")}if(r.length===1)return this.sessionDevice=r[0].deviceId;if(i.length===1)return this.sessionDevice=i[0].deviceId;if(i.length===0){const l=r.map(d=>d.deviceName).join(", ");throw new Error(`Connected devices (${l}) are not exposing any Buoy tools yet. Make sure the app is in the foreground with devtools mounted, then retry.`)}const c=i.map(l=>`${l.deviceName} (${l.deviceId})`).join(", ");throw new Error(`Multiple devices connected \u2014 specify deviceId. Connected: ${c}`)}requireProDevice(e){this.requireAdmission();if(e&&e!==ve)this.sessionDevice=e;const n=o=>{if(!o)return"";return o.tier==="locked"?` The broker has not confirmed account access for "${o.deviceName}"; a locked status does not establish whether a key is configured.`:` The connected app "${o.deviceName}" is on the ${o.tier} tier.`};const t=o=>`Buoy Pro is required to use the MCP.${n(o)} Enter a license in the app, or \u2014 if it runs headless (no on-device UI) \u2014 pass \`licenseKey\` to \`<FloatingDevTools />\`. Run \`list_devices\` to check status.`;if(e===ve){if(!this.connectedDevices().some(o=>o.isPro))throw new Error(t());return ve}const r=this.resolveDevice(e);const i=this.connectedDevices().find(o=>o.deviceId===r);if(!i?.isPro){const o=this.accessState(r);if(o==="offline")throw new Error(`${It} "${r}" is not connected right now. If the app is starting or reloading, it usually takes a few seconds. Run list_devices to check.`);if(o==="pending")throw new Error(`${It} account access for "${r}" is still being confirmed (the app just connected). Try again in a moment.`);throw new Error(t(i))}return r}accessState(e){const n=this.devices.find(t=>t.deviceId===e);if(!n||n.isConnected===false)return"offline";if(n.isPro===true)return"ready";return n.tier===void 0?"pending":"denied"}healthOf(e){let n=this.health.get(e);if(!n){n={consecutiveTimeouts:0,lastOkAt:0,lastFullBudgetAt:0};this.health.set(e,n)}return n}noteOk(e){const n=this.healthOf(e);n.consecutiveTimeouts=0;n.lastOkAt=Date.now()}noteTimeout(e){this.healthOf(e).consecutiveTimeouts+=1}isUnresponsive(e){return bi(this.healthOf(e).consecutiveTimeouts)}timeoutFor(e,n,t){const r=this.healthOf(e);const{timeoutMs:i,usedFullBudget:o}=Ac({consecutiveTimeouts:r.consecutiveTimeouts,lastFullBudgetAt:r.lastFullBudgetAt,now:Date.now(),fullMs:this.actionTimeoutMs,shortMs:Bn,recoveryProbeMs:ci,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=Dc({consecutiveTimeouts:n.consecutiveTimeouts,lastOkAt:n.lastOkAt,now:Date.now(),unresponsiveAfterMs:qs});const i=[`The app on "${e}" is not responding (${n.consecutiveTimeouts} call${n.consecutiveTimeouts===1?"":"s"} unanswered${t!=null?`, last answered ${t}s ago`:""}).`,r?"It is most likely CRASHED \u2014 a fatal render error unmounts the React tree, and the dev tools live in that tree, so nothing on-device can answer until the app is reloaded.":"It may be busy, mid-reload, or crashing."];const o=this.lastFatalFor(e);if(o)i.push(`Last captured error: ${o}`);i.push(o?"Read the crash state with get_console / get_storage (served from the last sync), then reload_app to recover.":"Try get_console (served from the last sync) for the app's last words, then reload_app to recover.");return i.join(" ")}noteCrashReport(e,n){const t=n?.entries;if(!Array.isArray(t)||t.length===0)return;const r=Math.max(...t.map(a=>typeof a?.timestamp==="number"?a.timestamp:-Infinity));const i=this.crashSeen.get(e)??new Set;let o=false;for(const a of t){const s=a?.fatal||/^\[(RENDER ERROR|FATAL)/.test(a?.message??"");if(!s||typeof a.timestamp!=="number")continue;const c=`${a.id??""}|${a.timestamp}|${(a.message??"").slice(0,120)}`;if(i.has(c))continue;i.add(c);if(r-a.timestamp<3e4)o=true}if(i.size>200)for(const a of[...i].slice(0,i.size-200))i.delete(a);this.crashSeen.set(e,i);if(!o)return;if(![...this.pendingActions.values()].some(a=>a.target===e&&a.expire&&!a.cut))return;void this.callAction("app","ping",{},e,{timeoutMs:1500,silent:true}).then(()=>void 0,()=>{const a=Date.now();for(const s of this.pendingActions.values()){if(s.target!==e||!s.expire||s.cut)continue;s.cut=true;if(s.deadline!==void 0&&s.deadline-a<=Bn)continue;clearTimeout(s.timer);s.timer=setTimeout(s.expire,Bn)}})}lastFatalFor(e){const n=this.snapshots.get(De(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(De(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=Sc(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(De(e,"app"));if(typeof t?.devServerOrigin==="string")return t.devServerOrigin;return null}ensureWatching(e,n){const t=De(n,e);if(this.watching.has(t))return;this.watching.set(t,{toolId:e,targetDeviceId:n});this.sendWatch(e,n)}sendWatch(e,n){if(!this.admitted||!this.socket?.connected||this.lockedDevices.has(n))return;this.socket?.emit("devtool-watch",{toolId:e,targetDeviceId:n,watching:true,stream:false})}rearmWatches(){for(const{toolId:e,targetDeviceId:n}of this.watching.values()){this.sendWatch(e,n)}}rearmReconnectedDevices(e){for(const n of e){if(!n.deviceId||n.isConnected===false)continue;const t=String(n.deviceId);const r=`${n.id}|${n.connectionNonce??""}`;const i=this.deviceConnections.get(t);this.deviceConnections.set(t,r);if(i===void 0||i===r)continue;for(const{toolId:o,targetDeviceId:a}of this.watching.values()){if(a===t)this.sendWatch(o,a)}}}unwatch(e,n){const t=De(n,e);if(!this.watching.delete(t))return;if(this.admitted&&this.socket?.connected)this.socket.emit("devtool-watch",{toolId:e,targetDeviceId:n,watching:false})}cachedSnapshot(e,n){this.requireAdmission();this.requireDeviceAccount(n);return this.snapshots.get(De(n,e))}async getSnapshot(e,n,t={}){const r=this.resolveDevice(n);const i=De(r,e);this.ensureWatching(e,r);let o=t.timeoutMs??li;if(t.timeoutMs===void 0&&this.isUnresponsive(r)){const l=this.healthOf(r);if(Date.now()-l.lastFullBudgetAt>ci){l.lastFullBudgetAt=Date.now()}else{o=Ls}}const a=this.waitForSnapshot(i,o);this.socket?.emit("request-devtool-state",{toolId:e,targetDeviceId:r});const s=await a;this.requireAdmission();this.requireDeviceAccount(r);if(s!==void 0){if(!t.silent)this.noteOk(r);return{deviceId:r,payload:s}}if(!t.silent)this.noteTimeout(r);const c=this.snapshots.get(i);if(c!==void 0){return{deviceId:r,payload:c,stale:this.staleNote(e,r)}}throw new Error(`Timed out waiting for "${e}" state from ${r} (is the tool active?). ${this.unresponsiveNote(r)}`)}lastSync(e,n){const t=this.snapshots.get(De(e,n));return t===void 0?void 0:{payload:t,ageMs:this.snapshotAgeMs(n,e)}}staleNote(e,n){const t=this.snapshotAgeMs(e,n);const r=t==null?"an earlier sync":`${Math.round(t/1e3)}s ago`;return`\u26A0\uFE0F Served from the last sync (${r}) \u2014 ${this.unresponsiveNote(n)}`}waitForSnapshot(e,n){return new Promise(t=>{const r=this.snapshotWaiters.get(e)??[];const i=setTimeout(()=>{const a=(this.snapshotWaiters.get(e)??[]).filter(s=>s!==o);this.snapshotWaiters.set(e,a);t(void 0)},n);const o=a=>{clearTimeout(i);t(a)};r.push(o);this.snapshotWaiters.set(e,r)})}async callAction(e,n,t,r,i={}){this.requireAdmission();const o=r===ve?ve:this.resolveDevice(r);if(!this.socket)throw new Error("SyncClient is not connected");const a=mc();const s=i.timeoutMs??this.timeoutFor(o,e,n);const c=await new Promise((l,d)=>{const u=Date.now();const h=()=>{this.pendingActions.delete(a);if(o!==ve&&!i.silent)this.noteTimeout(o);d(new Error(`Action "${e}.${n}" got no answer in ${Date.now()-u}ms. `+(o===ve?"No device responded.":this.unresponsiveNote(o))))};const p=setTimeout(h,s);this.pendingActions.set(a,{resolve:l,reject:d,timer:p,target:o,expire:h,deadline:u+s});this.socket.emit("devtool-action",{requestId:a,toolId:e,targetDeviceId:o,action:n,params:t??{}})});if(o!==ve&&!i.silent)this.noteOk(o);if(!c.ok){throw new Error(c.error||`Action "${e}.${n}" failed on device`)}return c.result}};var De=(e,n)=>`${e}::${n}`;function qn(e,n=800){return new Promise(t=>{const r=fc.get(e,i=>{i.resume();t((i.statusCode??0)>0)});r.setTimeout(n,()=>{r.destroy();t(false)});r.on("error",()=>t(false))})}async function Cc(e,n=20){for(let t=0;t<n;t++){if(await qn(e,300))return;await Ec(50)}throw new Error(`Spawned broker never became reachable at ${e}`)}var Ec=e=>new Promise(n=>setTimeout(n,e));var At="7.0.62"?"7.0.62":"0.0.0-dev";var Un="@buoy-gg/mcp";import{promises as vi}from"fs";import Oc from"os";import Rc from"path";var Pc=24*60*60*1e3;var Fc=1500;var Bc=`https://registry.npmjs.org/${Un}/latest`;var yi=Rc.join(Oc.tmpdir(),"buoy-mcp-update-check.json");function Nc(e,n){const t=o=>o.split("-")[0].split(".").map(a=>Number(a)||0);const r=t(e);const i=t(n);for(let o=0;o<3;o++){const a=r[o]??0;const s=i[o]??0;if(a>s)return true;if(a<s)return false}return false}async function jc(){try{const e=await vi.readFile(yi,"utf8");const n=JSON.parse(e);if(typeof n.checkedAt==="number"&&typeof n.latest==="string"){return n}}catch{}return null}async function Lc(e){const n=new AbortController;const t=setTimeout(()=>n.abort(),Fc);try{const r=await fetch(Bc,{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 vi.writeFile(yi,JSON.stringify({checkedAt:e,latest:o})).catch(()=>{})}return o}catch{return null}finally{clearTimeout(t)}}async function qc(e){const n=await jc();if(n&&e-n.checkedAt<Pc)return n.latest;return Lc(e)}async function $i(e=Date.now()){if(At==="0.0.0-dev")return null;try{const n=await qc(e);if(n&&Nc(n,At)){return`A newer buoy-mcp is available (${n}; you're on ${At}). Update by re-running: npx -y ${Un}@latest init \u2014 then restart your editor.`}}catch{}return null}import{z as G}from"zod";import{execFile as Uc}from"child_process";import{promisify as zc}from"util";import{promises as Se}from"fs";import ki from"os";import fe from"path";import{randomUUID as _i}from"crypto";var Dt=zc(Uc);var Zt=(e,n,t)=>Math.min(Math.max(e,n),t);function Si(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 Wc(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 Hc="@react_buoy_sync_device_id";async function Qt(e){try{return await Se.readdir(e)}catch{return[]}}async function Jc(e){const n=[];for(const t of await Qt(e))n.push(...await xi(fe.join(e,t)));return n}async function xi(e){const n=[];const t=fe.join(e,"Library","WebKit");for(const r of await Qt(t)){const i=fe.join(t,r,"WebsiteData","Default");for(const o of await Qt(i)){for(const a of await Qt(fe.join(i,o))){const s=fe.join(i,o,a,"LocalStorage","localstorage.sqlite3");try{await Se.access(s);const{stdout:c}=await Dt("sqlite3",["-readonly",s,`SELECT hex(value) FROM ItemTable WHERE key='${Hc}' LIMIT 1;`],{timeout:1500});const l=c.trim();if(l)n.push(Buffer.from(l,"hex").toString("utf16le").trim())}catch{}}}}return n}var Ti=new Map;var Gc=3e4;async function Ii(e){if(process.platform!=="darwin")return{ok:false,error:"Simulator lookup needs macOS."};let n=[];try{const{stdout:r}=await Dt("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const i=JSON.parse(r).devices;n=Object.entries(i).filter(([o])=>/iOS/.test(o)).flatMap(([,o])=>o.filter(a=>a.state==="Booted"))}catch(r){return{ok:false,error:Si(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=fe.join(r.dataPath,"Containers","Data","Application");let o=[];try{o=await Se.readdir(i)}catch{continue}for(const a of o){try{const s=(await Se.readFile(fe.join(i,a,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim();if(s===t)return{ok:true,udid:r.udid,how:`matched ${e} to "${r.name}"`}}catch{}}}}if(t&&e){const r=n.map(c=>c.udid).sort().join(",");const i=Ti.get(e);const o=i?.booted===r&&(i.udid!==null||Date.now()-i.at<Gc);const a=o&&i?.udid?n.find(c=>c.udid===i.udid):void 0;if(a)return{ok:true,udid:a.udid,how:`matched ${e} to "${a.name}" (WebView storage)`};const s=[];if(!o){const c=await Promise.all(n.map(l=>l.dataPath?Jc(fe.join(l.dataPath,"Containers","Data","Application")):Promise.resolve([])));c.forEach((l,d)=>{if(l.includes(t))s.push(n[d])});Ti.set(e,{booted:r,udid:s.length===1?s[0].udid:null,at:Date.now()})}if(s.length===1){return{ok:true,udid:s[0].udid,how:`matched ${e} to "${s[0].name}" (WebView storage)`}}if(s.length>1){return{ok:false,error:`${s.length} booted simulators (${s.map(c=>c.name).join(", ")}) hold ${e}. Pass the udid, or shut one down.`}}}if(n.length===1)return{ok:true,udid:n[0].udid,how:`only booted simulator "${n[0].name}"`};return{ok:false,error:`${n.length} iOS Simulators are booted (${n.map(r=>r.name).join(", ")}) and none could be matched to ${e??"this device"}. Shut down the others, or capture from a single booted simulator.`}}async function Kc(e){const n=new Map;if(process.platform!=="darwin"||e.length===0)return n;let t=[];try{const{stdout:i}=await Dt("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const o=JSON.parse(i).devices;t=Object.entries(o).filter(([a])=>/iOS/.test(a)).flatMap(([,a])=>a.filter(s=>s.state==="Booted"))}catch{return n}const r=new Map;for(const i of t){if(!i.dataPath)continue;const o=fe.join(i.dataPath,"Containers","Data","Application");let a=[];try{a=await Se.readdir(o)}catch{continue}for(const s of a){try{const c=(await Se.readFile(fe.join(o,s,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim();if(c)r.set(c,{name:i.name,udid:i.udid})}catch{}}}for(const i of e){const o=r.get(i.split("-").pop()??"");if(o)n.set(i,o)}return n}async function Ai(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=fe.join(ki.tmpdir(),`buoy-mcp-sim-${_i()}.png`);try{await Dt("xcrun",["simctl","io",e,"screenshot","--type=png",n],{timeout:15e3})}catch(t){return{ok:false,error:Si(t)}}try{const t=await Se.readFile(n);const r=Wc(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 Vc(e,n,t){const r=Zt(Math.round(t.x),0,Math.max(0,n.width-1));const i=Zt(Math.round(t.y),0,Math.max(0,n.height-1));const o=Zt(Math.round(t.width),1,n.width-r);const a=Zt(Math.round(t.height),1,n.height-i);const s=fe.join(ki.tmpdir(),`buoy-mcp-crop-${_i()}.png`);try{await Dt("sips",["-c",String(a),String(o),"--cropOffset",String(i),String(r),e,"--out",s],{timeout:1e4});const c=await Se.readFile(s);return{ok:true,buffer:c,width:o,height:a}}catch(c){const l=c;return{ok:false,error:`Crop failed: ${l?.stderr||l?.message||c}`}}finally{await Se.unlink(s).catch(()=>{});await Se.unlink(e).catch(()=>{})}}import{execFile as Yc}from"child_process";import{promisify as Xc}from"util";var zn=Vt(Yt());import{execFile as Zc}from"child_process";import{promisify as Qc}from"util";import{promises as V}from"fs";import Mt from"os";import z from"path";import{randomUUID as el}from"crypto";var tl=Vt(Yt());import{execFile as nl}from"child_process";import{promisify as rl}from"util";import{promises as Ve}from"fs";import Wn from"os";import Hn from"path";import{randomUUID as Jn}from"crypto";var il=rl(nl);async function he(e,n=3e4){const t=Hn.join(Wn.tmpdir(),`buoy-devicectl-${Jn()}.json`);try{await il("xcrun",["devicectl",...e,"--quiet","--json-output",t],{timeout:n,maxBuffer:16*1024*1024});return JSON.parse(await Ve.readFile(t,"utf8"))}catch(r){const i=r;let o=(i.stderr||i.stdout||i.message||"").trim();try{const a=JSON.parse(await Ve.readFile(t,"utf8"));o=a.error?.userInfo?.NSLocalizedDescription?.string??o}catch{}if(/locked/i.test(o))throw new Error("The iPhone is locked. Unlock it and try again.");throw new Error(`devicectl ${e.slice(0,2).join(" ")} failed: ${o.split("\n").slice(-3).join(" ").slice(0,300)}`)}finally{await Ve.unlink(t).catch(()=>void 0)}}async function ol(){if(process.platform!=="darwin")return[];return al(await he(["list","devices"],15e3).catch(()=>null))}function al(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 Di(e){const n=await he(["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 Mi(e,n,t){const r=await he(["device","info","files","--device",e,"--domain-type","appDataContainer","--domain-identifier",n],2e4);const i=new Set((r.result?.files??[]).map(a=>a.relativePath??a.name??""));if(!i.has(t))return null;const o=Hn.join(Wn.tmpdir(),`buoy-devfile-${Jn()}`);try{await he(["device","copy","from","--device",e,"--domain-type","appDataContainer","--domain-identifier",n,"--source",t,"--destination",o],2e4);return await Ve.readFile(o)}finally{await Ve.rm(o,{recursive:true,force:true}).catch(()=>void 0)}}async function Ci(e,n){const t=await Mi(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 Ei(e){const n=Hn.join(Wn.tmpdir(),`buoy-phone-shot-${Jn()}.png`);try{await he(["device","capture","screenshot","--device",e,"--destination",n],3e4);return await Ve.readFile(n)}finally{await Ve.unlink(n).catch(()=>void 0)}}var sl="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 cl(e){try{const n=tl.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 Gn(e,n,t={}){await he(["device","process","launch","--device",e,...t.terminateExisting?["--terminate-existing"]:[],...t.url?["--payload-url",t.url]:[],n])}async function ll(e,n){await he(["device","process","openURL","--device",e,n])}async function Oi(e,n){const t=await Di(e);const r=t.find(a=>a.bundleId===n)?.path;const i=await he(["device","info","processes","--device",e]);const o=(i.result?.runningProcesses??[]).find(a=>r&&decodeURIComponent(a.executable??"").replace(/^file:\/\//,"").startsWith(r.replace(/\/$/,"")));if(!o?.processIdentifier)return false;await he(["device","process","terminate","--device",e,"--pid",String(o.processIdentifier)]);return true}async function dl(e,n){await he(["device","uninstall","app","--device",e,n],12e4)}async function ul(e,n){await he(["device","install","app","--device",e,n],3e5)}async function hl(e,n,t,r){await he(["device","copy","to","--device",e,"--domain-type","appDataContainer","--domain-identifier",n,"--source",t,"--destination",r],3e4)}function pl(e,n,t){return["devicectl","device","capture","screen-record","--device",e,"--destination",n,"--duration",String(t)]}var Ri=new Map;async function Kn(e){const n=Ri.get(e);if(n)return n;const t=await he(["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.");Ri.set(e,r);return r}import{execFile as fl}from"child_process";import{promisify as ml}from"util";import{promises as Vn}from"fs";import lt from"path";import{WebSocket as wl}from"ws";import{execFile as gl}from"child_process";import{promisify as bl}from"util";var Yn=/\{\{\s*secret:([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;var dt=6;var Xn=new Map;var Pi=()=>false;function vl(e){Pi=e}function yl(e){Yn.lastIndex=0;return Yn.test(e)}function en(e,n=process.env){if(!yl(e))return e;if(Pi()){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(Yn,(o,a)=>{const s=n[`BUOY_SECRET_${a}`]??n[a];if(s===void 0||s===""){t.push(a);return""}if(s.length<dt){r.push(a);return""}Xn.set(a,s);return s});if(t.length){throw new Error(`No value for ${t.map(o=>`{{secret:${o}}}`).join(", ")}. Set ${t.map(o=>`BUOY_SECRET_${o}`).join(", ")} in the environment the MCP server runs in (for example in your editor's MCP config "env").`)}if(r.length){throw new Error(`${r.map(o=>`{{secret:${o}}}`).join(", ")} is shorter than ${dt} 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 Fi(e=process.env){const n=new Map(Xn);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 $l=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function pe(e){const n=new Map;for(const[i,o]of Fi()){if(o.length<dt)continue;for(const a of[o,JSON.stringify(o).slice(1,-1),encodeURIComponent(o)])n.set(a,i);for(let a=o.length-1;a>=dt;a--){n.set(`${o.slice(0,a)}\u2026`,i);n.set(`${o.slice(0,a)}...`,i);if(a>=8)n.set(o.slice(0,a),i)}}if(n.size===0)return e;const t=[...n.keys()].sort((i,o)=>o.length-i.length);const r=new RegExp(t.map($l).join("|"),"g");return e.replace(r,(i,o,a)=>{if(/^\d+$/.test(i)){const s=a.slice(Math.max(0,o-8),o);const c=a.slice(o+i.length,o+i.length+8);if(/(\d|\d\.)$/.test(s)||/^(\d|\.\d|[eE][+-]?\d)/.test(c))return i;if(/[:[,]\s*$/.test(s)&&/^\s*([,\]}]|$)/.test(c)&&!kl(a,o))return`"{{secret:${n.get(i)}}}"`}return`{{secret:${n.get(i)}}}`})}function kl(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 Zn(){return[...Xn.values()]}function _l(){return[...Fi().values()].filter(e=>e.length>=dt)}var Bi=bl(gl);var Ni="Android control needs adb on this computer (Android SDK platform-tools). Install it, or add it to PATH.";function ee(e){return`'${e.replace(/'/g,`'\\''`)}'`}function ji(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 xe(e,n,t=15e3){try{const{stdout:r}=await Bi("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(Ni);const o=n[0]==="shell"?`shell ${(n[1]??"").split(" ")[0]}`:n.slice(0,2).join(" ");const a=n[0]==="shell"?i.stderr||(i.killed?"timed out":"no error text"):i.stderr||i.message||"";const s=pe(a.replace(/'[^']*'/g,"'\u2026'")).trim().slice(0,300);throw new Error(`adb ${o} failed: ${s}`)}}function L(e,n,t=15e3){return xe(e,["shell",n],t)}async function Li(e,n,t=15e3){try{const{stdout:r}=await Bi("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(Ni);throw new Error(`adb ${n.slice(0,2).join(" ")} failed: ${i.message.slice(0,300)}`)}}async function Sl(){return xl(await xe(null,["devices"]))}function xl(e){return e.split("\n").slice(1).map(n=>n.trim().split(/\s+/)).filter(n=>n[1]==="device").map(n=>n[0])}async function qi(e){const n=Tl(await L(e,"wm size"));const t=Il(await L(e,"dumpsys input").catch(()=>""));return t%2===1?{width:n.height,height:n.width}:n}function Tl(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 Il(e){const n=/SurfaceOrientation:\s*(\d)/.exec(e);return n?Number(n[1]):0}async function Al(e,n){const t=await L(e,"dumpsys window windows").catch(()=>"");return Dl(t,n)}function Dl(e,n){const t=e.split(/\n(?=\s*Window #\d+)/);for(const r of t){if(!r.includes(`${n}/`))continue;const i=/mFrame=\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(r)??/\bframe=\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(r);if(i){const[o,a,s,c]=i.slice(1).map(Number);if(s>o&&c>a)return{x:o,y:a,width:s-o,height:c-a}}}return null}async function Ml(e){return Cl(await L(e,"dumpsys activity activities"))}function Cl(e){const n=/(?:topResumedActivity|mResumedActivity|ResumedActivity)[^\n]*?\s([a-zA-Z][\w.]*)\/[\w.$]+/.exec(e);return n?n[1]:null}async function El(e){const n=await L(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 Ui(e,n){ji(n);const t=await L(e,`run-as ${ee(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 Li(e,["exec-out",`run-as ${ee(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?Ol(i):null}function Ol(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 Rl(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 ee(e.replace(/ /g,"%s"))}async function Pl(e,n,t,r){const[i,o]=[Math.round(n),Math.round(t)];if(r)await L(e,`input swipe ${i} ${o} ${i} ${o} ${Math.round(r)}`);else await L(e,`input tap ${i} ${o}`)}async function Fl(e,n,t,r){const i=[...n,...t].map(o=>Math.round(o)).join(" ");await L(e,`input swipe ${i} ${Math.round(r)}`)}async function Bl(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 L(e,`input text ${Rl(i)}`)}}async function Nl(e){const n=await Li(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 zi(e,n){if(n){await L(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 L(e,`am broadcast -a com.android.systemui.demo ${t}`).catch(()=>void 0)}}else{await L(e,"am broadcast -a com.android.systemui.demo -e command exit").catch(()=>void 0)}}async function jl(e){const n=await xe(e,["exec-out","uiautomator","dump","/dev/tty"],2e4);return Ll(n)}function Ll(e){const n=[];const t=(r,i)=>{const o=new RegExp(`\\s${i}="([^"]*)"`).exec(r);return o?ql(o[1]):""};for(const r of e.matchAll(/<node\b[^>]*>/g)){const i=r[0];const o=/\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(t(i,"bounds"));if(!o)continue;const[a,s,c,l]=o.slice(1).map(Number);n.push({text:t(i,"text"),desc:t(i,"content-desc"),id:t(i,"resource-id"),cls:t(i,"class"),clickable:t(i,"clickable")==="true",bounds:{x:a,y:s,width:c-a,height:l-s}})}return n}function ql(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 Ul(e,n){const t=n.trim().toLowerCase();const r=c=>{let l=0;for(const d of[c.desc,c.text,c.id.split("/").pop()??""]){const u=d.trim().toLowerCase();if(!u)continue;if(u===t)l=Math.max(l,3);else if(u.startsWith(t))l=Math.max(l,2);else if(u.includes(t))l=Math.max(l,1)}return l};const i=e.filter(c=>c.bounds.width>0&&c.bounds.height>0&&r(c)>0);const o=Math.max(0,...i.map(r));const a=i.filter(c=>r(c)===o);let s=a.filter((c,l)=>a.findIndex(d=>JSON.stringify(d.bounds)===JSON.stringify(c.bounds))===l);if(s.length>1){const c=s.filter(l=>[l.desc,l.text,l.id.split("/").pop()??""].some(d=>d.trim()===n.trim()));if(c.length)s=c}if(s.length>1){const c=s.filter(l=>l.clickable||/EditText|Button/.test(l.cls));if(c.length)s=c}return s}var zl=ml(fl);var Wi=/^(@buoy\/session:|buoy-gg-license|buoy-gg-device-fingerprint$|@react_buoy_sync_device_id$|@react_buoy_install)/;async function Qn(e){return Vn.readdir(e).catch(()=>[])}async function er(e){const n=[];const t=lt.join(e,"Library","WebKit");for(const r of await Qn(t)){const i=lt.join(t,r,"WebsiteData","Default");for(const o of await Qn(i)){for(const a of await Qn(lt.join(i,o))){const s=lt.join(i,o,a);const c=lt.join(s,"LocalStorage","localstorage.sqlite3");if(!await Vn.access(c).then(()=>true,()=>false))continue;const l=await Vn.readFile(lt.join(s,"origin")).then(d=>d.toString("hex"),()=>"");if(l)n.push({db:c,origin:l})}}}return n}var Hi=(e,n,t=true)=>zl("sqlite3",[...t?["-readonly"]:[],e,n],{timeout:5e3}).then(r=>r.stdout);async function Wl(e){const n=[];for(const{db:t,origin:r}of await er(e)){const i=await Hi(t,"SELECT key, hex(value) FROM ItemTable;");for(const o of i.split("\n")){const a=o.lastIndexOf("|");if(a<0)continue;const s=o.slice(0,a);if(Wi.test(s))n.push({key:s,value:o.slice(a+1),origin:r})}}return n}async function Hl(e,n){if(!n.length)return false;const t=await er(e);const r=new Set(n.map(i=>i.origin??""));for(const i of r){const o=i?t.find(s=>s.origin===i):void 0;if(!o)return false;const a=n.filter(s=>(s.origin??"")===i&&/^[0-9A-F]*$/i.test(s.value)).map(s=>`('${s.key.replace(/'/g,"''")}', X'${s.value}')`).join(",");if(a)await Hi(o.db,`INSERT OR REPLACE INTO ItemTable (key, value) VALUES ${a};`,false)}return true}async function Jl(e,n=15e3){const t=Date.now()+n;while(Date.now()<t){if((await er(e)).length)return true;await new Promise(r=>setTimeout(r,500))}return false}async function Gl(e,n,t){const r=(await L(e,`pidof ${n}`).catch(()=>"")).trim().split(/\s+/)[0];if(!r)throw new Error("the app is not running");const i=(await xe(e,["forward","tcp:0",`localabstract:webview_devtools_remote_${r}`])).trim();try{const o=await(await fetch(`http://127.0.0.1:${i}/json`)).json();const a=o.find(s=>s.type==="page"&&s.webSocketDebuggerUrl);if(!a?.webSocketDebuggerUrl)throw new Error("no debuggable WebView page (needs a debug build)");return await new Promise((s,c)=>{const l=new wl(a.webSocketDebuggerUrl);const d=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",u=>{const h=JSON.parse(String(u));if(h.id!==1)return;clearTimeout(d);l.close();if(h.result?.exceptionDetails)c(new Error("the WebView script failed"));else s(h.result?.result?.value)});l.on("error",u=>{clearTimeout(d);c(u)})})}finally{await xe(e,["forward","--remove",`tcp:${i}`]).catch(()=>void 0)}}async function Ji(e,n,t,r=15e3){const i=Date.now()+r;let o;while(Date.now()<i){try{return await Gl(e,n,t)}catch(a){o=a;await new Promise(s=>setTimeout(s,700))}}throw o instanceof Error?o:new Error("the WebView did not open")}async function Kl(e,n){const t=await L(e,`run-as ${n} sh -c 'ls app_webview/Default/"Local Storage"/leveldb 2>/dev/null'`).catch(()=>"");return/CURRENT|\.log/.test(t)}async function Vl(e,n){if(!(await L(e,`pidof ${n}`).catch(()=>"")).trim()){await L(e,`monkey -p ${n} -c android.intent.category.LAUNCHER 1`)}const t=await Ji(e,n,`(() => { const re = ${Wi}; 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 Yl(e,n,t){await Ji(e,n,`(() => { for (const r of ${JSON.stringify(t)}) localStorage.setItem(r.key, r.value); setTimeout(() => location.reload(), 50); return true; })()`)}var Xl=Qc(Zc);var Ye=new Map;function tn(e){return Ye.get(e)}async function Le(e,n,t=2e4){try{const{stdout:r}=await Xl(e,n,{timeout:t,maxBuffer:16*1024*1024});return r}catch(r){const i=r;if(i.code==="ENOENT")throw new Error(e==="xcrun"?"This needs macOS with Xcode (xcrun simctl).":`${e} is not installed.`);throw new Error(`${e} ${n.slice(0,2).join(" ")} failed: ${(i.stderr||i.message||"").trim().slice(0,300)}`)}}var Y=(e,n)=>Le("xcrun",["simctl",...e],n);var nn=e=>e.split("-").pop()??"";async function tr(e){let n=[];try{const r=JSON.parse(await Y(["list","devices","booted","-j"])).devices;n=Object.entries(r).filter(([i])=>/iOS/.test(i)).flatMap(([,i])=>i.filter(o=>o.state==="Booted"))}catch{return[]}const t=[];for(const r of n)if(await Gi(e,r.udid))t.push(r);return t}function nr(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 Gi(e,n){const t=nn(e);if(!t)return null;let r;try{const a=JSON.parse(await Y(["list","devices","-j"])).devices;r=Object.values(a).flat().find(s=>s.udid===n)?.dataPath}catch{return null}if(!r)return null;const i=z.join(r,"Containers","Data","Application");let o=[];try{o=await V.readdir(i)}catch{return null}for(const a of o){const s=z.join(i,a);if(!await Ki(s,t))continue;let c=null;try{c=(await Le("plutil",["-extract","MCMMetadataIdentifier","raw","-o","-",z.join(s,".com.apple.mobile_container_manager.metadata.plist")])).trim()||null}catch{}return{container:s,bundleId:c}}return null}async function Ki(e,n){try{if((await V.readFile(z.join(e,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim()===n)return true}catch{}return(await xi(e).catch(()=>[])).includes(n)}async function Zl(e,n){const t=nn(e);const r=n.serial?[n.serial]:await Sl();if(r.length===0)throw new Error("No Android device or emulator is connected to adb.");for(const i of r){const o=await Ml(i).catch(()=>null);const a=await El(i).catch(()=>[]);const s=[n.bundleId,o,...a].filter((c,l,d)=>!!c&&d.indexOf(c)===l).slice(0,80);for(const c of s){if(await Ui(i,c).catch(()=>null)===t)return{platform:"android",serial:i,packageName:c}}}return null}async function Ql(e){const n=nn(e);for(const t of await ol()){for(const r of await Di(t.udid).catch(()=>[])){if(await Ci(t.udid,r.bundleId)===n)return{platform:"ios-device",udid:t.udid,name:t.name,bundleId:r.bundleId}}}return null}async function Ct(e,n,t={}){if(e==="All")throw new Error('Device control acts on one app. Pass its deviceId, not "All".');const r=Ye.get(e);if(r&&!t.udid&&!t.serial&&await Yi(e,r)){if(r.platform==="ios"&&!r.picked){const c=await tr(e);if(c.length>1)throw nr(e,c)}return r}if(r)Ye.delete(e);if(n==="android"){const c=await Zl(e,t);if(!c){throw new Error(`Could not prove which Android device and app run "${e}". Buoy checks the app's install id with run-as, which needs a debug build of the app on a device adb can reach${t.serial?` (looked on ${t.serial})`:""}.`)}Ye.set(e,c);return c}if(n&&n!=="ios")throw new Error(`Device control works on iOS Simulators and Android. This app runs on "${n}".`);if(process.platform!=="darwin")throw new Error("iOS control needs macOS with Xcode.");let i=t.udid;let o=i??"";if(!i){const c=await tr(e);if(c.length>1)throw nr(e,c);const l=c.length===1?{ok:true,udid:c[0].udid,how:`matched ${e} to "${c[0].name}"`}:await Ii(e);if(!l.ok||!/^matched /.test(l.how)){const d=await Ql(e).catch(()=>null);if(d){Ye.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=l.udid;o=/"([^"]+)"/.exec(l.how)?.[1]??i}const a=await Gi(e,i);if(!a&&t.udid)throw new Error(`Simulator ${t.udid} does not hold "${e}".`);const s={platform:"ios",udid:i,name:o,bundleId:t.bundleId??a?.bundleId??null,container:a?.container??null,picked:!!t.udid};Ye.set(e,s);return s}async function Vi(e,n){if(n.platform==="ios"&&!n.picked){const t=await tr(e);if(t.length>1)throw nr(e,t)}if(await Yi(e,n))return n;Ye.delete(e);return Ct(e,n.platform==="android"?"android":"ios",n.platform==="ios"&&n.picked?{udid:n.udid}:{})}async function Yi(e,n){const t=nn(e);if(n.platform==="android")return await Ui(n.serial,n.packageName).catch(()=>null)===t;if(n.platform==="ios-device")return await Ci(n.udid,n.bundleId).catch(()=>null)===t;if(n.container)return Ki(n.container,t);const r=await Ii(e);return r.ok&&r.udid===n.udid&&/^matched /.test(r.how)}function rr(e){if(e.platform==="android")return ji(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 Xi(e){if(e.platform==="android")return Nl(e.serial);if(e.platform==="ios-device")return Ei(e.udid);const n=await Ai(e.udid);if(!n.ok||!n.srcPath)throw new Error(n.error??"Screenshot failed.");try{return await V.readFile(n.srcPath)}finally{await V.unlink(n.srcPath).catch(()=>{})}}async function ir(e,n=1280){if(process.platform==="darwin"){const i=z.join(Mt.tmpdir(),`buoy-mcp-img-${el()}.png`);const o=i.replace(/\.png$/,".jpg");await V.writeFile(i,e);try{await Le("sips",["-Z",String(n),"-s","format","jpeg","-s","formatOptions","70",i,"--out",o],15e3);const a=await Le("sips",["-g","pixelWidth","-g","pixelHeight",o]);return{data:(await V.readFile(o)).toString("base64"),mimeType:"image/jpeg",width:Number(/pixelWidth:\s*(\d+)/.exec(a)?.[1]??0),height:Number(/pixelHeight:\s*(\d+)/.exec(a)?.[1]??0)}}finally{await V.unlink(i).catch(()=>{});await V.unlink(o).catch(()=>{})}}const t=ed(zn.PNG.sync.read(e),Math.min(n,1024));const r=zn.PNG.sync.write(t,{colorType:2,deflateLevel:9});return{data:r.toString("base64"),mimeType:"image/png",width:t.width,height:t.height}}function ed(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 zn.PNG({width:r,height:i});const a=e.width/r;const s=e.height/i;for(let c=0;c<i;c++){const l=Math.floor(c*s);const d=Math.max(l+1,Math.floor((c+1)*s));for(let u=0;u<r;u++){const h=Math.floor(u*a);const p=Math.max(h+1,Math.floor((u+1)*a));const m=[0,0,0,0];let g=0;for(let f=l;f<d;f++){for(let b=h;b<p;b++){const y=(f*e.width+b)*4;for(let v=0;v<4;v++)m[v]+=e.data[y+v];g++}}const w=(c*r+u)*4;for(let f=0;f<4;f++)o.data[w+f]=Math.round(m[f]/g)}}return o}var or=new Set;async function td(e,n){let t=false;try{if(e.platform==="ios"){const r=await Y(["status_bar",e.udid,"list"]).catch(()=>"");const i=r.split(/^=+$/m).slice(1).join("").trim();if(!i){await Y(["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 L(e.serial,"settings get global sysui_demo_allowed").catch(()=>"")).trim();if(r!=="1"&&!or.has(e.serial)){or.add(e.serial);await zi(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 Y(["status_bar",e.udid,"clear"]).catch(()=>void 0);else if(e.platform==="android"){await zi(e.serial,false);await L(e.serial,"settings put global sysui_demo_allowed 0").catch(()=>void 0);or.delete(e.serial)}}}}async function ar(e){const n=rr(e);if(e.platform==="ios-device"){const t=await Oi(e.udid,n);return t?`Quit ${n}.`:`${n} was not running.`}if(e.platform==="ios"){await Y(["terminate",e.udid,n]).catch(t=>{if(!/found nothing to terminate|not running/i.test(String(t)))throw t})}else{await L(e.serial,`am force-stop ${ee(n)}`)}return`Quit ${n}.`}async function ut(e){const n=rr(e);if(e.platform==="ios")await Y(["launch",e.udid,n]);else if(e.platform==="ios-device")await Gn(e.udid,n);else await L(e.serial,`monkey -p ${ee(n)} -c android.intent.category.LAUNCHER 1`);return`Launched ${n}.`}async function nd(e){if(e.platform==="ios-device"){await Gn(e.udid,"com.apple.Preferences");return"Sent to the background for real (Settings opened on top)."}if(e.platform==="ios"){await Y(["launch",e.udid,"com.apple.Preferences"]);return"Sent to the background for real (Settings opened on top)."}await L(e.serial,"input keyevent 3");return"Sent to the background for real (pressed Home)."}async function rd(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 ll(e.udid,n);return"Opened through the OS on the iPhone."}if(e.platform==="ios"){await Y(["openurl",e.udid,n]);return'Opened through the OS. A custom scheme may first show an "Open in" prompt on the simulator.'}await L(e.serial,`am start -a android.intent.action.VIEW -d ${ee(n)}`);return"Opened through the OS (an Android VIEW intent)."}var id=["buoy-license","react-buoy/@react_buoy_sync_device_id.json","react-buoy/@react_buoy_install.json"];async function Zi(e){const n=z.join(e,"Info.plist");const t=a=>Le("plutil",["-extract",a,"raw","-o","-",n]).then(s=>s.trim()).catch(()=>"");const r=await t("CFBundleIdentifier");if(!r)throw new Error(`${e} has no Info.plist with a bundle id. Pass a built .app folder.`);const i=(await Le("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 od(e){const n=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT,z.join(Mt.homedir(),"Library","Android","sdk"),z.join(Mt.homedir(),"Android","Sdk")].filter(t=>!!t);for(const t of n){const r=z.join(t,"build-tools");const i=(await V.readdir(r).catch(()=>[])).sort().reverse();for(const o of i){for(const a of["aapt2","aapt"]){const s=z.join(r,o,a);try{await V.access(s)}catch{continue}const c=await Le(s,a==="aapt2"?["dump","packagename",e]:["dump","badging",e]).catch(()=>"");const l=a==="aapt2"?c.trim().split("\n")[0]:/package: name='([^']+)'/.exec(c)?.[1]??"";if(l)return l}}}throw new Error("Could not read the APK's package name (needs aapt2 from the Android SDK build-tools). Nothing was changed.")}async function ad(e,n,t=true){const r=rr(e);const i=z.resolve(n);try{await V.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 sd(e,r,i,t);if(e.platform==="ios-device")return cd(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 Zi(i);if(o.bundleId!==r)throw new Error(`${z.basename(i)} is ${o.bundleId}, but this app is ${r}. Nothing was changed.`);if(!o.simulator)throw new Error(`${z.basename(i)} is a device build, not a simulator build. Nothing was changed.`);const a=t?await V.mkdtemp(z.join(Mt.tmpdir(),"buoy-mcp-keep-")):null;try{let s=false;let c=[];if(a){await V.chmod(a,448);const d=(await Y(["get_app_container",e.udid,r,"data"]).catch(()=>"")).trim();if(d)s=await Qi(z.join(d,"Documents"),a);if(d&&!s){try{c=await Wl(d)}catch(u){throw new Error(`Couldn't read Buoy's sign-in from the app's WebView storage (${u.message}). Nothing was changed. Pass keepBuoy: false to reinstall anyway.`)}}}await Y(["terminate",e.udid,r]).catch(()=>void 0);await Y(["uninstall",e.udid,r]);try{await Y(["install",e.udid,i],18e4)}catch(d){throw new Error(`The app was removed, but installing ${z.basename(i)} failed: ${d.message}. Install it again by hand.`)}let l="";if(a&&s){try{const d=(await Y(["get_app_container",e.udid,r,"data"])).trim();await Qi(a,z.join(d,"Documents"));e.container=d;l=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(d){l=` Buoy's sign-in could not be restored (${d.message}): sign in to Buoy again in the app.`}}else if(c.length){try{const d=(await Y(["get_app_container",e.udid,r,"data"])).trim();await Y(["launch",e.udid,r]);const u=await Jl(d);await Y(["terminate",e.udid,r]).catch(()=>void 0);if(!u||!await Hl(d,c))throw new Error("the app made no WebView storage");e.container=d;l=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(d){l=` Buoy's sign-in could not be restored (${d.message}): sign in to Buoy again in the app.`}}else if(t){l=" The old install had no Buoy sign-in to keep."}await Y(["launch",e.udid,r]);return`Reinstalled ${r} from ${i} and launched it. The app's own data is gone, like a new user.${l}`}finally{if(a)await V.rm(a,{recursive:true,force:true}).catch(()=>void 0)}}async function Qi(e,n){let t=false;for(const r of id){const i=z.join(e,r);try{await V.access(i)}catch{continue}const o=z.join(n,r);await V.mkdir(z.dirname(o),{recursive:true});await V.cp(i,o,{recursive:true,force:true});t=true}return t}async function sd(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 od(t);if(i!==n)throw new Error(`${z.basename(t)} is ${i}, but this app is ${n}. Nothing was changed.`);const o=[];if(r){const c=await L(e.serial,`run-as ${ee(n)} find files/buoy-license files/react-buoy -maxdepth 1 -type f 2>/dev/null`).catch(()=>"");const l=c.split("\n").map(d=>d.trim()).filter(d=>d.startsWith("files/buoy-license/")||/react-buoy\/@react_buoy_(sync_device_id|install)\.json$/.test(d));for(const d of l){const u=await L(e.serial,`run-as ${ee(n)} base64 ${ee(d)}`).catch(()=>"");if(u.trim())o.push({rel:d,data:u.replace(/\s+/g,"")})}}let a=[];if(r&&!o.length&&await Kl(e.serial,n)){try{a=await Vl(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 xe(e.serial,["install","-r","-d",t],18e4);await L(e.serial,`pm clear ${ee(n)}`);let s="";if(a.length){await ut(e);try{await Yl(e.serial,n,a);s=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(c){s=` Buoy's sign-in could not be restored (${c.message}): sign in to Buoy again in the app.`}return`Reinstalled ${n} from ${t} and launched it. The app's data is gone, like a new user.${s}`}if(o.length){try{for(const c of o){const l=z.posix.dirname(c.rel);await L(e.serial,`echo ${ee(c.data)} | run-as ${ee(n)} sh -c ${ee(`mkdir -p ${ee(l)} && base64 -d > ${ee(c.rel)}`)}`)}s=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(c){s=` Buoy's sign-in could not be restored (${c.message}): sign in to Buoy again in the app.`}}else if(r){s=" No Buoy sign-in could be read to keep (needs a debug build): sign in to Buoy again in the app."}await ut(e);return`Reinstalled ${n} from ${t} and launched it. The app's data is gone, like a new user.${s}`}async function cd(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 Zi(t);if(i.bundleId!==n)throw new Error(`${z.basename(t)} is ${i.bundleId}, but this app is ${n}. Nothing was changed.`);if(i.simulator)throw new Error(`${z.basename(t)} is a simulator build, not a device build. Nothing was changed.`);const o=["Documents/buoy-license/buoy-gg-license.json","Documents/react-buoy/@react_buoy_sync_device_id.json","Documents/react-buoy/@react_buoy_install.json"];const a=r?await V.mkdtemp(z.join(Mt.tmpdir(),"buoy-mcp-keep-")):null;try{const s=[];if(a){await V.chmod(a,448);for(const l of o){let d;try{d=await Mi(e.udid,n,l)}catch(h){throw new Error(`Could not back up Buoy's ${z.basename(l)} from the iPhone (${h.message}). Nothing was changed.`)}if(!d)continue;const u=z.join(a,l.replace(/\//g,"__"));await V.writeFile(u,d,{mode:384});s.push({rel:l,local:u})}}await Oi(e.udid,n).catch(()=>false);await dl(e.udid,n);try{await ul(e.udid,t)}catch(l){throw new Error(`The app was removed, but installing ${z.basename(t)} failed: ${l.message}. Install it again from Xcode.`)}let c="";if(s.length){try{for(const u of s)await hl(e.udid,n,u.local,u.rel);const l=s.some(u=>u.rel.includes("buoy-license"));const d=s.some(u=>u.rel.includes("sync_device_id"));c=l?` Kept Buoy's sign-in${d?" 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 Gn(e.udid,n);return`Reinstalled ${n} on the iPhone and launched it. The app's own data is gone, like a new user.${c}`}finally{if(a)await V.rm(a,{recursive:true,force:true}).catch(()=>void 0)}}async function ld(e){const n=JSON.parse(await Y(["list","devices","available","-j"])).devices;const t=Object.entries(n).filter(([s])=>/iOS/.test(s)).flatMap(([,s])=>s);const r=e.trim().toLowerCase();const i=t.filter(s=>s.udid.toLowerCase()===r||s.name.toLowerCase()===r);const o=i.length?i:t.filter(s=>s.name.toLowerCase().includes(r));if(o.length===0)throw new Error(`No iOS Simulator matches "${e}". Run \`xcrun simctl list devices available\` to see them.`);if(o.length>1)throw new Error(`${o.length} simulators match "${e}": ${o.map(s=>`${s.name} (${s.udid})`).join(", ")}. Pass the udid.`);const a=o[0];if(a.state!=="Booted")await Y(["boot",a.udid],12e4);await Le("open",["-a","Simulator","--args","-CurrentDeviceUDID",a.udid]).catch(()=>void 0);return a.state==="Booted"?`${a.name} (${a.udid}) was already booted.`:`Booted ${a.name} (${a.udid}).`}var dd=Xc(Yc);async function Me(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 d=l.startsWith(It)&&/is not connected right now/.test(l)?/"([^"]+)"/.exec(l)?.[1]:void 0;const u=d?e.listDevices().some(h=>h.deviceId===d&&h.isPro):false;if(!r.allowOffline||!d||!u)throw c;i=d;o=false}const a=e.listDevices().find(c=>c.deviceId===i)?.platform;let s=await Ct(i,a,t);if(r.changesApp&&tn(i)===s)s=await Vi(i,s);return{id:i,host:s,online:o}}function ht(e){if(e.platform==="ios")return`simulator "${e.name}"`;if(e.platform==="ios-device")return`iPhone "${e.name}"`;return`Android device ${e.serial}`}var sr=new Map;function eo(e){if(!sr.has(e))sr.set(e,dd("which",[e],{timeout:3e3}).then(()=>true,()=>false));return sr.get(e)}async function ud(e,n){let t=n;if(e.platform==="android"){const i=tn(e.deviceId);const o=i??(e.isConnected?await Promise.race([Ct(e.deviceId,"android").catch(()=>void 0),new Promise(s=>setTimeout(()=>s(void 0),3e3))]):void 0);const a=await eo("adb");return{kind:"android",...o&&o.platform==="android"?{id:o.serial,name:o.packageName}:{},can:["screenshot","screen_recording","baseline diffs","quit/launch/reinstall","real lifecycle events","native_tap/type/swipe"],...!a?{missing:["adb (Android SDK platform-tools)"]}:!o?{missing:["proof of which phone runs it (needs a debug build reachable by adb)"]}:{}}}if(e.platform!=="ios")return{kind:e.platform??"unknown",can:[],missing:["host control works on iOS and Android apps"]};let r=tn(e.deviceId);if(!r&&!t&&e.isConnected){r=await Promise.race([Ct(e.deviceId,"ios").catch(()=>void 0),new Promise(i=>setTimeout(()=>i(void 0),4e3))])}if(!t&&r?.platform==="ios")t={name:r.name,udid:r.udid};if(r?.platform==="ios-device"){return{kind:"physical iPhone",id:r.udid,name:r.name,can:["screenshot","screen_recording (if this iPhone supports it)","baseline diffs","quit/launch/reinstall","open_url","native_tap/type/swipe (by query, testID, nativeTag or x/y; not label)"]}}if(t){const i=await eo("idb");return{kind:"ios simulator",id:t.udid,name:t.name,can:["screenshot","screen_recording","baseline diffs","quit/launch/reinstall/boot","real lifecycle events",...i?["native_tap/type/swipe"]:[]],...i?{}:{missing:["idb for real touches (brew install facebook/fb/idb-companion && pipx install fb-idb)"]}}}return void 0}function pt(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function ft(e){return{isError:true,content:[{type:"text",text:e}]}}function to(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:G.boolean().optional().describe("Also list every action of every tool. Default false (tool names only); list_tool_actions gives one tool's actions."),includeDisconnected:G.boolean().optional().describe("Also list apps that were seen before but are not connected now. Default false.")}},async(t={})=>{const r=await $i();let i=n.listDevices();for(let p=0;i.length===0&&p<10;p++){await new Promise(m=>setTimeout(m,200));i=n.listDevices()}if(i.length===0){return pt({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 pt({devices:[],hint:`No app is connected right now${o?` (${o} seen before; pass includeDisconnected:true to list them)`:""}. Open the app with Buoy devtools running, then retry.`,...r?{updateAvailable:r}:{}})}const a=await Kc(i.filter(p=>p.platform==="ios").map(p=>p.deviceId)).catch(()=>new Map);const s=i.filter(p=>p.isConnected);const c=s.some(p=>p.isPro);const l=s.some(p=>p.tier!=="locked");const d=s.filter(p=>p.collision);const u=await Promise.all(i.map(p=>p.isConnected?ud(p,a.get(p.deviceId)).catch(()=>void 0):void 0));const h=i.map((p,m)=>{const g=a.get(p.deviceId);const w=u[m];return{deviceId:p.deviceId,deviceName:p.deviceName,platform:p.platform,isConnected:p.isConnected,isPro:p.isPro,tier:p.tier,access:n.accessState(p.deviceId),...g?{simulator:g}:{},...w?{host:w}:{},...p.collision?{collision:true}:{},tools:t.details?p.tools:p.tools.map(f=>f.toolId)}});return pt({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).`:""}`},...d.length>0?{warning:`${d.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 Buoy MCP is a Pro feature \u2014 the connected device is signed in on the free tier, so data/action tools are blocked. Upgrade to Buoy Pro in the app, or pass `licenseKey` to `<FloatingDevTools />` if it runs headless.":"The broker has not confirmed account access for the connected devices, so data/action tools are blocked. A locked status can mean missing configuration, pending/failed validation, or a missing account announcement after reconnect; it does not prove the user is signed out. Check app account status and broker compatibility."},...r?{updateAvailable:r}:{}})});e.registerTool("list_tool_actions",{description:"List the actions a tool exposes, and which connected devices offer it. Leave toolId out to list every tool's actions. Use the action names with call_action.",inputSchema:{toolId:G.string().optional().describe('The tool id, e.g. "perf-monitor", "network", "react-query". Leave out for every tool.'),tool:G.string().optional().describe("Same as toolId."),deviceId:G.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(d=>!i||d.deviceId===i);if(c.length===0)return ft(i?`No connected device "${i}". Call list_devices.`:"No devices are connected. Call list_devices.");const l=c.map(d=>[`**${d.deviceName}** (${d.deviceId})`,...d.tools.map(u=>`- ${u.toolId}: ${u.actions.join(", ")}`)].join("\n"));return{content:[{type:"text",text:`${l.join("\n\n")}
3
3
 
4
4
  Call one with call_action({toolId, action, params}).`}]}}const a=new Set(n.connectedDevices().map(c=>c.deviceId));const s=n.toolActions(o).filter(c=>a.has(c.deviceId)&&(!i||c.deviceId===i));if(s.length===0){const c=[...new Set(n.connectedDevices().flatMap(l=>l.tools.map(d=>d.toolId)))].sort();return ft(`No connected device exposes tool "${o}". Tool ids: ${c.join(", ")||"(none connected)"}. MCP tool names like "${o}" are not tool ids.`)}return pt({toolId:o,offerings:s})});e.registerTool("get_snapshot",{description:"Read a tool's current state (its sync snapshot) from a device. Starts watching the tool and returns the next fresh snapshot.",inputSchema:{toolId:G.string().optional().describe("The tool id to read state from."),tool:G.string().optional().describe("Same as toolId."),deviceId:G.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:G.number().optional().describe("How long to wait for a fresh snapshot before falling back to the cached one.")}},async({toolId:t,tool:r,deviceId:i,timeoutMs:o})=>{try{const a=t??r;if(!a)return ft("get_snapshot needs toolId (see list_tool_actions).");const s=n.requireProDevice(i);const{payload:c,stale:l}=await n.getSnapshot(a,s,{timeoutMs:o});return pt({toolId:a,deviceId:s,...l?{stale:l}:{},snapshot:c})}catch(a){return ft(no(a))}});e.registerTool("call_action",{description:"Invoke any action a tool exposes (see list_tool_actions) and return its result. This is the generic escape hatch that works for every Buoy tool.",inputSchema:{toolId:G.string().optional().describe('The tool id, e.g. "perf-monitor".'),tool:G.string().optional().describe("Same as toolId."),action:G.string().describe('The action name, e.g. "startRecording", "clearAll".'),params:G.union([G.record(G.unknown()),G.string()]).optional().describe("JSON params object for the action (shape depends on the action)."),args:G.union([G.record(G.unknown()),G.string()]).optional().describe("Same as params."),deviceId:G.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:G.number().optional().describe("Max time to wait for the device's result.")}},async({toolId:t,tool:r,action:i,params:o,args:a,deviceId:s,timeoutMs:c})=>{try{const l=t??r;if(!l)return ft("call_action needs toolId (see list_tool_actions).");const d=hd(o??a);const u=n.requireProDevice(s);const h=await n.callAction(l,i,d,u,{timeoutMs:c});return pt({toolId:l,action:i,ok:true,result:h??null})}catch(l){return ft(no(l))}})}function hd(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 no(e){return e instanceof Error?e.message:String(e)}var mt=(e,n,t)=>Math.max(n,Math.min(t,e));var ro="__batch_warmup__";var pd={nominal:"\u{1F7E2} nominal",fair:"\u{1F7E1} fair",serious:"\u{1F7E0} serious",critical:"\u{1F534} critical",unknown:"\u2014"};var wt={perCaseDurationMs:5e3,settleMs:600,navTimeoutMs:5e3,runsPerCase:3,coolDownMs:2e3,discardWarmupRuns:0};function gt(e,n,t){return e??n??t}function rn(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((u,h)=>{const p=(u.name||"").trim()||`case ${h+1}`;return{id:`case-${h}`,name:p,params:u.params??{},route:u.route}});const a=mt(Math.round(gt(e.runsPerCase,n.runsPerCase,wt.runsPerCase)),1,10);const s=mt(Math.round(gt(e.coolDownMs,n.coolDownMs,wt.coolDownMs)),0,3e4);const c=mt(Math.round(gt(e.discardWarmupRuns,n.discardWarmupRuns,wt.discardWarmupRuns)),0,a-1);const l=e.shuffleCases??n.shuffleCases??o.length>3;if(o.length>3&&l===false){t.push("shuffleCases is off with >3 cases \u2014 later cases may be thermally throttled, biasing results. Consider enabling it.")}if(a===1){t.push("runsPerCase=1 \u2014 no median/variance; a single noisy run can mislead. 3+ is recommended.")}const d={targetRoute:r,bounceRoute:i,perCaseDurationMs:mt(Math.round(gt(e.perCaseDurationMs,n.perCaseDurationMs,wt.perCaseDurationMs)),1e3,6e4),settleMs:mt(Math.round(gt(e.settleMs,n.settleMs,wt.settleMs)),0,1e4),navTimeoutMs:mt(Math.round(gt(e.navTimeoutMs,n.navTimeoutMs,wt.navTimeoutMs)),1e3,3e4),cases:o,runsPerCase:a,coolDownMs:s,discardWarmupRuns:c,discardWarmupCase:e.discardWarmupCase??n.discardWarmupCase??true,shuffleCases:l,reloadBetweenCases:e.reloadBetweenCases??n.reloadBetweenCases??false,captureRenders:e.captureRenders??n.captureRenders??true};return{config:d,warnings:t}}function io(e){const n=c=>c>=1e3?`${(c/1e3).toFixed(c%1e3?1:0)}s`:`${c}ms`;const t=e.runsPerCase??1;const r=cr(e);const i=r/6e4;const o=i>=1?`~${i.toFixed(1)} min`:`~${Math.round(r/1e3)}s`;const a=[`**${n(e.perCaseDurationMs)} measured per page**`,t>1?`**${t} runs each** (median taken)`:`**1 run each** (no median \u2014 noisier)`,e.reloadBetweenCases?"**full reload between pages** (no state leaks across tests)":"no reload between pages",e.shuffleCases?"shuffled order (cancels thermal bias)":"fixed order",e.captureRenders!==false?"render capture on (per-component why-data)":"render capture off"];const s=e.settleMs+e.perCaseDurationMs+(e.coolDownMs??0)+1800;return`${a.join(", ")}. That's ~${n(s)} wall-clock per page; for ${e.cases.length} page(s) \xD7 ${t} run(s), **${o}** total.`}function cr(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 fd(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 md(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 wd(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 gd(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 on(e,n,t,r=[]){const i=e.filter(f=>f.batchId===n);const o=new Map(r.map(f=>[f.index,f.reason]));const a=Array.from(new Set(i.map(f=>f.batchIndex??0))).sort((f,b)=>f-b);const s=f=>{const b=i.filter($=>($.batchIndex??0)===f);if(b.length===0)return void 0;const y=b.filter($=>!$.batchFailureReason&&!$.discardedWarmup);const v=y.filter($=>$.webRun?.fps!=null);if(v.length>0&&v.length===y.length){const $=[...v].sort((_,S)=>_.webRun.fps-S.webRun.fps);return $[Math.floor(($.length-1)/2)]}if(y.length>0){return y.find($=>$.isMedianRun===true)??y.find($=>$.runIndex===0||$.runIndex===void 0)??y[0]}return b.find($=>$.batchFailureReason)??b[0]};const c=f=>typeof f==="number"?f:null;const l=a.map(f=>{const b=s(f);const y=i.filter(U=>(U.batchIndex??0)===f);const v=y.length;const $=y.filter(U=>!U.batchFailureReason&&!U.discardedWarmup);const _=U=>U.webRun?U.webRun.fps??U.jsFpsAvg:U.uiFpsAvg;const S=$.map(_).filter(U=>typeof U==="number");const A=b?.name??t?.[f]?.name??`case ${f+1}`;const M=i.some(U=>(U.batchIndex??0)===f&&U.isBaseline===true);const E=o.get(f)??b?.batchFailureReason;const W=y.every(U=>U.batchFailureReason||U.discardedWarmup);const D=Boolean(E)||!b||W;const C={batchIndex:f,caseName:A,params:b?.params??{},runs:v,failed:D,...b?.route?{route:b.route}:{},...M?{isBaseline:true}:{},failureReason:D?E??(W&&b?"only warmup runs were saved":"no run recorded"):void 0,uiFps:c(b?.uiFpsAvg),jsFps:c(b?.jsFpsAvg),cpu:c(b?.cpuAvg),memMb:c(b?.memMaxMb),jsJank:c(b?.jsJankFrames),uiJank:c(b?.uiJankFrames),deviceMaxRefreshRate:c(b?.deviceMaxRefreshRate),deltaUiFps:null,deltaJsFps:null,validRuns:$.length,fpsMin:S.length?ye(Math.min(...S),1):null,fpsMax:S.length?ye(Math.max(...S),1):null,...b?.thermalState?{thermalState:b.thermalState}:{},renderCommits:c(b?.renderCommits),renderWasted:b?.renderWasted,topRenderers:b?.topRenderers??[]};const I=b?.webRun;if(!I)return{...C,flags:D?[]:fd(C)};const N=[...I.longTasksSupported?[]:["long tasks"],...I.heapSupported?[]:["JS heap"],...I.loaf===null?["long animation frames"]:[]];const Q={...C,platform:"web",uiFps:null,uiJank:null,jsJank:null,cpu:null,memMb:I.heapSupported?C.memMb:null,deviceMaxRefreshRate:Math.max(C.deviceMaxRefreshRate??0,I.refreshHz??0)||null,longTaskPct:I.longTaskPct,frameGapP95Ms:I.frameGapP95Ms,frameGapMaxMs:I.frameGapMaxMs,edgeSilenceMs:I.edgeSilenceMs??null,jsFps:I.fps??C.jsFps,longFrames:I.longFrames,...N.length?{missingMetrics:N}:{},loafBlockingMs:I.loaf?.blockingMs??null,styleLayoutMs:I.loaf?.styleLayoutMs??null,forcedLayoutMs:I.loaf?.forcedLayoutMs??null,topScripts:I.loaf?.topScripts??[],worstInteractionMs:I.interactions?.worstMs??null,layoutShift:I.layoutShift??null,domNodes:I.domNodesEnd??null,domGrowth:wd(y),pageLoad:I.pageLoad??null,refreshCalibrated:I.refreshCalibrated??null};return{...Q,flags:D?[]:md({...Q,frames:I.frames})}}).filter(f=>f.caseName!==ro).map((f,b)=>({...f,batchIndex:b}));const d=gd(l,t);if(d){d.isBaseline=true;for(const f of l){if(f===d)continue;if(f.uiFps!=null&&d.uiFps!=null)f.deltaUiFps=ye(f.uiFps-d.uiFps,1);if(f.jsFps!=null&&d.jsFps!=null)f.deltaJsFps=ye(f.jsFps-d.jsFps,1)}}const u=l.filter(f=>!f.failed);const h=(f,b)=>{let y;let v=NaN;for(const $ of u){const _=f($);if(_==null)continue;if(y===void 0||b(_,v)){y=$;v=_}}return y?.caseName};const p=f=>f.platform==="web"?f.longFrames??null:f.jsJank==null&&f.uiJank==null?null:(f.jsJank??0)+(f.uiJank??0);const m={uiFps:h(f=>f.uiFps,(f,b)=>f>b),jsFps:h(f=>f.jsFps,(f,b)=>f>b),lowestCpu:h(f=>f.cpu,(f,b)=>f<b),lowestMem:h(f=>f.memMb,(f,b)=>f<b),fewestJank:h(p,(f,b)=>f<b),fewestLongTasks:h(f=>f.longTaskPct??null,(f,b)=>f<b)};const g=u.filter(f=>f.flags.length>0).map(f=>({caseName:f.caseName,flags:f.flags}));const w=u.filter(f=>f.flags.length===0).sort((f,b)=>(b.uiFps??b.jsFps??0)-(f.uiFps??f.jsFps??0)||(f.cpu??f.longTaskPct??Infinity)-(b.cpu??b.longTaskPct??Infinity)||(f.memMb??Infinity)-(b.memMb??Infinity)).map(f=>f.caseName);return{batchId:n,baselineName:d?.caseName??null,deviceMaxRefreshRate:u.find(f=>f.deviceMaxRefreshRate!=null)?.deviceMaxRefreshRate??null,rows:l,leaders:m,flagged:g,balanced:w}}function bd(e){const n=e.filter(a=>!a.failed);if(n.length===0)return[];const t=n.map(a=>a.pageLoad?.navigationId);if(t.some(a=>a==null)||new Set(t).size!==t.length)return[];if(n.some(a=>(a.pageLoad?.pageAgeMs??Infinity)>3e4))return[];const r=a=>(a??"").replace(/\/+$/,"")||"/";const i=a=>{const s=a.pageLoad;if(!s?.loadPath||r(s.loadPath)!==r(a.route))return false;const c=new URLSearchParams(s.loadSearch??"");const l=[...c.keys()];if(new Set(l).size!==l.length)return false;const d=Object.entries(a.params);return l.length===d.length&&d.every(([u,h])=>c.get(u)===h)};if(n.some(a=>!i(a)))return[];const o=a=>a==null?"\u2014":String(Math.round(a));return[`**Page load** (each case started on a fresh page load):`,"",`| Case | TTFB ms | FCP ms | LCP ms | DOM ready ms | Script KB | Total KB |`,`|------|--------:|-------:|-------:|-------------:|----------:|---------:|`,...n.map(a=>{const s=a.pageLoad;return`| ${a.caseName} | ${o(s.ttfbMs)} | ${o(s.fcpMs)} | ${o(s.lcpMs)} | ${o(s.domContentLoadedMs)} | ${o(s.scriptKb)} | ${o(s.totalKb)} |`}),"",`_KB is bytes over the network. 0 can mean the file came from cache, so compare cold loads with cold loads._`]}function oo(e){const n=o=>o.platform==="web"?o.jsFps:o.uiFps;const t=e.filter(o=>!o.failed&&n(o)!=null&&o.fpsMin!=null&&o.fpsMax!=null).sort((o,a)=>(n(a)??0)-(n(o)??0));if(t.length<2)return null;const[r,i]=t;if((r.validRuns??0)<2||(i.validRuns??0)<2){return`**Too few runs to separate the top cases.** ${r.caseName} and ${i.caseName} each need 2+ valid runs before their FPS gap means anything.`}if((i.fpsMax??0)>=(r.fpsMin??0)||(n(r)??0)-(n(i)??0)<=2){return`**Too close to call:** ${r.caseName} (${r.fpsMin}\u2013${r.fpsMax} FPS) and ${i.caseName} (${i.fpsMin}\u2013${i.fpsMax} FPS) overlap or sit within 2 FPS. No clear winner between them; more runs may separate them.`}return null}function an(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")){yd(e,r);return r.join("\n")}r.push(`**No single winner \u2014 weigh the trade-offs.** UI-thread health matters more than raw averages: a cheap run that drops UI frames is worse than a pricier one that holds them.`);r.push("");const i=e.rows.some(h=>h.thermalState);const o=i?" Thermal |":"";const a=i?"-------|":"";r.push(`| # | Case | UI FPS | JS FPS | CPU % | Mem MB | JS jank | UI jank |${o} Flags |`);r.push(`|---|------|-------:|-------:|------:|-------:|--------:|--------:|${a}-------|`);for(const h of e.rows){const p=i?` ${pd[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 m=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} ${m} |`)}const s=oo(e.rows);if(s){r.push("");r.push(s)}const c=e.rows.filter(h=>h.thermalState==="serious"||h.thermalState==="critical");if(c.length){r.push("");r.push(`**\u{1F525} Thermally throttled: ${c.map(h=>h.caseName).join(", ")}.** A throttled device runs SLOWER at a LOWER cpu%, so these cases can look like the cheapest in the batch while actually delivering fewer frames \u2014 check their UI FPS and jank, and re-run them on a cool device before drawing any conclusion.`)}r.push("");const l=e.leaders;const d=[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(d)r.push(`**Per-metric best:** ${d}`);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 u=e.rows.filter(h=>!h.failed&&(h.renderCommits!=null||h.topRenderers.length>0)).map(h=>{const p=h.topRenderers.map(w=>`${w.name} \xD7${w.renders} (${w.totalMs}ms${w.cause?`, ${w.cause}`:""})`).join(", ");const m=h.renderCommits!=null?`${h.renderCommits} commits`:"";const g=h.renderWasted!=null?`${h.renderWasted} wasted`:"";return`- **${h.caseName}** \u2014 ${[m,g,p].filter(Boolean).join(": ")}`});if(u.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(...u)}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 lr(e,n){const t=(r,i)=>({a:{avg:ye(r.avg,1),p95:ye(r.p95,1)},b:{avg:ye(i.avg,1),p95:ye(i.p95,1)},deltaAvg:ye(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},...ao(e.renders,n.renders)}}function vd(e,n){const t=(a,s,c)=>({a:a??null,b:s??null,delta:a!=null&&s!=null?ye(s-a,1):null,better:c});const r=a=>a.webRun.heapSupported?ye(a.stats.memoryUsage.max,1):null;const i=e.webRun;const o=n.webRun;return{a:e.name,b:n.name,platform:"web",note:"Browser runs: FPS is the main thread's whole-run requestAnimationFrame rate; long tasks % is not CPU. null = this browser couldn't measure it.",fps:t(i.fps??e.stats.jsFps.avg,o.fps??n.stats.jsFps.avg,"higher"),frameGapP95Ms:t(i.frameGapP95Ms,o.frameGapP95Ms,"lower"),frameGapMaxMs:t(i.frameGapMaxMs,o.frameGapMaxMs,"lower"),longFrames:t(i.longFrames,o.longFrames,"lower"),longTaskPct:t(i.longTaskPct,o.longTaskPct,"lower"),slowFrameBlockingMs:t(i.loaf?.blockingMs,o.loaf?.blockingMs,"lower"),styleLayoutPaintMs:t(i.loaf?.styleLayoutMs,o.loaf?.styleLayoutMs,"lower"),forcedLayoutMs:t(i.loaf?.forcedLayoutMs,o.loaf?.forcedLayoutMs,"lower"),worstInteractionMs:t(i.interactions?.worstMs,o.interactions?.worstMs,"lower"),layoutShift:t(i.layoutShift,o.layoutShift,"lower"),domNodes:t(i.domNodesEnd,o.domNodesEnd,"lower"),jsHeapMb:t(r(e),r(n),"lower"),topScripts:{a:i.loaf?.topScripts??[],b:o.loaf?.topScripts??[]},...ao(e.renders,n.renders)}}function ao(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 ye(e,n){const t=Math.pow(10,n);return Math.round(e*t)/t}function yd(e,n){const t=(d,u=1)=>d==null?"\u2014":d.toFixed(u);const r=d=>d==null?"":d>0?` (+${d.toFixed(1)})`:` (${d.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 d of e.rows){const u=d.isBaseline?`${d.caseName} (baseline)`:d.caseName;if(d.failed){n.push(`| ${d.batchIndex} | ${u} | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u274C FAILED (${d.failureReason}) |`);continue}const h=d.flags.length?`\u26A0\uFE0F ${d.flags.join("; ")}`:"no flags";n.push(`| ${d.batchIndex} | ${u} | ${t(d.jsFps)}${r(d.deltaJsFps)} | ${t(d.frameGapP95Ms)} | ${t(d.frameGapMaxMs)} | ${t(d.longFrames,0)} | ${t(d.longTaskPct)} | ${t(d.memMb)} | ${h} |`)}const i=e.rows.filter(d=>!d.failed).map(d=>{const u=[d.loafBlockingMs!=null&&d.loafBlockingMs>0&&`slow frames blocked input ${d.loafBlockingMs} ms`,d.styleLayoutMs!=null&&d.styleLayoutMs>0&&`style + layout ${d.styleLayoutMs} ms`,d.forcedLayoutMs!=null&&d.forcedLayoutMs>0&&`forced layout ${d.forcedLayoutMs} ms`,d.worstInteractionMs!=null&&`slowest input ${d.worstInteractionMs} ms`,d.layoutShift!=null&&d.layoutShift>0&&`layout shift ${d.layoutShift}`,d.domNodes!=null&&`${d.domNodes} DOM nodes${d.domGrowth?` (+${d.domGrowth} over the runs)`:""}`,d.topScripts&&d.topScripts.length>0&&`top scripts: ${d.topScripts.slice(0,3).map(h=>`${h.name} ${h.ms} ms`).join(", ")}`].filter(Boolean);return u.length?`- **${d.caseName}**: ${u.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=bd(e.rows);if(o.length){n.push("");n.push(...o)}const a=oo(e.rows);if(a){n.push("");n.push(a)}const s=Array.from(new Set(e.rows.flatMap(d=>d.missingMetrics??[])));if(s.length){n.push("");n.push(`**Not measured in this browser:** ${s.join(", ")}. These show as \u2014 and can't win or lose.`)}if(e.rows.some(d=>d.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(d=>`${d.caseName} (${d.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._`)}import{z as q}from"zod";import{z as $d}from"zod";var x=e=>({content:[{type:"text",text:e}]});var k=e=>({isError:true,content:[{type:"text",text:e}]});var O=e=>e instanceof Error?e.message:String(e);var R=$d.string().optional().describe("The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out.");function kd(e,n){return typeof e==="number"&&e>0?e:n}function qe(e){return e?`${e}
5
5