@buoy-gg/mcp 7.0.62 → 7.0.63
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -0
- package/dist/{chunk-2EU3AYOZ.mjs → chunk-G5SISI2H.mjs} +1 -1
- package/dist/chunk-PGOSBKGQ.mjs +942 -0
- package/dist/cli.js +605 -415
- package/dist/cli.mjs +5 -5
- package/dist/{flowRun-S5MEYHGX.mjs → flowRun-UYRYZVRR.mjs} +1 -1
- package/dist/index.d.mts +5 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +668 -478
- package/dist/index.mjs +1 -1
- package/package.json +3 -3
- package/dist/chunk-ZPZBUGGW.mjs +0 -752
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __esm=(e,n)=>function t(){return e&&(n=(0,e[__getOwnPropNames(e)[0]])(e=0)),n};var __commonJS=(e,n)=>function t(){return n||(0,e[__getOwnPropNames(e)[0]])((n={exports:{}}).exports,n),n.exports};var __export=(e,n)=>{for(var t in n)__defProp(e,t,{get:n[t],enumerable:true})};var __copyProps=(e,n,t,r)=>{if(n&&typeof n==="object"||typeof n==="function"){for(let i of __getOwnPropNames(n))if(!__hasOwnProp.call(e,i)&&i!==t)__defProp(e,i,{get:()=>n[i],enumerable:!(r=__getOwnPropDesc(n,i))||r.enumerable})}return e};var __toESM=(e,n,t)=>(t=e!=null?__create(__getProtoOf(e)):{},__copyProps(n||!e||!e.__esModule?__defProp(t,"default",{value:e,enumerable:true}):t,e));function setRecordingProbe(e){recordingActive=e}function hasSecrets(e){PLACEHOLDER.lastIndex=0;return PLACEHOLDER.test(e)}function fillSecrets(e,n=process.env){if(!hasSecrets(e))return e;if(recordingActive()){throw new Error("A screen recording is running, and a video can't hide a typed secret. Stop the recording first (screen_recording stop), then type it.")}const t=[];const r=[];const i=e.replace(PLACEHOLDER,(s,o)=>{const a=n[`BUOY_SECRET_${o}`]??n[o];if(a===void 0||a===""){t.push(o);return""}if(a.length<MIN_SECRET_LENGTH){r.push(o);return""}used.set(o,a);return a});if(t.length){throw new Error(`No value for ${t.map(s=>`{{secret:${s}}}`).join(", ")}. Set ${t.map(s=>`BUOY_SECRET_${s}`).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(s=>`{{secret:${s}}}`).join(", ")} is shorter than ${MIN_SECRET_LENGTH} characters, so Buoy can't hide it reliably in what it sends back. Use a longer value, or type it as plain text if it isn't sensitive.`)}return i}function knownSecrets(e=process.env){const n=new Map(used);for(const[t,r]of Object.entries(e))if(t.startsWith("BUOY_SECRET_")&&r)n.set(t.slice("BUOY_SECRET_".length),r);return n}function scrubSecrets(e){const n=new Map;for(const[i,s]of knownSecrets()){if(s.length<MIN_SECRET_LENGTH)continue;for(const o of[s,JSON.stringify(s).slice(1,-1),encodeURIComponent(s)])n.set(o,i);for(let o=s.length-1;o>=MIN_SECRET_LENGTH;o--){n.set(`${s.slice(0,o)}\u2026`,i);n.set(`${s.slice(0,o)}...`,i);if(o>=8)n.set(s.slice(0,o),i)}}if(n.size===0)return e;const t=[...n.keys()].sort((i,s)=>s.length-i.length);const r=new RegExp(t.map(escapeRe).join("|"),"g");return e.replace(r,(i,s,o)=>{if(/^\d+$/.test(i)){const a=o.slice(Math.max(0,s-8),s);const c=o.slice(s+i.length,s+i.length+8);if(/(\d|\d\.)$/.test(a)||/^(\d|\.\d|[eE][+-]?\d)/.test(c))return i;if(/[:[,]\s*$/.test(a)&&/^\s*([,\]}]|$)/.test(c)&&!insideJsonString(o,s))return`"{{secret:${n.get(i)}}}"`}return`{{secret:${n.get(i)}}}`})}function insideJsonString(e,n){let t=false;for(let r=0;r<n;r++){if(e[r]==="\\")r++;else if(e[r]==='"')t=!t}return t}function typedSecretValues(){return[...used.values()]}function secretValues(){return[...knownSecrets().values()].filter(e=>e.length>=MIN_SECRET_LENGTH)}var PLACEHOLDER,MIN_SECRET_LENGTH,used,recordingActive,escapeRe;var init_secrets=__esm({"src/tools/secrets.ts"(){"use strict";PLACEHOLDER=/\{\{\s*secret:([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;MIN_SECRET_LENGTH=6;used=new Map;recordingActive=()=>false;escapeRe=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}});function q(e){return`'${e.replace(/'/g,`'\\''`)}'`}function assertPackage(e){if(!/^[A-Za-z][\w]*(\.[A-Za-z_][\w]*)+$/.test(e))throw new Error(`"${e}" is not a valid Android package name.`);return e}async function adb(e,n,t=15e3){try{const{stdout:r}=await execFileAsync("adb",e?["-s",e,...n]:n,{timeout:t,maxBuffer:32*1024*1024});return r}catch(r){const i=r;if(i.code==="ENOENT")throw new Error(ADB_MISSING);const s=n[0]==="shell"?`shell ${(n[1]??"").split(" ")[0]}`:n.slice(0,2).join(" ");const o=n[0]==="shell"?i.stderr||(i.killed?"timed out":"no error text"):i.stderr||i.message||"";const a=scrubSecrets(o.replace(/'[^']*'/g,"'\u2026'")).trim().slice(0,300);throw new Error(`adb ${s} failed: ${a}`)}}function adbShell(e,n,t=15e3){return adb(e,["shell",n],t)}async function adbBytes(e,n,t=15e3){try{const{stdout:r}=await execFileAsync("adb",["-s",e,...n],{timeout:t,encoding:"buffer",maxBuffer:64*1024*1024});return r}catch(r){const i=r;if(i.code==="ENOENT")throw new Error(ADB_MISSING);throw new Error(`adb ${n.slice(0,2).join(" ")} failed: ${i.message.slice(0,300)}`)}}async function adbSerials(){return parseAdbDevices(await adb(null,["devices"]))}function parseAdbDevices(e){return e.split("\n").slice(1).map(n=>n.trim().split(/\s+/)).filter(n=>n[1]==="device").map(n=>n[0])}async function adbScreenSize(e){const n=parseWmSize(await adbShell(e,"wm size"));const t=parseRotation(await adbShell(e,"dumpsys input").catch(()=>""));return t%2===1?{width:n.height,height:n.width}:n}function parseWmSize(e){const n=/Override size:\s*(\d+)x(\d+)/.exec(e);const t=/Physical size:\s*(\d+)x(\d+)/.exec(e);const r=n??t;if(!r)throw new Error(`Could not read the Android screen size (adb said: ${e.trim().slice(0,120)}).`);return{width:Number(r[1]),height:Number(r[2])}}function parseRotation(e){const n=/SurfaceOrientation:\s*(\d)/.exec(e);return n?Number(n[1]):0}async function adbAppFrame(e,n){const t=await adbShell(e,"dumpsys window windows").catch(()=>"");return parseAppFrame(t,n)}function parseAppFrame(e,n){const t=e.split(/\n(?=\s*Window #\d+)/);for(const r of t){if(!r.includes(`${n}/`))continue;const i=/mFrame=\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(r)??/\bframe=\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(r);if(i){const[s,o,a,c]=i.slice(1).map(Number);if(a>s&&c>o)return{x:s,y:o,width:a-s,height:c-o}}}return null}async function adbForegroundPackage(e){return parseForegroundPackage(await adbShell(e,"dumpsys activity activities"))}function parseForegroundPackage(e){const n=/(?:topResumedActivity|mResumedActivity|ResumedActivity)[^\n]*?\s([a-zA-Z][\w.]*)\/[\w.$]+/.exec(e);return n?n[1]:null}async function adbUserPackages(e){const n=await adbShell(e,"pm list packages -3");return n.split("\n").map(t=>t.trim().replace(/^package:/,"")).filter(t=>/^[A-Za-z][\w.]+$/.test(t))}async function adbInstallId(e,n){assertPackage(n);const t=await adbShell(e,`run-as ${q(n)} cat files/react-buoy/@react_buoy_sync_device_id.json 2>/dev/null`,5e3).catch(()=>"");const r=t.trim().replace(/^"|"$/g,"");if(/^[\w-]{4,64}$/.test(r))return r;const i=await adbBytes(e,["exec-out",`run-as ${q(n)} sh -c 'cat app_webview/Default/"Local Storage"/leveldb/*.log app_webview/Default/"Local Storage"/leveldb/*.ldb 2>/dev/null'`],5e3).catch(()=>null);return i?webViewLevelDbInstallId(i):null}function webViewLevelDbInstallId(e){const n=e.toString("latin1");const t=/@react_buoy_sync_device_id([\s\S])\x01([\w-]{4,64})/g;let r=null;for(let i=t.exec(n);i;i=t.exec(n)){const s=i[1].charCodeAt(0)-1;if(s>=4&&s<=i[2].length)r=i[2].slice(0,s)}return r}function escapeAdbText(e){if(/[^\x20-\x7e]/.test(e))throw new Error("adb can only type plain ASCII text. Use tap_element's text for other characters.");return q(e.replace(/ /g,"%s"))}async function adbTap(e,n,t,r){const[i,s]=[Math.round(n),Math.round(t)];if(r)await adbShell(e,`input swipe ${i} ${s} ${i} ${s} ${Math.round(r)}`);else await adbShell(e,`input tap ${i} ${s}`)}async function adbSwipe(e,n,t,r){const i=[...n,...t].map(s=>Math.round(s)).join(" ");await adbShell(e,`input swipe ${i} ${Math.round(r)}`)}async function adbText(e,n){const t=n.replace(/ /g,"\0");for(let r=0;r<t.length;r+=40){const i=t.slice(r,r+40).replace(/\u0000/g," ");await adbShell(e,`input text ${escapeAdbText(i)}`)}}async function adbScreenshot(e){const n=await adbBytes(e,["exec-out","screencap","-p"]);if(n.length<8||n.readUInt32BE(0)!==2303741511)throw new Error("The Android screenshot was not a PNG.");return n}async function adbDemoMode(e,n){if(n){await adbShell(e,"settings put global sysui_demo_allowed 1");for(const t of["-e command enter","-e command clock -e hhmm 0941","-e command battery -e level 100 -e plugged false","-e command network -e wifi show -e level 4","-e command notifications -e visible false"]){await adbShell(e,`am broadcast -a com.android.systemui.demo ${t}`).catch(()=>void 0)}}else{await adbShell(e,"am broadcast -a com.android.systemui.demo -e command exit").catch(()=>void 0)}}async function adbUiNodes(e){const n=await adb(e,["exec-out","uiautomator","dump","/dev/tty"],2e4);return parseUiDump(n)}function parseUiDump(e){const n=[];const t=(r,i)=>{const s=new RegExp(`\\s${i}="([^"]*)"`).exec(r);return s?decodeXml(s[1]):""};for(const r of e.matchAll(/<node\b[^>]*>/g)){const i=r[0];const s=/\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(t(i,"bounds"));if(!s)continue;const[o,a,c,u]=s.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:o,y:a,width:c-o,height:u-a}})}return n}function decodeXml(e){return e.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&#(\d+);/g,(n,t)=>String.fromCharCode(Number(t))).replace(/&/g,"&")}function findUiNodes(e,n){const t=n.trim().toLowerCase();const r=c=>{let u=0;for(const l of[c.desc,c.text,c.id.split("/").pop()??""]){const d=l.trim().toLowerCase();if(!d)continue;if(d===t)u=Math.max(u,3);else if(d.startsWith(t))u=Math.max(u,2);else if(d.includes(t))u=Math.max(u,1)}return u};const i=e.filter(c=>c.bounds.width>0&&c.bounds.height>0&&r(c)>0);const s=Math.max(0,...i.map(r));const o=i.filter(c=>r(c)===s);let a=o.filter((c,u)=>o.findIndex(l=>JSON.stringify(l.bounds)===JSON.stringify(c.bounds))===u);if(a.length>1){const c=a.filter(u=>[u.desc,u.text,u.id.split("/").pop()??""].some(l=>l.trim()===n.trim()));if(c.length)a=c}if(a.length>1){const c=a.filter(u=>u.clickable||/EditText|Button/.test(u.cls));if(c.length)a=c}return a}var import_node_child_process,import_node_util,execFileAsync,ADB_MISSING;var init_adb=__esm({"src/capture/adb.ts"(){"use strict";import_node_child_process=require("child_process");import_node_util=require("util");init_secrets();execFileAsync=(0,import_node_util.promisify)(import_node_child_process.execFile);ADB_MISSING="Android control needs adb on this computer (Android SDK platform-tools). Install it, or add it to PATH."}});var require_chunkstream=__commonJS({"../../node_modules/pngjs/lib/chunkstream.js"(e,n){"use strict";var t=require("util");var r=require("stream");var i=n.exports=function(){r.call(this);this._buffers=[];this._buffered=0;this._reads=[];this._paused=false;this._encoding="utf8";this.writable=true};t.inherits(i,r);i.prototype.read=function(s,o){this._reads.push({length:Math.abs(s),allowLess:s<0,func:o});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(s,o){if(!this.writable){this.emit("error",new Error("Stream not writable"));return false}let a;if(Buffer.isBuffer(s)){a=s}else{a=Buffer.from(s,o||this._encoding)}this._buffers.push(a);this._buffered+=a.length;this._process();if(this._reads&&this._reads.length===0){this._paused=true}return this.writable&&!this._paused};i.prototype.end=function(s,o){if(s){this.write(s,o)}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(s){this._reads.shift();let o=this._buffers[0];if(o.length>s.length){this._buffered-=s.length;this._buffers[0]=o.slice(s.length);s.func.call(this,o.slice(0,s.length))}else{this._buffered-=o.length;this._buffers.shift();s.func.call(this,o)}};i.prototype._processRead=function(s){this._reads.shift();let o=0;let a=0;let c=Buffer.alloc(s.length);while(o<s.length){let u=this._buffers[a++];let l=Math.min(u.length,s.length-o);u.copy(c,o,0,l);o+=l;if(l!==u.length){this._buffers[--a]=u.slice(l)}}if(a>0){this._buffers.splice(0,a)}this._buffered-=s.length;s.func.call(this,c)};i.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let s=this._reads[0];if(s.allowLess){this._processReadAllowingLess(s)}else if(this._buffered>=s.length){this._processRead(s)}else{break}}if(this._buffers&&!this.writable){this._end()}}catch(s){this.emit("error",s)}}}});var require_interlace=__commonJS({"../../node_modules/pngjs/lib/interlace.js"(e){"use strict";var n=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];e.getImagePasses=function(t,r){let i=[];let s=t%8;let o=r%8;let a=(t-s)/8;let c=(r-o)/8;for(let u=0;u<n.length;u++){let l=n[u];let d=a*l.x.length;let h=c*l.y.length;for(let p=0;p<l.x.length;p++){if(l.x[p]<s){d++}else{break}}for(let p=0;p<l.y.length;p++){if(l.y[p]<o){h++}else{break}}if(d>0&&h>0){i.push({width:d,height:h,index:u})}}return i};e.getInterlaceIterator=function(t){return function(r,i,s){let o=r%n[s].x.length;let a=(r-o)/n[s].x.length*8+n[s].x[o];let c=i%n[s].y.length;let u=(i-c)/n[s].y.length*8+n[s].y[c];return a*4+u*t*4}}}});var require_paeth_predictor=__commonJS({"../../node_modules/pngjs/lib/paeth-predictor.js"(e,n){"use strict";n.exports=function t(r,i,s){let o=r+i-s;let a=Math.abs(o-r);let c=Math.abs(o-i);let u=Math.abs(o-s);if(a<=c&&a<=u){return r}if(c<=u){return i}return s}}});var require_filter_parse=__commonJS({"../../node_modules/pngjs/lib/filter-parse.js"(e,n){"use strict";var t=require_interlace();var r=require_paeth_predictor();function i(o,a,c){let u=o*a;if(c!==8){u=Math.ceil(u/(8/c))}return u}var s=n.exports=function(o,a){let c=o.width;let u=o.height;let l=o.interlace;let d=o.bpp;let h=o.depth;this.read=a.read;this.write=a.write;this.complete=a.complete;this._imageIndex=0;this._images=[];if(l){let p=t.getImagePasses(c,u);for(let m=0;m<p.length;m++){this._images.push({byteWidth:i(p[m].width,d,h),height:p[m].height,lineIndex:0})}}else{this._images.push({byteWidth:i(c,d,h),height:u,lineIndex:0})}if(h===8){this._xComparison=d}else if(h===16){this._xComparison=d*2}else{this._xComparison=1}};s.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};s.prototype._unFilterType1=function(o,a,c){let u=this._xComparison;let l=u-1;for(let d=0;d<c;d++){let h=o[1+d];let p=d>l?a[d-u]:0;a[d]=h+p}};s.prototype._unFilterType2=function(o,a,c){let u=this._lastLine;for(let l=0;l<c;l++){let d=o[1+l];let h=u?u[l]:0;a[l]=d+h}};s.prototype._unFilterType3=function(o,a,c){let u=this._xComparison;let l=u-1;let d=this._lastLine;for(let h=0;h<c;h++){let p=o[1+h];let m=d?d[h]:0;let g=h>l?a[h-u]:0;let w=Math.floor((g+m)/2);a[h]=p+w}};s.prototype._unFilterType4=function(o,a,c){let u=this._xComparison;let l=u-1;let d=this._lastLine;for(let h=0;h<c;h++){let p=o[1+h];let m=d?d[h]:0;let g=h>l?a[h-u]:0;let w=h>l&&d?d[h-u]:0;let f=r(g,m,w);a[h]=p+f}};s.prototype._reverseFilterLine=function(o){let a=o[0];let c;let u=this._images[this._imageIndex];let l=u.byteWidth;if(a===0){c=o.slice(1,l+1)}else{c=Buffer.alloc(l);switch(a){case 1:this._unFilterType1(o,c,l);break;case 2:this._unFilterType2(o,c,l);break;case 3:this._unFilterType3(o,c,l);break;case 4:this._unFilterType4(o,c,l);break;default:throw new Error("Unrecognised filter type - "+a)}}this.write(c);u.lineIndex++;if(u.lineIndex>=u.height){this._lastLine=null;this._imageIndex++;u=this._images[this._imageIndex]}else{this._lastLine=c}if(u){this.read(u.byteWidth+1,this._reverseFilterLine.bind(this))}else{this._lastLine=null;this.complete()}}}});var require_filter_parse_async=__commonJS({"../../node_modules/pngjs/lib/filter-parse-async.js"(e,n){"use strict";var t=require("util");var r=require_chunkstream();var i=require_filter_parse();var s=n.exports=function(o){r.call(this);let a=[];let c=this;this._filter=new i(o,{read:this.read.bind(this),write:function(u){a.push(u)},complete:function(){c.emit("complete",Buffer.concat(a))}});this._filter.start()};t.inherits(s,r)}});var require_constants=__commonJS({"../../node_modules/pngjs/lib/constants.js"(e,n){"use strict";n.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}}});var require_crc=__commonJS({"../../node_modules/pngjs/lib/crc.js"(e,n){"use strict";var t=[];(function(){for(let i=0;i<256;i++){let s=i;for(let o=0;o<8;o++){if(s&1){s=3988292384^s>>>1}else{s=s>>>1}}t[i]=s}})();var r=n.exports=function(){this._crc=-1};r.prototype.write=function(i){for(let s=0;s<i.length;s++){this._crc=t[(this._crc^i[s])&255]^this._crc>>>8}return true};r.prototype.crc32=function(){return this._crc^-1};r.crc32=function(i){let s=-1;for(let o=0;o<i.length;o++){s=t[(s^i[o])&255]^s>>>8}return s^-1}}});var require_parser=__commonJS({"../../node_modules/pngjs/lib/parser.js"(e,n){"use strict";var t=require_constants();var r=require_crc();var i=n.exports=function(s,o){this._options=s;s.checkCRC=s.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=o.read;this.error=o.error;this.metadata=o.metadata;this.gamma=o.gamma;this.transColor=o.transColor;this.palette=o.palette;this.parsed=o.parsed;this.inflateData=o.inflateData;this.finished=o.finished;this.simpleTransparency=o.simpleTransparency;this.headersFinished=o.headersFinished||function(){}};i.prototype.start=function(){this.read(t.PNG_SIGNATURE.length,this._parseSignature.bind(this))};i.prototype._parseSignature=function(s){let o=t.PNG_SIGNATURE;for(let a=0;a<o.length;a++){if(s[a]!==o[a]){this.error(new Error("Invalid file signature"));return}}this.read(8,this._parseChunkBegin.bind(this))};i.prototype._parseChunkBegin=function(s){let o=s.readUInt32BE(0);let a=s.readUInt32BE(4);let c="";for(let l=4;l<8;l++){c+=String.fromCharCode(s[l])}let u=Boolean(s[4]&32);if(!this._hasIHDR&&a!==t.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}this._crc=new r;this._crc.write(Buffer.from(c));if(this._chunks[a]){return this._chunks[a](o)}if(!u){this.error(new Error("Unsupported critical chunk type "+c));return}this.read(o+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(s){let o=s.readInt32BE(0);let a=this._crc.crc32();if(this._options.checkCRC&&a!==o){this.error(new Error("Crc error - "+o+" - "+a));return}if(!this._hasIEND){this.read(8,this._parseChunkBegin.bind(this))}};i.prototype._handleIHDR=function(s){this.read(s,this._parseIHDR.bind(this))};i.prototype._parseIHDR=function(s){this._crc.write(s);let o=s.readUInt32BE(0);let a=s.readUInt32BE(4);let c=s[8];let u=s[9];let l=s[10];let d=s[11];let h=s[12];if(c!==8&&c!==4&&c!==2&&c!==1&&c!==16){this.error(new Error("Unsupported bit depth "+c));return}if(!(u in t.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(l!==0){this.error(new Error("Unsupported compression method"));return}if(d!==0){this.error(new Error("Unsupported filter method"));return}if(h!==0&&h!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=u;let p=t.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=true;this.metadata({width:o,height:a,depth:c,interlace:Boolean(h),palette:Boolean(u&t.COLORTYPE_PALETTE),color:Boolean(u&t.COLORTYPE_COLOR),alpha:Boolean(u&t.COLORTYPE_ALPHA),bpp:p,colorType:u});this._handleChunkEnd()};i.prototype._handlePLTE=function(s){this.read(s,this._parsePLTE.bind(this))};i.prototype._parsePLTE=function(s){this._crc.write(s);let o=Math.floor(s.length/3);for(let a=0;a<o;a++){this._palette.push([s[a*3],s[a*3+1],s[a*3+2],255])}this.palette(this._palette);this._handleChunkEnd()};i.prototype._handleTRNS=function(s){this.simpleTransparency();this.read(s,this._parseTRNS.bind(this))};i.prototype._parseTRNS=function(s){this._crc.write(s);if(this._colorType===t.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(s.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let o=0;o<s.length;o++){this._palette[o][3]=s[o]}this.palette(this._palette)}if(this._colorType===t.COLORTYPE_GRAYSCALE){this.transColor([s.readUInt16BE(0)])}if(this._colorType===t.COLORTYPE_COLOR){this.transColor([s.readUInt16BE(0),s.readUInt16BE(2),s.readUInt16BE(4)])}this._handleChunkEnd()};i.prototype._handleGAMA=function(s){this.read(s,this._parseGAMA.bind(this))};i.prototype._parseGAMA=function(s){this._crc.write(s);this.gamma(s.readUInt32BE(0)/t.GAMMA_DIVISION);this._handleChunkEnd()};i.prototype._handleIDAT=function(s){if(!this._emittedHeadersFinished){this._emittedHeadersFinished=true;this.headersFinished()}this.read(-s,this._parseIDAT.bind(this,s))};i.prototype._parseIDAT=function(s,o){this._crc.write(o);if(this._colorType===t.COLORTYPE_PALETTE_COLOR&&this._palette.length===0){throw new Error("Expected palette not found")}this.inflateData(o);let a=s-o.length;if(a>0){this._handleIDAT(a)}else{this._handleChunkEnd()}};i.prototype._handleIEND=function(s){this.read(s,this._parseIEND.bind(this))};i.prototype._parseIEND=function(s){this._crc.write(s);this._hasIEND=true;this._handleChunkEnd();if(this.finished){this.finished()}}}});var require_bitmapper=__commonJS({"../../node_modules/pngjs/lib/bitmapper.js"(e){"use strict";var n=require_interlace();var t=[function(){},function(a,c,u,l){if(l===c.length){throw new Error("Ran out of data")}let d=c[l];a[u]=d;a[u+1]=d;a[u+2]=d;a[u+3]=255},function(a,c,u,l){if(l+1>=c.length){throw new Error("Ran out of data")}let d=c[l];a[u]=d;a[u+1]=d;a[u+2]=d;a[u+3]=c[l+1]},function(a,c,u,l){if(l+2>=c.length){throw new Error("Ran out of data")}a[u]=c[l];a[u+1]=c[l+1];a[u+2]=c[l+2];a[u+3]=255},function(a,c,u,l){if(l+3>=c.length){throw new Error("Ran out of data")}a[u]=c[l];a[u+1]=c[l+1];a[u+2]=c[l+2];a[u+3]=c[l+3]}];var r=[function(){},function(a,c,u,l){let d=c[0];a[u]=d;a[u+1]=d;a[u+2]=d;a[u+3]=l},function(a,c,u){let l=c[0];a[u]=l;a[u+1]=l;a[u+2]=l;a[u+3]=c[1]},function(a,c,u,l){a[u]=c[0];a[u+1]=c[1];a[u+2]=c[2];a[u+3]=l},function(a,c,u){a[u]=c[0];a[u+1]=c[1];a[u+2]=c[2];a[u+3]=c[3]}];function i(a,c){let u=[];let l=0;function d(){if(l===a.length){throw new Error("Ran out of data")}let h=a[l];l++;let p,m,g,w,f,b,v,y;switch(c){default:throw new Error("unrecognised depth");case 16:v=a[l];l++;u.push((h<<8)+v);break;case 4:v=h&15;y=h>>4;u.push(y,v);break;case 2:f=h&3;b=h>>2&3;v=h>>4&3;y=h>>6&3;u.push(y,v,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;v=h>>6&1;y=h>>7&1;u.push(y,v,b,f,w,g,m,p);break}}return{get:function(h){while(u.length<h){d()}let p=u.slice(0,h);u=u.slice(h);return p},resetAfterLine:function(){u.length=0},end:function(){if(l!==a.length){throw new Error("extra data found")}}}}function s(a,c,u,l,d,h){let p=a.width;let m=a.height;let g=a.index;for(let w=0;w<m;w++){for(let f=0;f<p;f++){let b=u(f,w,g);t[l](c,d,b,h);h+=l}}return h}function o(a,c,u,l,d,h){let p=a.width;let m=a.height;let g=a.index;for(let w=0;w<m;w++){for(let f=0;f<p;f++){let b=d.get(l);let v=u(f,w,g);r[l](c,b,v,h)}d.resetAfterLine()}}e.dataToBitMap=function(a,c){let u=c.width;let l=c.height;let d=c.depth;let h=c.bpp;let p=c.interlace;let m;if(d!==8){m=i(a,d)}let g;if(d<=8){g=Buffer.alloc(u*l*4)}else{g=new Uint16Array(u*l*4)}let w=Math.pow(2,d)-1;let f=0;let b;let v;if(p){b=n.getImagePasses(u,l);v=n.getInterlaceIterator(u,l)}else{let y=0;v=function(){let _=y;y+=4;return _};b=[{width:u,height:l}]}for(let y=0;y<b.length;y++){if(d===8){f=s(b[y],g,v,h,a,f)}else{o(b[y],g,v,h,m,w)}}if(d===8){if(f!==a.length){throw new Error("extra data found")}}else{m.end()}return g}}});var require_format_normaliser=__commonJS({"../../node_modules/pngjs/lib/format-normaliser.js"(e,n){"use strict";function t(s,o,a,c,u){let l=0;for(let d=0;d<c;d++){for(let h=0;h<a;h++){let p=u[s[l]];if(!p){throw new Error("index "+s[l]+" not in palette")}for(let m=0;m<4;m++){o[l+m]=p[m]}l+=4}}}function r(s,o,a,c,u){let l=0;for(let d=0;d<c;d++){for(let h=0;h<a;h++){let p=false;if(u.length===1){if(u[0]===s[l]){p=true}}else if(u[0]===s[l]&&u[1]===s[l+1]&&u[2]===s[l+2]){p=true}if(p){for(let m=0;m<4;m++){o[l+m]=0}}l+=4}}}function i(s,o,a,c,u){let l=255;let d=Math.pow(2,u)-1;let h=0;for(let p=0;p<c;p++){for(let m=0;m<a;m++){for(let g=0;g<4;g++){o[h+g]=Math.floor(s[h+g]*l/d+.5)}h+=4}}}n.exports=function(s,o,a=false){let c=o.depth;let u=o.width;let l=o.height;let d=o.colorType;let h=o.transColor;let p=o.palette;let m=s;if(d===3){t(s,m,u,l,p)}else{if(h){r(s,m,u,l,h)}if(c!==8&&!a){if(c===16){m=Buffer.alloc(u*l*4)}i(s,m,u,l,c)}}return m}}});var require_parser_async=__commonJS({"../../node_modules/pngjs/lib/parser-async.js"(e,n){"use strict";var t=require("util");var r=require("zlib");var i=require_chunkstream();var s=require_filter_parse_async();var o=require_parser();var a=require_bitmapper();var c=require_format_normaliser();var u=n.exports=function(l){i.call(this);this._parser=new o(l,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)});this._options=l;this.writable=true;this._parser.start()};t.inherits(u,i);u.prototype._handleError=function(l){this.emit("error",l);this.writable=false;this.destroy();if(this._inflate&&this._inflate.destroy){this._inflate.destroy()}if(this._filter){this._filter.destroy();this._filter.on("error",function(){})}this.errord=true};u.prototype._inflateData=function(l){if(!this._inflate){if(this._bitmapInfo.interlace){this._inflate=r.createInflate();this._inflate.on("error",this.emit.bind(this,"error"));this._filter.on("complete",this._complete.bind(this));this._inflate.pipe(this._filter)}else{let d=(this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1;let h=d*this._bitmapInfo.height;let p=Math.max(h,r.Z_MIN_CHUNK);this._inflate=r.createInflate({chunkSize:p});let m=h;let 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(l)};u.prototype._handleMetaData=function(l){this._metaData=l;this._bitmapInfo=Object.create(l);this._filter=new s(this._bitmapInfo)};u.prototype._handleTransColor=function(l){this._bitmapInfo.transColor=l};u.prototype._handlePalette=function(l){this._bitmapInfo.palette=l};u.prototype._simpleTransparency=function(){this._metaData.alpha=true};u.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};u.prototype._finished=function(){if(this.errord){return}if(!this._inflate){this.emit("error","No Inflate block")}else{this._inflate.end()}};u.prototype._complete=function(l){if(this.errord){return}let d;try{let h=a.dataToBitMap(l,this._bitmapInfo);d=c(h,this._bitmapInfo,this._options.skipRescale);h=null}catch(h){this._handleError(h);return}this.emit("parsed",d)}}});var require_bitpacker=__commonJS({"../../node_modules/pngjs/lib/bitpacker.js"(e,n){"use strict";var t=require_constants();n.exports=function(r,i,s,o){let a=[t.COLORTYPE_COLOR_ALPHA,t.COLORTYPE_ALPHA].indexOf(o.colorType)!==-1;if(o.colorType===o.inputColorType){let f=(function(){let b=new ArrayBuffer(2);new DataView(b).setInt16(0,256,true);return new Int16Array(b)[0]!==256})();if(o.bitDepth===8||o.bitDepth===16&&f){return r}}let c=o.bitDepth!==16?r:new Uint16Array(r.buffer);let u=255;let l=t.COLORTYPE_TO_BPP_MAP[o.inputColorType];if(l===4&&!o.inputHasAlpha){l=3}let d=t.COLORTYPE_TO_BPP_MAP[o.colorType];if(o.bitDepth===16){u=65535;d*=2}let h=Buffer.alloc(i*s*d);let p=0;let m=0;let g=o.bgColor||{};if(g.red===void 0){g.red=u}if(g.green===void 0){g.green=u}if(g.blue===void 0){g.blue=u}function w(){let f;let b;let v;let y=u;switch(o.inputColorType){case t.COLORTYPE_COLOR_ALPHA:y=c[p+3];f=c[p];b=c[p+1];v=c[p+2];break;case t.COLORTYPE_COLOR:f=c[p];b=c[p+1];v=c[p+2];break;case t.COLORTYPE_ALPHA:y=c[p+1];f=c[p];b=f;v=f;break;case t.COLORTYPE_GRAYSCALE:f=c[p];b=f;v=f;break;default:throw new Error("input color type:"+o.inputColorType+" is not supported at present")}if(o.inputHasAlpha){if(!a){y/=u;f=Math.min(Math.max(Math.round((1-y)*g.red+y*f),0),u);b=Math.min(Math.max(Math.round((1-y)*g.green+y*b),0),u);v=Math.min(Math.max(Math.round((1-y)*g.blue+y*v),0),u)}}return{red:f,green:b,blue:v,alpha:y}}for(let f=0;f<s;f++){for(let b=0;b<i;b++){let v=w(c,p);switch(o.colorType){case t.COLORTYPE_COLOR_ALPHA:case t.COLORTYPE_COLOR:if(o.bitDepth===8){h[m]=v.red;h[m+1]=v.green;h[m+2]=v.blue;if(a){h[m+3]=v.alpha}}else{h.writeUInt16BE(v.red,m);h.writeUInt16BE(v.green,m+2);h.writeUInt16BE(v.blue,m+4);if(a){h.writeUInt16BE(v.alpha,m+6)}}break;case t.COLORTYPE_ALPHA:case t.COLORTYPE_GRAYSCALE:{let y=(v.red+v.green+v.blue)/3;if(o.bitDepth===8){h[m]=y;if(a){h[m+1]=v.alpha}}else{h.writeUInt16BE(y,m);if(a){h.writeUInt16BE(v.alpha,m+2)}}break}default:throw new Error("unrecognised color Type "+o.colorType)}p+=l;m+=d}}return h}}});var require_filter_pack=__commonJS({"../../node_modules/pngjs/lib/filter-pack.js"(e,n){"use strict";var t=require_paeth_predictor();function r(g,w,f,b,v){for(let y=0;y<f;y++){b[v+y]=g[w+y]}}function i(g,w,f){let b=0;let v=w+f;for(let y=w;y<v;y++){b+=Math.abs(g[y])}return b}function s(g,w,f,b,v,y){for(let _=0;_<f;_++){let $=_>=y?g[w+_-y]:0;let k=g[w+_]-$;b[v+_]=k}}function o(g,w,f,b){let v=0;for(let y=0;y<f;y++){let _=y>=b?g[w+y-b]:0;let $=g[w+y]-_;v+=Math.abs($)}return v}function a(g,w,f,b,v){for(let y=0;y<f;y++){let _=w>0?g[w+y-f]:0;let $=g[w+y]-_;b[v+y]=$}}function c(g,w,f){let b=0;let v=w+f;for(let y=w;y<v;y++){let _=w>0?g[y-f]:0;let $=g[y]-_;b+=Math.abs($)}return b}function u(g,w,f,b,v,y){for(let _=0;_<f;_++){let $=_>=y?g[w+_-y]:0;let k=w>0?g[w+_-f]:0;let T=g[w+_]-($+k>>1);b[v+_]=T}}function l(g,w,f,b){let v=0;for(let y=0;y<f;y++){let _=y>=b?g[w+y-b]:0;let $=w>0?g[w+y-f]:0;let k=g[w+y]-(_+$>>1);v+=Math.abs(k)}return v}function d(g,w,f,b,v,y){for(let _=0;_<f;_++){let $=_>=y?g[w+_-y]:0;let k=w>0?g[w+_-f]:0;let T=w>0&&_>=y?g[w+_-(f+y)]:0;let A=g[w+_]-t($,k,T);b[v+_]=A}}function h(g,w,f,b){let v=0;for(let y=0;y<f;y++){let _=y>=b?g[w+y-b]:0;let $=w>0?g[w+y-f]:0;let k=w>0&&y>=b?g[w+y-(f+b)]:0;let T=g[w+y]-t(_,$,k);v+=Math.abs(T)}return v}var p={0:r,1:s,2:a,3:u,4:d};var m={0:i,1:o,2:c,3:l,4:h};n.exports=function(g,w,f,b,v){let y;if(!("filterType"in b)||b.filterType===-1){y=[0,1,2,3,4]}else if(typeof b.filterType==="number"){y=[b.filterType]}else{throw new Error("unrecognised filter types")}if(b.bitDepth===16){v*=2}let _=w*v;let $=0;let k=0;let T=Buffer.alloc((_+1)*f);let A=y[0];for(let I=0;I<f;I++){if(y.length>1){let R=Infinity;for(let M=0;M<y.length;M++){let S=m[y[M]](g,k,_,v);if(S<R){A=y[M];R=S}}}T[$]=A;$++;p[A](g,k,_,T,$,v);$+=_;k+=_}return T}}});var require_packer=__commonJS({"../../node_modules/pngjs/lib/packer.js"(e,n){"use strict";var t=require_constants();var r=require_crc();var i=require_bitpacker();var s=require_filter_pack();var o=require("zlib");var a=n.exports=function(c){this._options=c;c.deflateChunkSize=c.deflateChunkSize||32*1024;c.deflateLevel=c.deflateLevel!=null?c.deflateLevel:9;c.deflateStrategy=c.deflateStrategy!=null?c.deflateStrategy:3;c.inputHasAlpha=c.inputHasAlpha!=null?c.inputHasAlpha:true;c.deflateFactory=c.deflateFactory||o.createDeflate;c.bitDepth=c.bitDepth||8;c.colorType=typeof c.colorType==="number"?c.colorType:t.COLORTYPE_COLOR_ALPHA;c.inputColorType=typeof c.inputColorType==="number"?c.inputColorType:t.COLORTYPE_COLOR_ALPHA;if([t.COLORTYPE_GRAYSCALE,t.COLORTYPE_COLOR,t.COLORTYPE_COLOR_ALPHA,t.COLORTYPE_ALPHA].indexOf(c.colorType)===-1){throw new Error("option color type:"+c.colorType+" is not supported at present")}if([t.COLORTYPE_GRAYSCALE,t.COLORTYPE_COLOR,t.COLORTYPE_COLOR_ALPHA,t.COLORTYPE_ALPHA].indexOf(c.inputColorType)===-1){throw new Error("option input color type:"+c.inputColorType+" is not supported at present")}if(c.bitDepth!==8&&c.bitDepth!==16){throw new Error("option bit depth:"+c.bitDepth+" is not supported at present")}};a.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};a.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};a.prototype.filterData=function(c,u,l){let d=i(c,u,l,this._options);let h=t.COLORTYPE_TO_BPP_MAP[this._options.colorType];let p=s(d,u,l,this._options,h);return p};a.prototype._packChunk=function(c,u){let l=u?u.length:0;let d=Buffer.alloc(l+12);d.writeUInt32BE(l,0);d.writeUInt32BE(c,4);if(u){u.copy(d,8)}d.writeInt32BE(r.crc32(d.slice(4,d.length-4)),d.length-4);return d};a.prototype.packGAMA=function(c){let u=Buffer.alloc(4);u.writeUInt32BE(Math.floor(c*t.GAMMA_DIVISION),0);return this._packChunk(t.TYPE_gAMA,u)};a.prototype.packIHDR=function(c,u){let l=Buffer.alloc(13);l.writeUInt32BE(c,0);l.writeUInt32BE(u,4);l[8]=this._options.bitDepth;l[9]=this._options.colorType;l[10]=0;l[11]=0;l[12]=0;return this._packChunk(t.TYPE_IHDR,l)};a.prototype.packIDAT=function(c){return this._packChunk(t.TYPE_IDAT,c)};a.prototype.packIEND=function(){return this._packChunk(t.TYPE_IEND,null)}}});var require_packer_async=__commonJS({"../../node_modules/pngjs/lib/packer-async.js"(e,n){"use strict";var t=require("util");var r=require("stream");var i=require_constants();var s=require_packer();var o=n.exports=function(a){r.call(this);let c=a||{};this._packer=new s(c);this._deflate=this._packer.createDeflate();this.readable=true};t.inherits(o,r);o.prototype.pack=function(a,c,u,l){this.emit("data",Buffer.from(i.PNG_SIGNATURE));this.emit("data",this._packer.packIHDR(c,u));if(l){this.emit("data",this._packer.packGAMA(l))}let d=this._packer.filterData(a,c,u);this._deflate.on("error",this.emit.bind(this,"error"));this._deflate.on("data",function(h){this.emit("data",this._packer.packIDAT(h))}.bind(this));this._deflate.on("end",function(){this.emit("data",this._packer.packIEND());this.emit("end")}.bind(this));this._deflate.end(d)}}});var require_sync_inflate=__commonJS({"../../node_modules/pngjs/lib/sync-inflate.js"(e,n){"use strict";var t=require("assert").ok;var r=require("zlib");var i=require("util");var s=require("buffer").kMaxLength;function o(d){if(!(this instanceof o)){return new o(d)}if(d&&d.chunkSize<r.Z_MIN_CHUNK){d.chunkSize=r.Z_MIN_CHUNK}r.Inflate.call(this,d);this._offset=this._offset===void 0?this._outOffset:this._offset;this._buffer=this._buffer||this._outBuffer;if(d&&d.maxLength!=null){this._maxLength=d.maxLength}}function a(d){return new o(d)}function c(d,h){if(h){process.nextTick(h)}if(!d._handle){return}d._handle.close();d._handle=null}o.prototype._processChunk=function(d,h,p){if(typeof p==="function"){return r.Inflate._processChunk.call(this,d,h,p)}let m=this;let g=d&&d.length;let w=this._chunkSize-this._offset;let f=this._maxLength;let b=0;let v=[];let y=0;let _;this.on("error",function(A){_=A});function $(A,I){if(m._hadError){return}let R=w-I;t(R>=0,"have should not go down");if(R>0){let M=m._buffer.slice(m._offset,m._offset+R);m._offset+=R;if(M.length>f){M=M.slice(0,f)}v.push(M);y+=M.length;f-=M.length;if(f===0){return false}}if(I===0||m._offset>=m._chunkSize){w=m._chunkSize;m._offset=0;m._buffer=Buffer.allocUnsafe(m._chunkSize)}if(I===0){b+=g-A;g=A;return true}return false}t(this._handle,"zlib binding closed");let k;do{k=this._handle.writeSync(h,d,b,g,this._buffer,this._offset,w);k=k||this._writeState}while(!this._hadError&&$(k[0],k[1]));if(this._hadError){throw _}if(y>=s){c(this);throw new RangeError("Cannot create final Buffer. It would be larger than 0x"+s.toString(16)+" bytes")}let T=Buffer.concat(v,y);c(this);return T};i.inherits(o,r.Inflate);function u(d,h){if(typeof h==="string"){h=Buffer.from(h)}if(!(h instanceof Buffer)){throw new TypeError("Not a string or buffer")}let p=d._finishFlushFlag;if(p==null){p=r.Z_FINISH}return d._processChunk(h,p)}function l(d,h){return u(new o(h),d)}n.exports=e=l;e.Inflate=o;e.createInflate=a;e.inflateSync=l}});var require_sync_reader=__commonJS({"../../node_modules/pngjs/lib/sync-reader.js"(e,n){"use strict";var t=n.exports=function(r){this._buffer=r;this._reads=[]};t.prototype.read=function(r,i){this._reads.push({length:Math.abs(r),allowLess:r<0,func:i})};t.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let r=this._reads[0];if(this._buffer.length&&(this._buffer.length>=r.length||r.allowLess)){this._reads.shift();let i=this._buffer;this._buffer=i.slice(r.length);r.func.call(this,i.slice(0,r.length))}else{break}}if(this._reads.length>0){throw new Error("There are some read requests waitng on finished stream")}if(this._buffer.length>0){throw new Error("unrecognised content at end of stream")}}}});var require_filter_parse_sync=__commonJS({"../../node_modules/pngjs/lib/filter-parse-sync.js"(e){"use strict";var n=require_sync_reader();var t=require_filter_parse();e.process=function(r,i){let s=[];let o=new n(r);let a=new t(i,{read:o.read.bind(o),write:function(c){s.push(c)},complete:function(){}});a.start();o.process();return Buffer.concat(s)}}});var require_parser_sync=__commonJS({"../../node_modules/pngjs/lib/parser-sync.js"(e,n){"use strict";var t=true;var r=require("zlib");var i=require_sync_inflate();if(!r.deflateSync){t=false}var s=require_sync_reader();var o=require_filter_parse_sync();var a=require_parser();var c=require_bitmapper();var u=require_format_normaliser();n.exports=function(l,d){if(!t){throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0")}let h;function p(x){h=x}let m;function g(x){m=x}function w(x){m.transColor=x}function f(x){m.palette=x}function b(){m.alpha=true}let v;function y(x){v=x}let _=[];function $(x){_.push(x)}let k=new s(l);let T=new a(d,{read:k.read.bind(k),error:p,metadata:g,gamma:y,palette:f,transColor:w,inflateData:$,simpleTransparency:b});T.start();k.process();if(h){throw h}let A=Buffer.concat(_);_.length=0;let I;if(m.interlace){I=r.inflateSync(A)}else{let x=(m.width*m.bpp*m.depth+7>>3)+1;let E=x*m.height;I=i(A,{chunkSize:E,maxLength:E})}A=null;if(!I||!I.length){throw new Error("bad png - invalid inflate data response")}let R=o.process(I,m);A=null;let M=c.dataToBitMap(R,m);R=null;let S=u(M,m,d.skipRescale);m.data=S;m.gamma=v||0;return m}}});var require_packer_sync=__commonJS({"../../node_modules/pngjs/lib/packer-sync.js"(e,n){"use strict";var t=true;var r=require("zlib");if(!r.deflateSync){t=false}var i=require_constants();var s=require_packer();n.exports=function(o,a){if(!t){throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0")}let c=a||{};let u=new s(c);let l=[];l.push(Buffer.from(i.PNG_SIGNATURE));l.push(u.packIHDR(o.width,o.height));if(o.gamma){l.push(u.packGAMA(o.gamma))}let d=u.filterData(o.data,o.width,o.height);let h=r.deflateSync(d,u.getDeflateOptions());d=null;if(!h||!h.length){throw new Error("bad png - invalid compressed data response")}l.push(u.packIDAT(h));l.push(u.packIEND());return Buffer.concat(l)}}});var require_png_sync=__commonJS({"../../node_modules/pngjs/lib/png-sync.js"(e){"use strict";var n=require_parser_sync();var t=require_packer_sync();e.read=function(r,i){return n(r,i||{})};e.write=function(r,i){return t(r,i)}}});var require_png=__commonJS({"../../node_modules/pngjs/lib/png.js"(e){"use strict";var n=require("util");var t=require("stream");var r=require_parser_async();var i=require_packer_async();var s=require_png_sync();var o=e.PNG=function(a){t.call(this);a=a||{};this.width=a.width|0;this.height=a.height|0;this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null;if(a.fill&&this.data){this.data.fill(0)}this.gamma=0;this.readable=this.writable=true;this._parser=new r(a);this._parser.on("error",this.emit.bind(this,"error"));this._parser.on("close",this._handleClose.bind(this));this._parser.on("metadata",this._metadata.bind(this));this._parser.on("gamma",this._gamma.bind(this));this._parser.on("parsed",function(c){this.data=c;this.emit("parsed",c)}.bind(this));this._packer=new i(a);this._packer.on("data",this.emit.bind(this,"data"));this._packer.on("end",this.emit.bind(this,"end"));this._parser.on("close",this._handleClose.bind(this));this._packer.on("error",this.emit.bind(this,"error"))};n.inherits(o,t);o.sync=s;o.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};o.prototype.parse=function(a,c){if(c){let u,l;u=function(d){this.removeListener("error",l);this.data=d;c(null,this)}.bind(this);l=function(d){this.removeListener("parsed",u);c(d,null)}.bind(this);this.once("parsed",u);this.once("error",l)}this.end(a);return this};o.prototype.write=function(a){this._parser.write(a);return true};o.prototype.end=function(a){this._parser.end(a)};o.prototype._metadata=function(a){this.width=a.width;this.height=a.height;this.emit("metadata",a)};o.prototype._gamma=function(a){this.gamma=a};o.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable){this.emit("close")}};o.bitblt=function(a,c,u,l,d,h,p,m){u|=0;l|=0;d|=0;h|=0;p|=0;m|=0;if(u>a.width||l>a.height||u+d>a.width||l+h>a.height){throw new Error("bitblt reading outside image")}if(p>c.width||m>c.height||p+d>c.width||m+h>c.height){throw new Error("bitblt writing outside image")}for(let g=0;g<h;g++){a.data.copy(c.data,(m+g)*c.width+p<<2,(l+g)*a.width+u<<2,(l+g)*a.width+u+d<<2)}};o.prototype.bitblt=function(a,c,u,l,d,h,p){o.bitblt(this,a,c,u,l,d,h,p);return this};o.adjustGamma=function(a){if(a.gamma){for(let c=0;c<a.height;c++){for(let u=0;u<a.width;u++){let l=a.width*c+u<<2;for(let d=0;d<3;d++){let h=a.data[l+d]/255;h=Math.pow(h,1/2.2/a.gamma);a.data[l+d]=Math.round(h*255)}}}a.gamma=0}};o.prototype.adjustGamma=function(){o.adjustGamma(this)}}});async function devicectl(e,n=3e4){const t=import_node_path.default.join(import_node_os.default.tmpdir(),`buoy-devicectl-${(0,import_node_crypto.randomUUID)()}.json`);try{await execFileAsync2("xcrun",["devicectl",...e,"--quiet","--json-output",t],{timeout:n,maxBuffer:16*1024*1024});return JSON.parse(await import_node_fs.promises.readFile(t,"utf8"))}catch(r){const i=r;let s=(i.stderr||i.stdout||i.message||"").trim();try{const o=JSON.parse(await import_node_fs.promises.readFile(t,"utf8"));s=o.error?.userInfo?.NSLocalizedDescription?.string??s}catch{}if(/locked/i.test(s))throw new Error("The iPhone is locked. Unlock it and try again.");throw new Error(`devicectl ${e.slice(0,2).join(" ")} failed: ${s.split("\n").slice(-3).join(" ").slice(0,300)}`)}finally{await import_node_fs.promises.unlink(t).catch(()=>void 0)}}async function physicalPhones(){if(process.platform!=="darwin")return[];return parsePhones(await devicectl(["list","devices"],15e3).catch(()=>null))}function parsePhones(e){const n=e;return(n?.result?.devices??[]).filter(t=>t.hardwareProperties?.reality==="physical"&&t.hardwareProperties?.platform==="iOS"&&t.connectionProperties?.pairingState==="paired"&&t.connectionProperties?.tunnelState!=="unavailable").map(t=>({udid:t.hardwareProperties.udid,name:t.deviceProperties?.name??"iPhone"})).filter(t=>!!t.udid)}async function developerApps(e){const n=await devicectl(["device","info","apps","--device",e]);return(n.result?.apps??[]).filter(t=>t.bundleIdentifier&&!t.bundleIdentifier.startsWith("com.apple.")&&t.builtByDeveloper!==false).map(t=>({bundleId:t.bundleIdentifier,name:t.name??t.bundleIdentifier,path:t.url?.replace(/^file:\/\//,"")}))}async function readAppFile(e,n,t){const r=await devicectl(["device","info","files","--device",e,"--domain-type","appDataContainer","--domain-identifier",n],2e4);const i=new Set((r.result?.files??[]).map(o=>o.relativePath??o.name??""));if(!i.has(t))return null;const s=import_node_path.default.join(import_node_os.default.tmpdir(),`buoy-devfile-${(0,import_node_crypto.randomUUID)()}`);try{await devicectl(["device","copy","from","--device",e,"--domain-type","appDataContainer","--domain-identifier",n,"--source",t,"--destination",s],2e4);return await import_node_fs.promises.readFile(s)}finally{await import_node_fs.promises.rm(s,{recursive:true,force:true}).catch(()=>void 0)}}async function phoneInstallId(e,n){const t=await readAppFile(e,n,"Documents/react-buoy/@react_buoy_sync_device_id.json").catch(()=>null);const r=t?.toString("utf8").trim().replace(/^"|"$/g,"")??"";return/^[\w-]{4,64}$/.test(r)?r:null}async function phoneScreenshot(e){const n=import_node_path.default.join(import_node_os.default.tmpdir(),`buoy-phone-shot-${(0,import_node_crypto.randomUUID)()}.png`);try{await devicectl(["device","capture","screenshot","--device",e,"--destination",n],3e4);return await import_node_fs.promises.readFile(n)}finally{await import_node_fs.promises.unlink(n).catch(()=>void 0)}}function isAllBlack(e){try{const n=import_pngjs.PNG.sync.read(e);const t=Math.max(1,Math.floor(n.width*n.height/4e3));for(let r=0;r<n.width*n.height;r+=t){const i=r*4;if(n.data[i]>12||n.data[i+1]>12||n.data[i+2]>12)return false}return true}catch{return false}}async function phoneLaunch(e,n,t={}){await devicectl(["device","process","launch","--device",e,...t.terminateExisting?["--terminate-existing"]:[],...t.url?["--payload-url",t.url]:[],n])}async function phoneOpenUrl(e,n){await devicectl(["device","process","openURL","--device",e,n])}async function phoneQuit(e,n){const t=await developerApps(e);const r=t.find(o=>o.bundleId===n)?.path;const i=await devicectl(["device","info","processes","--device",e]);const s=(i.result?.runningProcesses??[]).find(o=>r&&decodeURIComponent(o.executable??"").replace(/^file:\/\//,"").startsWith(r.replace(/\/$/,"")));if(!s?.processIdentifier)return false;await devicectl(["device","process","terminate","--device",e,"--pid",String(s.processIdentifier)]);return true}async function phoneUninstall(e,n){await devicectl(["device","uninstall","app","--device",e,n],12e4)}async function phoneInstall(e,n){await devicectl(["device","install","app","--device",e,n],3e5)}async function writeAppFile(e,n,t,r){await devicectl(["device","copy","to","--device",e,"--domain-type","appDataContainer","--domain-identifier",n,"--source",t,"--destination",r],3e4)}function phoneRecordArgs(e,n,t){return["devicectl","device","capture","screen-record","--device",e,"--destination",n,"--duration",String(t)]}async function coreDeviceId(e){const n=coreIds.get(e);if(n)return n;const t=await devicectl(["list","devices"]);const r=t.result?.devices?.find(i=>i.hardwareProperties?.udid===e)?.identifier;if(!r)throw new Error("CoreDevice doesn't list this iPhone right now. Check that it is connected and unlocked.");coreIds.set(e,r);return r}var import_node_child_process2,import_node_util2,import_node_fs,import_node_os,import_node_path,import_node_crypto,import_pngjs,execFileAsync2,BLACK_PHONE_NOTE,coreIds;var init_iosDevice=__esm({"src/capture/iosDevice.ts"(){"use strict";import_node_child_process2=require("child_process");import_node_util2=require("util");import_node_fs=require("fs");import_node_os=__toESM(require("os"));import_node_path=__toESM(require("path"));import_node_crypto=require("crypto");import_pngjs=__toESM(require_png());execFileAsync2=(0,import_node_util2.promisify)(import_node_child_process2.execFile);BLACK_PHONE_NOTE="The picture is all black. If the app isn't really showing black, the iPhone's own screen is off: it is asleep, or the Mac shows it in iPhone Mirroring (the phone stays locked then). Quit iPhone Mirroring, unlock the phone and keep its screen on, then try again.";coreIds=new Map}});async function startRecording(e,n){await import_node_fs2.promises.mkdir(import_node_path2.default.dirname(n),{recursive:true});const t=Date.now();let r;let i;if(e.platform==="ios"){r=(0,import_node_child_process3.spawn)("xcrun",["simctl","io",e.udid,"recordVideo","--codec=h264","--force",n],{stdio:["ignore","ignore","pipe"]})}else if(e.platform==="ios-device"){r=(0,import_node_child_process3.spawn)("xcrun",phoneRecordArgs(e.udid,n,MAX_RECORDING_MS/1e3),{stdio:["ignore","ignore","pipe"]})}else{i=`/sdcard/buoy-recording-${t}-${Math.random().toString(36).slice(2,8)}.mp4`;r=(0,import_node_child_process3.spawn)("adb",["-s",e.serial,"shell",`echo $$; exec screenrecord --time-limit ${MAX_RECORDING_MS/1e3} ${q(i)}`],{stdio:["ignore","pipe","pipe"]})}const s={host:e,file:n,startedAt:t,proc:r,remote:i};live.add(s);let o="";let a=t;let c;r.stderr?.on("data",d=>{o+=String(d);if(/Recording started/i.test(String(d)))a=Date.now()});r.stdout?.on("data",d=>{const h=/^(\d+)/m.exec(String(d));if(h&&c===void 0)c=Number(h[1])});const u=await new Promise(d=>{const h=setTimeout(()=>d(null),e.platform==="ios"?3e3:e.platform==="ios-device"?4e3:1200);const p=setInterval(()=>{if(e.platform==="ios"&&a!==t||e.platform==="android"&&c!==void 0){clearTimeout(h);clearInterval(p);d(null)}},50);r.once("exit",m=>{clearTimeout(h);clearInterval(p);d(m??-1)});r.once("error",()=>{clearTimeout(h);clearInterval(p);d(-1)})});live.delete(s);if(u!==null){if(/not supported by this device/i.test(o)){throw new Error("This iPhone can't record its screen through Xcode (devicectl says the device doesn't support it). Record on a simulator, or use the iPhone's own Screen Recording in Control Center.")}throw new Error(`The screen recorder stopped right away: ${o.trim().slice(0,300)||`exit ${u}`}`)}if(e.platform==="ios"&&r.pid){const d=r.pid;const h=(0,import_node_child_process3.spawn)("sh",["-c",`sleep ${MAX_RECORDING_MS/1e3+15}; ps -p ${d} -o command= | grep -q 'simctl io .* recordVideo' && kill -INT ${d}`],{detached:true,stdio:"ignore"});h.on("error",()=>void 0);h.unref();r.once("exit",()=>{try{if(h.pid)process.kill(-h.pid,"SIGTERM")}catch{h.kill("SIGTERM")}})}const l={host:e,file:n,startedAt:a,proc:r,remote:i,remotePid:c};live.add(l);return l}async function stopRecording(e){if(e.stopTimer)clearTimeout(e.stopTimer);const n=Date.now();const t=new Promise(i=>{if(e.proc.exitCode!==null||e.proc.signalCode!==null)return i();e.proc.once("exit",()=>i())});if(e.host.platform==="ios"||e.host.platform==="ios-device"){e.proc.kill("SIGINT")}else if(e.remotePid){await adbShell(e.host.serial,`kill -INT ${e.remotePid}`).catch(()=>void 0)}await Promise.race([t,new Promise(i=>setTimeout(i,e.host.platform==="ios-device"?6e4:1e4))]);if(e.proc.exitCode===null&&e.proc.signalCode===null)e.proc.kill("SIGKILL");live.delete(e);if(e.host.platform==="android"&&e.remote){await new Promise(i=>setTimeout(i,800));await adb(e.host.serial,["pull",e.remote,e.file],6e4);await adbShell(e.host.serial,`rm -f ${q(e.remote)}`).catch(()=>void 0)}const r=await import_node_fs2.promises.stat(e.file).catch(()=>null);if(!r||r.size<1e3)throw new Error("The recording file is missing or empty. Was the screen showing anything?");return n-e.startedAt}function stopAllRecordingsNow(){for(const e of live){try{if(e.host.platform!=="android")e.proc.kill("SIGINT");else if(e.remotePid)(0,import_node_child_process3.spawn)("adb",["-s",e.host.serial,"shell",`kill -INT ${e.remotePid}`],{stdio:"ignore",detached:true}).unref()}catch{}}live.clear()}function redact(e){return e.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi,"$1 [redacted]").replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}/g,"[redacted jwt]").replace(/((?:api[_-]?key|token|secret|password|passwd|authorization|cookie|session)["']?\s*[:=]\s*["']?)([^\s"'&,;}]{4,})/gi,"$1[redacted]")}function viewerHtml(e){const n=JSON.stringify(e).replace(/</g,"\\u003c");return`<!doctype html>
|
|
2
|
+
"use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __esm=(e,n)=>function t(){return e&&(n=(0,e[__getOwnPropNames(e)[0]])(e=0)),n};var __commonJS=(e,n)=>function t(){return n||(0,e[__getOwnPropNames(e)[0]])((n={exports:{}}).exports,n),n.exports};var __export=(e,n)=>{for(var t in n)__defProp(e,t,{get:n[t],enumerable:true})};var __copyProps=(e,n,t,r)=>{if(n&&typeof n==="object"||typeof n==="function"){for(let i of __getOwnPropNames(n))if(!__hasOwnProp.call(e,i)&&i!==t)__defProp(e,i,{get:()=>n[i],enumerable:!(r=__getOwnPropDesc(n,i))||r.enumerable})}return e};var __toESM=(e,n,t)=>(t=e!=null?__create(__getProtoOf(e)):{},__copyProps(n||!e||!e.__esModule?__defProp(t,"default",{value:e,enumerable:true}):t,e));function stopAllHidStreamsNow(){for(const e of workers.values())e.child.kill("SIGKILL")}function runHidStream(e,n,t,r=""){const i=n;const o=(queues.get(i)??Promise.resolve()).catch(()=>void 0).then(()=>send(i,e,t,r));queues.set(i,o);void o.finally(()=>{if(queues.get(i)===o)queues.delete(i)}).catch(()=>void 0);return o}async function send(e,n,t,r){let i=workers.get(e);if(i&&i.bin!==n)i.stop(new Error("The touch helper build changed."));if(i?.stopped){await i.exited;i=void 0}if(!i){const s=(0,import_node_child_process.spawn)(n,["--stream"],{stdio:["pipe","pipe","pipe"]});let a;const c=new Promise(d=>{a=d});i={bin:n,child:s,buffer:"",stopped:false,exited:c,stop:()=>{}};if(workers.size===0)process.once("exit",stopAllHidStreamsNow);workers.set(e,i);const l=i;const u=d=>{if(l.stopped)return;l.stopped=true;if(l.idle)clearTimeout(l.idle);const h=l.pending;l.pending=void 0;if(h)clearTimeout(h.timer);s.ref();s.kill("SIGKILL");void c.then(()=>{if(workers.get(e)===l)workers.delete(e);if(workers.size===0)process.removeListener("exit",stopAllHidStreamsNow);h?.reject(d)})};l.stop=u;s.on("error",d=>{a();u(d)});s.on("exit",()=>{a();u(new Error("The touch helper closed. Try the next touch."))});s.stdin.on("error",d=>u(d));s.stdout.on("data",d=>{l.buffer+=d;let h;while((h=l.buffer.indexOf("\n"))>=0){const w=l.buffer.slice(0,h);l.buffer=l.buffer.slice(h+1);const p=l.pending;if(!p)continue;try{const g=JSON.parse(w);if(!g||typeof g.ok!=="boolean")throw new Error("Bad reply.");if(g.ok===true){clearTimeout(p.timer);l.pending=void 0;p.resolve()}else u(new Error(g.error??"The touch failed."))}catch{u(new Error("The touch helper sent a bad reply."))}}});s.stderr.resume();s.unref();for(const d of[s.stdin,s.stdout,s.stderr])d.unref?.()}const o=i;if(o.idle)clearTimeout(o.idle);return new Promise((s,a)=>{const c=setTimeout(()=>{o.stop(new Error("The touch helper timed out."))},45e3);o.pending={resolve:s,reject:a,timer:c};o.child.stdin.write(JSON.stringify({args:t,input:r})+"\n")}).finally(()=>{if(o.stopped)return;o.idle=setTimeout(()=>{o.child.stdin.end();o.stop(new Error("The touch helper went idle."))},1e4);o.idle.unref()})}var import_node_child_process,workers,queues;var init_hidStream=__esm({"src/capture/hidStream.ts"(){"use strict";import_node_child_process=require("child_process");workers=new Map;queues=new Map}});function setRecordingProbe(e){recordingActive=e}function hasSecrets(e){PLACEHOLDER.lastIndex=0;return PLACEHOLDER.test(e)}function fillSecrets(e,n=process.env){if(!hasSecrets(e))return e;if(recordingActive()){throw new Error("A screen recording is running, and a video can't hide a typed secret. Stop the recording first (screen_recording stop), then type it.")}const t=[];const r=[];const i=e.replace(PLACEHOLDER,(o,s)=>{const a=n[`BUOY_SECRET_${s}`]??n[s];if(a===void 0||a===""){t.push(s);return""}if(a.length<MIN_SECRET_LENGTH){r.push(s);return""}used.set(s,a);return a});if(t.length){throw new Error(`No value for ${t.map(o=>`{{secret:${o}}}`).join(", ")}. Set ${t.map(o=>`BUOY_SECRET_${o}`).join(", ")} in the environment the MCP server runs in (for example in your editor's MCP config "env").`)}if(r.length){throw new Error(`${r.map(o=>`{{secret:${o}}}`).join(", ")} is shorter than ${MIN_SECRET_LENGTH} characters, so Buoy can't hide it reliably in what it sends back. Use a longer value, or type it as plain text if it isn't sensitive.`)}return i}function knownSecrets(e=process.env){const n=new Map(used);for(const[t,r]of Object.entries(e))if(t.startsWith("BUOY_SECRET_")&&r)n.set(t.slice("BUOY_SECRET_".length),r);return n}function scrubSecrets(e){const n=new Map;for(const[i,o]of knownSecrets()){if(o.length<MIN_SECRET_LENGTH)continue;for(const s of[o,JSON.stringify(o).slice(1,-1),encodeURIComponent(o)])n.set(s,i);for(let s=o.length-1;s>=MIN_SECRET_LENGTH;s--){n.set(`${o.slice(0,s)}\u2026`,i);n.set(`${o.slice(0,s)}...`,i);if(s>=8)n.set(o.slice(0,s),i)}}if(n.size===0)return e;const t=[...n.keys()].sort((i,o)=>o.length-i.length);const r=new RegExp(t.map(escapeRe).join("|"),"g");return e.replace(r,(i,o,s)=>{if(/^\d+$/.test(i)){const a=s.slice(Math.max(0,o-8),o);const c=s.slice(o+i.length,o+i.length+8);if(/(\d|\d\.)$/.test(a)||/^(\d|\.\d|[eE][+-]?\d)/.test(c))return i;if(/[:[,]\s*$/.test(a)&&/^\s*([,\]}]|$)/.test(c)&&!insideJsonString(s,o))return`"{{secret:${n.get(i)}}}"`}return`{{secret:${n.get(i)}}}`})}function insideJsonString(e,n){let t=false;for(let r=0;r<n;r++){if(e[r]==="\\")r++;else if(e[r]==='"')t=!t}return t}function typedSecretValues(){return[...used.values()]}function secretValues(){return[...knownSecrets().values()].filter(e=>e.length>=MIN_SECRET_LENGTH)}var PLACEHOLDER,MIN_SECRET_LENGTH,used,recordingActive,escapeRe;var init_secrets=__esm({"src/tools/secrets.ts"(){"use strict";PLACEHOLDER=/\{\{\s*secret:([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;MIN_SECRET_LENGTH=6;used=new Map;recordingActive=()=>false;escapeRe=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}});function q(e){return`'${e.replace(/'/g,`'\\''`)}'`}function assertPackage(e){if(!/^[A-Za-z][\w]*(\.[A-Za-z_][\w]*)+$/.test(e))throw new Error(`"${e}" is not a valid Android package name.`);return e}async function adb(e,n,t=15e3){try{const{stdout:r}=await execFileAsync("adb",e?["-s",e,...n]:n,{timeout:t,maxBuffer:32*1024*1024});return r}catch(r){const i=r;if(i.code==="ENOENT")throw new Error(ADB_MISSING);const o=n[0]==="shell"?`shell ${(n[1]??"").split(" ")[0]}`:n.slice(0,2).join(" ");const s=n[0]==="shell"?i.stderr||(i.killed?"timed out":"no error text"):i.stderr||i.message||"";const a=scrubSecrets(s.replace(/'[^']*'/g,"'\u2026'")).trim().slice(0,300);throw new Error(`adb ${o} failed: ${a}`)}}function adbShell(e,n,t=15e3){return adb(e,["shell",n],t)}async function adbBytes(e,n,t=15e3){try{const{stdout:r}=await execFileAsync("adb",["-s",e,...n],{timeout:t,encoding:"buffer",maxBuffer:64*1024*1024});return r}catch(r){const i=r;if(i.code==="ENOENT")throw new Error(ADB_MISSING);throw new Error(`adb ${n.slice(0,2).join(" ")} failed: ${i.message.slice(0,300)}`)}}async function adbSerials(){return parseAdbDevices(await adb(null,["devices"]))}function parseAdbDevices(e){return e.split("\n").slice(1).map(n=>n.trim().split(/\s+/)).filter(n=>n[1]==="device").map(n=>n[0])}async function adbScreenSize(e){const n=parseWmSize(await adbShell(e,"wm size"));const t=parseRotation(await adbShell(e,"dumpsys input").catch(()=>""));return t%2===1?{width:n.height,height:n.width}:n}function parseWmSize(e){const n=/Override size:\s*(\d+)x(\d+)/.exec(e);const t=/Physical size:\s*(\d+)x(\d+)/.exec(e);const r=n??t;if(!r)throw new Error(`Could not read the Android screen size (adb said: ${e.trim().slice(0,120)}).`);return{width:Number(r[1]),height:Number(r[2])}}function parseRotation(e){const n=/SurfaceOrientation:\s*(\d)/.exec(e);return n?Number(n[1]):0}async function adbAppFrame(e,n){const t=await adbShell(e,"dumpsys window windows").catch(()=>"");return parseAppFrame(t,n)}function parseAppFrame(e,n){const t=e.split(/\n(?=\s*Window #\d+)/);for(const r of t){if(!r.includes(`${n}/`))continue;const i=/mFrame=\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(r)??/\bframe=\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(r);if(i){const[o,s,a,c]=i.slice(1).map(Number);if(a>o&&c>s)return{x:o,y:s,width:a-o,height:c-s}}}return null}async function adbForegroundPackage(e){return parseForegroundPackage(await adbShell(e,"dumpsys activity activities"))}function parseForegroundPackage(e){const n=/(?:topResumedActivity|mResumedActivity|ResumedActivity)[^\n]*?\s([a-zA-Z][\w.]*)\/[\w.$]+/.exec(e);return n?n[1]:null}async function adbUserPackages(e){const n=await adbShell(e,"pm list packages -3");return n.split("\n").map(t=>t.trim().replace(/^package:/,"")).filter(t=>/^[A-Za-z][\w.]+$/.test(t))}async function adbInstallId(e,n){assertPackage(n);const t=await adbShell(e,`run-as ${q(n)} cat files/react-buoy/@react_buoy_sync_device_id.json 2>/dev/null`,5e3).catch(()=>"");const r=t.trim().replace(/^"|"$/g,"");if(/^[\w-]{4,64}$/.test(r))return r;const i=await adbBytes(e,["exec-out",`run-as ${q(n)} sh -c 'cat app_webview/Default/"Local Storage"/leveldb/*.log app_webview/Default/"Local Storage"/leveldb/*.ldb 2>/dev/null'`],5e3).catch(()=>null);return i?webViewLevelDbInstallId(i):null}function webViewLevelDbInstallId(e){const n=e.toString("latin1");const t=/@react_buoy_sync_device_id([\s\S])\x01([\w-]{4,64})/g;let r=null;for(let i=t.exec(n);i;i=t.exec(n)){const o=i[1].charCodeAt(0)-1;if(o>=4&&o<=i[2].length)r=i[2].slice(0,o)}return r}function escapeAdbText(e){if(/[^\x20-\x7e]/.test(e))throw new Error("adb can only type plain ASCII text. Use tap_element's text for other characters.");return q(e.replace(/ /g,"%s"))}async function adbTap(e,n,t,r){const[i,o]=[Math.round(n),Math.round(t)];if(r)await adbShell(e,`input swipe ${i} ${o} ${i} ${o} ${Math.round(r)}`);else await adbShell(e,`input tap ${i} ${o}`)}async function adbSwipe(e,n,t,r){const i=[...n,...t].map(o=>Math.round(o)).join(" ");await adbShell(e,`input swipe ${i} ${Math.round(r)}`)}async function adbText(e,n){const t=n.replace(/ /g,"\0");for(let r=0;r<t.length;r+=40){const i=t.slice(r,r+40).replace(/\u0000/g," ");await adbShell(e,`input text ${escapeAdbText(i)}`)}}async function adbScreenshot(e){const n=await adbBytes(e,["exec-out","screencap","-p"]);if(n.length<8||n.readUInt32BE(0)!==2303741511)throw new Error("The Android screenshot was not a PNG.");return n}async function adbDemoMode(e,n){if(n){await adbShell(e,"settings put global sysui_demo_allowed 1");for(const t of["-e command enter","-e command clock -e hhmm 0941","-e command battery -e level 100 -e plugged false","-e command network -e wifi show -e level 4","-e command notifications -e visible false"]){await adbShell(e,`am broadcast -a com.android.systemui.demo ${t}`).catch(()=>void 0)}}else{await adbShell(e,"am broadcast -a com.android.systemui.demo -e command exit").catch(()=>void 0)}}async function adbUiNodes(e){const n=await adb(e,["exec-out","uiautomator","dump","/dev/tty"],2e4);return parseUiDump(n)}function parseUiDump(e){const n=[];const t=(r,i)=>{const o=new RegExp(`\\s${i}="([^"]*)"`).exec(r);return o?decodeXml(o[1]):""};for(const r of e.matchAll(/<node\b[^>]*>/g)){const i=r[0];const o=/\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(t(i,"bounds"));if(!o)continue;const[s,a,c,l]=o.slice(1).map(Number);n.push({text:t(i,"text"),desc:t(i,"content-desc"),id:t(i,"resource-id"),cls:t(i,"class"),clickable:t(i,"clickable")==="true",bounds:{x:s,y:a,width:c-s,height:l-a}})}return n}function decodeXml(e){return e.replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&#(\d+);/g,(n,t)=>String.fromCharCode(Number(t))).replace(/&/g,"&")}function findUiNodes(e,n){const t=n.trim().toLowerCase();const r=c=>{let l=0;for(const u of[c.desc,c.text,c.id.split("/").pop()??""]){const d=u.trim().toLowerCase();if(!d)continue;if(d===t)l=Math.max(l,3);else if(d.startsWith(t))l=Math.max(l,2);else if(d.includes(t))l=Math.max(l,1)}return l};const i=e.filter(c=>c.bounds.width>0&&c.bounds.height>0&&r(c)>0);const o=Math.max(0,...i.map(r));const s=i.filter(c=>r(c)===o);let a=s.filter((c,l)=>s.findIndex(u=>JSON.stringify(u.bounds)===JSON.stringify(c.bounds))===l);if(a.length>1){const c=a.filter(l=>[l.desc,l.text,l.id.split("/").pop()??""].some(u=>u.trim()===n.trim()));if(c.length)a=c}if(a.length>1){const c=a.filter(l=>l.clickable||/EditText|Button/.test(l.cls));if(c.length)a=c}return a}var import_node_child_process2,import_node_util,execFileAsync,ADB_MISSING;var init_adb=__esm({"src/capture/adb.ts"(){"use strict";import_node_child_process2=require("child_process");import_node_util=require("util");init_secrets();execFileAsync=(0,import_node_util.promisify)(import_node_child_process2.execFile);ADB_MISSING="Android control needs adb on this computer (Android SDK platform-tools). Install it, or add it to PATH."}});var require_chunkstream=__commonJS({"../../node_modules/pngjs/lib/chunkstream.js"(e,n){"use strict";var t=require("util");var r=require("stream");var i=n.exports=function(){r.call(this);this._buffers=[];this._buffered=0;this._reads=[];this._paused=false;this._encoding="utf8";this.writable=true};t.inherits(i,r);i.prototype.read=function(o,s){this._reads.push({length:Math.abs(o),allowLess:o<0,func:s});process.nextTick(function(){this._process();if(this._paused&&this._reads&&this._reads.length>0){this._paused=false;this.emit("drain")}}.bind(this))};i.prototype.write=function(o,s){if(!this.writable){this.emit("error",new Error("Stream not writable"));return false}let a;if(Buffer.isBuffer(o)){a=o}else{a=Buffer.from(o,s||this._encoding)}this._buffers.push(a);this._buffered+=a.length;this._process();if(this._reads&&this._reads.length===0){this._paused=true}return this.writable&&!this._paused};i.prototype.end=function(o,s){if(o){this.write(o,s)}this.writable=false;if(!this._buffers){return}if(this._buffers.length===0){this._end()}else{this._buffers.push(null);this._process()}};i.prototype.destroySoon=i.prototype.end;i.prototype._end=function(){if(this._reads.length>0){this.emit("error",new Error("Unexpected end of input"))}this.destroy()};i.prototype.destroy=function(){if(!this._buffers){return}this.writable=false;this._reads=null;this._buffers=null;this.emit("close")};i.prototype._processReadAllowingLess=function(o){this._reads.shift();let s=this._buffers[0];if(s.length>o.length){this._buffered-=o.length;this._buffers[0]=s.slice(o.length);o.func.call(this,s.slice(0,o.length))}else{this._buffered-=s.length;this._buffers.shift();o.func.call(this,s)}};i.prototype._processRead=function(o){this._reads.shift();let s=0;let a=0;let c=Buffer.alloc(o.length);while(s<o.length){let l=this._buffers[a++];let u=Math.min(l.length,o.length-s);l.copy(c,s,0,u);s+=u;if(u!==l.length){this._buffers[--a]=l.slice(u)}}if(a>0){this._buffers.splice(0,a)}this._buffered-=o.length;o.func.call(this,c)};i.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let o=this._reads[0];if(o.allowLess){this._processReadAllowingLess(o)}else if(this._buffered>=o.length){this._processRead(o)}else{break}}if(this._buffers&&!this.writable){this._end()}}catch(o){this.emit("error",o)}}}});var require_interlace=__commonJS({"../../node_modules/pngjs/lib/interlace.js"(e){"use strict";var n=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];e.getImagePasses=function(t,r){let i=[];let o=t%8;let s=r%8;let a=(t-o)/8;let c=(r-s)/8;for(let l=0;l<n.length;l++){let u=n[l];let d=a*u.x.length;let h=c*u.y.length;for(let w=0;w<u.x.length;w++){if(u.x[w]<o){d++}else{break}}for(let w=0;w<u.y.length;w++){if(u.y[w]<s){h++}else{break}}if(d>0&&h>0){i.push({width:d,height:h,index:l})}}return i};e.getInterlaceIterator=function(t){return function(r,i,o){let s=r%n[o].x.length;let a=(r-s)/n[o].x.length*8+n[o].x[s];let c=i%n[o].y.length;let l=(i-c)/n[o].y.length*8+n[o].y[c];return a*4+l*t*4}}}});var require_paeth_predictor=__commonJS({"../../node_modules/pngjs/lib/paeth-predictor.js"(e,n){"use strict";n.exports=function t(r,i,o){let s=r+i-o;let a=Math.abs(s-r);let c=Math.abs(s-i);let l=Math.abs(s-o);if(a<=c&&a<=l){return r}if(c<=l){return i}return o}}});var require_filter_parse=__commonJS({"../../node_modules/pngjs/lib/filter-parse.js"(e,n){"use strict";var t=require_interlace();var r=require_paeth_predictor();function i(s,a,c){let l=s*a;if(c!==8){l=Math.ceil(l/(8/c))}return l}var o=n.exports=function(s,a){let c=s.width;let l=s.height;let u=s.interlace;let d=s.bpp;let h=s.depth;this.read=a.read;this.write=a.write;this.complete=a.complete;this._imageIndex=0;this._images=[];if(u){let w=t.getImagePasses(c,l);for(let p=0;p<w.length;p++){this._images.push({byteWidth:i(w[p].width,d,h),height:w[p].height,lineIndex:0})}}else{this._images.push({byteWidth:i(c,d,h),height:l,lineIndex:0})}if(h===8){this._xComparison=d}else if(h===16){this._xComparison=d*2}else{this._xComparison=1}};o.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};o.prototype._unFilterType1=function(s,a,c){let l=this._xComparison;let u=l-1;for(let d=0;d<c;d++){let h=s[1+d];let w=d>u?a[d-l]:0;a[d]=h+w}};o.prototype._unFilterType2=function(s,a,c){let l=this._lastLine;for(let u=0;u<c;u++){let d=s[1+u];let h=l?l[u]:0;a[u]=d+h}};o.prototype._unFilterType3=function(s,a,c){let l=this._xComparison;let u=l-1;let d=this._lastLine;for(let h=0;h<c;h++){let w=s[1+h];let p=d?d[h]:0;let g=h>u?a[h-l]:0;let m=Math.floor((g+p)/2);a[h]=w+m}};o.prototype._unFilterType4=function(s,a,c){let l=this._xComparison;let u=l-1;let d=this._lastLine;for(let h=0;h<c;h++){let w=s[1+h];let p=d?d[h]:0;let g=h>u?a[h-l]:0;let m=h>u&&d?d[h-l]:0;let f=r(g,p,m);a[h]=w+f}};o.prototype._reverseFilterLine=function(s){let a=s[0];let c;let l=this._images[this._imageIndex];let u=l.byteWidth;if(a===0){c=s.slice(1,u+1)}else{c=Buffer.alloc(u);switch(a){case 1:this._unFilterType1(s,c,u);break;case 2:this._unFilterType2(s,c,u);break;case 3:this._unFilterType3(s,c,u);break;case 4:this._unFilterType4(s,c,u);break;default:throw new Error("Unrecognised filter type - "+a)}}this.write(c);l.lineIndex++;if(l.lineIndex>=l.height){this._lastLine=null;this._imageIndex++;l=this._images[this._imageIndex]}else{this._lastLine=c}if(l){this.read(l.byteWidth+1,this._reverseFilterLine.bind(this))}else{this._lastLine=null;this.complete()}}}});var require_filter_parse_async=__commonJS({"../../node_modules/pngjs/lib/filter-parse-async.js"(e,n){"use strict";var t=require("util");var r=require_chunkstream();var i=require_filter_parse();var o=n.exports=function(s){r.call(this);let a=[];let c=this;this._filter=new i(s,{read:this.read.bind(this),write:function(l){a.push(l)},complete:function(){c.emit("complete",Buffer.concat(a))}});this._filter.start()};t.inherits(o,r)}});var require_constants=__commonJS({"../../node_modules/pngjs/lib/constants.js"(e,n){"use strict";n.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}}});var require_crc=__commonJS({"../../node_modules/pngjs/lib/crc.js"(e,n){"use strict";var t=[];(function(){for(let i=0;i<256;i++){let o=i;for(let s=0;s<8;s++){if(o&1){o=3988292384^o>>>1}else{o=o>>>1}}t[i]=o}})();var r=n.exports=function(){this._crc=-1};r.prototype.write=function(i){for(let o=0;o<i.length;o++){this._crc=t[(this._crc^i[o])&255]^this._crc>>>8}return true};r.prototype.crc32=function(){return this._crc^-1};r.crc32=function(i){let o=-1;for(let s=0;s<i.length;s++){o=t[(o^i[s])&255]^o>>>8}return o^-1}}});var require_parser=__commonJS({"../../node_modules/pngjs/lib/parser.js"(e,n){"use strict";var t=require_constants();var r=require_crc();var i=n.exports=function(o,s){this._options=o;o.checkCRC=o.checkCRC!==false;this._hasIHDR=false;this._hasIEND=false;this._emittedHeadersFinished=false;this._palette=[];this._colorType=0;this._chunks={};this._chunks[t.TYPE_IHDR]=this._handleIHDR.bind(this);this._chunks[t.TYPE_IEND]=this._handleIEND.bind(this);this._chunks[t.TYPE_IDAT]=this._handleIDAT.bind(this);this._chunks[t.TYPE_PLTE]=this._handlePLTE.bind(this);this._chunks[t.TYPE_tRNS]=this._handleTRNS.bind(this);this._chunks[t.TYPE_gAMA]=this._handleGAMA.bind(this);this.read=s.read;this.error=s.error;this.metadata=s.metadata;this.gamma=s.gamma;this.transColor=s.transColor;this.palette=s.palette;this.parsed=s.parsed;this.inflateData=s.inflateData;this.finished=s.finished;this.simpleTransparency=s.simpleTransparency;this.headersFinished=s.headersFinished||function(){}};i.prototype.start=function(){this.read(t.PNG_SIGNATURE.length,this._parseSignature.bind(this))};i.prototype._parseSignature=function(o){let s=t.PNG_SIGNATURE;for(let a=0;a<s.length;a++){if(o[a]!==s[a]){this.error(new Error("Invalid file signature"));return}}this.read(8,this._parseChunkBegin.bind(this))};i.prototype._parseChunkBegin=function(o){let s=o.readUInt32BE(0);let a=o.readUInt32BE(4);let c="";for(let u=4;u<8;u++){c+=String.fromCharCode(o[u])}let l=Boolean(o[4]&32);if(!this._hasIHDR&&a!==t.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}this._crc=new r;this._crc.write(Buffer.from(c));if(this._chunks[a]){return this._chunks[a](s)}if(!l){this.error(new Error("Unsupported critical chunk type "+c));return}this.read(s+4,this._skipChunk.bind(this))};i.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};i.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};i.prototype._parseChunkEnd=function(o){let s=o.readInt32BE(0);let a=this._crc.crc32();if(this._options.checkCRC&&a!==s){this.error(new Error("Crc error - "+s+" - "+a));return}if(!this._hasIEND){this.read(8,this._parseChunkBegin.bind(this))}};i.prototype._handleIHDR=function(o){this.read(o,this._parseIHDR.bind(this))};i.prototype._parseIHDR=function(o){this._crc.write(o);let s=o.readUInt32BE(0);let a=o.readUInt32BE(4);let c=o[8];let l=o[9];let u=o[10];let d=o[11];let h=o[12];if(c!==8&&c!==4&&c!==2&&c!==1&&c!==16){this.error(new Error("Unsupported bit depth "+c));return}if(!(l in t.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(u!==0){this.error(new Error("Unsupported compression method"));return}if(d!==0){this.error(new Error("Unsupported filter method"));return}if(h!==0&&h!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=l;let w=t.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=true;this.metadata({width:s,height:a,depth:c,interlace:Boolean(h),palette:Boolean(l&t.COLORTYPE_PALETTE),color:Boolean(l&t.COLORTYPE_COLOR),alpha:Boolean(l&t.COLORTYPE_ALPHA),bpp:w,colorType:l});this._handleChunkEnd()};i.prototype._handlePLTE=function(o){this.read(o,this._parsePLTE.bind(this))};i.prototype._parsePLTE=function(o){this._crc.write(o);let s=Math.floor(o.length/3);for(let a=0;a<s;a++){this._palette.push([o[a*3],o[a*3+1],o[a*3+2],255])}this.palette(this._palette);this._handleChunkEnd()};i.prototype._handleTRNS=function(o){this.simpleTransparency();this.read(o,this._parseTRNS.bind(this))};i.prototype._parseTRNS=function(o){this._crc.write(o);if(this._colorType===t.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(o.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let s=0;s<o.length;s++){this._palette[s][3]=o[s]}this.palette(this._palette)}if(this._colorType===t.COLORTYPE_GRAYSCALE){this.transColor([o.readUInt16BE(0)])}if(this._colorType===t.COLORTYPE_COLOR){this.transColor([o.readUInt16BE(0),o.readUInt16BE(2),o.readUInt16BE(4)])}this._handleChunkEnd()};i.prototype._handleGAMA=function(o){this.read(o,this._parseGAMA.bind(this))};i.prototype._parseGAMA=function(o){this._crc.write(o);this.gamma(o.readUInt32BE(0)/t.GAMMA_DIVISION);this._handleChunkEnd()};i.prototype._handleIDAT=function(o){if(!this._emittedHeadersFinished){this._emittedHeadersFinished=true;this.headersFinished()}this.read(-o,this._parseIDAT.bind(this,o))};i.prototype._parseIDAT=function(o,s){this._crc.write(s);if(this._colorType===t.COLORTYPE_PALETTE_COLOR&&this._palette.length===0){throw new Error("Expected palette not found")}this.inflateData(s);let a=o-s.length;if(a>0){this._handleIDAT(a)}else{this._handleChunkEnd()}};i.prototype._handleIEND=function(o){this.read(o,this._parseIEND.bind(this))};i.prototype._parseIEND=function(o){this._crc.write(o);this._hasIEND=true;this._handleChunkEnd();if(this.finished){this.finished()}}}});var require_bitmapper=__commonJS({"../../node_modules/pngjs/lib/bitmapper.js"(e){"use strict";var n=require_interlace();var t=[function(){},function(a,c,l,u){if(u===c.length){throw new Error("Ran out of data")}let d=c[u];a[l]=d;a[l+1]=d;a[l+2]=d;a[l+3]=255},function(a,c,l,u){if(u+1>=c.length){throw new Error("Ran out of data")}let d=c[u];a[l]=d;a[l+1]=d;a[l+2]=d;a[l+3]=c[u+1]},function(a,c,l,u){if(u+2>=c.length){throw new Error("Ran out of data")}a[l]=c[u];a[l+1]=c[u+1];a[l+2]=c[u+2];a[l+3]=255},function(a,c,l,u){if(u+3>=c.length){throw new Error("Ran out of data")}a[l]=c[u];a[l+1]=c[u+1];a[l+2]=c[u+2];a[l+3]=c[u+3]}];var r=[function(){},function(a,c,l,u){let d=c[0];a[l]=d;a[l+1]=d;a[l+2]=d;a[l+3]=u},function(a,c,l){let u=c[0];a[l]=u;a[l+1]=u;a[l+2]=u;a[l+3]=c[1]},function(a,c,l,u){a[l]=c[0];a[l+1]=c[1];a[l+2]=c[2];a[l+3]=u},function(a,c,l){a[l]=c[0];a[l+1]=c[1];a[l+2]=c[2];a[l+3]=c[3]}];function i(a,c){let l=[];let u=0;function d(){if(u===a.length){throw new Error("Ran out of data")}let h=a[u];u++;let w,p,g,m,f,b,v,y;switch(c){default:throw new Error("unrecognised depth");case 16:v=a[u];u++;l.push((h<<8)+v);break;case 4:v=h&15;y=h>>4;l.push(y,v);break;case 2:f=h&3;b=h>>2&3;v=h>>4&3;y=h>>6&3;l.push(y,v,b,f);break;case 1:w=h&1;p=h>>1&1;g=h>>2&1;m=h>>3&1;f=h>>4&1;b=h>>5&1;v=h>>6&1;y=h>>7&1;l.push(y,v,b,f,m,g,p,w);break}}return{get:function(h){while(l.length<h){d()}let w=l.slice(0,h);l=l.slice(h);return w},resetAfterLine:function(){l.length=0},end:function(){if(u!==a.length){throw new Error("extra data found")}}}}function o(a,c,l,u,d,h){let w=a.width;let p=a.height;let g=a.index;for(let m=0;m<p;m++){for(let f=0;f<w;f++){let b=l(f,m,g);t[u](c,d,b,h);h+=u}}return h}function s(a,c,l,u,d,h){let w=a.width;let p=a.height;let g=a.index;for(let m=0;m<p;m++){for(let f=0;f<w;f++){let b=d.get(u);let v=l(f,m,g);r[u](c,b,v,h)}d.resetAfterLine()}}e.dataToBitMap=function(a,c){let l=c.width;let u=c.height;let d=c.depth;let h=c.bpp;let w=c.interlace;let p;if(d!==8){p=i(a,d)}let g;if(d<=8){g=Buffer.alloc(l*u*4)}else{g=new Uint16Array(l*u*4)}let m=Math.pow(2,d)-1;let f=0;let b;let v;if(w){b=n.getImagePasses(l,u);v=n.getInterlaceIterator(l,u)}else{let y=0;v=function(){let $=y;y+=4;return $};b=[{width:l,height:u}]}for(let y=0;y<b.length;y++){if(d===8){f=o(b[y],g,v,h,a,f)}else{s(b[y],g,v,h,p,m)}}if(d===8){if(f!==a.length){throw new Error("extra data found")}}else{p.end()}return g}}});var require_format_normaliser=__commonJS({"../../node_modules/pngjs/lib/format-normaliser.js"(e,n){"use strict";function t(o,s,a,c,l){let u=0;for(let d=0;d<c;d++){for(let h=0;h<a;h++){let w=l[o[u]];if(!w){throw new Error("index "+o[u]+" not in palette")}for(let p=0;p<4;p++){s[u+p]=w[p]}u+=4}}}function r(o,s,a,c,l){let u=0;for(let d=0;d<c;d++){for(let h=0;h<a;h++){let w=false;if(l.length===1){if(l[0]===o[u]){w=true}}else if(l[0]===o[u]&&l[1]===o[u+1]&&l[2]===o[u+2]){w=true}if(w){for(let p=0;p<4;p++){s[u+p]=0}}u+=4}}}function i(o,s,a,c,l){let u=255;let d=Math.pow(2,l)-1;let h=0;for(let w=0;w<c;w++){for(let p=0;p<a;p++){for(let g=0;g<4;g++){s[h+g]=Math.floor(o[h+g]*u/d+.5)}h+=4}}}n.exports=function(o,s,a=false){let c=s.depth;let l=s.width;let u=s.height;let d=s.colorType;let h=s.transColor;let w=s.palette;let p=o;if(d===3){t(o,p,l,u,w)}else{if(h){r(o,p,l,u,h)}if(c!==8&&!a){if(c===16){p=Buffer.alloc(l*u*4)}i(o,p,l,u,c)}}return p}}});var require_parser_async=__commonJS({"../../node_modules/pngjs/lib/parser-async.js"(e,n){"use strict";var t=require("util");var r=require("zlib");var i=require_chunkstream();var o=require_filter_parse_async();var s=require_parser();var a=require_bitmapper();var c=require_format_normaliser();var l=n.exports=function(u){i.call(this);this._parser=new s(u,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)});this._options=u;this.writable=true;this._parser.start()};t.inherits(l,i);l.prototype._handleError=function(u){this.emit("error",u);this.writable=false;this.destroy();if(this._inflate&&this._inflate.destroy){this._inflate.destroy()}if(this._filter){this._filter.destroy();this._filter.on("error",function(){})}this.errord=true};l.prototype._inflateData=function(u){if(!this._inflate){if(this._bitmapInfo.interlace){this._inflate=r.createInflate();this._inflate.on("error",this.emit.bind(this,"error"));this._filter.on("complete",this._complete.bind(this));this._inflate.pipe(this._filter)}else{let d=(this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1;let h=d*this._bitmapInfo.height;let w=Math.max(h,r.Z_MIN_CHUNK);this._inflate=r.createInflate({chunkSize:w});let p=h;let g=this.emit.bind(this,"error");this._inflate.on("error",function(f){if(!p){return}g(f)});this._filter.on("complete",this._complete.bind(this));let m=this._filter.write.bind(this._filter);this._inflate.on("data",function(f){if(!p){return}if(f.length>p){f=f.slice(0,p)}p-=f.length;m(f)});this._inflate.on("end",this._filter.end.bind(this._filter))}}this._inflate.write(u)};l.prototype._handleMetaData=function(u){this._metaData=u;this._bitmapInfo=Object.create(u);this._filter=new o(this._bitmapInfo)};l.prototype._handleTransColor=function(u){this._bitmapInfo.transColor=u};l.prototype._handlePalette=function(u){this._bitmapInfo.palette=u};l.prototype._simpleTransparency=function(){this._metaData.alpha=true};l.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};l.prototype._finished=function(){if(this.errord){return}if(!this._inflate){this.emit("error","No Inflate block")}else{this._inflate.end()}};l.prototype._complete=function(u){if(this.errord){return}let d;try{let h=a.dataToBitMap(u,this._bitmapInfo);d=c(h,this._bitmapInfo,this._options.skipRescale);h=null}catch(h){this._handleError(h);return}this.emit("parsed",d)}}});var require_bitpacker=__commonJS({"../../node_modules/pngjs/lib/bitpacker.js"(e,n){"use strict";var t=require_constants();n.exports=function(r,i,o,s){let a=[t.COLORTYPE_COLOR_ALPHA,t.COLORTYPE_ALPHA].indexOf(s.colorType)!==-1;if(s.colorType===s.inputColorType){let f=(function(){let b=new ArrayBuffer(2);new DataView(b).setInt16(0,256,true);return new Int16Array(b)[0]!==256})();if(s.bitDepth===8||s.bitDepth===16&&f){return r}}let c=s.bitDepth!==16?r:new Uint16Array(r.buffer);let l=255;let u=t.COLORTYPE_TO_BPP_MAP[s.inputColorType];if(u===4&&!s.inputHasAlpha){u=3}let d=t.COLORTYPE_TO_BPP_MAP[s.colorType];if(s.bitDepth===16){l=65535;d*=2}let h=Buffer.alloc(i*o*d);let w=0;let p=0;let g=s.bgColor||{};if(g.red===void 0){g.red=l}if(g.green===void 0){g.green=l}if(g.blue===void 0){g.blue=l}function m(){let f;let b;let v;let y=l;switch(s.inputColorType){case t.COLORTYPE_COLOR_ALPHA:y=c[w+3];f=c[w];b=c[w+1];v=c[w+2];break;case t.COLORTYPE_COLOR:f=c[w];b=c[w+1];v=c[w+2];break;case t.COLORTYPE_ALPHA:y=c[w+1];f=c[w];b=f;v=f;break;case t.COLORTYPE_GRAYSCALE:f=c[w];b=f;v=f;break;default:throw new Error("input color type:"+s.inputColorType+" is not supported at present")}if(s.inputHasAlpha){if(!a){y/=l;f=Math.min(Math.max(Math.round((1-y)*g.red+y*f),0),l);b=Math.min(Math.max(Math.round((1-y)*g.green+y*b),0),l);v=Math.min(Math.max(Math.round((1-y)*g.blue+y*v),0),l)}}return{red:f,green:b,blue:v,alpha:y}}for(let f=0;f<o;f++){for(let b=0;b<i;b++){let v=m(c,w);switch(s.colorType){case t.COLORTYPE_COLOR_ALPHA:case t.COLORTYPE_COLOR:if(s.bitDepth===8){h[p]=v.red;h[p+1]=v.green;h[p+2]=v.blue;if(a){h[p+3]=v.alpha}}else{h.writeUInt16BE(v.red,p);h.writeUInt16BE(v.green,p+2);h.writeUInt16BE(v.blue,p+4);if(a){h.writeUInt16BE(v.alpha,p+6)}}break;case t.COLORTYPE_ALPHA:case t.COLORTYPE_GRAYSCALE:{let y=(v.red+v.green+v.blue)/3;if(s.bitDepth===8){h[p]=y;if(a){h[p+1]=v.alpha}}else{h.writeUInt16BE(y,p);if(a){h.writeUInt16BE(v.alpha,p+2)}}break}default:throw new Error("unrecognised color Type "+s.colorType)}w+=u;p+=d}}return h}}});var require_filter_pack=__commonJS({"../../node_modules/pngjs/lib/filter-pack.js"(e,n){"use strict";var t=require_paeth_predictor();function r(g,m,f,b,v){for(let y=0;y<f;y++){b[v+y]=g[m+y]}}function i(g,m,f){let b=0;let v=m+f;for(let y=m;y<v;y++){b+=Math.abs(g[y])}return b}function o(g,m,f,b,v,y){for(let $=0;$<f;$++){let T=$>=y?g[m+$-y]:0;let _=g[m+$]-T;b[v+$]=_}}function s(g,m,f,b){let v=0;for(let y=0;y<f;y++){let $=y>=b?g[m+y-b]:0;let T=g[m+y]-$;v+=Math.abs(T)}return v}function a(g,m,f,b,v){for(let y=0;y<f;y++){let $=m>0?g[m+y-f]:0;let T=g[m+y]-$;b[v+y]=T}}function c(g,m,f){let b=0;let v=m+f;for(let y=m;y<v;y++){let $=m>0?g[y-f]:0;let T=g[y]-$;b+=Math.abs(T)}return b}function l(g,m,f,b,v,y){for(let $=0;$<f;$++){let T=$>=y?g[m+$-y]:0;let _=m>0?g[m+$-f]:0;let x=g[m+$]-(T+_>>1);b[v+$]=x}}function u(g,m,f,b){let v=0;for(let y=0;y<f;y++){let $=y>=b?g[m+y-b]:0;let T=m>0?g[m+y-f]:0;let _=g[m+y]-($+T>>1);v+=Math.abs(_)}return v}function d(g,m,f,b,v,y){for(let $=0;$<f;$++){let T=$>=y?g[m+$-y]:0;let _=m>0?g[m+$-f]:0;let x=m>0&&$>=y?g[m+$-(f+y)]:0;let I=g[m+$]-t(T,_,x);b[v+$]=I}}function h(g,m,f,b){let v=0;for(let y=0;y<f;y++){let $=y>=b?g[m+y-b]:0;let T=m>0?g[m+y-f]:0;let _=m>0&&y>=b?g[m+y-(f+b)]:0;let x=g[m+y]-t($,T,_);v+=Math.abs(x)}return v}var w={0:r,1:o,2:a,3:l,4:d};var p={0:i,1:s,2:c,3:u,4:h};n.exports=function(g,m,f,b,v){let y;if(!("filterType"in b)||b.filterType===-1){y=[0,1,2,3,4]}else if(typeof b.filterType==="number"){y=[b.filterType]}else{throw new Error("unrecognised filter types")}if(b.bitDepth===16){v*=2}let $=m*v;let T=0;let _=0;let x=Buffer.alloc(($+1)*f);let I=y[0];for(let D=0;D<f;D++){if(y.length>1){let E=Infinity;for(let S=0;S<y.length;S++){let k=p[y[S]](g,_,$,v);if(k<E){I=y[S];E=k}}}x[T]=I;T++;w[I](g,_,$,x,T,v);T+=$;_+=$}return x}}});var require_packer=__commonJS({"../../node_modules/pngjs/lib/packer.js"(e,n){"use strict";var t=require_constants();var r=require_crc();var i=require_bitpacker();var o=require_filter_pack();var s=require("zlib");var a=n.exports=function(c){this._options=c;c.deflateChunkSize=c.deflateChunkSize||32*1024;c.deflateLevel=c.deflateLevel!=null?c.deflateLevel:9;c.deflateStrategy=c.deflateStrategy!=null?c.deflateStrategy:3;c.inputHasAlpha=c.inputHasAlpha!=null?c.inputHasAlpha:true;c.deflateFactory=c.deflateFactory||s.createDeflate;c.bitDepth=c.bitDepth||8;c.colorType=typeof c.colorType==="number"?c.colorType:t.COLORTYPE_COLOR_ALPHA;c.inputColorType=typeof c.inputColorType==="number"?c.inputColorType:t.COLORTYPE_COLOR_ALPHA;if([t.COLORTYPE_GRAYSCALE,t.COLORTYPE_COLOR,t.COLORTYPE_COLOR_ALPHA,t.COLORTYPE_ALPHA].indexOf(c.colorType)===-1){throw new Error("option color type:"+c.colorType+" is not supported at present")}if([t.COLORTYPE_GRAYSCALE,t.COLORTYPE_COLOR,t.COLORTYPE_COLOR_ALPHA,t.COLORTYPE_ALPHA].indexOf(c.inputColorType)===-1){throw new Error("option input color type:"+c.inputColorType+" is not supported at present")}if(c.bitDepth!==8&&c.bitDepth!==16){throw new Error("option bit depth:"+c.bitDepth+" is not supported at present")}};a.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};a.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};a.prototype.filterData=function(c,l,u){let d=i(c,l,u,this._options);let h=t.COLORTYPE_TO_BPP_MAP[this._options.colorType];let w=o(d,l,u,this._options,h);return w};a.prototype._packChunk=function(c,l){let u=l?l.length:0;let d=Buffer.alloc(u+12);d.writeUInt32BE(u,0);d.writeUInt32BE(c,4);if(l){l.copy(d,8)}d.writeInt32BE(r.crc32(d.slice(4,d.length-4)),d.length-4);return d};a.prototype.packGAMA=function(c){let l=Buffer.alloc(4);l.writeUInt32BE(Math.floor(c*t.GAMMA_DIVISION),0);return this._packChunk(t.TYPE_gAMA,l)};a.prototype.packIHDR=function(c,l){let u=Buffer.alloc(13);u.writeUInt32BE(c,0);u.writeUInt32BE(l,4);u[8]=this._options.bitDepth;u[9]=this._options.colorType;u[10]=0;u[11]=0;u[12]=0;return this._packChunk(t.TYPE_IHDR,u)};a.prototype.packIDAT=function(c){return this._packChunk(t.TYPE_IDAT,c)};a.prototype.packIEND=function(){return this._packChunk(t.TYPE_IEND,null)}}});var require_packer_async=__commonJS({"../../node_modules/pngjs/lib/packer-async.js"(e,n){"use strict";var t=require("util");var r=require("stream");var i=require_constants();var o=require_packer();var s=n.exports=function(a){r.call(this);let c=a||{};this._packer=new o(c);this._deflate=this._packer.createDeflate();this.readable=true};t.inherits(s,r);s.prototype.pack=function(a,c,l,u){this.emit("data",Buffer.from(i.PNG_SIGNATURE));this.emit("data",this._packer.packIHDR(c,l));if(u){this.emit("data",this._packer.packGAMA(u))}let d=this._packer.filterData(a,c,l);this._deflate.on("error",this.emit.bind(this,"error"));this._deflate.on("data",function(h){this.emit("data",this._packer.packIDAT(h))}.bind(this));this._deflate.on("end",function(){this.emit("data",this._packer.packIEND());this.emit("end")}.bind(this));this._deflate.end(d)}}});var require_sync_inflate=__commonJS({"../../node_modules/pngjs/lib/sync-inflate.js"(e,n){"use strict";var t=require("assert").ok;var r=require("zlib");var i=require("util");var o=require("buffer").kMaxLength;function s(d){if(!(this instanceof s)){return new s(d)}if(d&&d.chunkSize<r.Z_MIN_CHUNK){d.chunkSize=r.Z_MIN_CHUNK}r.Inflate.call(this,d);this._offset=this._offset===void 0?this._outOffset:this._offset;this._buffer=this._buffer||this._outBuffer;if(d&&d.maxLength!=null){this._maxLength=d.maxLength}}function a(d){return new s(d)}function c(d,h){if(h){process.nextTick(h)}if(!d._handle){return}d._handle.close();d._handle=null}s.prototype._processChunk=function(d,h,w){if(typeof w==="function"){return r.Inflate._processChunk.call(this,d,h,w)}let p=this;let g=d&&d.length;let m=this._chunkSize-this._offset;let f=this._maxLength;let b=0;let v=[];let y=0;let $;this.on("error",function(I){$=I});function T(I,D){if(p._hadError){return}let E=m-D;t(E>=0,"have should not go down");if(E>0){let S=p._buffer.slice(p._offset,p._offset+E);p._offset+=E;if(S.length>f){S=S.slice(0,f)}v.push(S);y+=S.length;f-=S.length;if(f===0){return false}}if(D===0||p._offset>=p._chunkSize){m=p._chunkSize;p._offset=0;p._buffer=Buffer.allocUnsafe(p._chunkSize)}if(D===0){b+=g-I;g=I;return true}return false}t(this._handle,"zlib binding closed");let _;do{_=this._handle.writeSync(h,d,b,g,this._buffer,this._offset,m);_=_||this._writeState}while(!this._hadError&&T(_[0],_[1]));if(this._hadError){throw $}if(y>=o){c(this);throw new RangeError("Cannot create final Buffer. It would be larger than 0x"+o.toString(16)+" bytes")}let x=Buffer.concat(v,y);c(this);return x};i.inherits(s,r.Inflate);function l(d,h){if(typeof h==="string"){h=Buffer.from(h)}if(!(h instanceof Buffer)){throw new TypeError("Not a string or buffer")}let w=d._finishFlushFlag;if(w==null){w=r.Z_FINISH}return d._processChunk(h,w)}function u(d,h){return l(new s(h),d)}n.exports=e=u;e.Inflate=s;e.createInflate=a;e.inflateSync=u}});var require_sync_reader=__commonJS({"../../node_modules/pngjs/lib/sync-reader.js"(e,n){"use strict";var t=n.exports=function(r){this._buffer=r;this._reads=[]};t.prototype.read=function(r,i){this._reads.push({length:Math.abs(r),allowLess:r<0,func:i})};t.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let r=this._reads[0];if(this._buffer.length&&(this._buffer.length>=r.length||r.allowLess)){this._reads.shift();let i=this._buffer;this._buffer=i.slice(r.length);r.func.call(this,i.slice(0,r.length))}else{break}}if(this._reads.length>0){throw new Error("There are some read requests waitng on finished stream")}if(this._buffer.length>0){throw new Error("unrecognised content at end of stream")}}}});var require_filter_parse_sync=__commonJS({"../../node_modules/pngjs/lib/filter-parse-sync.js"(e){"use strict";var n=require_sync_reader();var t=require_filter_parse();e.process=function(r,i){let o=[];let s=new n(r);let a=new t(i,{read:s.read.bind(s),write:function(c){o.push(c)},complete:function(){}});a.start();s.process();return Buffer.concat(o)}}});var require_parser_sync=__commonJS({"../../node_modules/pngjs/lib/parser-sync.js"(e,n){"use strict";var t=true;var r=require("zlib");var i=require_sync_inflate();if(!r.deflateSync){t=false}var o=require_sync_reader();var s=require_filter_parse_sync();var a=require_parser();var c=require_bitmapper();var l=require_format_normaliser();n.exports=function(u,d){if(!t){throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0")}let h;function w(M){h=M}let p;function g(M){p=M}function m(M){p.transColor=M}function f(M){p.palette=M}function b(){p.alpha=true}let v;function y(M){v=M}let $=[];function T(M){$.push(M)}let _=new o(u);let x=new a(d,{read:_.read.bind(_),error:w,metadata:g,gamma:y,palette:f,transColor:m,inflateData:T,simpleTransparency:b});x.start();_.process();if(h){throw h}let I=Buffer.concat($);$.length=0;let D;if(p.interlace){D=r.inflateSync(I)}else{let M=(p.width*p.bpp*p.depth+7>>3)+1;let A=M*p.height;D=i(I,{chunkSize:A,maxLength:A})}I=null;if(!D||!D.length){throw new Error("bad png - invalid inflate data response")}let E=s.process(D,p);I=null;let S=c.dataToBitMap(E,p);E=null;let k=l(S,p,d.skipRescale);p.data=k;p.gamma=v||0;return p}}});var require_packer_sync=__commonJS({"../../node_modules/pngjs/lib/packer-sync.js"(e,n){"use strict";var t=true;var r=require("zlib");if(!r.deflateSync){t=false}var i=require_constants();var o=require_packer();n.exports=function(s,a){if(!t){throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0")}let c=a||{};let l=new o(c);let u=[];u.push(Buffer.from(i.PNG_SIGNATURE));u.push(l.packIHDR(s.width,s.height));if(s.gamma){u.push(l.packGAMA(s.gamma))}let d=l.filterData(s.data,s.width,s.height);let h=r.deflateSync(d,l.getDeflateOptions());d=null;if(!h||!h.length){throw new Error("bad png - invalid compressed data response")}u.push(l.packIDAT(h));u.push(l.packIEND());return Buffer.concat(u)}}});var require_png_sync=__commonJS({"../../node_modules/pngjs/lib/png-sync.js"(e){"use strict";var n=require_parser_sync();var t=require_packer_sync();e.read=function(r,i){return n(r,i||{})};e.write=function(r,i){return t(r,i)}}});var require_png=__commonJS({"../../node_modules/pngjs/lib/png.js"(e){"use strict";var n=require("util");var t=require("stream");var r=require_parser_async();var i=require_packer_async();var o=require_png_sync();var s=e.PNG=function(a){t.call(this);a=a||{};this.width=a.width|0;this.height=a.height|0;this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null;if(a.fill&&this.data){this.data.fill(0)}this.gamma=0;this.readable=this.writable=true;this._parser=new r(a);this._parser.on("error",this.emit.bind(this,"error"));this._parser.on("close",this._handleClose.bind(this));this._parser.on("metadata",this._metadata.bind(this));this._parser.on("gamma",this._gamma.bind(this));this._parser.on("parsed",function(c){this.data=c;this.emit("parsed",c)}.bind(this));this._packer=new i(a);this._packer.on("data",this.emit.bind(this,"data"));this._packer.on("end",this.emit.bind(this,"end"));this._parser.on("close",this._handleClose.bind(this));this._packer.on("error",this.emit.bind(this,"error"))};n.inherits(s,t);s.sync=o;s.prototype.pack=function(){if(!this.data||!this.data.length){this.emit("error","No data provided");return this}process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this));return this};s.prototype.parse=function(a,c){if(c){let l,u;l=function(d){this.removeListener("error",u);this.data=d;c(null,this)}.bind(this);u=function(d){this.removeListener("parsed",l);c(d,null)}.bind(this);this.once("parsed",l);this.once("error",u)}this.end(a);return this};s.prototype.write=function(a){this._parser.write(a);return true};s.prototype.end=function(a){this._parser.end(a)};s.prototype._metadata=function(a){this.width=a.width;this.height=a.height;this.emit("metadata",a)};s.prototype._gamma=function(a){this.gamma=a};s.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable){this.emit("close")}};s.bitblt=function(a,c,l,u,d,h,w,p){l|=0;u|=0;d|=0;h|=0;w|=0;p|=0;if(l>a.width||u>a.height||l+d>a.width||u+h>a.height){throw new Error("bitblt reading outside image")}if(w>c.width||p>c.height||w+d>c.width||p+h>c.height){throw new Error("bitblt writing outside image")}for(let g=0;g<h;g++){a.data.copy(c.data,(p+g)*c.width+w<<2,(u+g)*a.width+l<<2,(u+g)*a.width+l+d<<2)}};s.prototype.bitblt=function(a,c,l,u,d,h,w){s.bitblt(this,a,c,l,u,d,h,w);return this};s.adjustGamma=function(a){if(a.gamma){for(let c=0;c<a.height;c++){for(let l=0;l<a.width;l++){let u=a.width*c+l<<2;for(let d=0;d<3;d++){let h=a.data[u+d]/255;h=Math.pow(h,1/2.2/a.gamma);a.data[u+d]=Math.round(h*255)}}}a.gamma=0}};s.prototype.adjustGamma=function(){s.adjustGamma(this)}}});async function devicectl(e,n=3e4){const t=import_node_path.default.join(import_node_os.default.tmpdir(),`buoy-devicectl-${(0,import_node_crypto.randomUUID)()}.json`);try{await execFileAsync2("xcrun",["devicectl",...e,"--quiet","--json-output",t],{timeout:n,maxBuffer:16*1024*1024});return JSON.parse(await import_node_fs.promises.readFile(t,"utf8"))}catch(r){const i=r;let o=(i.stderr||i.stdout||i.message||"").trim();try{const s=JSON.parse(await import_node_fs.promises.readFile(t,"utf8"));o=s.error?.userInfo?.NSLocalizedDescription?.string??o}catch{}if(/locked/i.test(o))throw new Error("The iPhone is locked. Unlock it and try again.");throw new Error(`devicectl ${e.slice(0,2).join(" ")} failed: ${o.split("\n").slice(-3).join(" ").slice(0,300)}`)}finally{await import_node_fs.promises.unlink(t).catch(()=>void 0)}}async function physicalPhones(){if(process.platform!=="darwin")return[];return parsePhones(await devicectl(["list","devices"],15e3).catch(()=>null))}function parsePhones(e){const n=e;return(n?.result?.devices??[]).filter(t=>t.hardwareProperties?.reality==="physical"&&t.hardwareProperties?.platform==="iOS"&&t.connectionProperties?.pairingState==="paired"&&t.connectionProperties?.tunnelState!=="unavailable").map(t=>({udid:t.hardwareProperties.udid,name:t.deviceProperties?.name??"iPhone"})).filter(t=>!!t.udid)}async function developerApps(e){const n=await devicectl(["device","info","apps","--device",e]);return(n.result?.apps??[]).filter(t=>t.bundleIdentifier&&!t.bundleIdentifier.startsWith("com.apple.")&&t.builtByDeveloper!==false).map(t=>({bundleId:t.bundleIdentifier,name:t.name??t.bundleIdentifier,path:t.url?.replace(/^file:\/\//,"")}))}async function readAppFile(e,n,t){const r=await devicectl(["device","info","files","--device",e,"--domain-type","appDataContainer","--domain-identifier",n],2e4);const i=new Set((r.result?.files??[]).map(s=>s.relativePath??s.name??""));if(!i.has(t))return null;const o=import_node_path.default.join(import_node_os.default.tmpdir(),`buoy-devfile-${(0,import_node_crypto.randomUUID)()}`);try{await devicectl(["device","copy","from","--device",e,"--domain-type","appDataContainer","--domain-identifier",n,"--source",t,"--destination",o],2e4);return await import_node_fs.promises.readFile(o)}finally{await import_node_fs.promises.rm(o,{recursive:true,force:true}).catch(()=>void 0)}}async function phoneInstallId(e,n){const t=await readAppFile(e,n,"Documents/react-buoy/@react_buoy_sync_device_id.json").catch(()=>null);const r=t?.toString("utf8").trim().replace(/^"|"$/g,"")??"";return/^[\w-]{4,64}$/.test(r)?r:null}async function phoneScreenshot(e){const n=import_node_path.default.join(import_node_os.default.tmpdir(),`buoy-phone-shot-${(0,import_node_crypto.randomUUID)()}.png`);try{await devicectl(["device","capture","screenshot","--device",e,"--destination",n],3e4);return await import_node_fs.promises.readFile(n)}finally{await import_node_fs.promises.unlink(n).catch(()=>void 0)}}function isAllBlack(e){try{const n=import_pngjs.PNG.sync.read(e);const t=Math.max(1,Math.floor(n.width*n.height/4e3));for(let r=0;r<n.width*n.height;r+=t){const i=r*4;if(n.data[i]>12||n.data[i+1]>12||n.data[i+2]>12)return false}return true}catch{return false}}async function phoneLaunch(e,n,t={}){await devicectl(["device","process","launch","--device",e,...t.terminateExisting?["--terminate-existing"]:[],...t.url?["--payload-url",t.url]:[],n])}async function phoneOpenUrl(e,n){await devicectl(["device","process","openURL","--device",e,n])}async function phoneQuit(e,n){const t=await developerApps(e);const r=t.find(s=>s.bundleId===n)?.path;const i=await devicectl(["device","info","processes","--device",e]);const o=(i.result?.runningProcesses??[]).find(s=>r&&decodeURIComponent(s.executable??"").replace(/^file:\/\//,"").startsWith(r.replace(/\/$/,"")));if(!o?.processIdentifier)return false;await devicectl(["device","process","terminate","--device",e,"--pid",String(o.processIdentifier)]);return true}async function phoneUninstall(e,n){await devicectl(["device","uninstall","app","--device",e,n],12e4)}async function phoneInstall(e,n){await devicectl(["device","install","app","--device",e,n],3e5)}async function writeAppFile(e,n,t,r){await devicectl(["device","copy","to","--device",e,"--domain-type","appDataContainer","--domain-identifier",n,"--source",t,"--destination",r],3e4)}function phoneRecordArgs(e,n,t){return["devicectl","device","capture","screen-record","--device",e,"--destination",n,"--duration",String(t)]}async function coreDeviceId(e){const n=coreIds.get(e);if(n)return n;const t=await devicectl(["list","devices"]);const r=t.result?.devices?.find(i=>i.hardwareProperties?.udid===e)?.identifier;if(!r)throw new Error("CoreDevice doesn't list this iPhone right now. Check that it is connected and unlocked.");coreIds.set(e,r);return r}var import_node_child_process3,import_node_util2,import_node_fs,import_node_os,import_node_path,import_node_crypto,import_pngjs,execFileAsync2,BLACK_PHONE_NOTE,coreIds;var init_iosDevice=__esm({"src/capture/iosDevice.ts"(){"use strict";import_node_child_process3=require("child_process");import_node_util2=require("util");import_node_fs=require("fs");import_node_os=__toESM(require("os"));import_node_path=__toESM(require("path"));import_node_crypto=require("crypto");import_pngjs=__toESM(require_png());execFileAsync2=(0,import_node_util2.promisify)(import_node_child_process3.execFile);BLACK_PHONE_NOTE="The picture is all black. If the app isn't really showing black, the iPhone's own screen is off: it is asleep, or the Mac shows it in iPhone Mirroring (the phone stays locked then). Quit iPhone Mirroring, unlock the phone and keep its screen on, then try again.";coreIds=new Map}});async function startRecording(e,n){await import_node_fs2.promises.mkdir(import_node_path2.default.dirname(n),{recursive:true});const t=Date.now();let r;let i;if(e.platform==="ios"){r=(0,import_node_child_process4.spawn)("xcrun",["simctl","io",e.udid,"recordVideo","--codec=h264","--force",n],{stdio:["ignore","ignore","pipe"]})}else if(e.platform==="ios-device"){r=(0,import_node_child_process4.spawn)("xcrun",phoneRecordArgs(e.udid,n,MAX_RECORDING_MS/1e3),{stdio:["ignore","ignore","pipe"]})}else{i=`/sdcard/buoy-recording-${t}-${Math.random().toString(36).slice(2,8)}.mp4`;r=(0,import_node_child_process4.spawn)("adb",["-s",e.serial,"shell",`echo $$; exec screenrecord --time-limit ${MAX_RECORDING_MS/1e3} ${q(i)}`],{stdio:["ignore","pipe","pipe"]})}const o={host:e,file:n,startedAt:t,proc:r,remote:i};live.add(o);let s="";let a=t;let c;r.stderr?.on("data",d=>{s+=String(d);if(/Recording started/i.test(String(d)))a=Date.now()});r.stdout?.on("data",d=>{const h=/^(\d+)/m.exec(String(d));if(h&&c===void 0)c=Number(h[1])});const l=await new Promise(d=>{const h=setTimeout(()=>d(null),e.platform==="ios"?3e3:e.platform==="ios-device"?4e3:1200);const w=setInterval(()=>{if(e.platform==="ios"&&a!==t||e.platform==="android"&&c!==void 0){clearTimeout(h);clearInterval(w);d(null)}},50);r.once("exit",p=>{clearTimeout(h);clearInterval(w);d(p??-1)});r.once("error",()=>{clearTimeout(h);clearInterval(w);d(-1)})});live.delete(o);if(l!==null){if(/not supported by this device/i.test(s)){throw new Error("This iPhone can't record its screen through Xcode (devicectl says the device doesn't support it). Record on a simulator, or use the iPhone's own Screen Recording in Control Center.")}throw new Error(`The screen recorder stopped right away: ${s.trim().slice(0,300)||`exit ${l}`}`)}if(e.platform==="ios"&&r.pid){const d=r.pid;const h=(0,import_node_child_process4.spawn)("sh",["-c",`sleep ${MAX_RECORDING_MS/1e3+15}; ps -p ${d} -o command= | grep -q 'simctl io .* recordVideo' && kill -INT ${d}`],{detached:true,stdio:"ignore"});h.on("error",()=>void 0);h.unref();r.once("exit",()=>{try{if(h.pid)process.kill(-h.pid,"SIGTERM")}catch{h.kill("SIGTERM")}})}const u={host:e,file:n,startedAt:a,proc:r,remote:i,remotePid:c};live.add(u);return u}async function stopRecording(e){if(e.stopTimer)clearTimeout(e.stopTimer);const n=Date.now();const t=new Promise(o=>{if(e.proc.exitCode!==null||e.proc.signalCode!==null)return o();e.proc.once("exit",()=>o())});if(e.host.platform==="ios"||e.host.platform==="ios-device"){e.proc.kill("SIGINT")}else if(e.remotePid){await adbShell(e.host.serial,`kill -INT ${e.remotePid}`).catch(()=>void 0)}await Promise.race([t,new Promise(o=>setTimeout(o,e.host.platform==="ios-device"?6e4:1e4))]);if(e.proc.exitCode===null&&e.proc.signalCode===null)e.proc.kill("SIGKILL");live.delete(e);if(e.host.platform==="android"&&e.remote){await new Promise(o=>setTimeout(o,800));await adb(e.host.serial,["pull",e.remote,e.file],6e4);await adbShell(e.host.serial,`rm -f ${q(e.remote)}`).catch(()=>void 0)}const r=await import_node_fs2.promises.stat(e.file).catch(()=>null);if(!r||r.size<1e3)throw new Error("The recording file is missing or empty. Was the screen showing anything?");const i=n-e.startedAt;if(e.host.platform==="ios"||e.host.platform==="ios-device")await padToWallTime(e.file,i).catch(()=>void 0);return i}async function padToWallTime(e,n){const t=(await execFileAsync3("ffprobe",["-v","error","-show_entries","format=duration","-of","csv=p=0",e],{timeout:2e4})).stdout;const r=Number(t.trim());const i=n/1e3-.3-r;if(!Number.isFinite(r)||i<.25)return;const o=e.replace(/\.mp4$/,".pad.mp4");const s=a=>execFileAsync3("ffmpeg",["-y","-v","error","-i",e,"-vf",`tpad=stop_mode=clone:stop_duration=${i.toFixed(2)},fps=30`,"-an",...a,"-pix_fmt","yuv420p","-movflags","+faststart",o],{timeout:24e4,maxBuffer:4*1024*1024});try{await s(["-c:v","h264_videotoolbox","-b:v","6M"])}catch{await s(["-c:v","libx264","-preset","veryfast","-crf","22"])}await import_node_fs2.promises.rename(o,e)}function stopAllRecordingsNow(){for(const e of live){try{if(e.host.platform!=="android")e.proc.kill("SIGINT");else if(e.remotePid)(0,import_node_child_process4.spawn)("adb",["-s",e.host.serial,"shell",`kill -INT ${e.remotePid}`],{stdio:"ignore",detached:true}).unref()}catch{}}live.clear()}function markPoint(e,n,t,r){const i=n.width!==n.height&&t.width!==t.height&&n.width>n.height!==t.width>t.height;if(!i)return e;const o=r==="landscapeRight";const s=n.width>n.height?!o:o;return s?[1-e[1],e[0]]:[e[1],1-e[0]]}function pinchPath(e){if(e.kind!=="pinch"||e.from.length!==2||e.to?.length!==2)return null;const{width:n,height:t}=e.screen;const r=h=>[h[0]*n,h[1]*t];const[i,o,s,a]=[r(e.from[0]),r(e.from[1]),r(e.to[0]),r(e.to[1])];const c=[(i[0]+o[0])/2,(i[1]+o[1])/2];const l=[(s[0]+a[0])/2,(s[1]+a[1])/2];const u=Math.atan2(i[1]-c[1],i[0]-c[0]);let d=Math.atan2(s[1]-l[1],s[0]-l[0])-u;if(d>Math.PI)d-=2*Math.PI;if(d<-Math.PI)d+=2*Math.PI;return{c0:c,c1:l,r0:Math.hypot(i[0]-c[0],i[1]-c[1]),r1:Math.hypot(s[0]-l[0],s[1]-l[1]),a0:u,turn:d}}function touchDotNote(e){const n=Math.max(0,e.reduce((t,r)=>t+r.from.length,0)-MAX_BURN_DOTS);return n?`${n} touch dots were left out of the MP4. The viewer keeps all dots.`:null}async function burnTouchMarks(e,n,t){let r;try{r=(await execFileAsync3("ffprobe",["-v","error","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0:s=x",e],{timeout:2e4})).stdout}catch(g){if(g.code==="ENOENT")return null;throw g}const[i,o]=r.trim().split("x").map(Number);if(!i||!o)throw new Error("could not read the video's size");const s={width:i,height:o};const a=Math.max(8,Math.round(Math.min(i,o)*.045));const c=a*2;const l=Math.max(2,Math.round(a*.18));const u=g=>g.toFixed(3);const d=[];for(const g of n){const m=g.t/1e3;const f=Math.max(g.ms,1)/1e3;const b=`clip((t-${u(m)})/${u(f)},0,1)`;const v=`enable='between(t,${u(m)},${u(m+f+.35)})':eval=frame:shortest=1`;const y=pinchPath(g);if(y){const{width:$,height:T}=g.screen;const _=markPoint([0,0],g.screen,s,g.orientation);const x=markPoint([1,0],g.screen,s,g.orientation);const I=markPoint([0,1],g.screen,s,g.orientation);[1,-1].forEach(D=>{const E=`(${u(y.r0)}+(${u(y.r1-y.r0)})*${b})`;const S=`(${u(y.a0)}+(${u(y.turn)})*${b})`;const k=`clip((${u(y.c0[0])}+(${u(y.c1[0]-y.c0[0])})*${b}+${D}*${E}*cos(${S}))/${u($)},0,1)`;const M=`clip((${u(y.c0[1])}+(${u(y.c1[1]-y.c0[1])})*${b}+${D}*${E}*sin(${S}))/${u(T)},0,1)`;const[A,P]=[0,1].map(R=>`(${_[R]}+(${x[R]-_[R]})*${k}+(${I[R]-_[R]})*${M})`);d.push(`overlay=x='${A}*${i}-${a}':y='${P}*${o}-${a}':${v}`)});continue}g.from.forEach(($,T)=>{const[_,x]=markPoint($,g.screen,s,g.orientation);const[I,D]=markPoint(g.to?.[T]??$,g.screen,s,g.orientation);d.push(`overlay=x='${u(_*i-a)}+(${u((I-_)*i)})*${b}':y='${u(x*o-a)}+(${u((D-x)*o)})*${b}':${v}`)})}const h=d.slice(0,MAX_BURN_DOTS);const w=["[0:v]fps=30[base]",`[1:v]split=${h.length}${h.map((g,m)=>`[c${m}]`).join("")}`,...h.map((g,m)=>`${m===0?"[base]":`[v${m-1}]`}[c${m}]${g}[v${m}]`)].join(";");const p=`color=c=white@0:s=${c}x${c},format=rgba,geq=r='255':g='255':b='255':a='if(lte(hypot(X-${a},Y-${a}),${a}),if(gte(hypot(X-${a},Y-${a}),${a-l}),235,105),0)'`;await execFileAsync3("ffmpeg",["-y","-v","error","-i",e,"-f","lavfi","-i",p,"-filter_complex",w,"-map",`[v${h.length-1}]`,"-an","-c:v","libx264","-preset","veryfast","-crf","22","-pix_fmt","yuv420p","-movflags","+faststart",t],{timeout:24e4,maxBuffer:4*1024*1024});return t}function redact(e){return e.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi,"$1 [redacted]").replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}/g,"[redacted jwt]").replace(/((?:api[_-]?key|token|secret|password|passwd|authorization|cookie|session)["']?\s*[:=]\s*["']?)([^\s"'&,;}]{4,})/gi,"$1[redacted]")}function viewerHtml(e){const n=(e.marks??[]).map(r=>({...r,arc:pinchPath(r)??void 0}));const t=JSON.stringify({...e,marks:n}).replace(/</g,"\\u003c");return`<!doctype html>
|
|
3
3
|
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
4
4
|
<title>${escapeHtml(e.title)}</title>
|
|
5
5
|
<style>
|
|
@@ -9,7 +9,10 @@
|
|
|
9
9
|
header{padding:14px 18px;border-bottom:1px solid var(--line)}h1{font-size:16px;margin:0}header p{margin:2px 0 0;color:var(--muted);font-size:12px}
|
|
10
10
|
.note{margin:6px 0 0;color:var(--warn);font-size:12px}
|
|
11
11
|
main{display:flex;gap:18px;padding:18px;align-items:flex-start;flex-wrap:wrap}
|
|
12
|
-
|
|
12
|
+
.stage{position:sticky;top:18px;display:inline-block;max-width:100%;line-height:0}
|
|
13
|
+
video{max-height:80vh;max-width:100%;border-radius:12px;background:#000}
|
|
14
|
+
#marks{position:absolute;inset:0;pointer-events:none;overflow:hidden;border-radius:12px}
|
|
15
|
+
.dot{position:absolute;width:34px;height:34px;margin:-17px 0 0 -17px;border-radius:50%;background:rgba(255,255,255,.42);border:3px solid rgba(255,255,255,.92);box-shadow:0 0 0 1px rgba(0,0,0,.35)}
|
|
13
16
|
.side{flex:1;min-width:280px}.chips{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:10px}
|
|
14
17
|
.chip{border:1px solid var(--line);background:var(--card);color:var(--fg);border-radius:999px;padding:3px 10px;font-size:12px;cursor:pointer}.chip.off{opacity:.4}
|
|
15
18
|
ol{list-style:none;margin:0;padding:0;border:1px solid var(--line);border-radius:10px;background:var(--card);max-height:78vh;overflow:auto}
|
|
@@ -20,11 +23,11 @@ li.error .ti{color:var(--err);font-weight:600}li.warning .ti{color:var(--warn)}l
|
|
|
20
23
|
.empty{padding:14px;color:var(--muted)}
|
|
21
24
|
</style></head><body>
|
|
22
25
|
<header><h1>${escapeHtml(e.title)}</h1><p>${escapeHtml(e.device)} \xB7 ${(e.durationMs/1e3).toFixed(1)} s \xB7 ${e.items.length} events \xB7 recorded by Buoy \xB7 secrets in logs are hidden</p>
|
|
23
|
-
${(e.notes??[]).map(
|
|
24
|
-
<main><video id="v" src="${escapeHtml(e.video)}" controls playsinline></video>
|
|
26
|
+
${(e.notes??[]).map(r=>`<p class="note">${escapeHtml(r)}</p>`).join("")}</header>
|
|
27
|
+
<main><div class="stage"><video id="v" src="${escapeHtml(e.video)}" controls playsinline></video><div id="marks"></div></div>
|
|
25
28
|
<div class="side"><div class="chips" id="chips"></div><ol id="list"></ol></div></main>
|
|
26
29
|
<script>
|
|
27
|
-
const D=${
|
|
30
|
+
const D=${t};const v=document.getElementById('v'),list=document.getElementById('list'),chips=document.getElementById('chips');
|
|
28
31
|
const off=new Set();const sources=[...new Set(D.items.map(i=>i.source))];
|
|
29
32
|
const fmt=ms=>{const s=Math.max(0,ms)/1000;return Math.floor(s/60)+':'+(s%60).toFixed(1).padStart(4,'0')};
|
|
30
33
|
function draw(){list.innerHTML='';const shown=D.items.filter(i=>!off.has(i.source));
|
|
@@ -36,425 +39,153 @@ li.onclick=()=>{v.currentTime=Math.max(0,i.t/1000-0.3);v.play()};list.appendChil
|
|
|
36
39
|
for(const s of sources){const b=document.createElement('button');b.className='chip';b.textContent=s;b.onclick=()=>{off.has(s)?off.delete(s):off.add(s);b.classList.toggle('off');draw()};chips.appendChild(b)}
|
|
37
40
|
v.ontimeupdate=()=>{const ms=v.currentTime*1000;let cur=null;for(const li of list.children){li.classList.remove('now');if(+li.dataset.t<=ms)cur=li}if(cur){cur.classList.add('now');if(!v.paused)cur.scrollIntoView({block:'nearest'})}};
|
|
38
41
|
draw();
|
|
42
|
+
const M=D.marks||[],layer=document.getElementById('marks');
|
|
43
|
+
// A landscape app can be recorded as a portrait video: turn its points to match.
|
|
44
|
+
const mapPoint=${markPoint.toString()};
|
|
45
|
+
const place=(p,m)=>mapPoint(p,m.screen,{width:v.videoWidth,height:v.videoHeight},m.orientation);
|
|
46
|
+
function marks(){const ms=v.currentTime*1000;layer.innerHTML='';
|
|
47
|
+
const dot=(p)=>{const d=document.createElement('div');d.className='dot';d.style.left=p[0]*100+'%';d.style.top=p[1]*100+'%';layer.appendChild(d)};
|
|
48
|
+
for(const m of M){const len=Math.max(m.ms,1);if(ms<m.t||ms>m.t+len+350)continue;const k=Math.min(1,(ms-m.t)/len);
|
|
49
|
+
if(m.arc){const a=m.arc,w=m.screen.width,h=m.screen.height,r=a.r0+(a.r1-a.r0)*k,g=a.a0+a.turn*k,cx=a.c0[0]+(a.c1[0]-a.c0[0])*k,cy=a.c0[1]+(a.c1[1]-a.c0[1])*k;
|
|
50
|
+
const c=(n)=>Math.min(1,Math.max(0,n));for(const s of [1,-1])dot(place([c((cx+s*r*Math.cos(g))/w),c((cy+s*r*Math.sin(g))/h)],m));continue}
|
|
51
|
+
m.from.forEach((p,i)=>{const q=(m.to&&m.to[i])||p;const a=place(p,m),b=place(q,m);dot([a[0]+(b[0]-a[0])*k,a[1]+(b[1]-a[1])*k])})}}
|
|
52
|
+
(function tick(){marks();requestAnimationFrame(tick)})();
|
|
39
53
|
<\/script></body></html>
|
|
40
|
-
`}function escapeHtml(e){return e.replace(/[&<>"']/g,n=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[n])}var import_node_child_process3,import_node_fs2,import_node_path2,MAX_RECORDING_MS,live;var init_recorder=__esm({"src/capture/recorder.ts"(){"use strict";import_node_child_process3=require("child_process");import_node_fs2=require("fs");import_node_path2=__toESM(require("path"));init_adb();init_iosDevice();MAX_RECORDING_MS=3*6e4;live=new Set}});function readProjectKey(e,n=process.env){for(const t of KEY_NAMES)if(n[t]!==void 0)return(0,import_headless.normalizeLicenseKey)(n[t])||null;for(const t of[".env.development.local",".env.local",".env"]){let r;try{r=(0,import_node_fs3.readFileSync)((0,import_node_path3.join)(e,t),"utf8")}catch{continue}const i=new Map;for(const s of r.split(/\r?\n/)){const o=s.match(/^\s*(?:export\s+)?([A-Z_][A-Z_0-9]*)\s*=\s*(.*)$/);if(!o)continue;const a=o[2].trim();const c=a.match(/^(['"])(.*?)\1\s*(?:#.*)?$/);i.set(o[1],c?c[2]:a.split("#")[0].trim())}for(const s of KEY_NAMES)if(i.has(s))return(0,import_headless.normalizeLicenseKey)(i.get(s))||null}return null}var import_node_fs3,import_node_path3,import_node_os2,import_node_crypto2,import_headless,KEY_NAMES,NodeAccount;var init_NodeAccount=__esm({"src/sync/NodeAccount.ts"(){"use strict";import_node_fs3=require("fs");import_node_path3=require("path");import_node_os2=require("os");import_node_crypto2=require("crypto");import_headless=require("@buoy-gg/license/headless");KEY_NAMES=["BUOY_LICENSE_KEY","BUOY_KEY","EXPO_PUBLIC_BUOY_KEY","VITE_BUOY_KEY","NEXT_PUBLIC_BUOY_KEY","REACT_APP_BUOY_KEY"];NodeAccount=class{constructor(e,n={}){this.changed=e;this.key=null;this.cache=null;this.timer=null;this.unsubscribeSession=null;this.generation=0;this.busy=false;this.nextCheck=0;this.retry=0;this.lastAdmission=false;this.hasAccess=()=>this.hasKeyAccess()||this.session?.getStatus().state==="active";this.lastSessionSync=0;this.projectDir=(0,import_node_path3.resolve)(n.projectDir??process.env.BUOY_PROJECT_DIR??process.cwd());const t=(0,import_node_crypto2.createHash)("sha256").update(this.projectDir).digest("hex").slice(0,20);this.cacheFile=n.cacheFile??(0,import_node_path3.join)((0,import_node_os2.homedir)(),".buoy",`account-${t}.json`);this.session=n.session!==void 0?n.session:(0,import_headless.createNodeSession)({audience:import_headless.CLI_AUDIENCE,openBrowser:()=>{throw new Error("The MCP does not open a browser. Run `npx buoy login`.")}})}hasKeyAccess(){return(0,import_headless.resolveAccountAccess)({initialized:true,validating:false,key:this.key,tierSource:this.cache?.tier?"key":"none",verifiedAt:this.cache?.cachedAt??null}).status==="admitted"}start(){if(this.timer)return;if(this.session){this.unsubscribeSession=this.session.subscribe(()=>this.notify());void this.session.load().then(()=>this.notify(),()=>{})}try{const e=JSON.parse((0,import_node_fs3.readFileSync)(this.cacheFile,"utf8"));if(e.valid&&(0,import_headless.verifyCacheSignature)(e))this.cache=e}catch{}void this.tick();this.timer=setInterval(()=>{void this.tick()},1e3);this.timer.unref()}stop(){++this.generation;this.unsubscribeSession?.();this.unsubscribeSession=null;if(this.timer)clearInterval(this.timer);this.timer=null;this.key=null;this.cache=null;this.notify()}notify(){const e=this.hasAccess();if(e===this.lastAdmission)return;this.lastAdmission=e;this.changed()}async tick(){if(this.session&&Date.now()-this.lastSessionSync>15e3){this.lastSessionSync=Date.now();void this.session.sync().catch(()=>{})}const e=readProjectKey(this.projectDir);if(e!==this.key){++this.generation;this.key=e;if(this.cache?.licenseKey!==e)this.cache=null;this.nextCheck=0;this.retry=0;if(!e)this.removeCache()}this.notify();if(!e||this.busy||Date.now()<this.nextCheck)return;if(this.cache&&this.hasKeyAccess()&&Date.now()-this.cache.lastValidatedAt<import_headless.LICENSE_LAUNCH_VALIDATION_TTL&&this.nextCheck===0){this.nextCheck=this.cache.lastValidatedAt+import_headless.LICENSE_LAUNCH_VALIDATION_TTL;return}this.busy=true;const n=this.generation;try{if((0,import_headless.isDevToken)(e)){const a=(0,import_headless.checkDevToken)(e);if(!a.ok){this.cache=null;this.removeCache()}else{const c=Math.min(Date.now(),a.claims.iat*1e3);const u=a.claims.tier==="free"?"free":"pro";this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`dev:${a.claims.sid}`,valid:true,tier:u,isPro:u==="pro",expiresAt:new Date(a.claims.exp*1e3).toISOString(),cachedAt:c,lastValidatedAt:Date.now()});this.persistCache()}this.nextCheck=Date.now()+import_headless.LICENSE_REVALIDATION_INTERVAL;return}if((0,import_headless.isServiceKey)(e)){const a=await(0,import_headless.exchangeServiceKey)(e,{origin:process.env.BUOY_SITE_URL||"https://buoy.gg"});if(n!==this.generation||readProjectKey(this.projectDir)!==e)return;if(!a.ok){if(a.reason==="rejected"){this.cache=null;this.removeCache();this.nextCheck=Date.now()+import_headless.LICENSE_REVALIDATION_INTERVAL}else{this.nextCheck=Date.now()+(import_headless.LICENSE_TRANSIENT_RETRY_DELAYS[this.retry++]??import_headless.LICENSE_REVALIDATION_INTERVAL)}return}const c=Date.now();const u=a.claims.exp*1e3;this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`service:${a.claims.sid}`,valid:true,tier:"pro",isPro:true,expiresAt:new Date(u).toISOString(),cachedAt:c,lastValidatedAt:c});this.persistCache();this.retry=0;this.nextCheck=Math.max(c+6e4,u-60*60*1e3);return}if((0,import_headless.isBuoyToken)(e)){const a=(0,import_headless.verifyFreeToken)(e);if(!a){this.cache=null;this.removeCache()}else{const c=Date.now();this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`token:${a.accountHash}`,valid:true,tier:"free",isPro:false,expiresAt:null,cachedAt:c,lastValidatedAt:c});this.persistCache()}this.nextCheck=Date.now()+import_headless.LICENSE_REVALIDATION_INTERVAL;return}const t=await(0,import_headless.validateLicense)(e);if(n!==this.generation||readProjectKey(this.projectDir)!==e)return;const r=t.data?.relationships?.product?.data?.id;const i=t.meta.code==="EXPIRED"&&((0,import_headless.isRecognizedAccount)(t.data)||this.cache?.licenseKey===e);if(r&&r!==import_headless.KEYGEN_CONFIG.productId||!i&&!(0,import_headless.isAcceptedValidation)(t)){this.cache=null;this.removeCache();this.nextCheck=Date.now()+import_headless.LICENSE_REVALIDATION_INTERVAL;return}const s=i?"free":(0,import_headless.resolveTier)(t.data);const o=Date.now();this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:t.data?.id??"",valid:true,tier:s,isPro:s==="pro",expiresAt:i?null:t.data.attributes.expiry,cachedAt:o,lastValidatedAt:o});this.persistCache();this.retry=0;this.nextCheck=o+import_headless.LICENSE_REVALIDATION_INTERVAL}catch(t){if(n!==this.generation)return;const r=(0,import_headless.isTransientLicenseError)(t)?import_headless.LICENSE_TRANSIENT_RETRY_DELAYS[this.retry++]:void 0;this.nextCheck=Date.now()+(r??import_headless.LICENSE_REVALIDATION_INTERVAL)}finally{this.busy=false;this.notify()}}persistCache(){try{(0,import_node_fs3.mkdirSync)((0,import_node_path3.dirname)(this.cacheFile),{recursive:true,mode:448});(0,import_node_fs3.writeFileSync)(`${this.cacheFile}.tmp`,JSON.stringify(this.cache),{mode:384});(0,import_node_fs3.renameSync)(`${this.cacheFile}.tmp`,this.cacheFile)}catch{}}removeCache(){try{(0,import_node_fs3.unlinkSync)(this.cacheFile)}catch{}}}}});var import_sync_broker,BROKER_PORT,BROKER_URL,DEFAULT_ACTION_TIMEOUT_MS,UNRESPONSIVE_ACTION_TIMEOUT_MS,UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS,RECOVERY_PROBE_MS,UNRESPONSIVE_AFTER_MS,DEFAULT_SNAPSHOT_TIMEOUT_MS,DEVICE_RETENTION_MS,DASHBOARD_NAME,ALL_DEVICES;var init_config=__esm({"src/config.ts"(){"use strict";import_sync_broker=require("@buoy-gg/sync-broker");BROKER_PORT=import_sync_broker.DEFAULT_BROKER_PORT;BROKER_URL=`http://localhost:${BROKER_PORT}`;DEFAULT_ACTION_TIMEOUT_MS=15e3;UNRESPONSIVE_ACTION_TIMEOUT_MS=2500;UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS=1200;RECOVERY_PROBE_MS=2e4;UNRESPONSIVE_AFTER_MS=3e4;DEFAULT_SNAPSHOT_TIMEOUT_MS=5e3;DEVICE_RETENTION_MS=15*6e4;DASHBOARD_NAME="Dashboard";ALL_DEVICES="All"}});async function devServerRoot(e){let n;try{n=new URL(e)}catch{return null}if(!isLocalHost(n.hostname))return null;const t=n.port||(n.protocol==="https:"?"443":"80");try{const{stdout:r}=await execFileAsync3("lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"],{timeout:3e3});const i=r.split("\n").map(a=>a.trim()).find(Boolean);if(!i)return null;const{stdout:s}=await execFileAsync3("lsof",["-a","-p",i,"-d","cwd","-Fn"],{timeout:3e3});const o=s.split("\n").find(a=>a.startsWith("n"));return o?import_node_path4.default.resolve(o.slice(1)):null}catch{return null}}function isLocalHost(e,n=import_node_os3.default.networkInterfaces()){const t=e.replace(/^\[|\]$/g,"").toLowerCase();if(t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="10.0.2.2"||t==="10.0.3.2")return true;return Object.values(n).flat().some(r=>r?.address?.toLowerCase()===t)}function pickByProject(e,n){const t=import_node_path4.default.resolve(n);const r=e.map(o=>({deviceId:o.deviceId,score:o.root?closeness(import_node_path4.default.resolve(o.root),t):-1})).filter(o=>o.score>=0);if(r.length===0)return null;const i=Math.min(...r.map(o=>o.score));const s=r.filter(o=>o.score===i);return s.length===1?s[0].deviceId:null}function closeness(e,n){if(e===n)return 0;const t=import_node_path4.default.relative(e,n);const r=import_node_path4.default.relative(n,e);const i=s=>s&&!s.startsWith("..")&&!import_node_path4.default.isAbsolute(s);if(i(t))return t.split(import_node_path4.default.sep).length;if(i(r))return r.split(import_node_path4.default.sep).length;return-1}var import_node_child_process4,import_node_util3,import_node_path4,import_node_os3,execFileAsync3;var init_projectRoot=__esm({"src/sync/projectRoot.ts"(){"use strict";import_node_child_process4=require("child_process");import_node_util3=require("util");import_node_path4=__toESM(require("path"));import_node_os3=__toESM(require("os"));execFileAsync3=(0,import_node_util3.promisify)(import_node_child_process4.execFile)}});function isRecoveryAction(e,n){return e==="app"&&(n==="ping"||n==="reloadApp")}function isUnresponsive(e){return e>=2}function actionTimeoutMs(e){if(isRecoveryAction(e.toolId,e.action)){return{timeoutMs:e.fullMs,usedFullBudget:false}}if(!isUnresponsive(e.consecutiveTimeouts)){return{timeoutMs:e.fullMs,usedFullBudget:false}}if(e.now-e.lastFullBudgetAt>e.recoveryProbeMs){return{timeoutMs:e.fullMs,usedFullBudget:true}}return{timeoutMs:e.shortMs,usedFullBudget:false}}function diagnoseCrashed(e){if(e.consecutiveTimeouts>=2)return true;if(e.lastOkAt>0&&e.now-e.lastOkAt>e.unresponsiveAfterMs){return true}return false}var init_actionTimeout=__esm({"src/sync/actionTimeout.ts"(){"use strict"}});function probeBroker(e,n=800){return new Promise(t=>{const r=import_node_http.default.get(e,i=>{i.resume();t((i.statusCode??0)>0)});r.setTimeout(n,()=>{r.destroy();t(false)});r.on("error",()=>t(false))})}async function waitForBroker(e,n=20){for(let t=0;t<n;t++){if(await probeBroker(e,300))return;await delay(50)}throw new Error(`Spawned broker never became reachable at ${e}`)}var import_node_http,import_node_crypto3,import_socket,import_sync_broker2,NOT_READY_MARK,SyncClient,snapKey,delay;var init_SyncClient=__esm({"src/sync/SyncClient.ts"(){"use strict";init_NodeAccount();import_node_http=__toESM(require("http"));import_node_crypto3=require("crypto");import_socket=require("socket.io-client");import_sync_broker2=require("@buoy-gg/sync-broker");init_config();init_projectRoot();init_actionTimeout();NOT_READY_MARK="Not ready:";SyncClient=class{constructor(e={}){this.socket=null;this.admitted=false;this.createdAt=Date.now();this.lockedDevices=new Set;this.hostAccount=null;this.broker=null;this.capabilities=new Map;this.devices=[];this.sessionDevice=null;this.snapshots=new Map;this.watching=new Map;this.pendingActions=new Map;this.snapshotWaiters=new Map;this.snapshotAt=new Map;this.health=new Map;this.devServerOrigins=new Map;this.crashSeen=new Map;this.rootLookups=new Set;this.devServerRoots=new Map;this.originProbed=new Set;this.lastSeen=new Map;this.deviceConnections=new Map;this.port=e.port??BROKER_PORT;this.url=e.url??(e.port?`http://localhost:${e.port}`:BROKER_URL);this.actionTimeoutMs=e.actionTimeoutMs??DEFAULT_ACTION_TIMEOUT_MS;this.log=e.log??(n=>process.stderr.write(`[buoy-mcp] ${n}
|
|
41
|
-
`));this.autoSpawn=e.autoSpawnBroker??true}async start(){const e=await probeBroker(this.url)||await probeBroker(this.url,8e3);let n="connected";if(!e){if(!this.autoSpawn){throw new Error(`No Buoy broker reachable at ${this.url} and autoSpawnBroker is off. Start the Buoy desktop app, or enable autoSpawnBroker.`)}this.log(`no broker at ${this.url} \u2014 spawning one in-process on :${this.port}`);this.hostAccount=new NodeAccount(()=>this.broker?.refreshAccess());this.hostAccount.start();let t=false;this.broker=(0,import_sync_broker2.createBroker)({canUseDesktop:this.hostAccount.hasAccess,port:this.port,onError:r=>{if(r.code==="EADDRINUSE")t=true;this.log(`broker error: ${r.code??r.message}`)}});await waitForBroker(this.url).catch(r=>{if(!t)throw r});if(!this.broker.httpServer.listening)t=true;if(t){this.log(`another broker holds :${this.port} \u2014 connecting to it as a dashboard`);await this.broker.close().catch(()=>void 0);this.broker=null;this.hostAccount.stop();this.hostAccount=null;await this.connectSocket();return"connected"}try{(0,import_sync_broker2.writeBrokerToken)(this.broker.dashboardToken,(0,import_sync_broker2.brokerTokenPath)(this.port))}catch(r){this.log(`could not write the broker token file: ${r.message}`)}n="spawned"}else{this.log(`found a running broker at ${this.url} \u2014 connecting as a dashboard`)}await this.connectSocket();return n}connectSocket(){return new Promise((e,n)=>{const t=(0,import_socket.io)(this.url,{transports:["websocket"],query:{deviceName:DASHBOARD_NAME},auth:a=>{const c=this.broker?.dashboardToken??(0,import_sync_broker2.readBrokerToken)((0,import_sync_broker2.brokerTokenPath)(this.port));a(c?{dashboardToken:c}:{})},reconnection:true,reconnectionDelay:500,timeout:4e3});this.socket=t;let r=false;const i=()=>{if(r)return;r=true;this.log("connected to broker");e()};const s=setTimeout(()=>{if(r)return;r=true;n(new Error("Broker account is locked or the broker needs an update. Sign in to Buoy Desktop or run npx buoy login for standalone MCP."))},5e3);t.on("buoy:access",a=>{const c=!!a&&typeof a==="object"&&a.protocol===1&&a.ready===true;this.setAdmission(c);if(c){clearTimeout(s);this.rearmWatches();i()}});t.on("connect",()=>{t.emit("buoy:access:request")});t.on("disconnect",()=>this.setAdmission(false,true));const o=a=>a.message===import_sync_broker2.DASHBOARD_TOKEN_REQUIRED;t.once("connect_error",a=>{if(r)return;r=true;clearTimeout(s);n(new Error(o(a)?`The broker at ${this.url} refused this MCP as a dashboard: the token in ${(0,import_sync_broker2.brokerTokenPath)(this.port)} is missing or stale. Update Buoy Desktop, or restart it so it writes the file.`:`failed to connect to broker at ${this.url}: ${a.message}`))});t.on("connect_error",a=>{if(!o(a)||t.active)return;setTimeout(()=>{if(this.socket===t&&!t.connected)t.connect()},1e3).unref?.()});t.on("devtool-capabilities",a=>{if(!this.admitted||this.lockedDevices.has(a.persistentDeviceId))return;this.capabilities.set(a.persistentDeviceId,a);this.trackRootLookup(this.learnDevServerOrigin(a.persistentDeviceId));if(a.tools?.some(c=>c.toolId==="console"))this.ensureWatching("console",a.persistentDeviceId)});t.on("all-devices-update",a=>{if(!this.admitted)return;if(!Array.isArray(a))return;let c=false;for(const l of a){if(l.deviceId&&l.tier==="locked")this.lockDevice(String(l.deviceId));else if(l.deviceId&&(l.tier==="free"||l.tier==="pro")){c=this.lockedDevices.delete(String(l.deviceId))||c}}this.devices=a;const u=Date.now();for(const l of a)if(l.deviceId)this.lastSeen.set(l.deviceId,u);this.pruneStaleDevices();if(c)this.rearmWatches();else this.rearmReconnectedDevices(a)});t.on("devtool-sync",a=>{if(!this.admitted||this.lockedDevices.has(a.persistentDeviceId))return;const c=snapKey(a.persistentDeviceId,a.toolId);this.snapshots.set(c,a.payload);this.snapshotAt.set(c,Date.now());if(a.toolId==="console")this.noteCrashReport(a.persistentDeviceId,a.payload);const u=this.snapshotWaiters.get(c);if(u&&u.length){this.snapshotWaiters.set(c,[]);for(const l of u)l(a.payload)}});t.on("devtool-action-result",a=>{if(!this.admitted)return;const c=this.pendingActions.get(a.requestId);if(!c)return;this.pendingActions.delete(a.requestId);clearTimeout(c.timer);c.resolve(a)})})}requireAdmission(){if(!this.admitted)throw new Error("A verified Buoy account and an updated broker are required. Sign in to Buoy Desktop, or run npx buoy login for standalone MCP.")}setAdmission(e,n=false){this.admitted=e;if(e)return;this.devices=[];this.lockedDevices.clear();this.capabilities.clear();this.snapshots.clear();this.snapshotAt.clear();this.devServerOrigins.clear();this.devServerRoots.clear();this.crashSeen.clear();this.originProbed.clear();this.health.clear();this.lastSeen.clear();if(!n)this.watching.clear();for(const t of this.pendingActions.values()){clearTimeout(t.timer);t.reject(new Error("Buoy account access ended while the action was pending."))}this.pendingActions.clear();for(const t of this.snapshotWaiters.values())for(const r of t)r(void 0);this.snapshotWaiters.clear();if(this.socket)this.socket.sendBuffer=[]}requireDeviceAccount(e){if(this.lockedDevices.has(e))throw new Error("The device's Buoy account access ended. Sign in and verify its key.")}lockDevice(e){this.lockedDevices.add(e);this.capabilities.delete(e);this.health.delete(e);this.devServerOrigins.delete(e);this.devServerRoots.delete(e);this.originProbed.delete(e);const n=`${e}::`;for(const t of this.snapshots.keys())if(t.startsWith(n)){this.snapshots.delete(t);this.snapshotAt.delete(t)}for(const[t,r]of this.snapshotWaiters)if(t.startsWith(n)){this.snapshotWaiters.delete(t);for(const i of r)i(void 0)}for(const[t,r]of this.pendingActions)if(r.target===e||r.target===ALL_DEVICES){clearTimeout(r.timer);this.pendingActions.delete(t);r.reject(new Error("Device account access ended while the action was pending."))}}pruneStaleDevices(){const e=Date.now()-DEVICE_RETENTION_MS;for(const[n,t]of this.lastSeen){if(t>e)continue;if(this.devices.some(i=>i.deviceId===n))continue;this.lastSeen.delete(n);this.capabilities.delete(n);this.health.delete(n);this.devServerOrigins.delete(n);this.devServerRoots.delete(n);this.originProbed.delete(n);const r=`${n}::`;for(const i of[...this.snapshots.keys()]){if(i.startsWith(r)){this.snapshots.delete(i);this.snapshotAt.delete(i)}}for(const i of[...this.watching.keys()]){if(i.startsWith(r))this.watching.delete(i)}}}async stop(){this.setAdmission(false);this.hostAccount?.stop();this.hostAccount=null;for(const[,e]of this.pendingActions){clearTimeout(e.timer);e.reject(new Error("SyncClient stopped"))}this.pendingActions.clear();for(const[,e]of this.snapshotWaiters)for(const n of e)n(void 0);this.snapshotWaiters.clear();this.socket?.close();this.socket=null;if(this.broker){await this.broker.close();this.broker=null}}listDevices(){if(!this.admitted)return[];return this.devices.filter(e=>e.deviceName!==DASHBOARD_NAME&&e.deviceId).map(e=>{const n=this.capabilities.get(e.deviceId);return{deviceId:e.deviceId,deviceName:e.deviceName,platform:e.platform,isConnected:e.isConnected!==false,isPro:e.isPro===true,tier:e.tier==="free"||e.tier==="pro"?e.tier:e.tier===void 0&&e.isPro===true?"pro":"locked",collision:e.collision===true,tools:n?.tools??[]}})}connectedDevices(){return this.listDevices().filter(e=>e.isConnected)}toolActions(e){return this.listDevices().map(n=>{const t=n.tools.find(r=>r.toolId===e);return t?{deviceId:n.deviceId,deviceName:n.deviceName,actions:t.actions}:null}).filter(n=>n!==null)}resolveDevice(e){this.requireAdmission();if(e){this.requireDeviceAccount(e);return e}const n=(u,l)=>new Error(`${NOT_READY_MARK} "${u}" (${l}) is not connected right now. If it is restarting, it usually takes a few seconds; to use another device, pass deviceId (run list_devices to see them).`);if(this.sessionDevice){const u=this.devices.find(l=>l.deviceId===this.sessionDevice);if(u&&u.isConnected!==false)return this.sessionDevice;throw n(this.sessionDevice,"the device this session was using")}const t=this.connectedDevices();const r=t.filter(u=>!this.lockedDevices.has(u.deviceId));const i=r.filter(u=>u.tools.length>0);const s=process.env.BUOY_PROJECT_ROOT||process.cwd();const o=pickByProject(i.map(u=>({deviceId:u.deviceId,root:this.devServerRoots.get(u.deviceId)})),s);if(o)return this.sessionDevice=o;const a=pickByProject(this.devices.filter(u=>u.deviceId&&u.isConnected===false&&!this.lockedDevices.has(u.deviceId)).map(u=>({deviceId:u.deviceId,root:this.devServerRoots.get(u.deviceId)})),s);if(a)throw n(a,"this project's app");if(r.length===0){if(t.length>0){throw new Error(`Devices are connected (${t.map(u=>u.deviceName).join(", ")}), but the broker has not admitted their accounts. Check app account validation and the account announcement after reconnect; this does not prove the user is signed out.`)}throw new Error("No devices are connected to the broker. Open the app with Buoy devtools running.")}if(r.length===1)return this.sessionDevice=r[0].deviceId;if(i.length===1)return this.sessionDevice=i[0].deviceId;if(i.length===0){const u=r.map(l=>l.deviceName).join(", ");throw new Error(`Connected devices (${u}) are not exposing any Buoy tools yet. Make sure the app is in the foreground with devtools mounted, then retry.`)}const c=i.map(u=>`${u.deviceName} (${u.deviceId})`).join(", ");throw new Error(`Multiple devices connected \u2014 specify deviceId. Connected: ${c}`)}requireProDevice(e){this.requireAdmission();if(e&&e!==ALL_DEVICES)this.sessionDevice=e;const n=s=>{if(!s)return"";return s.tier==="locked"?` The broker has not confirmed account access for "${s.deviceName}"; a locked status does not establish whether a key is configured.`:` The connected app "${s.deviceName}" is on the ${s.tier} tier.`};const t=s=>`Buoy Pro is required to use the MCP.${n(s)} Enter a license in the app, or \u2014 if it runs headless (no on-device UI) \u2014 pass \`licenseKey\` to \`<FloatingDevTools />\`. Run \`list_devices\` to check status.`;if(e===ALL_DEVICES){if(!this.connectedDevices().some(s=>s.isPro))throw new Error(t());return ALL_DEVICES}const r=this.resolveDevice(e);const i=this.connectedDevices().find(s=>s.deviceId===r);if(!i?.isPro){const s=this.accessState(r);if(s==="offline")throw new Error(`${NOT_READY_MARK} "${r}" is not connected right now. If the app is starting or reloading, it usually takes a few seconds. Run list_devices to check.`);if(s==="pending")throw new Error(`${NOT_READY_MARK} account access for "${r}" is still being confirmed (the app just connected). Try again in a moment.`);throw new Error(t(i))}return r}accessState(e){const n=this.devices.find(t=>t.deviceId===e);if(!n||n.isConnected===false)return"offline";if(n.isPro===true)return"ready";return n.tier===void 0?"pending":"denied"}healthOf(e){let n=this.health.get(e);if(!n){n={consecutiveTimeouts:0,lastOkAt:0,lastFullBudgetAt:0};this.health.set(e,n)}return n}noteOk(e){const n=this.healthOf(e);n.consecutiveTimeouts=0;n.lastOkAt=Date.now()}noteTimeout(e){this.healthOf(e).consecutiveTimeouts+=1}isUnresponsive(e){return isUnresponsive(this.healthOf(e).consecutiveTimeouts)}timeoutFor(e,n,t){const r=this.healthOf(e);const{timeoutMs:i,usedFullBudget:s}=actionTimeoutMs({consecutiveTimeouts:r.consecutiveTimeouts,lastFullBudgetAt:r.lastFullBudgetAt,now:Date.now(),fullMs:this.actionTimeoutMs,shortMs:UNRESPONSIVE_ACTION_TIMEOUT_MS,recoveryProbeMs:RECOVERY_PROBE_MS,toolId:n,action:t});if(s)r.lastFullBudgetAt=Date.now();return i}unresponsiveNote(e){const n=this.healthOf(e);const t=n.lastOkAt?Math.round((Date.now()-n.lastOkAt)/1e3):null;const r=diagnoseCrashed({consecutiveTimeouts:n.consecutiveTimeouts,lastOkAt:n.lastOkAt,now:Date.now(),unresponsiveAfterMs:UNRESPONSIVE_AFTER_MS});const i=[`The app on "${e}" is not responding (${n.consecutiveTimeouts} call${n.consecutiveTimeouts===1?"":"s"} unanswered${t!=null?`, last answered ${t}s ago`:""}).`,r?"It is most likely CRASHED \u2014 a fatal render error unmounts the React tree, and the dev tools live in that tree, so nothing on-device can answer until the app is reloaded.":"It may be busy, mid-reload, or crashing."];const s=this.lastFatalFor(e);if(s)i.push(`Last captured error: ${s}`);i.push(s?"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(o=>typeof o?.timestamp==="number"?o.timestamp:-Infinity));const i=this.crashSeen.get(e)??new Set;let s=false;for(const o of t){const a=o?.fatal||/^\[(RENDER ERROR|FATAL)/.test(o?.message??"");if(!a||typeof o.timestamp!=="number")continue;const c=`${o.id??""}|${o.timestamp}|${(o.message??"").slice(0,120)}`;if(i.has(c))continue;i.add(c);if(r-o.timestamp<3e4)s=true}if(i.size>200)for(const o of[...i].slice(0,i.size-200))i.delete(o);this.crashSeen.set(e,i);if(!s)return;if(![...this.pendingActions.values()].some(o=>o.target===e&&o.expire&&!o.cut))return;void this.callAction("app","ping",{},e,{timeoutMs:1500,silent:true}).then(()=>void 0,()=>{const o=Date.now();for(const a of this.pendingActions.values()){if(a.target!==e||!a.expire||a.cut)continue;a.cut=true;if(a.deadline!==void 0&&a.deadline-o<=UNRESPONSIVE_ACTION_TIMEOUT_MS)continue;clearTimeout(a.timer);a.timer=setTimeout(a.expire,UNRESPONSIVE_ACTION_TIMEOUT_MS)}})}lastFatalFor(e){const n=this.snapshots.get(snapKey(e,"console"));const t=n?.entries;if(!Array.isArray(t))return null;for(let r=t.length-1;r>=0;r--){const i=t[r];if(i?.fatal||i?.level==="error"){const s=(i.message??"").split("\n")[0];if(s)return s.length>300?`${s.slice(0,300)}\u2026`:s}}return null}snapshotAgeMs(e,n){this.requireAdmission();const t=this.snapshotAt.get(snapKey(n,e));return t?Date.now()-t:null}noteDevServerOrigin(e,n){if(typeof n==="string"&&/^https?:\/\//.test(n)){const t=this.devServerOrigins.get(e)!==n;this.devServerOrigins.set(e,n);if(t)this.devServerRoots.delete(e);if(t||!this.devServerRoots.has(e)){const r=devServerRoot(n).then(i=>{if(i&&this.devServerOrigins.get(e)===n)this.devServerRoots.set(e,i)});this.trackRootLookup(r)}}}async learnDevServerOrigin(e){if(this.devServerOrigins.has(e)||this.originProbed.has(e))return;this.originProbed.add(e);const n=this.capabilities.get(e)?.tools?.some(t=>t.toolId==="app");if(!n)return;try{const{payload:t}=await this.getSnapshot("app",e,{timeoutMs:4e3,silent:true});this.noteDevServerOrigin(e,t?.devServerOrigin)}catch{}}trackRootLookup(e){const n=e.catch(()=>void 0).finally(()=>this.rootLookups.delete(n));this.rootLookups.add(n)}async awaitBroker(){if(Date.now()-this.createdAt>15e3)return;for(let e=0;!this.admitted&&e<4e3;e+=100)await new Promise(n=>setTimeout(n,100));for(let e=0;this.admitted&&this.devices.length===0&&e<1500;e+=100)await new Promise(n=>setTimeout(n,100))}async settleDeviceChoice(e=1500){await this.awaitBroker();if(this.sessionDevice||this.rootLookups.size===0||this.connectedDevices().length<2)return;await Promise.race([Promise.all([...this.rootLookups]),new Promise(n=>setTimeout(n,e))]);if(this.rootLookups.size)await Promise.race([Promise.all([...this.rootLookups]),new Promise(n=>setTimeout(n,Math.min(800,e)))])}devServerOrigin(e){this.requireAdmission();const n=this.devServerOrigins.get(e);if(n)return n;const t=this.snapshots.get(snapKey(e,"app"));if(typeof t?.devServerOrigin==="string")return t.devServerOrigin;return null}ensureWatching(e,n){const t=snapKey(n,e);if(this.watching.has(t))return;this.watching.set(t,{toolId:e,targetDeviceId:n});this.sendWatch(e,n)}sendWatch(e,n){if(!this.admitted||!this.socket?.connected||this.lockedDevices.has(n))return;this.socket?.emit("devtool-watch",{toolId:e,targetDeviceId:n,watching:true,stream:false})}rearmWatches(){for(const{toolId:e,targetDeviceId:n}of this.watching.values()){this.sendWatch(e,n)}}rearmReconnectedDevices(e){for(const n of e){if(!n.deviceId||n.isConnected===false)continue;const t=String(n.deviceId);const r=`${n.id}|${n.connectionNonce??""}`;const i=this.deviceConnections.get(t);this.deviceConnections.set(t,r);if(i===void 0||i===r)continue;for(const{toolId:s,targetDeviceId:o}of this.watching.values()){if(o===t)this.sendWatch(s,o)}}}unwatch(e,n){const t=snapKey(n,e);if(!this.watching.delete(t))return;if(this.admitted&&this.socket?.connected)this.socket.emit("devtool-watch",{toolId:e,targetDeviceId:n,watching:false})}cachedSnapshot(e,n){this.requireAdmission();this.requireDeviceAccount(n);return this.snapshots.get(snapKey(n,e))}async getSnapshot(e,n,t={}){const r=this.resolveDevice(n);const i=snapKey(r,e);this.ensureWatching(e,r);let s=t.timeoutMs??DEFAULT_SNAPSHOT_TIMEOUT_MS;if(t.timeoutMs===void 0&&this.isUnresponsive(r)){const u=this.healthOf(r);if(Date.now()-u.lastFullBudgetAt>RECOVERY_PROBE_MS){u.lastFullBudgetAt=Date.now()}else{s=UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS}}const o=this.waitForSnapshot(i,s);this.socket?.emit("request-devtool-state",{toolId:e,targetDeviceId:r});const a=await o;this.requireAdmission();this.requireDeviceAccount(r);if(a!==void 0){if(!t.silent)this.noteOk(r);return{deviceId:r,payload:a}}if(!t.silent)this.noteTimeout(r);const c=this.snapshots.get(i);if(c!==void 0){return{deviceId:r,payload:c,stale:this.staleNote(e,r)}}throw new Error(`Timed out waiting for "${e}" state from ${r} (is the tool active?). ${this.unresponsiveNote(r)}`)}lastSync(e,n){const t=this.snapshots.get(snapKey(e,n));return t===void 0?void 0:{payload:t,ageMs:this.snapshotAgeMs(n,e)}}staleNote(e,n){const t=this.snapshotAgeMs(e,n);const r=t==null?"an earlier sync":`${Math.round(t/1e3)}s ago`;return`\u26A0\uFE0F Served from the last sync (${r}) \u2014 ${this.unresponsiveNote(n)}`}waitForSnapshot(e,n){return new Promise(t=>{const r=this.snapshotWaiters.get(e)??[];const i=setTimeout(()=>{const o=(this.snapshotWaiters.get(e)??[]).filter(a=>a!==s);this.snapshotWaiters.set(e,o);t(void 0)},n);const s=o=>{clearTimeout(i);t(o)};r.push(s);this.snapshotWaiters.set(e,r)})}async callAction(e,n,t,r,i={}){this.requireAdmission();const s=r===ALL_DEVICES?ALL_DEVICES:this.resolveDevice(r);if(!this.socket)throw new Error("SyncClient is not connected");const o=(0,import_node_crypto3.randomUUID)();const a=i.timeoutMs??this.timeoutFor(s,e,n);const c=await new Promise((u,l)=>{const d=Date.now();const h=()=>{this.pendingActions.delete(o);if(s!==ALL_DEVICES&&!i.silent)this.noteTimeout(s);l(new Error(`Action "${e}.${n}" got no answer in ${Date.now()-d}ms. `+(s===ALL_DEVICES?"No device responded.":this.unresponsiveNote(s))))};const p=setTimeout(h,a);this.pendingActions.set(o,{resolve:u,reject:l,timer:p,target:s,expire:h,deadline:d+a});this.socket.emit("devtool-action",{requestId:o,toolId:e,targetDeviceId:s,action:n,params:t??{}})});if(s!==ALL_DEVICES&&!i.silent)this.noteOk(s);if(!c.ok){throw new Error(c.error||`Action "${e}.${n}" failed on device`)}return c.result}};snapKey=(e,n)=>`${e}::${n}`;delay=e=>new Promise(n=>setTimeout(n,e))}});var VERSION,PACKAGE_NAME;var init_version=__esm({"src/version.ts"(){"use strict";VERSION="7.0.62"?"7.0.62":"0.0.0-dev";PACKAGE_NAME="@buoy-gg/mcp"}});function isNewer(e,n){const t=s=>s.split("-")[0].split(".").map(o=>Number(o)||0);const r=t(e);const i=t(n);for(let s=0;s<3;s++){const o=r[s]??0;const a=i[s]??0;if(o>a)return true;if(o<a)return false}return false}async function readCache(){try{const e=await import_node_fs4.promises.readFile(CACHE_FILE,"utf8");const n=JSON.parse(e);if(typeof n.checkedAt==="number"&&typeof n.latest==="string"){return n}}catch{}return null}async function fetchLatest(e){const n=new AbortController;const t=setTimeout(()=>n.abort(),FETCH_TIMEOUT_MS);try{const r=await fetch(REGISTRY_URL,{signal:n.signal});if(!r.ok)return null;const i=await r.json();const s=typeof i.version==="string"?i.version:null;if(s){await import_node_fs4.promises.writeFile(CACHE_FILE,JSON.stringify({checkedAt:e,latest:s})).catch(()=>{})}return s}catch{return null}finally{clearTimeout(t)}}async function resolveLatest(e){const n=await readCache();if(n&&e-n.checkedAt<CHECK_TTL_MS)return n.latest;return fetchLatest(e)}async function getUpdateNotice(e=Date.now()){if(VERSION==="0.0.0-dev")return null;try{const n=await resolveLatest(e);if(n&&isNewer(n,VERSION)){return`A newer buoy-mcp is available (${n}; you're on ${VERSION}). Update by re-running: npx -y ${PACKAGE_NAME}@latest init \u2014 then restart your editor.`}}catch{}return null}var import_node_fs4,import_node_os4,import_node_path5,CHECK_TTL_MS,FETCH_TIMEOUT_MS,REGISTRY_URL,CACHE_FILE;var init_checkForUpdate=__esm({"src/update/checkForUpdate.ts"(){"use strict";import_node_fs4=require("fs");import_node_os4=__toESM(require("os"));import_node_path5=__toESM(require("path"));init_version();CHECK_TTL_MS=24*60*60*1e3;FETCH_TIMEOUT_MS=1500;REGISTRY_URL=`https://registry.npmjs.org/${PACKAGE_NAME}/latest`;CACHE_FILE=import_node_path5.default.join(import_node_os4.default.tmpdir(),"buoy-mcp-update-check.json")}});function humanizeSimctlError(e){const n=e;if(n?.code==="ENOENT"){return"Xcode command-line tools (xcrun) not found. Install Xcode to capture the iOS Simulator."}const t=String(n?.stderr||n?.message||e);if(/No devices are booted|Unable to find device|current device/i.test(t)){return"No booted iOS Simulator found. Boot the Simulator with your app running, then try again."}return t.trim()||"Failed to capture the iOS Simulator."}function pngSize(e){const n=[137,80,78,71,13,10,26,10];if(e.length<24||!n.every((t,r)=>e[r]===t))return null;return{width:e.readUInt32BE(16),height:e.readUInt32BE(20)}}async function listDir(e){try{return await import_node_fs5.promises.readdir(e)}catch{return[]}}async function webViewInstallIds(e){const n=[];for(const t of await listDir(e))n.push(...await containerWebViewInstallIds(import_node_path6.default.join(e,t)));return n}async function containerWebViewInstallIds(e){const n=[];const t=import_node_path6.default.join(e,"Library","WebKit");for(const r of await listDir(t)){const i=import_node_path6.default.join(t,r,"WebsiteData","Default");for(const s of await listDir(i)){for(const o of await listDir(import_node_path6.default.join(i,s))){const a=import_node_path6.default.join(i,s,o,"LocalStorage","localstorage.sqlite3");try{await import_node_fs5.promises.access(a);const{stdout:c}=await execFileAsync4("sqlite3",["-readonly",a,`SELECT hex(value) FROM ItemTable WHERE key='${WEBVIEW_ID_KEY}' LIMIT 1;`],{timeout:1500});const u=c.trim();if(u)n.push(Buffer.from(u,"hex").toString("utf16le").trim())}catch{}}}}return n}async function resolveSimUdid(e){if(process.platform!=="darwin")return{ok:false,error:"Simulator lookup needs macOS."};let n=[];try{const{stdout:r}=await execFileAsync4("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const i=JSON.parse(r).devices;n=Object.entries(i).filter(([s])=>/iOS/.test(s)).flatMap(([,s])=>s.filter(o=>o.state==="Booted"))}catch(r){return{ok:false,error:humanizeSimctlError(r)}}if(n.length===0)return{ok:false,error:"No iOS Simulator is booted."};const t=e?.split("-").pop();if(t){for(const r of n){if(!r.dataPath)continue;const i=import_node_path6.default.join(r.dataPath,"Containers","Data","Application");let s=[];try{s=await import_node_fs5.promises.readdir(i)}catch{continue}for(const o of s){try{const a=(await import_node_fs5.promises.readFile(import_node_path6.default.join(i,o,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim();if(a===t)return{ok:true,udid:r.udid,how:`matched ${e} to "${r.name}"`}}catch{}}}}if(t&&e){const r=n.map(c=>c.udid).sort().join(",");const i=webViewLookups.get(e);const s=i?.booted===r&&(i.udid!==null||Date.now()-i.at<WEBVIEW_MISS_MS);const o=s&&i?.udid?n.find(c=>c.udid===i.udid):void 0;if(o)return{ok:true,udid:o.udid,how:`matched ${e} to "${o.name}" (WebView storage)`};const a=[];if(!s){const c=await Promise.all(n.map(u=>u.dataPath?webViewInstallIds(import_node_path6.default.join(u.dataPath,"Containers","Data","Application")):Promise.resolve([])));c.forEach((u,l)=>{if(u.includes(t))a.push(n[l])});webViewLookups.set(e,{booted:r,udid:a.length===1?a[0].udid:null,at:Date.now()})}if(a.length===1){return{ok:true,udid:a[0].udid,how:`matched ${e} to "${a[0].name}" (WebView storage)`}}if(a.length>1){return{ok:false,error:`${a.length} booted simulators (${a.map(c=>c.name).join(", ")}) hold ${e}. Pass the udid, or shut one down.`}}}if(n.length===1)return{ok:true,udid:n[0].udid,how:`only booted simulator "${n[0].name}"`};return{ok:false,error:`${n.length} iOS Simulators are booted (${n.map(r=>r.name).join(", ")}) and none could be matched to ${e??"this device"}. Shut down the others, or capture from a single booted simulator.`}}async function resolveSims(e){const n=new Map;if(process.platform!=="darwin"||e.length===0)return n;let t=[];try{const{stdout:i}=await execFileAsync4("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const s=JSON.parse(i).devices;t=Object.entries(s).filter(([o])=>/iOS/.test(o)).flatMap(([,o])=>o.filter(a=>a.state==="Booted"))}catch{return n}const r=new Map;for(const i of t){if(!i.dataPath)continue;const s=import_node_path6.default.join(i.dataPath,"Containers","Data","Application");let o=[];try{o=await import_node_fs5.promises.readdir(s)}catch{continue}for(const a of o){try{const c=(await import_node_fs5.promises.readFile(import_node_path6.default.join(s,a,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim();if(c)r.set(c,{name:i.name,udid:i.udid})}catch{}}}for(const i of e){const s=r.get(i.split("-").pop()??"");if(s)n.set(i,s)}return n}async function captureIosFramebuffer(e="booted"){if(process.platform!=="darwin"){return{ok:false,error:"Screenshotting a component requires macOS with Xcode's iOS Simulator (uses `xcrun simctl`)."}}const n=import_node_path6.default.join(import_node_os5.default.tmpdir(),`buoy-mcp-sim-${(0,import_node_crypto4.randomUUID)()}.png`);try{await execFileAsync4("xcrun",["simctl","io",e,"screenshot","--type=png",n],{timeout:15e3})}catch(t){return{ok:false,error:humanizeSimctlError(t)}}try{const t=await import_node_fs5.promises.readFile(n);const r=pngSize(t);if(!r)return{ok:false,error:"Captured file wasn't a valid PNG."};return{ok:true,srcPath:n,width:r.width,height:r.height}}catch(t){return{ok:false,error:`Failed to read screenshot: ${t.message}`}}}async function cropToBuffer(e,n,t){const r=clamp(Math.round(t.x),0,Math.max(0,n.width-1));const i=clamp(Math.round(t.y),0,Math.max(0,n.height-1));const s=clamp(Math.round(t.width),1,n.width-r);const o=clamp(Math.round(t.height),1,n.height-i);const a=import_node_path6.default.join(import_node_os5.default.tmpdir(),`buoy-mcp-crop-${(0,import_node_crypto4.randomUUID)()}.png`);try{await execFileAsync4("sips",["-c",String(o),String(s),"--cropOffset",String(i),String(r),e,"--out",a],{timeout:1e4});const c=await import_node_fs5.promises.readFile(a);return{ok:true,buffer:c,width:s,height:o}}catch(c){const u=c;return{ok:false,error:`Crop failed: ${u?.stderr||u?.message||c}`}}finally{await import_node_fs5.promises.unlink(a).catch(()=>{});await import_node_fs5.promises.unlink(e).catch(()=>{})}}var import_node_child_process5,import_node_util4,import_node_fs5,import_node_os5,import_node_path6,import_node_crypto4,execFileAsync4,clamp,WEBVIEW_ID_KEY,webViewLookups,WEBVIEW_MISS_MS;var init_simctl=__esm({"src/capture/simctl.ts"(){"use strict";import_node_child_process5=require("child_process");import_node_util4=require("util");import_node_fs5=require("fs");import_node_os5=__toESM(require("os"));import_node_path6=__toESM(require("path"));import_node_crypto4=require("crypto");execFileAsync4=(0,import_node_util4.promisify)(import_node_child_process5.execFile);clamp=(e,n,t)=>Math.min(Math.max(e,n),t);WEBVIEW_ID_KEY="@react_buoy_sync_device_id";webViewLookups=new Map;WEBVIEW_MISS_MS=3e4}});async function listDir2(e){return import_node_fs6.promises.readdir(e).catch(()=>[])}async function containerLocalStorageFiles(e){const n=[];const t=import_node_path7.default.join(e,"Library","WebKit");for(const r of await listDir2(t)){const i=import_node_path7.default.join(t,r,"WebsiteData","Default");for(const s of await listDir2(i)){for(const o of await listDir2(import_node_path7.default.join(i,s))){const a=import_node_path7.default.join(i,s,o);const c=import_node_path7.default.join(a,"LocalStorage","localstorage.sqlite3");if(!await import_node_fs6.promises.access(c).then(()=>true,()=>false))continue;const u=await import_node_fs6.promises.readFile(import_node_path7.default.join(a,"origin")).then(l=>l.toString("hex"),()=>"");if(u)n.push({db:c,origin:u})}}}return n}async function iosReadWebKeep(e){const n=[];for(const{db:t,origin:r}of await containerLocalStorageFiles(e)){const i=await sqlite(t,"SELECT key, hex(value) FROM ItemTable;");for(const s of i.split("\n")){const o=s.lastIndexOf("|");if(o<0)continue;const a=s.slice(0,o);if(WEB_KEEP_KEY.test(a))n.push({key:a,value:s.slice(o+1),origin:r})}}return n}async function iosWriteWebKeep(e,n){if(!n.length)return false;const t=await containerLocalStorageFiles(e);const r=new Set(n.map(i=>i.origin??""));for(const i of r){const s=i?t.find(a=>a.origin===i):void 0;if(!s)return false;const o=n.filter(a=>(a.origin??"")===i&&/^[0-9A-F]*$/i.test(a.value)).map(a=>`('${a.key.replace(/'/g,"''")}', X'${a.value}')`).join(",");if(o)await sqlite(s.db,`INSERT OR REPLACE INTO ItemTable (key, value) VALUES ${o};`,false)}return true}async function iosWaitForLocalStorage(e,n=15e3){const t=Date.now()+n;while(Date.now()<t){if((await containerLocalStorageFiles(e)).length)return true;await new Promise(r=>setTimeout(r,500))}return false}async function evaluateInWebView(e,n,t){const r=(await adbShell(e,`pidof ${n}`).catch(()=>"")).trim().split(/\s+/)[0];if(!r)throw new Error("the app is not running");const i=(await adb(e,["forward","tcp:0",`localabstract:webview_devtools_remote_${r}`])).trim();try{const s=await(await fetch(`http://127.0.0.1:${i}/json`)).json();const o=s.find(a=>a.type==="page"&&a.webSocketDebuggerUrl);if(!o?.webSocketDebuggerUrl)throw new Error("no debuggable WebView page (needs a debug build)");return await new Promise((a,c)=>{const u=new import_ws.WebSocket(o.webSocketDebuggerUrl);const l=setTimeout(()=>{u.close();c(new Error("the WebView did not answer"))},5e3);u.on("open",()=>u.send(JSON.stringify({id:1,method:"Runtime.evaluate",params:{expression:t,returnByValue:true}})));u.on("message",d=>{const h=JSON.parse(String(d));if(h.id!==1)return;clearTimeout(l);u.close();if(h.result?.exceptionDetails)c(new Error("the WebView script failed"));else a(h.result?.result?.value)});u.on("error",d=>{clearTimeout(l);c(d)})})}finally{await adb(e,["forward","--remove",`tcp:${i}`]).catch(()=>void 0)}}async function evaluateWhenReady(e,n,t,r=15e3){const i=Date.now()+r;let s;while(Date.now()<i){try{return await evaluateInWebView(e,n,t)}catch(o){s=o;await new Promise(a=>setTimeout(a,700))}}throw s instanceof Error?s:new Error("the WebView did not open")}async function androidHasWebViewStorage(e,n){const t=await adbShell(e,`run-as ${n} sh -c 'ls app_webview/Default/"Local Storage"/leveldb 2>/dev/null'`).catch(()=>"");return/CURRENT|\.log/.test(t)}async function androidReadWebKeep(e,n){if(!(await adbShell(e,`pidof ${n}`).catch(()=>"")).trim()){await adbShell(e,`monkey -p ${n} -c android.intent.category.LAUNCHER 1`)}const t=await evaluateWhenReady(e,n,`(() => { const re = ${WEB_KEEP_KEY}; const out = []; for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (k && re.test(k)) out.push({ key: k, value: localStorage.getItem(k) }); } return out; })()`);return Array.isArray(t)?t.filter(r=>typeof r.key==="string"&&typeof r.value==="string"):[]}async function androidWriteWebKeep(e,n,t){await evaluateWhenReady(e,n,`(() => { for (const r of ${JSON.stringify(t)}) localStorage.setItem(r.key, r.value); setTimeout(() => location.reload(), 50); return true; })()`)}var import_node_child_process6,import_node_util5,import_node_fs6,import_node_path7,import_ws,execFileAsync5,WEB_KEEP_KEY,sqlite;var init_webViewKeep=__esm({"src/capture/webViewKeep.ts"(){"use strict";import_node_child_process6=require("child_process");import_node_util5=require("util");import_node_fs6=require("fs");import_node_path7=__toESM(require("path"));import_ws=require("ws");init_adb();execFileAsync5=(0,import_node_util5.promisify)(import_node_child_process6.execFile);WEB_KEEP_KEY=/^(@buoy\/session:|buoy-gg-license|buoy-gg-device-fingerprint$|@react_buoy_sync_device_id$|@react_buoy_install)/;sqlite=(e,n,t=true)=>execFileAsync5("sqlite3",[...t?["-readonly"]:[],e,n],{timeout:5e3}).then(r=>r.stdout)}});function rememberedHost(e){return hosts.get(e)}async function sh(e,n,t=2e4){try{const{stdout:r}=await execFileAsync6(e,n,{timeout:t,maxBuffer:16*1024*1024});return r}catch(r){const i=r;if(i.code==="ENOENT")throw new Error(e==="xcrun"?"This needs macOS with Xcode (xcrun simctl).":`${e} is not installed.`);throw new Error(`${e} ${n.slice(0,2).join(" ")} failed: ${(i.stderr||i.message||"").trim().slice(0,300)}`)}}async function simsHolding(e){let n=[];try{const r=JSON.parse(await simctl(["list","devices","booted","-j"])).devices;n=Object.entries(r).filter(([i])=>/iOS/.test(i)).flatMap(([,i])=>i.filter(s=>s.state==="Booted"))}catch{return[]}const t=[];for(const r of n)if(await findIosContainer(e,r.udid))t.push(r);return t}function cloneError(e,n){return new Error(`${n.length} booted simulators hold "${e}" (one is probably a clone): ${n.map(t=>`${t.name} (${t.udid})`).join(", ")}. Pass udid to choose, or shut the extra one down.`)}async function findIosContainer(e,n){const t=tailOf(e);if(!t)return null;let r;try{const o=JSON.parse(await simctl(["list","devices","-j"])).devices;r=Object.values(o).flat().find(a=>a.udid===n)?.dataPath}catch{return null}if(!r)return null;const i=import_node_path8.default.join(r,"Containers","Data","Application");let s=[];try{s=await import_node_fs7.promises.readdir(i)}catch{return null}for(const o of s){const a=import_node_path8.default.join(i,o);if(!await iosContainerHolds(a,t))continue;let c=null;try{c=(await sh("plutil",["-extract","MCMMetadataIdentifier","raw","-o","-",import_node_path8.default.join(a,".com.apple.mobile_container_manager.metadata.plist")])).trim()||null}catch{}return{container:a,bundleId:c}}return null}async function iosContainerHolds(e,n){try{if((await import_node_fs7.promises.readFile(import_node_path8.default.join(e,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim()===n)return true}catch{}return(await containerWebViewInstallIds(e).catch(()=>[])).includes(n)}async function findAndroid(e,n){const t=tailOf(e);const r=n.serial?[n.serial]:await adbSerials();if(r.length===0)throw new Error("No Android device or emulator is connected to adb.");for(const i of r){const s=await adbForegroundPackage(i).catch(()=>null);const o=await adbUserPackages(i).catch(()=>[]);const a=[n.bundleId,s,...o].filter((c,u,l)=>!!c&&l.indexOf(c)===u).slice(0,80);for(const c of a){if(await adbInstallId(i,c).catch(()=>null)===t)return{platform:"android",serial:i,packageName:c}}}return null}async function findPhone(e){const n=tailOf(e);for(const t of await physicalPhones()){for(const r of await developerApps(t.udid).catch(()=>[])){if(await phoneInstallId(t.udid,r.bundleId)===n)return{platform:"ios-device",udid:t.udid,name:t.name,bundleId:r.bundleId}}}return null}async function findHost(e,n,t={}){if(e==="All")throw new Error('Device control acts on one app. Pass its deviceId, not "All".');const r=hosts.get(e);if(r&&!t.udid&&!t.serial&&await stillHolds(e,r)){if(r.platform==="ios"&&!r.picked){const c=await simsHolding(e);if(c.length>1)throw cloneError(e,c)}return r}if(r)hosts.delete(e);if(n==="android"){const c=await findAndroid(e,t);if(!c){throw new Error(`Could not prove which Android device and app run "${e}". Buoy checks the app's install id with run-as, which needs a debug build of the app on a device adb can reach${t.serial?` (looked on ${t.serial})`:""}.`)}hosts.set(e,c);return c}if(n&&n!=="ios")throw new Error(`Device control works on iOS Simulators and Android. This app runs on "${n}".`);if(process.platform!=="darwin")throw new Error("iOS control needs macOS with Xcode.");let i=t.udid;let s=i??"";if(!i){const c=await simsHolding(e);if(c.length>1)throw cloneError(e,c);const u=c.length===1?{ok:true,udid:c[0].udid,how:`matched ${e} to "${c[0].name}"`}:await resolveSimUdid(e);if(!u.ok||!/^matched /.test(u.how)){const l=await findPhone(e).catch(()=>null);if(l){hosts.set(e,l);return l}throw new Error(`Could not find which simulator or iPhone runs "${e}": no booted simulator holds its install id, and no connected iPhone has it (an iPhone must be unlocked, paired, and run a development build).`)}i=u.udid;s=/"([^"]+)"/.exec(u.how)?.[1]??i}const o=await findIosContainer(e,i);if(!o&&t.udid)throw new Error(`Simulator ${t.udid} does not hold "${e}".`);const a={platform:"ios",udid:i,name:s,bundleId:t.bundleId??o?.bundleId??null,container:o?.container??null,picked:!!t.udid};hosts.set(e,a);return a}async function verifyHost(e,n){if(n.platform==="ios"&&!n.picked){const t=await simsHolding(e);if(t.length>1)throw cloneError(e,t)}if(await stillHolds(e,n))return n;hosts.delete(e);return findHost(e,n.platform==="android"?"android":"ios",n.platform==="ios"&&n.picked?{udid:n.udid}:{})}async function stillHolds(e,n){const t=tailOf(e);if(n.platform==="android")return await adbInstallId(n.serial,n.packageName).catch(()=>null)===t;if(n.platform==="ios-device")return await phoneInstallId(n.udid,n.bundleId).catch(()=>null)===t;if(n.container)return iosContainerHolds(n.container,t);const r=await resolveSimUdid(e);return r.ok&&r.udid===n.udid&&/^matched /.test(r.how)}function needApp(e){if(e.platform==="android")return assertPackage(e.packageName);if(e.platform==="ios-device")return e.bundleId;if(!e.bundleId)throw new Error("Could not tell which app this is on the simulator (its container has no bundle metadata).");return e.bundleId}async function hostPng(e){if(e.platform==="android")return adbScreenshot(e.serial);if(e.platform==="ios-device")return phoneScreenshot(e.udid);const n=await captureIosFramebuffer(e.udid);if(!n.ok||!n.srcPath)throw new Error(n.error??"Screenshot failed.");try{return await import_node_fs7.promises.readFile(n.srcPath)}finally{await import_node_fs7.promises.unlink(n.srcPath).catch(()=>{})}}async function toSmallImage(e,n=1280){if(process.platform==="darwin"){const i=import_node_path8.default.join(import_node_os6.default.tmpdir(),`buoy-mcp-img-${(0,import_node_crypto5.randomUUID)()}.png`);const s=i.replace(/\.png$/,".jpg");await import_node_fs7.promises.writeFile(i,e);try{await sh("sips",["-Z",String(n),"-s","format","jpeg","-s","formatOptions","70",i,"--out",s],15e3);const o=await sh("sips",["-g","pixelWidth","-g","pixelHeight",s]);return{data:(await import_node_fs7.promises.readFile(s)).toString("base64"),mimeType:"image/jpeg",width:Number(/pixelWidth:\s*(\d+)/.exec(o)?.[1]??0),height:Number(/pixelHeight:\s*(\d+)/.exec(o)?.[1]??0)}}finally{await import_node_fs7.promises.unlink(i).catch(()=>{});await import_node_fs7.promises.unlink(s).catch(()=>{})}}const t=downscalePng(import_pngjs2.PNG.sync.read(e),Math.min(n,1024));const r=import_pngjs2.PNG.sync.write(t,{colorType:2,deflateLevel:9});return{data:r.toString("base64"),mimeType:"image/png",width:t.width,height:t.height}}function downscalePng(e,n){const t=Math.min(1,n/Math.max(e.width,e.height));if(t===1)return e;const r=Math.max(1,Math.round(e.width*t));const i=Math.max(1,Math.round(e.height*t));const s=new import_pngjs2.PNG({width:r,height:i});const o=e.width/r;const a=e.height/i;for(let c=0;c<i;c++){const u=Math.floor(c*a);const l=Math.max(u+1,Math.floor((c+1)*a));for(let d=0;d<r;d++){const h=Math.floor(d*o);const p=Math.max(h+1,Math.floor((d+1)*o));const m=[0,0,0,0];let g=0;for(let f=u;f<l;f++){for(let b=h;b<p;b++){const v=(f*e.width+b)*4;for(let y=0;y<4;y++)m[y]+=e.data[v+y];g++}}const w=(c*r+d)*4;for(let f=0;f<4;f++)s.data[w+f]=Math.round(m[f]/g)}}return s}async function withSteadyStatusBar(e,n){let t=false;try{if(e.platform==="ios"){const r=await simctl(["status_bar",e.udid,"list"]).catch(()=>"");const i=r.split(/^=+$/m).slice(1).join("").trim();if(!i){await simctl(["status_bar",e.udid,"override","--time","9:41","--batteryState","charged","--batteryLevel","100","--wifiBars","3","--cellularBars","4"]);t=true}}else if(e.platform==="android"){const r=(await adbShell(e.serial,"settings get global sysui_demo_allowed").catch(()=>"")).trim();if(r!=="1"&&!steadying.has(e.serial)){steadying.add(e.serial);await adbDemoMode(e.serial,true);t=true}}if(t)await new Promise(r=>setTimeout(r,400))}catch{t=false}try{return{result:await n(),steadied:t}}finally{if(t){if(e.platform==="ios")await simctl(["status_bar",e.udid,"clear"]).catch(()=>void 0);else if(e.platform==="android"){await adbDemoMode(e.serial,false);await adbShell(e.serial,"settings put global sysui_demo_allowed 0").catch(()=>void 0);steadying.delete(e.serial)}}}}async function hostQuit(e){const n=needApp(e);if(e.platform==="ios-device"){const t=await phoneQuit(e.udid,n);return t?`Quit ${n}.`:`${n} was not running.`}if(e.platform==="ios"){await simctl(["terminate",e.udid,n]).catch(t=>{if(!/found nothing to terminate|not running/i.test(String(t)))throw t})}else{await adbShell(e.serial,`am force-stop ${q(n)}`)}return`Quit ${n}.`}async function hostLaunch(e){const n=needApp(e);if(e.platform==="ios")await simctl(["launch",e.udid,n]);else if(e.platform==="ios-device")await phoneLaunch(e.udid,n);else await adbShell(e.serial,`monkey -p ${q(n)} -c android.intent.category.LAUNCHER 1`);return`Launched ${n}.`}async function hostBackground(e){if(e.platform==="ios-device"){await phoneLaunch(e.udid,"com.apple.Preferences");return"Sent to the background for real (Settings opened on top)."}if(e.platform==="ios"){await simctl(["launch",e.udid,"com.apple.Preferences"]);return"Sent to the background for real (Settings opened on top)."}await adbShell(e.serial,"input keyevent 3");return"Sent to the background for real (pressed Home)."}async function hostOpenUrl(e,n){if(!/^[a-zA-Z][\w+.-]*:/.test(n))throw new Error(`"${n}" is not a link with a scheme (like https://\u2026 or myapp://\u2026).`);if(e.platform==="ios-device"){await phoneOpenUrl(e.udid,n);return"Opened through the OS on the iPhone."}if(e.platform==="ios"){await simctl(["openurl",e.udid,n]);return'Opened through the OS. A custom scheme may first show an "Open in" prompt on the simulator.'}await adbShell(e.serial,`am start -a android.intent.action.VIEW -d ${q(n)}`);return"Opened through the OS (an Android VIEW intent)."}async function appBundleInfo(e){const n=import_node_path8.default.join(e,"Info.plist");const t=o=>sh("plutil",["-extract",o,"raw","-o","-",n]).then(a=>a.trim()).catch(()=>"");const r=await t("CFBundleIdentifier");if(!r)throw new Error(`${e} has no Info.plist with a bundle id. Pass a built .app folder.`);const i=(await sh("plutil",["-extract","CFBundleSupportedPlatforms","json","-o","-",n]).catch(()=>"[]")).toLowerCase();const s=(await t("DTPlatformName")).toLowerCase();return{bundleId:r,simulator:i.includes("iphonesimulator")||s==="iphonesimulator"}}async function apkPackage(e){const n=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT,import_node_path8.default.join(import_node_os6.default.homedir(),"Library","Android","sdk"),import_node_path8.default.join(import_node_os6.default.homedir(),"Android","Sdk")].filter(t=>!!t);for(const t of n){const r=import_node_path8.default.join(t,"build-tools");const i=(await import_node_fs7.promises.readdir(r).catch(()=>[])).sort().reverse();for(const s of i){for(const o of["aapt2","aapt"]){const a=import_node_path8.default.join(r,s,o);try{await import_node_fs7.promises.access(a)}catch{continue}const c=await sh(a,o==="aapt2"?["dump","packagename",e]:["dump","badging",e]).catch(()=>"");const u=o==="aapt2"?c.trim().split("\n")[0]:/package: name='([^']+)'/.exec(c)?.[1]??"";if(u)return u}}}throw new Error("Could not read the APK's package name (needs aapt2 from the Android SDK build-tools). Nothing was changed.")}async function hostReinstall(e,n,t=true){const r=needApp(e);const i=import_node_path8.default.resolve(n);try{await import_node_fs7.promises.access(i)}catch{throw new Error(`No build at ${i}. Pass appPath: the built .app folder (iOS Simulator) or .apk file (Android). Nothing was changed.`)}if(e.platform==="android")return reinstallAndroid(e,r,i,t);if(e.platform==="ios-device")return reinstallPhone(e,r,i,t);if(!/\.app\/?$/i.test(i))throw new Error("On the iOS Simulator, appPath must be a built .app folder. Nothing was changed.");const s=await appBundleInfo(i);if(s.bundleId!==r)throw new Error(`${import_node_path8.default.basename(i)} is ${s.bundleId}, but this app is ${r}. Nothing was changed.`);if(!s.simulator)throw new Error(`${import_node_path8.default.basename(i)} is a device build, not a simulator build. Nothing was changed.`);const o=t?await import_node_fs7.promises.mkdtemp(import_node_path8.default.join(import_node_os6.default.tmpdir(),"buoy-mcp-keep-")):null;try{let a=false;let c=[];if(o){await import_node_fs7.promises.chmod(o,448);const l=(await simctl(["get_app_container",e.udid,r,"data"]).catch(()=>"")).trim();if(l)a=await copyBuoyFiles(import_node_path8.default.join(l,"Documents"),o);if(l&&!a){try{c=await iosReadWebKeep(l)}catch(d){throw new Error(`Couldn't read Buoy's sign-in from the app's WebView storage (${d.message}). Nothing was changed. Pass keepBuoy: false to reinstall anyway.`)}}}await simctl(["terminate",e.udid,r]).catch(()=>void 0);await simctl(["uninstall",e.udid,r]);try{await simctl(["install",e.udid,i],18e4)}catch(l){throw new Error(`The app was removed, but installing ${import_node_path8.default.basename(i)} failed: ${l.message}. Install it again by hand.`)}let u="";if(o&&a){try{const l=(await simctl(["get_app_container",e.udid,r,"data"])).trim();await copyBuoyFiles(o,import_node_path8.default.join(l,"Documents"));e.container=l;u=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(l){u=` Buoy's sign-in could not be restored (${l.message}): sign in to Buoy again in the app.`}}else if(c.length){try{const l=(await simctl(["get_app_container",e.udid,r,"data"])).trim();await simctl(["launch",e.udid,r]);const d=await iosWaitForLocalStorage(l);await simctl(["terminate",e.udid,r]).catch(()=>void 0);if(!d||!await iosWriteWebKeep(l,c))throw new Error("the app made no WebView storage");e.container=l;u=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(l){u=` Buoy's sign-in could not be restored (${l.message}): sign in to Buoy again in the app.`}}else if(t){u=" The old install had no Buoy sign-in to keep."}await simctl(["launch",e.udid,r]);return`Reinstalled ${r} from ${i} and launched it. The app's own data is gone, like a new user.${u}`}finally{if(o)await import_node_fs7.promises.rm(o,{recursive:true,force:true}).catch(()=>void 0)}}async function copyBuoyFiles(e,n){let t=false;for(const r of BUOY_KEEP){const i=import_node_path8.default.join(e,r);try{await import_node_fs7.promises.access(i)}catch{continue}const s=import_node_path8.default.join(n,r);await import_node_fs7.promises.mkdir(import_node_path8.default.dirname(s),{recursive:true});await import_node_fs7.promises.cp(i,s,{recursive:true,force:true});t=true}return t}async function reinstallAndroid(e,n,t,r){if(!/\.apk$/i.test(t))throw new Error("On Android, appPath must be an .apk file. Nothing was changed.");const i=await apkPackage(t);if(i!==n)throw new Error(`${import_node_path8.default.basename(t)} is ${i}, but this app is ${n}. Nothing was changed.`);const s=[];if(r){const c=await adbShell(e.serial,`run-as ${q(n)} find files/buoy-license files/react-buoy -maxdepth 1 -type f 2>/dev/null`).catch(()=>"");const u=c.split("\n").map(l=>l.trim()).filter(l=>l.startsWith("files/buoy-license/")||/react-buoy\/@react_buoy_(sync_device_id|install)\.json$/.test(l));for(const l of u){const d=await adbShell(e.serial,`run-as ${q(n)} base64 ${q(l)}`).catch(()=>"");if(d.trim())s.push({rel:l,data:d.replace(/\s+/g,"")})}}let o=[];if(r&&!s.length&&await androidHasWebViewStorage(e.serial,n)){try{o=await androidReadWebKeep(e.serial,n)}catch(c){throw new Error(`Couldn't read Buoy's sign-in from the app's WebView (${c.message}). Nothing was changed. Pass keepBuoy: false to reinstall anyway.`)}}await adb(e.serial,["install","-r","-d",t],18e4);await adbShell(e.serial,`pm clear ${q(n)}`);let a="";if(o.length){await hostLaunch(e);try{await androidWriteWebKeep(e.serial,n,o);a=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(c){a=` Buoy's sign-in could not be restored (${c.message}): sign in to Buoy again in the app.`}return`Reinstalled ${n} from ${t} and launched it. The app's data is gone, like a new user.${a}`}if(s.length){try{for(const c of s){const u=import_node_path8.default.posix.dirname(c.rel);await adbShell(e.serial,`echo ${q(c.data)} | run-as ${q(n)} sh -c ${q(`mkdir -p ${q(u)} && base64 -d > ${q(c.rel)}`)}`)}a=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(c){a=` Buoy's sign-in could not be restored (${c.message}): sign in to Buoy again in the app.`}}else if(r){a=" No Buoy sign-in could be read to keep (needs a debug build): sign in to Buoy again in the app."}await hostLaunch(e);return`Reinstalled ${n} from ${t} and launched it. The app's data is gone, like a new user.${a}`}async function reinstallPhone(e,n,t,r){if(!/\.app\/?$/i.test(t))throw new Error("On an iPhone, appPath must be a built .app folder (a device build). Nothing was changed.");const i=await appBundleInfo(t);if(i.bundleId!==n)throw new Error(`${import_node_path8.default.basename(t)} is ${i.bundleId}, but this app is ${n}. Nothing was changed.`);if(i.simulator)throw new Error(`${import_node_path8.default.basename(t)} is a simulator build, not a device build. Nothing was changed.`);const s=["Documents/buoy-license/buoy-gg-license.json","Documents/react-buoy/@react_buoy_sync_device_id.json","Documents/react-buoy/@react_buoy_install.json"];const o=r?await import_node_fs7.promises.mkdtemp(import_node_path8.default.join(import_node_os6.default.tmpdir(),"buoy-mcp-keep-")):null;try{const a=[];if(o){await import_node_fs7.promises.chmod(o,448);for(const u of s){let l;try{l=await readAppFile(e.udid,n,u)}catch(h){throw new Error(`Could not back up Buoy's ${import_node_path8.default.basename(u)} from the iPhone (${h.message}). Nothing was changed.`)}if(!l)continue;const d=import_node_path8.default.join(o,u.replace(/\//g,"__"));await import_node_fs7.promises.writeFile(d,l,{mode:384});a.push({rel:u,local:d})}}await phoneQuit(e.udid,n).catch(()=>false);await phoneUninstall(e.udid,n);try{await phoneInstall(e.udid,t)}catch(u){throw new Error(`The app was removed, but installing ${import_node_path8.default.basename(t)} failed: ${u.message}. Install it again from Xcode.`)}let c="";if(a.length){try{for(const d of a)await writeAppFile(e.udid,n,d.local,d.rel);const u=a.some(d=>d.rel.includes("buoy-license"));const l=a.some(d=>d.rel.includes("sync_device_id"));c=u?` Kept Buoy's sign-in${l?" and device id, so the same deviceId still works":""}.`:` Kept the device id; there was no Buoy sign-in to keep, so sign in to Buoy in the app.`}catch(u){c=` Buoy's sign-in could not be restored (${u.message}): sign in to Buoy again in the app.`}}else if(r)c=" The old install had no Buoy sign-in to keep.";await phoneLaunch(e.udid,n);return`Reinstalled ${n} on the iPhone and launched it. The app's own data is gone, like a new user.${c}`}finally{if(o)await import_node_fs7.promises.rm(o,{recursive:true,force:true}).catch(()=>void 0)}}async function bootSimulator(e){const n=JSON.parse(await simctl(["list","devices","available","-j"])).devices;const t=Object.entries(n).filter(([a])=>/iOS/.test(a)).flatMap(([,a])=>a);const r=e.trim().toLowerCase();const i=t.filter(a=>a.udid.toLowerCase()===r||a.name.toLowerCase()===r);const s=i.length?i:t.filter(a=>a.name.toLowerCase().includes(r));if(s.length===0)throw new Error(`No iOS Simulator matches "${e}". Run \`xcrun simctl list devices available\` to see them.`);if(s.length>1)throw new Error(`${s.length} simulators match "${e}": ${s.map(a=>`${a.name} (${a.udid})`).join(", ")}. Pass the udid.`);const o=s[0];if(o.state!=="Booted")await simctl(["boot",o.udid],12e4);await sh("open",["-a","Simulator","--args","-CurrentDeviceUDID",o.udid]).catch(()=>void 0);return o.state==="Booted"?`${o.name} (${o.udid}) was already booted.`:`Booted ${o.name} (${o.udid}).`}var import_node_child_process7,import_node_util6,import_node_fs7,import_node_os6,import_node_path8,import_node_crypto5,import_pngjs2,execFileAsync6,hosts,simctl,tailOf,steadying,BUOY_KEEP;var init_hostDevice=__esm({"src/capture/hostDevice.ts"(){"use strict";import_node_child_process7=require("child_process");import_node_util6=require("util");import_node_fs7=require("fs");import_node_os6=__toESM(require("os"));import_node_path8=__toESM(require("path"));import_node_crypto5=require("crypto");import_pngjs2=__toESM(require_png());init_simctl();init_iosDevice();init_webViewKeep();init_adb();execFileAsync6=(0,import_node_util6.promisify)(import_node_child_process7.execFile);hosts=new Map;simctl=(e,n)=>sh("xcrun",["simctl",...e],n);tailOf=e=>e.split("-").pop()??"";steadying=new Set;BUOY_KEEP=["buoy-license","react-buoy/@react_buoy_sync_device_id.json","react-buoy/@react_buoy_install.json"]}});async function hostTarget(e,n,t={},r={}){if(n==="All")throw new Error('Device control acts on one app. Pass its deviceId, not "All".');let i;let s=true;try{i=e.requireProDevice(n)}catch(c){const u=c instanceof Error?c.message:String(c);const l=u.startsWith(NOT_READY_MARK)&&/is not connected right now/.test(u)?/"([^"]+)"/.exec(u)?.[1]:void 0;const d=l?e.listDevices().some(h=>h.deviceId===l&&h.isPro):false;if(!r.allowOffline||!l||!d)throw c;i=l;s=false}const o=e.listDevices().find(c=>c.deviceId===i)?.platform;let a=await findHost(i,o,t);if(r.changesApp&&rememberedHost(i)===a)a=await verifyHost(i,a);return{id:i,host:a,online:s}}function hostLabel(e){if(e.platform==="ios")return`simulator "${e.name}"`;if(e.platform==="ios-device")return`iPhone "${e.name}"`;return`Android device ${e.serial}`}function has(e){if(!onPath.has(e))onPath.set(e,execFileAsync7("which",[e],{timeout:3e3}).then(()=>true,()=>false));return onPath.get(e)}async function hostSummary(e,n){let t=n;if(e.platform==="android"){const i=rememberedHost(e.deviceId);const s=i??(e.isConnected?await Promise.race([findHost(e.deviceId,"android").catch(()=>void 0),new Promise(a=>setTimeout(()=>a(void 0),3e3))]):void 0);const o=await has("adb");return{kind:"android",...s&&s.platform==="android"?{id:s.serial,name:s.packageName}:{},can:["screenshot","screen_recording","baseline diffs","quit/launch/reinstall","real lifecycle events","native_tap/type/swipe"],...!o?{missing:["adb (Android SDK platform-tools)"]}:!s?{missing:["proof of which phone runs it (needs a debug build reachable by adb)"]}:{}}}if(e.platform!=="ios")return{kind:e.platform??"unknown",can:[],missing:["host control works on iOS and Android apps"]};let r=rememberedHost(e.deviceId);if(!r&&!t&&e.isConnected){r=await Promise.race([findHost(e.deviceId,"ios").catch(()=>void 0),new Promise(i=>setTimeout(()=>i(void 0),4e3))])}if(!t&&r?.platform==="ios")t={name:r.name,udid:r.udid};if(r?.platform==="ios-device"){return{kind:"physical iPhone",id:r.udid,name:r.name,can:["screenshot","screen_recording (if this iPhone supports it)","baseline diffs","quit/launch/reinstall","open_url","native_tap/type/swipe (by query, testID, nativeTag or x/y; not label)"]}}if(t){const i=await has("idb");return{kind:"ios simulator",id:t.udid,name:t.name,can:["screenshot","screen_recording","baseline diffs","quit/launch/reinstall/boot","real lifecycle events",...i?["native_tap/type/swipe"]:[]],...i?{}:{missing:["idb for real touches (brew install facebook/fb/idb-companion && pipx install fb-idb)"]}}}return void 0}var import_node_child_process8,import_node_util7,execFileAsync7,onPath;var init_hostKit=__esm({"src/tools/hostKit.ts"(){"use strict";init_SyncClient();import_node_child_process8=require("child_process");import_node_util7=require("util");init_hostDevice();execFileAsync7=(0,import_node_util7.promisify)(import_node_child_process8.execFile);onPath=new Map}});function json(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function fail(e){return{isError:true,content:[{type:"text",text:e}]}}function registerGenericTools(e,n){e.registerTool("list_devices",{description:"List the apps connected to Buoy: id, name, platform, whether it is connected and has MCP access, the simulator or phone it runs on with the host controls that work there (screenshot, recording, app control, real touches) and anything missing, and the Buoy tools it exposes. Start here. Pass details:true for every tool's action names.",inputSchema:{details:import_zod.z.boolean().optional().describe("Also list every action of every tool. Default false (tool names only); list_tool_actions gives one tool's actions."),includeDisconnected:import_zod.z.boolean().optional().describe("Also list apps that were seen before but are not connected now. Default false.")}},async(t={})=>{const r=await getUpdateNotice();let i=n.listDevices();for(let p=0;i.length===0&&p<10;p++){await new Promise(m=>setTimeout(m,200));i=n.listDevices()}if(i.length===0){return json({devices:[],hint:"No devices connected. Open the app with Buoy devtools running, then retry.",...r?{updateAvailable:r}:{}})}const s=t.includeDisconnected?0:i.filter(p=>!p.isConnected).length;if(!t.includeDisconnected)i=i.filter(p=>p.isConnected);if(i.length===0){return json({devices:[],hint:`No app is connected right now${s?` (${s} seen before; pass includeDisconnected:true to list them)`:""}. Open the app with Buoy devtools running, then retry.`,...r?{updateAvailable:r}:{}})}const o=await resolveSims(i.filter(p=>p.platform==="ios").map(p=>p.deviceId)).catch(()=>new Map);const a=i.filter(p=>p.isConnected);const c=a.some(p=>p.isPro);const u=a.some(p=>p.tier!=="locked");const l=a.filter(p=>p.collision);const d=await Promise.all(i.map(p=>p.isConnected?hostSummary(p,o.get(p.deviceId)).catch(()=>void 0):void 0));const h=i.map((p,m)=>{const g=o.get(p.deviceId);const w=d[m];return{deviceId:p.deviceId,deviceName:p.deviceName,platform:p.platform,isConnected:p.isConnected,isPro:p.isPro,tier:p.tier,access:n.accessState(p.deviceId),...g?{simulator:g}:{},...w?{host:w}:{},...p.collision?{collision:true}:{},tools:t.details?p.tools:p.tools.map(f=>f.toolId)}});return json({devices:h,...t.details?{}:{note:`Tool names only. Pass details:true, or list_tool_actions({toolId}), for action names.${s?` ${s} apps seen before but not connected now are left out (includeDisconnected:true lists them).`:""}`},...l.length>0?{warning:`${l.map(p=>`"${p.deviceId}"`).join(", ")}: more than one app is registered under this id, so actions sent to it land on an arbitrary device. Give each device its own externalSync.deviceId (or leave it unset for a per-install default) before mutating anything.`}:{},...c?{}:{hint:u?"The Buoy MCP is a Pro feature \u2014 the connected device is signed in on the free tier, so data/action tools are blocked. Upgrade to Buoy Pro in the app, or pass `licenseKey` to `<FloatingDevTools />` if it runs headless.":"The broker has not confirmed account access for the connected devices, so data/action tools are blocked. A locked status can mean missing configuration, pending/failed validation, or a missing account announcement after reconnect; it does not prove the user is signed out. Check app account status and broker compatibility."},...r?{updateAvailable:r}:{}})});e.registerTool("list_tool_actions",{description:"List the actions a tool exposes, and which connected devices offer it. Leave toolId out to list every tool's actions. Use the action names with call_action.",inputSchema:{toolId:import_zod.z.string().optional().describe('The tool id, e.g. "perf-monitor", "network", "react-query". Leave out for every tool.'),tool:import_zod.z.string().optional().describe("Same as toolId."),deviceId:import_zod.z.string().optional().describe("Only list what this device offers.")}},async({toolId:t,tool:r,deviceId:i})=>{const s=t??r;if(!s){const c=n.connectedDevices().filter(l=>!i||l.deviceId===i);if(c.length===0)return fail(i?`No connected device "${i}". Call list_devices.`:"No devices are connected. Call list_devices.");const u=c.map(l=>[`**${l.deviceName}** (${l.deviceId})`,...l.tools.map(d=>`- ${d.toolId}: ${d.actions.join(", ")}`)].join("\n"));return{content:[{type:"text",text:`${u.join("\n\n")}
|
|
54
|
+
`}function escapeHtml(e){return e.replace(/[&<>"']/g,n=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[n])}var import_node_child_process4,import_node_util3,import_node_fs2,import_node_path2,MAX_RECORDING_MS,live,MAX_BURN_DOTS,execFileAsync3;var init_recorder=__esm({"src/capture/recorder.ts"(){"use strict";import_node_child_process4=require("child_process");import_node_util3=require("util");import_node_fs2=require("fs");import_node_path2=__toESM(require("path"));init_adb();init_iosDevice();MAX_RECORDING_MS=3*6e4;live=new Set;MAX_BURN_DOTS=300;execFileAsync3=(0,import_node_util3.promisify)(import_node_child_process4.execFile)}});function readProjectKey(e,n=process.env){for(const t of KEY_NAMES)if(n[t]!==void 0)return(0,import_headless.normalizeLicenseKey)(n[t])||null;for(const t of[".env.development.local",".env.local",".env"]){let r;try{r=(0,import_node_fs3.readFileSync)((0,import_node_path3.join)(e,t),"utf8")}catch{continue}const i=new Map;for(const o of r.split(/\r?\n/)){const s=o.match(/^\s*(?:export\s+)?([A-Z_][A-Z_0-9]*)\s*=\s*(.*)$/);if(!s)continue;const a=s[2].trim();const c=a.match(/^(['"])(.*?)\1\s*(?:#.*)?$/);i.set(s[1],c?c[2]:a.split("#")[0].trim())}for(const o of KEY_NAMES)if(i.has(o))return(0,import_headless.normalizeLicenseKey)(i.get(o))||null}return null}var import_node_fs3,import_node_path3,import_node_os2,import_node_crypto2,import_headless,KEY_NAMES,NodeAccount;var init_NodeAccount=__esm({"src/sync/NodeAccount.ts"(){"use strict";import_node_fs3=require("fs");import_node_path3=require("path");import_node_os2=require("os");import_node_crypto2=require("crypto");import_headless=require("@buoy-gg/license/headless");KEY_NAMES=["BUOY_LICENSE_KEY","BUOY_KEY","EXPO_PUBLIC_BUOY_KEY","VITE_BUOY_KEY","NEXT_PUBLIC_BUOY_KEY","REACT_APP_BUOY_KEY"];NodeAccount=class{constructor(e,n={}){this.changed=e;this.key=null;this.cache=null;this.timer=null;this.unsubscribeSession=null;this.generation=0;this.busy=false;this.nextCheck=0;this.retry=0;this.lastAdmission=false;this.hasAccess=()=>this.hasKeyAccess()||this.session?.getStatus().state==="active";this.lastSessionSync=0;this.projectDir=(0,import_node_path3.resolve)(n.projectDir??process.env.BUOY_PROJECT_DIR??process.cwd());const t=(0,import_node_crypto2.createHash)("sha256").update(this.projectDir).digest("hex").slice(0,20);this.cacheFile=n.cacheFile??(0,import_node_path3.join)((0,import_node_os2.homedir)(),".buoy",`account-${t}.json`);this.session=n.session!==void 0?n.session:(0,import_headless.createNodeSession)({audience:import_headless.CLI_AUDIENCE,openBrowser:()=>{throw new Error("The MCP does not open a browser. Run `npx buoy login`.")}})}hasKeyAccess(){return(0,import_headless.resolveAccountAccess)({initialized:true,validating:false,key:this.key,tierSource:this.cache?.tier?"key":"none",verifiedAt:this.cache?.cachedAt??null}).status==="admitted"}start(){if(this.timer)return;if(this.session){this.unsubscribeSession=this.session.subscribe(()=>this.notify());void this.session.load().then(()=>this.notify(),()=>{})}try{const e=JSON.parse((0,import_node_fs3.readFileSync)(this.cacheFile,"utf8"));if(e.valid&&(0,import_headless.verifyCacheSignature)(e))this.cache=e}catch{}void this.tick();this.timer=setInterval(()=>{void this.tick()},1e3);this.timer.unref()}stop(){++this.generation;this.unsubscribeSession?.();this.unsubscribeSession=null;if(this.timer)clearInterval(this.timer);this.timer=null;this.key=null;this.cache=null;this.notify()}notify(){const e=this.hasAccess();if(e===this.lastAdmission)return;this.lastAdmission=e;this.changed()}async tick(){if(this.session&&Date.now()-this.lastSessionSync>15e3){this.lastSessionSync=Date.now();void this.session.sync().catch(()=>{})}const e=readProjectKey(this.projectDir);if(e!==this.key){++this.generation;this.key=e;if(this.cache?.licenseKey!==e)this.cache=null;this.nextCheck=0;this.retry=0;if(!e)this.removeCache()}this.notify();if(!e||this.busy||Date.now()<this.nextCheck)return;if(this.cache&&this.hasKeyAccess()&&Date.now()-this.cache.lastValidatedAt<import_headless.LICENSE_LAUNCH_VALIDATION_TTL&&this.nextCheck===0){this.nextCheck=this.cache.lastValidatedAt+import_headless.LICENSE_LAUNCH_VALIDATION_TTL;return}this.busy=true;const n=this.generation;try{if((0,import_headless.isDevToken)(e)){const a=(0,import_headless.checkDevToken)(e);if(!a.ok){this.cache=null;this.removeCache()}else{const c=Math.min(Date.now(),a.claims.iat*1e3);const l=a.claims.tier==="free"?"free":"pro";this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`dev:${a.claims.sid}`,valid:true,tier:l,isPro:l==="pro",expiresAt:new Date(a.claims.exp*1e3).toISOString(),cachedAt:c,lastValidatedAt:Date.now()});this.persistCache()}this.nextCheck=Date.now()+import_headless.LICENSE_REVALIDATION_INTERVAL;return}if((0,import_headless.isServiceKey)(e)){const a=await(0,import_headless.exchangeServiceKey)(e,{origin:process.env.BUOY_SITE_URL||"https://buoy.gg"});if(n!==this.generation||readProjectKey(this.projectDir)!==e)return;if(!a.ok){if(a.reason==="rejected"){this.cache=null;this.removeCache();this.nextCheck=Date.now()+import_headless.LICENSE_REVALIDATION_INTERVAL}else{this.nextCheck=Date.now()+(import_headless.LICENSE_TRANSIENT_RETRY_DELAYS[this.retry++]??import_headless.LICENSE_REVALIDATION_INTERVAL)}return}const c=Date.now();const l=a.claims.exp*1e3;this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`service:${a.claims.sid}`,valid:true,tier:"pro",isPro:true,expiresAt:new Date(l).toISOString(),cachedAt:c,lastValidatedAt:c});this.persistCache();this.retry=0;this.nextCheck=Math.max(c+6e4,l-60*60*1e3);return}if((0,import_headless.isBuoyToken)(e)){const a=(0,import_headless.verifyFreeToken)(e);if(!a){this.cache=null;this.removeCache()}else{const c=Date.now();this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`token:${a.accountHash}`,valid:true,tier:"free",isPro:false,expiresAt:null,cachedAt:c,lastValidatedAt:c});this.persistCache()}this.nextCheck=Date.now()+import_headless.LICENSE_REVALIDATION_INTERVAL;return}const t=await(0,import_headless.validateLicense)(e);if(n!==this.generation||readProjectKey(this.projectDir)!==e)return;const r=t.data?.relationships?.product?.data?.id;const i=t.meta.code==="EXPIRED"&&((0,import_headless.isRecognizedAccount)(t.data)||this.cache?.licenseKey===e);if(r&&r!==import_headless.KEYGEN_CONFIG.productId||!i&&!(0,import_headless.isAcceptedValidation)(t)){this.cache=null;this.removeCache();this.nextCheck=Date.now()+import_headless.LICENSE_REVALIDATION_INTERVAL;return}const o=i?"free":(0,import_headless.resolveTier)(t.data);const s=Date.now();this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:t.data?.id??"",valid:true,tier:o,isPro:o==="pro",expiresAt:i?null:t.data.attributes.expiry,cachedAt:s,lastValidatedAt:s});this.persistCache();this.retry=0;this.nextCheck=s+import_headless.LICENSE_REVALIDATION_INTERVAL}catch(t){if(n!==this.generation)return;const r=(0,import_headless.isTransientLicenseError)(t)?import_headless.LICENSE_TRANSIENT_RETRY_DELAYS[this.retry++]:void 0;this.nextCheck=Date.now()+(r??import_headless.LICENSE_REVALIDATION_INTERVAL)}finally{this.busy=false;this.notify()}}persistCache(){try{(0,import_node_fs3.mkdirSync)((0,import_node_path3.dirname)(this.cacheFile),{recursive:true,mode:448});(0,import_node_fs3.writeFileSync)(`${this.cacheFile}.tmp`,JSON.stringify(this.cache),{mode:384});(0,import_node_fs3.renameSync)(`${this.cacheFile}.tmp`,this.cacheFile)}catch{}}removeCache(){try{(0,import_node_fs3.unlinkSync)(this.cacheFile)}catch{}}}}});var import_sync_broker,BROKER_PORT,BROKER_URL,DEFAULT_ACTION_TIMEOUT_MS,UNRESPONSIVE_ACTION_TIMEOUT_MS,UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS,RECOVERY_PROBE_MS,UNRESPONSIVE_AFTER_MS,DEFAULT_SNAPSHOT_TIMEOUT_MS,DEVICE_RETENTION_MS,DASHBOARD_NAME,ALL_DEVICES;var init_config=__esm({"src/config.ts"(){"use strict";import_sync_broker=require("@buoy-gg/sync-broker");BROKER_PORT=import_sync_broker.DEFAULT_BROKER_PORT;BROKER_URL=`http://localhost:${BROKER_PORT}`;DEFAULT_ACTION_TIMEOUT_MS=15e3;UNRESPONSIVE_ACTION_TIMEOUT_MS=2500;UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS=1200;RECOVERY_PROBE_MS=2e4;UNRESPONSIVE_AFTER_MS=3e4;DEFAULT_SNAPSHOT_TIMEOUT_MS=5e3;DEVICE_RETENTION_MS=15*6e4;DASHBOARD_NAME="Dashboard";ALL_DEVICES="All"}});async function devServerRoot(e){let n;try{n=new URL(e)}catch{return null}if(!isLocalHost(n.hostname))return null;const t=n.port||(n.protocol==="https:"?"443":"80");try{const{stdout:r}=await execFileAsync4("lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"],{timeout:3e3});const i=r.split("\n").map(a=>a.trim()).find(Boolean);if(!i)return null;const{stdout:o}=await execFileAsync4("lsof",["-a","-p",i,"-d","cwd","-Fn"],{timeout:3e3});const s=o.split("\n").find(a=>a.startsWith("n"));return s?import_node_path4.default.resolve(s.slice(1)):null}catch{return null}}function isLocalHost(e,n=import_node_os3.default.networkInterfaces()){const t=e.replace(/^\[|\]$/g,"").toLowerCase();if(t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="10.0.2.2"||t==="10.0.3.2")return true;return Object.values(n).flat().some(r=>r?.address?.toLowerCase()===t)}function pickByProject(e,n){const t=import_node_path4.default.resolve(n);const r=e.map(s=>({deviceId:s.deviceId,score:s.root?closeness(import_node_path4.default.resolve(s.root),t):-1})).filter(s=>s.score>=0);if(r.length===0)return null;const i=Math.min(...r.map(s=>s.score));const o=r.filter(s=>s.score===i);return o.length===1?o[0].deviceId:null}function closeness(e,n){if(e===n)return 0;const t=import_node_path4.default.relative(e,n);const r=import_node_path4.default.relative(n,e);const i=o=>o&&!o.startsWith("..")&&!import_node_path4.default.isAbsolute(o);if(i(t))return t.split(import_node_path4.default.sep).length;if(i(r))return r.split(import_node_path4.default.sep).length;return-1}var import_node_child_process5,import_node_util4,import_node_path4,import_node_os3,execFileAsync4;var init_projectRoot=__esm({"src/sync/projectRoot.ts"(){"use strict";import_node_child_process5=require("child_process");import_node_util4=require("util");import_node_path4=__toESM(require("path"));import_node_os3=__toESM(require("os"));execFileAsync4=(0,import_node_util4.promisify)(import_node_child_process5.execFile)}});function isRecoveryAction(e,n){return e==="app"&&(n==="ping"||n==="reloadApp")}function isUnresponsive(e){return e>=2}function actionTimeoutMs(e){if(isRecoveryAction(e.toolId,e.action)){return{timeoutMs:e.fullMs,usedFullBudget:false}}if(!isUnresponsive(e.consecutiveTimeouts)){return{timeoutMs:e.fullMs,usedFullBudget:false}}if(e.now-e.lastFullBudgetAt>e.recoveryProbeMs){return{timeoutMs:e.fullMs,usedFullBudget:true}}return{timeoutMs:e.shortMs,usedFullBudget:false}}function diagnoseCrashed(e){if(e.consecutiveTimeouts>=2)return true;if(e.lastOkAt>0&&e.now-e.lastOkAt>e.unresponsiveAfterMs){return true}return false}var init_actionTimeout=__esm({"src/sync/actionTimeout.ts"(){"use strict"}});function probeBroker(e,n=800){return new Promise(t=>{const r=import_node_http.default.get(e,i=>{i.resume();t((i.statusCode??0)>0)});r.setTimeout(n,()=>{r.destroy();t(false)});r.on("error",()=>t(false))})}async function waitForBroker(e,n=20){for(let t=0;t<n;t++){if(await probeBroker(e,300))return;await delay(50)}throw new Error(`Spawned broker never became reachable at ${e}`)}var import_node_http,import_node_crypto3,import_socket,import_sync_broker2,NOT_READY_MARK,SyncClient,snapKey,delay;var init_SyncClient=__esm({"src/sync/SyncClient.ts"(){"use strict";init_NodeAccount();import_node_http=__toESM(require("http"));import_node_crypto3=require("crypto");import_socket=require("socket.io-client");import_sync_broker2=require("@buoy-gg/sync-broker");init_config();init_projectRoot();init_actionTimeout();NOT_READY_MARK="Not ready:";SyncClient=class{constructor(e={}){this.socket=null;this.admitted=false;this.createdAt=Date.now();this.lockedDevices=new Set;this.hostAccount=null;this.broker=null;this.capabilities=new Map;this.devices=[];this.sessionDevice=null;this.snapshots=new Map;this.watching=new Map;this.pendingActions=new Map;this.snapshotWaiters=new Map;this.snapshotAt=new Map;this.health=new Map;this.devServerOrigins=new Map;this.crashSeen=new Map;this.rootLookups=new Set;this.devServerRoots=new Map;this.originProbed=new Set;this.lastSeen=new Map;this.deviceConnections=new Map;this.port=e.port??BROKER_PORT;this.url=e.url??(e.port?`http://localhost:${e.port}`:BROKER_URL);this.actionTimeoutMs=e.actionTimeoutMs??DEFAULT_ACTION_TIMEOUT_MS;this.log=e.log??(n=>process.stderr.write(`[buoy-mcp] ${n}
|
|
55
|
+
`));this.autoSpawn=e.autoSpawnBroker??true}async start(){const e=await probeBroker(this.url)||await probeBroker(this.url,8e3);let n="connected";if(!e){if(!this.autoSpawn){throw new Error(`No Buoy broker reachable at ${this.url} and autoSpawnBroker is off. Start the Buoy desktop app, or enable autoSpawnBroker.`)}this.log(`no broker at ${this.url} \u2014 spawning one in-process on :${this.port}`);this.hostAccount=new NodeAccount(()=>this.broker?.refreshAccess());this.hostAccount.start();let t=false;this.broker=(0,import_sync_broker2.createBroker)({canUseDesktop:this.hostAccount.hasAccess,port:this.port,onError:r=>{if(r.code==="EADDRINUSE")t=true;this.log(`broker error: ${r.code??r.message}`)}});await waitForBroker(this.url).catch(r=>{if(!t)throw r});if(!this.broker.httpServer.listening)t=true;if(t){this.log(`another broker holds :${this.port} \u2014 connecting to it as a dashboard`);await this.broker.close().catch(()=>void 0);this.broker=null;this.hostAccount.stop();this.hostAccount=null;await this.connectSocket();return"connected"}try{(0,import_sync_broker2.writeBrokerToken)(this.broker.dashboardToken,(0,import_sync_broker2.brokerTokenPath)(this.port))}catch(r){this.log(`could not write the broker token file: ${r.message}`)}n="spawned"}else{this.log(`found a running broker at ${this.url} \u2014 connecting as a dashboard`)}await this.connectSocket();return n}connectSocket(){return new Promise((e,n)=>{const t=(0,import_socket.io)(this.url,{transports:["websocket"],query:{deviceName:DASHBOARD_NAME},auth:a=>{const c=this.broker?.dashboardToken??(0,import_sync_broker2.readBrokerToken)((0,import_sync_broker2.brokerTokenPath)(this.port));a(c?{dashboardToken:c}:{})},reconnection:true,reconnectionDelay:500,timeout:4e3});this.socket=t;let r=false;const i=()=>{if(r)return;r=true;this.log("connected to broker");e()};const o=setTimeout(()=>{if(r)return;r=true;n(new Error("Broker account is locked or the broker needs an update. Sign in to Buoy Desktop or run npx buoy login for standalone MCP."))},5e3);t.on("buoy:access",a=>{const c=!!a&&typeof a==="object"&&a.protocol===1&&a.ready===true;this.setAdmission(c);if(c){clearTimeout(o);this.rearmWatches();i()}});t.on("connect",()=>{t.emit("buoy:access:request")});t.on("disconnect",()=>this.setAdmission(false,true));const s=a=>a.message===import_sync_broker2.DASHBOARD_TOKEN_REQUIRED;t.once("connect_error",a=>{if(r)return;r=true;clearTimeout(o);n(new Error(s(a)?`The broker at ${this.url} refused this MCP as a dashboard: the token in ${(0,import_sync_broker2.brokerTokenPath)(this.port)} is missing or stale. Update Buoy Desktop, or restart it so it writes the file.`:`failed to connect to broker at ${this.url}: ${a.message}`))});t.on("connect_error",a=>{if(!s(a)||t.active)return;setTimeout(()=>{if(this.socket===t&&!t.connected)t.connect()},1e3).unref?.()});t.on("devtool-capabilities",a=>{if(!this.admitted||this.lockedDevices.has(a.persistentDeviceId))return;this.capabilities.set(a.persistentDeviceId,a);this.trackRootLookup(this.learnDevServerOrigin(a.persistentDeviceId));if(a.tools?.some(c=>c.toolId==="console"))this.ensureWatching("console",a.persistentDeviceId)});t.on("all-devices-update",a=>{if(!this.admitted)return;if(!Array.isArray(a))return;let c=false;for(const u of a){if(u.deviceId&&u.tier==="locked")this.lockDevice(String(u.deviceId));else if(u.deviceId&&(u.tier==="free"||u.tier==="pro")){c=this.lockedDevices.delete(String(u.deviceId))||c}}this.devices=a;const l=Date.now();for(const u of a)if(u.deviceId)this.lastSeen.set(u.deviceId,l);this.pruneStaleDevices();if(c)this.rearmWatches();else this.rearmReconnectedDevices(a)});t.on("devtool-sync",a=>{if(!this.admitted||this.lockedDevices.has(a.persistentDeviceId))return;const c=snapKey(a.persistentDeviceId,a.toolId);this.snapshots.set(c,a.payload);this.snapshotAt.set(c,Date.now());if(a.toolId==="console")this.noteCrashReport(a.persistentDeviceId,a.payload);const l=this.snapshotWaiters.get(c);if(l&&l.length){this.snapshotWaiters.set(c,[]);for(const u of l)u(a.payload)}});t.on("devtool-action-result",a=>{if(!this.admitted)return;const c=this.pendingActions.get(a.requestId);if(!c)return;this.pendingActions.delete(a.requestId);clearTimeout(c.timer);c.resolve(a)})})}requireAdmission(){if(!this.admitted)throw new Error("A verified Buoy account and an updated broker are required. Sign in to Buoy Desktop, or run npx buoy login for standalone MCP.")}setAdmission(e,n=false){this.admitted=e;if(e)return;this.devices=[];this.lockedDevices.clear();this.capabilities.clear();this.snapshots.clear();this.snapshotAt.clear();this.devServerOrigins.clear();this.devServerRoots.clear();this.crashSeen.clear();this.originProbed.clear();this.health.clear();this.lastSeen.clear();if(!n)this.watching.clear();for(const t of this.pendingActions.values()){clearTimeout(t.timer);t.reject(new Error("Buoy account access ended while the action was pending."))}this.pendingActions.clear();for(const t of this.snapshotWaiters.values())for(const r of t)r(void 0);this.snapshotWaiters.clear();if(this.socket)this.socket.sendBuffer=[]}requireDeviceAccount(e){if(this.lockedDevices.has(e))throw new Error("The device's Buoy account access ended. Sign in and verify its key.")}lockDevice(e){this.lockedDevices.add(e);this.capabilities.delete(e);this.health.delete(e);this.devServerOrigins.delete(e);this.devServerRoots.delete(e);this.originProbed.delete(e);const n=`${e}::`;for(const t of this.snapshots.keys())if(t.startsWith(n)){this.snapshots.delete(t);this.snapshotAt.delete(t)}for(const[t,r]of this.snapshotWaiters)if(t.startsWith(n)){this.snapshotWaiters.delete(t);for(const i of r)i(void 0)}for(const[t,r]of this.pendingActions)if(r.target===e||r.target===ALL_DEVICES){clearTimeout(r.timer);this.pendingActions.delete(t);r.reject(new Error("Device account access ended while the action was pending."))}}pruneStaleDevices(){const e=Date.now()-DEVICE_RETENTION_MS;for(const[n,t]of this.lastSeen){if(t>e)continue;if(this.devices.some(i=>i.deviceId===n))continue;this.lastSeen.delete(n);this.capabilities.delete(n);this.health.delete(n);this.devServerOrigins.delete(n);this.devServerRoots.delete(n);this.originProbed.delete(n);const r=`${n}::`;for(const i of[...this.snapshots.keys()]){if(i.startsWith(r)){this.snapshots.delete(i);this.snapshotAt.delete(i)}}for(const i of[...this.watching.keys()]){if(i.startsWith(r))this.watching.delete(i)}}}async stop(){this.setAdmission(false);this.hostAccount?.stop();this.hostAccount=null;for(const[,e]of this.pendingActions){clearTimeout(e.timer);e.reject(new Error("SyncClient stopped"))}this.pendingActions.clear();for(const[,e]of this.snapshotWaiters)for(const n of e)n(void 0);this.snapshotWaiters.clear();this.socket?.close();this.socket=null;if(this.broker){await this.broker.close();this.broker=null}}listDevices(){if(!this.admitted)return[];return this.devices.filter(e=>e.deviceName!==DASHBOARD_NAME&&e.deviceId).map(e=>{const n=this.capabilities.get(e.deviceId);return{deviceId:e.deviceId,deviceName:e.deviceName,platform:e.platform,isConnected:e.isConnected!==false,isPro:e.isPro===true,tier:e.tier==="free"||e.tier==="pro"?e.tier:e.tier===void 0&&e.isPro===true?"pro":"locked",collision:e.collision===true,tools:n?.tools??[]}})}connectedDevices(){return this.listDevices().filter(e=>e.isConnected)}toolActions(e){return this.listDevices().map(n=>{const t=n.tools.find(r=>r.toolId===e);return t?{deviceId:n.deviceId,deviceName:n.deviceName,actions:t.actions}:null}).filter(n=>n!==null)}peekProjectDevice(){if(!this.admitted)return null;if(this.sessionDevice)return this.sessionDevice;const e=this.connectedDevices().filter(t=>!this.lockedDevices.has(t.deviceId)&&t.tools.length>0);const n=process.env.BUOY_PROJECT_ROOT||process.cwd();return pickByProject(e.map(t=>({deviceId:t.deviceId,root:this.devServerRoots.get(t.deviceId)})),n)??null}resolveDevice(e){this.requireAdmission();if(e){this.requireDeviceAccount(e);return e}const n=(l,u)=>new Error(`${NOT_READY_MARK} "${l}" (${u}) is not connected right now. If it is restarting, it usually takes a few seconds; to use another device, pass deviceId (run list_devices to see them).`);if(this.sessionDevice){const l=this.devices.find(u=>u.deviceId===this.sessionDevice);if(l&&l.isConnected!==false)return this.sessionDevice;throw n(this.sessionDevice,"the device this session was using")}const t=this.connectedDevices();const r=t.filter(l=>!this.lockedDevices.has(l.deviceId));const i=r.filter(l=>l.tools.length>0);const o=process.env.BUOY_PROJECT_ROOT||process.cwd();const s=pickByProject(i.map(l=>({deviceId:l.deviceId,root:this.devServerRoots.get(l.deviceId)})),o);if(s)return this.sessionDevice=s;const a=pickByProject(this.devices.filter(l=>l.deviceId&&l.isConnected===false&&!this.lockedDevices.has(l.deviceId)).map(l=>({deviceId:l.deviceId,root:this.devServerRoots.get(l.deviceId)})),o);if(a)throw n(a,"this project's app");if(r.length===0){if(t.length>0){throw new Error(`Devices are connected (${t.map(l=>l.deviceName).join(", ")}), but the broker has not admitted their accounts. Check app account validation and the account announcement after reconnect; this does not prove the user is signed out.`)}throw new Error("No devices are connected to the broker. Open the app with Buoy devtools running.")}if(r.length===1)return this.sessionDevice=r[0].deviceId;if(i.length===1)return this.sessionDevice=i[0].deviceId;if(i.length===0){const l=r.map(u=>u.deviceName).join(", ");throw new Error(`Connected devices (${l}) are not exposing any Buoy tools yet. Make sure the app is in the foreground with devtools mounted, then retry.`)}const c=i.map(l=>`${l.deviceName} (${l.deviceId})`).join(", ");throw new Error(`Multiple devices connected \u2014 specify deviceId. Connected: ${c}`)}requireProDevice(e){this.requireAdmission();if(e&&e!==ALL_DEVICES)this.sessionDevice=e;const n=o=>{if(!o)return"";return o.tier==="locked"?` The broker has not confirmed account access for "${o.deviceName}"; a locked status does not establish whether a key is configured.`:` The connected app "${o.deviceName}" is on the ${o.tier} tier.`};const t=o=>`Buoy Pro is required to use the MCP.${n(o)} Enter a license in the app, or \u2014 if it runs headless (no on-device UI) \u2014 pass \`licenseKey\` to \`<FloatingDevTools />\`. Run \`list_devices\` to check status.`;if(e===ALL_DEVICES){if(!this.connectedDevices().some(o=>o.isPro))throw new Error(t());return ALL_DEVICES}const r=this.resolveDevice(e);const i=this.connectedDevices().find(o=>o.deviceId===r);if(!i?.isPro){const o=this.accessState(r);if(o==="offline")throw new Error(`${NOT_READY_MARK} "${r}" is not connected right now. If the app is starting or reloading, it usually takes a few seconds. Run list_devices to check.`);if(o==="pending")throw new Error(`${NOT_READY_MARK} account access for "${r}" is still being confirmed (the app just connected). Try again in a moment.`);throw new Error(t(i))}return r}accessState(e){const n=this.devices.find(t=>t.deviceId===e);if(!n||n.isConnected===false)return"offline";if(n.isPro===true)return"ready";return n.tier===void 0?"pending":"denied"}healthOf(e){let n=this.health.get(e);if(!n){n={consecutiveTimeouts:0,lastOkAt:0,lastFullBudgetAt:0};this.health.set(e,n)}return n}noteOk(e){const n=this.healthOf(e);n.consecutiveTimeouts=0;n.lastOkAt=Date.now()}noteTimeout(e){this.healthOf(e).consecutiveTimeouts+=1}isUnresponsive(e){return isUnresponsive(this.healthOf(e).consecutiveTimeouts)}timeoutFor(e,n,t){const r=this.healthOf(e);const{timeoutMs:i,usedFullBudget:o}=actionTimeoutMs({consecutiveTimeouts:r.consecutiveTimeouts,lastFullBudgetAt:r.lastFullBudgetAt,now:Date.now(),fullMs:this.actionTimeoutMs,shortMs:UNRESPONSIVE_ACTION_TIMEOUT_MS,recoveryProbeMs:RECOVERY_PROBE_MS,toolId:n,action:t});if(o)r.lastFullBudgetAt=Date.now();return i}unresponsiveNote(e){const n=this.healthOf(e);const t=n.lastOkAt?Math.round((Date.now()-n.lastOkAt)/1e3):null;const r=diagnoseCrashed({consecutiveTimeouts:n.consecutiveTimeouts,lastOkAt:n.lastOkAt,now:Date.now(),unresponsiveAfterMs:UNRESPONSIVE_AFTER_MS});const i=[`The app on "${e}" is not responding (${n.consecutiveTimeouts} call${n.consecutiveTimeouts===1?"":"s"} unanswered${t!=null?`, last answered ${t}s ago`:""}).`,r?"It is most likely CRASHED \u2014 a fatal render error unmounts the React tree, and the dev tools live in that tree, so nothing on-device can answer until the app is reloaded.":"It may be busy, mid-reload, or crashing."];const o=this.lastFatalFor(e);if(o)i.push(`Last captured error: ${o}`);i.push(o?"Read the crash state with get_console / get_storage (served from the last sync), then reload_app to recover.":"Try get_console (served from the last sync) for the app's last words, then reload_app to recover.");return i.join(" ")}noteCrashReport(e,n){const t=n?.entries;if(!Array.isArray(t)||t.length===0)return;const r=Math.max(...t.map(s=>typeof s?.timestamp==="number"?s.timestamp:-Infinity));const i=this.crashSeen.get(e)??new Set;let o=false;for(const s of t){const a=s?.fatal||/^\[(RENDER ERROR|FATAL)/.test(s?.message??"");if(!a||typeof s.timestamp!=="number")continue;const c=`${s.id??""}|${s.timestamp}|${(s.message??"").slice(0,120)}`;if(i.has(c))continue;i.add(c);if(r-s.timestamp<3e4)o=true}if(i.size>200)for(const s of[...i].slice(0,i.size-200))i.delete(s);this.crashSeen.set(e,i);if(!o)return;if(![...this.pendingActions.values()].some(s=>s.target===e&&s.expire&&!s.cut))return;void this.callAction("app","ping",{},e,{timeoutMs:1500,silent:true}).then(()=>void 0,()=>{const s=Date.now();for(const a of this.pendingActions.values()){if(a.target!==e||!a.expire||a.cut)continue;a.cut=true;if(a.deadline!==void 0&&a.deadline-s<=UNRESPONSIVE_ACTION_TIMEOUT_MS)continue;clearTimeout(a.timer);a.timer=setTimeout(a.expire,UNRESPONSIVE_ACTION_TIMEOUT_MS)}})}lastFatalFor(e){const n=this.snapshots.get(snapKey(e,"console"));const t=n?.entries;if(!Array.isArray(t))return null;for(let r=t.length-1;r>=0;r--){const i=t[r];if(i?.fatal||i?.level==="error"){const o=(i.message??"").split("\n")[0];if(o)return o.length>300?`${o.slice(0,300)}\u2026`:o}}return null}snapshotAgeMs(e,n){this.requireAdmission();const t=this.snapshotAt.get(snapKey(n,e));return t?Date.now()-t:null}noteDevServerOrigin(e,n){if(typeof n==="string"&&/^https?:\/\//.test(n)){const t=this.devServerOrigins.get(e)!==n;this.devServerOrigins.set(e,n);if(t)this.devServerRoots.delete(e);if(t||!this.devServerRoots.has(e)){const r=devServerRoot(n).then(i=>{if(i&&this.devServerOrigins.get(e)===n)this.devServerRoots.set(e,i)});this.trackRootLookup(r)}}}async learnDevServerOrigin(e){if(this.devServerOrigins.has(e)||this.originProbed.has(e))return;this.originProbed.add(e);const n=this.capabilities.get(e)?.tools?.some(t=>t.toolId==="app");if(!n)return;try{const{payload:t}=await this.getSnapshot("app",e,{timeoutMs:4e3,silent:true});this.noteDevServerOrigin(e,t?.devServerOrigin)}catch{}}trackRootLookup(e){const n=e.catch(()=>void 0).finally(()=>this.rootLookups.delete(n));this.rootLookups.add(n)}async awaitBroker(){if(Date.now()-this.createdAt>15e3)return;for(let e=0;!this.admitted&&e<4e3;e+=100)await new Promise(n=>setTimeout(n,100));for(let e=0;this.admitted&&this.devices.length===0&&e<1500;e+=100)await new Promise(n=>setTimeout(n,100))}async settleDeviceChoice(e=1500){await this.awaitBroker();if(this.sessionDevice||this.rootLookups.size===0||this.connectedDevices().length<2)return;await Promise.race([Promise.all([...this.rootLookups]),new Promise(n=>setTimeout(n,e))]);if(this.rootLookups.size)await Promise.race([Promise.all([...this.rootLookups]),new Promise(n=>setTimeout(n,Math.min(800,e)))])}devServerOrigin(e){this.requireAdmission();const n=this.devServerOrigins.get(e);if(n)return n;const t=this.snapshots.get(snapKey(e,"app"));if(typeof t?.devServerOrigin==="string")return t.devServerOrigin;return null}ensureWatching(e,n){const t=snapKey(n,e);if(this.watching.has(t))return;this.watching.set(t,{toolId:e,targetDeviceId:n});this.sendWatch(e,n)}sendWatch(e,n){if(!this.admitted||!this.socket?.connected||this.lockedDevices.has(n))return;this.socket?.emit("devtool-watch",{toolId:e,targetDeviceId:n,watching:true,stream:false})}rearmWatches(){for(const{toolId:e,targetDeviceId:n}of this.watching.values()){this.sendWatch(e,n)}}rearmReconnectedDevices(e){for(const n of e){if(!n.deviceId||n.isConnected===false)continue;const t=String(n.deviceId);const r=`${n.id}|${n.connectionNonce??""}`;const i=this.deviceConnections.get(t);this.deviceConnections.set(t,r);if(i===void 0||i===r)continue;for(const{toolId:o,targetDeviceId:s}of this.watching.values()){if(s===t)this.sendWatch(o,s)}}}unwatch(e,n){const t=snapKey(n,e);if(!this.watching.delete(t))return;if(this.admitted&&this.socket?.connected)this.socket.emit("devtool-watch",{toolId:e,targetDeviceId:n,watching:false})}cachedSnapshot(e,n){this.requireAdmission();this.requireDeviceAccount(n);return this.snapshots.get(snapKey(n,e))}async getSnapshot(e,n,t={}){const r=this.resolveDevice(n);const i=snapKey(r,e);this.ensureWatching(e,r);let o=t.timeoutMs??DEFAULT_SNAPSHOT_TIMEOUT_MS;if(t.timeoutMs===void 0&&this.isUnresponsive(r)){const l=this.healthOf(r);if(Date.now()-l.lastFullBudgetAt>RECOVERY_PROBE_MS){l.lastFullBudgetAt=Date.now()}else{o=UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS}}const s=this.waitForSnapshot(i,o);this.socket?.emit("request-devtool-state",{toolId:e,targetDeviceId:r});const a=await s;this.requireAdmission();this.requireDeviceAccount(r);if(a!==void 0){if(!t.silent)this.noteOk(r);return{deviceId:r,payload:a}}if(!t.silent)this.noteTimeout(r);const c=this.snapshots.get(i);if(c!==void 0){return{deviceId:r,payload:c,stale:this.staleNote(e,r)}}throw new Error(`Timed out waiting for "${e}" state from ${r} (is the tool active?). ${this.unresponsiveNote(r)}`)}lastSync(e,n){const t=this.snapshots.get(snapKey(e,n));return t===void 0?void 0:{payload:t,ageMs:this.snapshotAgeMs(n,e)}}staleNote(e,n){const t=this.snapshotAgeMs(e,n);const r=t==null?"an earlier sync":`${Math.round(t/1e3)}s ago`;return`\u26A0\uFE0F Served from the last sync (${r}) \u2014 ${this.unresponsiveNote(n)}`}waitForSnapshot(e,n){return new Promise(t=>{const r=this.snapshotWaiters.get(e)??[];const i=setTimeout(()=>{const s=(this.snapshotWaiters.get(e)??[]).filter(a=>a!==o);this.snapshotWaiters.set(e,s);t(void 0)},n);const o=s=>{clearTimeout(i);t(s)};r.push(o);this.snapshotWaiters.set(e,r)})}async callAction(e,n,t,r,i={}){this.requireAdmission();const o=r===ALL_DEVICES?ALL_DEVICES:this.resolveDevice(r);if(!this.socket)throw new Error("SyncClient is not connected");const s=(0,import_node_crypto3.randomUUID)();const a=i.timeoutMs??this.timeoutFor(o,e,n);const c=await new Promise((l,u)=>{const d=Date.now();const h=()=>{this.pendingActions.delete(s);if(o!==ALL_DEVICES&&!i.silent)this.noteTimeout(o);u(new Error(`Action "${e}.${n}" got no answer in ${Date.now()-d}ms. `+(o===ALL_DEVICES?"No device responded.":this.unresponsiveNote(o))))};const w=setTimeout(h,a);this.pendingActions.set(s,{resolve:l,reject:u,timer:w,target:o,expire:h,deadline:d+a});this.socket.emit("devtool-action",{requestId:s,toolId:e,targetDeviceId:o,action:n,params:t??{}})});if(o!==ALL_DEVICES&&!i.silent)this.noteOk(o);if(!c.ok){throw new Error(c.error||`Action "${e}.${n}" failed on device`)}return c.result}};snapKey=(e,n)=>`${e}::${n}`;delay=e=>new Promise(n=>setTimeout(n,e))}});var VERSION,PACKAGE_NAME;var init_version=__esm({"src/version.ts"(){"use strict";VERSION="7.0.63"?"7.0.63":"0.0.0-dev";PACKAGE_NAME="@buoy-gg/mcp"}});function isNewer(e,n){const t=o=>o.split("-")[0].split(".").map(s=>Number(s)||0);const r=t(e);const i=t(n);for(let o=0;o<3;o++){const s=r[o]??0;const a=i[o]??0;if(s>a)return true;if(s<a)return false}return false}async function readCache(){try{const e=await import_node_fs4.promises.readFile(CACHE_FILE,"utf8");const n=JSON.parse(e);if(typeof n.checkedAt==="number"&&typeof n.latest==="string"){return n}}catch{}return null}async function fetchLatest(e){const n=new AbortController;const t=setTimeout(()=>n.abort(),FETCH_TIMEOUT_MS);try{const r=await fetch(REGISTRY_URL,{signal:n.signal});if(!r.ok)return null;const i=await r.json();const o=typeof i.version==="string"?i.version:null;if(o){await import_node_fs4.promises.writeFile(CACHE_FILE,JSON.stringify({checkedAt:e,latest:o})).catch(()=>{})}return o}catch{return null}finally{clearTimeout(t)}}async function resolveLatest(e){const n=await readCache();if(n&&e-n.checkedAt<CHECK_TTL_MS)return n.latest;return fetchLatest(e)}async function getUpdateNotice(e=Date.now()){if(VERSION==="0.0.0-dev")return null;try{const n=await resolveLatest(e);if(n&&isNewer(n,VERSION)){return`A newer buoy-mcp is available (${n}; you're on ${VERSION}). Update by re-running: npx -y ${PACKAGE_NAME}@latest init \u2014 then restart your editor.`}}catch{}return null}var import_node_fs4,import_node_os4,import_node_path5,CHECK_TTL_MS,FETCH_TIMEOUT_MS,REGISTRY_URL,CACHE_FILE;var init_checkForUpdate=__esm({"src/update/checkForUpdate.ts"(){"use strict";import_node_fs4=require("fs");import_node_os4=__toESM(require("os"));import_node_path5=__toESM(require("path"));init_version();CHECK_TTL_MS=24*60*60*1e3;FETCH_TIMEOUT_MS=1500;REGISTRY_URL=`https://registry.npmjs.org/${PACKAGE_NAME}/latest`;CACHE_FILE=import_node_path5.default.join(import_node_os4.default.tmpdir(),"buoy-mcp-update-check.json")}});function humanizeSimctlError(e){const n=e;if(n?.code==="ENOENT"){return"Xcode command-line tools (xcrun) not found. Install Xcode to capture the iOS Simulator."}const t=String(n?.stderr||n?.message||e);if(/No devices are booted|Unable to find device|current device/i.test(t)){return"No booted iOS Simulator found. Boot the Simulator with your app running, then try again."}return t.trim()||"Failed to capture the iOS Simulator."}function pngSize(e){const n=[137,80,78,71,13,10,26,10];if(e.length<24||!n.every((t,r)=>e[r]===t))return null;return{width:e.readUInt32BE(16),height:e.readUInt32BE(20)}}async function listDir(e){try{return await import_node_fs5.promises.readdir(e)}catch{return[]}}async function webViewInstallIds(e){const n=[];for(const t of await listDir(e))n.push(...await containerWebViewInstallIds(import_node_path6.default.join(e,t)));return n}async function containerWebViewInstallIds(e){const n=[];const t=import_node_path6.default.join(e,"Library","WebKit");for(const r of await listDir(t)){const i=import_node_path6.default.join(t,r,"WebsiteData","Default");for(const o of await listDir(i)){for(const s of await listDir(import_node_path6.default.join(i,o))){const a=import_node_path6.default.join(i,o,s,"LocalStorage","localstorage.sqlite3");try{await import_node_fs5.promises.access(a);const{stdout:c}=await execFileAsync5("sqlite3",["-readonly",a,`SELECT hex(value) FROM ItemTable WHERE key='${WEBVIEW_ID_KEY}' LIMIT 1;`],{timeout:1500});const l=c.trim();if(l)n.push(Buffer.from(l,"hex").toString("utf16le").trim())}catch{}}}}return n}async function resolveSimUdid(e){if(process.platform!=="darwin")return{ok:false,error:"Simulator lookup needs macOS."};let n=[];try{const{stdout:r}=await execFileAsync5("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const i=JSON.parse(r).devices;n=Object.entries(i).filter(([o])=>/iOS/.test(o)).flatMap(([,o])=>o.filter(s=>s.state==="Booted"))}catch(r){return{ok:false,error:humanizeSimctlError(r)}}if(n.length===0)return{ok:false,error:"No iOS Simulator is booted."};const t=e?.split("-").pop();if(t){for(const r of n){if(!r.dataPath)continue;const i=import_node_path6.default.join(r.dataPath,"Containers","Data","Application");let o=[];try{o=await import_node_fs5.promises.readdir(i)}catch{continue}for(const s of o){try{const a=(await import_node_fs5.promises.readFile(import_node_path6.default.join(i,s,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim();if(a===t)return{ok:true,udid:r.udid,how:`matched ${e} to "${r.name}"`}}catch{}}}}if(t&&e){const r=n.map(c=>c.udid).sort().join(",");const i=webViewLookups.get(e);const o=i?.booted===r&&(i.udid!==null||Date.now()-i.at<WEBVIEW_MISS_MS);const s=o&&i?.udid?n.find(c=>c.udid===i.udid):void 0;if(s)return{ok:true,udid:s.udid,how:`matched ${e} to "${s.name}" (WebView storage)`};const a=[];if(!o){const c=await Promise.all(n.map(l=>l.dataPath?webViewInstallIds(import_node_path6.default.join(l.dataPath,"Containers","Data","Application")):Promise.resolve([])));c.forEach((l,u)=>{if(l.includes(t))a.push(n[u])});webViewLookups.set(e,{booted:r,udid:a.length===1?a[0].udid:null,at:Date.now()})}if(a.length===1){return{ok:true,udid:a[0].udid,how:`matched ${e} to "${a[0].name}" (WebView storage)`}}if(a.length>1){return{ok:false,error:`${a.length} booted simulators (${a.map(c=>c.name).join(", ")}) hold ${e}. Pass the udid, or shut one down.`}}}if(n.length===1)return{ok:true,udid:n[0].udid,how:`only booted simulator "${n[0].name}"`};return{ok:false,error:`${n.length} iOS Simulators are booted (${n.map(r=>r.name).join(", ")}) and none could be matched to ${e??"this device"}. Shut down the others, or capture from a single booted simulator.`}}async function resolveSims(e){const n=new Map;if(process.platform!=="darwin"||e.length===0)return n;let t=[];try{const{stdout:i}=await execFileAsync5("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const o=JSON.parse(i).devices;t=Object.entries(o).filter(([s])=>/iOS/.test(s)).flatMap(([,s])=>s.filter(a=>a.state==="Booted"))}catch{return n}const r=new Map;for(const i of t){if(!i.dataPath)continue;const o=import_node_path6.default.join(i.dataPath,"Containers","Data","Application");let s=[];try{s=await import_node_fs5.promises.readdir(o)}catch{continue}for(const a of s){try{const c=(await import_node_fs5.promises.readFile(import_node_path6.default.join(o,a,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim();if(c)r.set(c,{name:i.name,udid:i.udid})}catch{}}}for(const i of e){const o=r.get(i.split("-").pop()??"");if(o)n.set(i,o)}return n}async function captureIosFramebuffer(e="booted"){if(process.platform!=="darwin"){return{ok:false,error:"Screenshotting a component requires macOS with Xcode's iOS Simulator (uses `xcrun simctl`)."}}const n=import_node_path6.default.join(import_node_os5.default.tmpdir(),`buoy-mcp-sim-${(0,import_node_crypto4.randomUUID)()}.png`);try{await execFileAsync5("xcrun",["simctl","io",e,"screenshot","--type=png",n],{timeout:15e3})}catch(t){return{ok:false,error:humanizeSimctlError(t)}}try{const t=await import_node_fs5.promises.readFile(n);const r=pngSize(t);if(!r)return{ok:false,error:"Captured file wasn't a valid PNG."};return{ok:true,srcPath:n,width:r.width,height:r.height}}catch(t){return{ok:false,error:`Failed to read screenshot: ${t.message}`}}}async function cropToBuffer(e,n,t){const r=clamp(Math.round(t.x),0,Math.max(0,n.width-1));const i=clamp(Math.round(t.y),0,Math.max(0,n.height-1));const o=clamp(Math.round(t.width),1,n.width-r);const s=clamp(Math.round(t.height),1,n.height-i);const a=import_node_path6.default.join(import_node_os5.default.tmpdir(),`buoy-mcp-crop-${(0,import_node_crypto4.randomUUID)()}.png`);try{await execFileAsync5("sips",["-c",String(s),String(o),"--cropOffset",String(i),String(r),e,"--out",a],{timeout:1e4});const c=await import_node_fs5.promises.readFile(a);return{ok:true,buffer:c,width:o,height:s}}catch(c){const l=c;return{ok:false,error:`Crop failed: ${l?.stderr||l?.message||c}`}}finally{await import_node_fs5.promises.unlink(a).catch(()=>{});await import_node_fs5.promises.unlink(e).catch(()=>{})}}var import_node_child_process6,import_node_util5,import_node_fs5,import_node_os5,import_node_path6,import_node_crypto4,execFileAsync5,clamp,WEBVIEW_ID_KEY,webViewLookups,WEBVIEW_MISS_MS;var init_simctl=__esm({"src/capture/simctl.ts"(){"use strict";import_node_child_process6=require("child_process");import_node_util5=require("util");import_node_fs5=require("fs");import_node_os5=__toESM(require("os"));import_node_path6=__toESM(require("path"));import_node_crypto4=require("crypto");execFileAsync5=(0,import_node_util5.promisify)(import_node_child_process6.execFile);clamp=(e,n,t)=>Math.min(Math.max(e,n),t);WEBVIEW_ID_KEY="@react_buoy_sync_device_id";webViewLookups=new Map;WEBVIEW_MISS_MS=3e4}});async function listDir2(e){return import_node_fs6.promises.readdir(e).catch(()=>[])}async function containerLocalStorageFiles(e){const n=[];const t=import_node_path7.default.join(e,"Library","WebKit");for(const r of await listDir2(t)){const i=import_node_path7.default.join(t,r,"WebsiteData","Default");for(const o of await listDir2(i)){for(const s of await listDir2(import_node_path7.default.join(i,o))){const a=import_node_path7.default.join(i,o,s);const c=import_node_path7.default.join(a,"LocalStorage","localstorage.sqlite3");if(!await import_node_fs6.promises.access(c).then(()=>true,()=>false))continue;const l=await import_node_fs6.promises.readFile(import_node_path7.default.join(a,"origin")).then(u=>u.toString("hex"),()=>"");if(l)n.push({db:c,origin:l})}}}return n}async function iosReadWebKeep(e){const n=[];for(const{db:t,origin:r}of await containerLocalStorageFiles(e)){const i=await sqlite(t,"SELECT key, hex(value) FROM ItemTable;");for(const o of i.split("\n")){const s=o.lastIndexOf("|");if(s<0)continue;const a=o.slice(0,s);if(WEB_KEEP_KEY.test(a))n.push({key:a,value:o.slice(s+1),origin:r})}}return n}async function iosWriteWebKeep(e,n){if(!n.length)return false;const t=await containerLocalStorageFiles(e);const r=new Set(n.map(i=>i.origin??""));for(const i of r){const o=i?t.find(a=>a.origin===i):void 0;if(!o)return false;const s=n.filter(a=>(a.origin??"")===i&&/^[0-9A-F]*$/i.test(a.value)).map(a=>`('${a.key.replace(/'/g,"''")}', X'${a.value}')`).join(",");if(s)await sqlite(o.db,`INSERT OR REPLACE INTO ItemTable (key, value) VALUES ${s};`,false)}return true}async function iosWaitForLocalStorage(e,n=15e3){const t=Date.now()+n;while(Date.now()<t){if((await containerLocalStorageFiles(e)).length)return true;await new Promise(r=>setTimeout(r,500))}return false}async function evaluateInWebView(e,n,t){const r=(await adbShell(e,`pidof ${n}`).catch(()=>"")).trim().split(/\s+/)[0];if(!r)throw new Error("the app is not running");const i=(await adb(e,["forward","tcp:0",`localabstract:webview_devtools_remote_${r}`])).trim();try{const o=await(await fetch(`http://127.0.0.1:${i}/json`)).json();const s=o.find(a=>a.type==="page"&&a.webSocketDebuggerUrl);if(!s?.webSocketDebuggerUrl)throw new Error("no debuggable WebView page (needs a debug build)");return await new Promise((a,c)=>{const l=new import_ws.WebSocket(s.webSocketDebuggerUrl);const u=setTimeout(()=>{l.close();c(new Error("the WebView did not answer"))},5e3);l.on("open",()=>l.send(JSON.stringify({id:1,method:"Runtime.evaluate",params:{expression:t,returnByValue:true}})));l.on("message",d=>{const h=JSON.parse(String(d));if(h.id!==1)return;clearTimeout(u);l.close();if(h.result?.exceptionDetails)c(new Error("the WebView script failed"));else a(h.result?.result?.value)});l.on("error",d=>{clearTimeout(u);c(d)})})}finally{await adb(e,["forward","--remove",`tcp:${i}`]).catch(()=>void 0)}}async function evaluateWhenReady(e,n,t,r=15e3){const i=Date.now()+r;let o;while(Date.now()<i){try{return await evaluateInWebView(e,n,t)}catch(s){o=s;await new Promise(a=>setTimeout(a,700))}}throw o instanceof Error?o:new Error("the WebView did not open")}async function androidHasWebViewStorage(e,n){const t=await adbShell(e,`run-as ${n} sh -c 'ls app_webview/Default/"Local Storage"/leveldb 2>/dev/null'`).catch(()=>"");return/CURRENT|\.log/.test(t)}async function androidReadWebKeep(e,n){if(!(await adbShell(e,`pidof ${n}`).catch(()=>"")).trim()){await adbShell(e,`monkey -p ${n} -c android.intent.category.LAUNCHER 1`)}const t=await evaluateWhenReady(e,n,`(() => { const re = ${WEB_KEEP_KEY}; const out = []; for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (k && re.test(k)) out.push({ key: k, value: localStorage.getItem(k) }); } return out; })()`);return Array.isArray(t)?t.filter(r=>typeof r.key==="string"&&typeof r.value==="string"):[]}async function androidWriteWebKeep(e,n,t){await evaluateWhenReady(e,n,`(() => { for (const r of ${JSON.stringify(t)}) localStorage.setItem(r.key, r.value); setTimeout(() => location.reload(), 50); return true; })()`)}var import_node_child_process7,import_node_util6,import_node_fs6,import_node_path7,import_ws,execFileAsync6,WEB_KEEP_KEY,sqlite;var init_webViewKeep=__esm({"src/capture/webViewKeep.ts"(){"use strict";import_node_child_process7=require("child_process");import_node_util6=require("util");import_node_fs6=require("fs");import_node_path7=__toESM(require("path"));import_ws=require("ws");init_adb();execFileAsync6=(0,import_node_util6.promisify)(import_node_child_process7.execFile);WEB_KEEP_KEY=/^(@buoy\/session:|buoy-gg-license|buoy-gg-device-fingerprint$|@react_buoy_sync_device_id$|@react_buoy_install)/;sqlite=(e,n,t=true)=>execFileAsync6("sqlite3",[...t?["-readonly"]:[],e,n],{timeout:5e3}).then(r=>r.stdout)}});function rememberedHost(e){return hosts.get(e)}async function sh(e,n,t=2e4){try{const{stdout:r}=await execFileAsync7(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)}`)}}async function simsHolding(e,n){if(!n){const t=await simsHoldingOf(e,["rn"]);return t.length?t:simsHoldingOf(e,["webview"])}return simsHoldingOf(e,n)}async function simsHoldingOf(e,n){let t=[];try{const i=JSON.parse(await simctl(["list","devices","booted","-j"])).devices;t=Object.entries(i).filter(([o])=>/iOS/.test(o)).flatMap(([,o])=>o.filter(s=>s.state==="Booted"))}catch{return[]}const r=await Promise.all(t.map(i=>findIosContainer(e,i.udid,i.dataPath,n)));return t.flatMap((i,o)=>r[o]?[{udid:i.udid,name:i.name,found:r[o]}]:[])}function cloneError(e,n){return new Error(`${n.length} booted simulators hold "${e}" (one is probably a clone): ${n.map(t=>`${t.name} (${t.udid})`).join(", ")}. Pass udid to choose, or shut the extra one down.`)}async function findIosContainer(e,n,t,r){const i=tailOf(e);if(!i)return null;if(!t){try{const c=JSON.parse(await simctl(["list","devices","-j"])).devices;t=Object.values(c).flat().find(l=>l.udid===n)?.dataPath}catch{return null}}if(!t)return null;const o=import_node_path8.default.join(t,"Containers","Data","Application");let s=[];try{s=await import_node_fs7.promises.readdir(o)}catch{return null}const a=await Promise.all(s.map(c=>iosContainerHolds(import_node_path8.default.join(o,c),i,r)));for(const[c,l]of s.entries()){const u=import_node_path8.default.join(o,l);if(!a[c])continue;let d=null;try{d=(await sh("plutil",["-extract","MCMMetadataIdentifier","raw","-o","-",import_node_path8.default.join(u,".com.apple.mobile_container_manager.metadata.plist")])).trim()||null}catch{}return{container:u,bundleId:d,kind:a[c]}}return null}async function iosContainerHolds(e,n,t=["rn","webview"]){if(t.includes("rn")){try{if((await import_node_fs7.promises.readFile(import_node_path8.default.join(e,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim()===n)return"rn"}catch{}}if(!t.includes("webview"))return null;return(await containerWebViewInstallIds(e).catch(()=>[])).includes(n)?"webview":null}async function findAndroid(e,n){const t=tailOf(e);const r=n.serial?[n.serial]:await adbSerials();if(r.length===0)throw new Error("No Android device or emulator is connected to adb.");for(const i of r){const o=await adbForegroundPackage(i).catch(()=>null);const s=await adbUserPackages(i).catch(()=>[]);const a=[n.bundleId,o,...s].filter((c,l,u)=>!!c&&u.indexOf(c)===l).slice(0,80);for(const c of a){if(await adbInstallId(i,c).catch(()=>null)===t)return{platform:"android",serial:i,packageName:c}}}return null}async function findPhone(e){const n=tailOf(e);for(const t of await physicalPhones()){for(const r of await developerApps(t.udid).catch(()=>[])){if(await phoneInstallId(t.udid,r.bundleId)===n)return{platform:"ios-device",udid:t.udid,name:t.name,bundleId:r.bundleId}}}return null}function findHost(e,n,t={}){if(t.udid||t.serial||t.bundleId)return findHostNow(e,n,t);const r=`${e}|${n??""}`;const i=finding.get(r);if(i)return i;const o=findHostNow(e,n,t).finally(()=>finding.delete(r));finding.set(r,o);return o}async function findHostNow(e,n,t={}){if(e==="All")throw new Error('Device control acts on one app. Pass its deviceId, not "All".');const r=hosts.get(e);if(r&&!t.udid&&!t.serial&&await stillHolds(e,r)){if(r.platform==="ios"&&!r.picked){const l=await simsHolding(e,r.idKind?[r.idKind]:void 0);if(l.length>1)throw cloneError(e,l);if(!l.some(u=>u.udid===r.udid)){hosts.delete(e);throw new Error(`The sim no longer holds "${e}". Try the host scan again.`)}}return r}if(r)hosts.delete(e);if(n==="android"){const l=await findAndroid(e,t);if(!l){throw new Error(`Could not prove which Android device and app run "${e}". Buoy checks the app's install id with run-as, which needs a debug build of the app on a device adb can reach${t.serial?` (looked on ${t.serial})`:""}.`)}hosts.set(e,l);return l}if(n&&n!=="ios")throw new Error(`Device control works on iOS Simulators and Android. This app runs on "${n}".`);if(process.platform!=="darwin")throw new Error("iOS control needs macOS with Xcode.");let i=t.udid;let o=i??"";let s=null;if(!i){const l=await simsHolding(e);s=l.length===1?l[0]:null;if(l.length>1)throw cloneError(e,l);const u=l.length===1?{ok:true,udid:l[0].udid,how:`matched ${e} to "${l[0].name}"`}:await resolveSimUdid(e);if(!u.ok||!/^matched /.test(u.how)){const d=await findPhone(e).catch(()=>null);if(d){hosts.set(e,d);return d}throw new Error(`Could not find which simulator or iPhone runs "${e}": no booted simulator holds its install id, and no connected iPhone has it (an iPhone must be unlocked, paired, and run a development build).`)}i=u.udid;o=/"([^"]+)"/.exec(u.how)?.[1]??i}const a=s?.udid===i?await iosContainerHolds(s.found.container,tailOf(e),[s.found.kind])?s.found:null:await findIosContainer(e,i);if(!a)throw new Error(`Simulator ${i} does not hold "${e}".`);const c={platform:"ios",udid:i,name:o,bundleId:t.bundleId??a?.bundleId??null,container:a?.container??null,picked:!!t.udid,idKind:a.kind};hosts.set(e,c);return c}async function verifyHost(e,n){if(n.platform==="ios"&&!n.picked){const t=await simsHolding(e);if(t.length>1)throw cloneError(e,t)}if(await stillHolds(e,n))return n;hosts.delete(e);return findHost(e,n.platform==="android"?"android":"ios",n.platform==="ios"&&n.picked?{udid:n.udid}:{})}async function stillHolds(e,n){const t=tailOf(e);if(n.platform==="android")return await adbInstallId(n.serial,n.packageName).catch(()=>null)===t;if(n.platform==="ios-device")return await phoneInstallId(n.udid,n.bundleId).catch(()=>null)===t;if(n.container)return!!await iosContainerHolds(n.container,t);const r=await resolveSimUdid(e);return r.ok&&r.udid===n.udid&&/^matched /.test(r.how)}function needApp(e){if(e.platform==="android")return assertPackage(e.packageName);if(e.platform==="ios-device")return e.bundleId;if(!e.bundleId)throw new Error("Could not tell which app this is on the simulator (its container has no bundle metadata).");return e.bundleId}async function hostPng(e){if(e.platform==="android")return adbScreenshot(e.serial);if(e.platform==="ios-device")return phoneScreenshot(e.udid);const n=await captureIosFramebuffer(e.udid);if(!n.ok||!n.srcPath)throw new Error(n.error??"Screenshot failed.");try{return await import_node_fs7.promises.readFile(n.srcPath)}finally{await import_node_fs7.promises.unlink(n.srcPath).catch(()=>{})}}async function toSmallImage(e,n=1280){if(process.platform==="darwin"){const i=import_node_path8.default.join(import_node_os6.default.tmpdir(),`buoy-mcp-img-${(0,import_node_crypto5.randomUUID)()}.png`);const o=i.replace(/\.png$/,".jpg");await import_node_fs7.promises.writeFile(i,e);try{await sh("sips",["-Z",String(n),"-s","format","jpeg","-s","formatOptions","70",i,"--out",o],15e3);const s=await sh("sips",["-g","pixelWidth","-g","pixelHeight",o]);return{data:(await import_node_fs7.promises.readFile(o)).toString("base64"),mimeType:"image/jpeg",width:Number(/pixelWidth:\s*(\d+)/.exec(s)?.[1]??0),height:Number(/pixelHeight:\s*(\d+)/.exec(s)?.[1]??0)}}finally{await import_node_fs7.promises.unlink(i).catch(()=>{});await import_node_fs7.promises.unlink(o).catch(()=>{})}}const t=downscalePng(import_pngjs2.PNG.sync.read(e),Math.min(n,1024));const r=import_pngjs2.PNG.sync.write(t,{colorType:2,deflateLevel:9});return{data:r.toString("base64"),mimeType:"image/png",width:t.width,height:t.height}}function downscalePng(e,n){const t=Math.min(1,n/Math.max(e.width,e.height));if(t===1)return e;const r=Math.max(1,Math.round(e.width*t));const i=Math.max(1,Math.round(e.height*t));const o=new import_pngjs2.PNG({width:r,height:i});const s=e.width/r;const a=e.height/i;for(let c=0;c<i;c++){const l=Math.floor(c*a);const u=Math.max(l+1,Math.floor((c+1)*a));for(let d=0;d<r;d++){const h=Math.floor(d*s);const w=Math.max(h+1,Math.floor((d+1)*s));const p=[0,0,0,0];let g=0;for(let f=l;f<u;f++){for(let b=h;b<w;b++){const v=(f*e.width+b)*4;for(let y=0;y<4;y++)p[y]+=e.data[v+y];g++}}const m=(c*r+d)*4;for(let f=0;f<4;f++)o.data[m+f]=Math.round(p[f]/g)}}return o}async function withSteadyStatusBar(e,n){let t=false;try{if(e.platform==="ios"){const r=await simctl(["status_bar",e.udid,"list"]).catch(()=>"");const i=r.split(/^=+$/m).slice(1).join("").trim();if(!i){await simctl(["status_bar",e.udid,"override","--time","9:41","--batteryState","charged","--batteryLevel","100","--wifiBars","3","--cellularBars","4"]);t=true}}else if(e.platform==="android"){const r=(await adbShell(e.serial,"settings get global sysui_demo_allowed").catch(()=>"")).trim();if(r!=="1"&&!steadying.has(e.serial)){steadying.add(e.serial);await adbDemoMode(e.serial,true);t=true}}if(t)await new Promise(r=>setTimeout(r,400))}catch{t=false}try{return{result:await n(),steadied:t}}finally{if(t){if(e.platform==="ios")await simctl(["status_bar",e.udid,"clear"]).catch(()=>void 0);else if(e.platform==="android"){await adbDemoMode(e.serial,false);await adbShell(e.serial,"settings put global sysui_demo_allowed 0").catch(()=>void 0);steadying.delete(e.serial)}}}}async function hostQuit(e){const n=needApp(e);if(e.platform==="ios-device"){const t=await phoneQuit(e.udid,n);return t?`Quit ${n}.`:`${n} was not running.`}if(e.platform==="ios"){await simctl(["terminate",e.udid,n]).catch(t=>{if(!/found nothing to terminate|not running/i.test(String(t)))throw t})}else{await adbShell(e.serial,`am force-stop ${q(n)}`)}return`Quit ${n}.`}async function hostLaunch(e){const n=needApp(e);if(e.platform==="ios")await simctl(["launch",e.udid,n]);else if(e.platform==="ios-device")await phoneLaunch(e.udid,n);else await adbShell(e.serial,`monkey -p ${q(n)} -c android.intent.category.LAUNCHER 1`);return`Launched ${n}.`}async function hostBackground(e){if(e.platform==="ios-device"){await phoneLaunch(e.udid,"com.apple.Preferences");return"Sent to the background for real (Settings opened on top)."}if(e.platform==="ios"){await simctl(["launch",e.udid,"com.apple.Preferences"]);return"Sent to the background for real (Settings opened on top)."}await adbShell(e.serial,"input keyevent 3");return"Sent to the background for real (pressed Home)."}async function hostOpenUrl(e,n){if(!/^[a-zA-Z][\w+.-]*:/.test(n))throw new Error(`"${n}" is not a link with a scheme (like https://\u2026 or myapp://\u2026).`);if(e.platform==="ios-device"){await phoneOpenUrl(e.udid,n);return"Opened through the OS on the iPhone."}if(e.platform==="ios"){await simctl(["openurl",e.udid,n]);return'Opened through the OS. A custom scheme may first show an "Open in" prompt on the simulator.'}await adbShell(e.serial,`am start -a android.intent.action.VIEW -d ${q(n)}`);return"Opened through the OS (an Android VIEW intent)."}async function appBundleInfo(e){const n=import_node_path8.default.join(e,"Info.plist");const t=s=>sh("plutil",["-extract",s,"raw","-o","-",n]).then(a=>a.trim()).catch(()=>"");const r=await t("CFBundleIdentifier");if(!r)throw new Error(`${e} has no Info.plist with a bundle id. Pass a built .app folder.`);const i=(await sh("plutil",["-extract","CFBundleSupportedPlatforms","json","-o","-",n]).catch(()=>"[]")).toLowerCase();const o=(await t("DTPlatformName")).toLowerCase();return{bundleId:r,simulator:i.includes("iphonesimulator")||o==="iphonesimulator"}}async function apkPackage(e){const n=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT,import_node_path8.default.join(import_node_os6.default.homedir(),"Library","Android","sdk"),import_node_path8.default.join(import_node_os6.default.homedir(),"Android","Sdk")].filter(t=>!!t);for(const t of n){const r=import_node_path8.default.join(t,"build-tools");const i=(await import_node_fs7.promises.readdir(r).catch(()=>[])).sort().reverse();for(const o of i){for(const s of["aapt2","aapt"]){const a=import_node_path8.default.join(r,o,s);try{await import_node_fs7.promises.access(a)}catch{continue}const c=await sh(a,s==="aapt2"?["dump","packagename",e]:["dump","badging",e]).catch(()=>"");const l=s==="aapt2"?c.trim().split("\n")[0]:/package: name='([^']+)'/.exec(c)?.[1]??"";if(l)return l}}}throw new Error("Could not read the APK's package name (needs aapt2 from the Android SDK build-tools). Nothing was changed.")}async function hostReinstall(e,n,t=true){const r=needApp(e);const i=import_node_path8.default.resolve(n);try{await import_node_fs7.promises.access(i)}catch{throw new Error(`No build at ${i}. Pass appPath: the built .app folder (iOS Simulator) or .apk file (Android). Nothing was changed.`)}if(e.platform==="android")return reinstallAndroid(e,r,i,t);if(e.platform==="ios-device")return reinstallPhone(e,r,i,t);if(!/\.app\/?$/i.test(i))throw new Error("On the iOS Simulator, appPath must be a built .app folder. Nothing was changed.");const o=await appBundleInfo(i);if(o.bundleId!==r)throw new Error(`${import_node_path8.default.basename(i)} is ${o.bundleId}, but this app is ${r}. Nothing was changed.`);if(!o.simulator)throw new Error(`${import_node_path8.default.basename(i)} is a device build, not a simulator build. Nothing was changed.`);const s=t?await import_node_fs7.promises.mkdtemp(import_node_path8.default.join(import_node_os6.default.tmpdir(),"buoy-mcp-keep-")):null;try{let a=false;let c=[];if(s){await import_node_fs7.promises.chmod(s,448);const u=(await simctl(["get_app_container",e.udid,r,"data"]).catch(()=>"")).trim();if(u)a=await copyBuoyFiles(import_node_path8.default.join(u,"Documents"),s);if(u&&!a){try{c=await iosReadWebKeep(u)}catch(d){throw new Error(`Couldn't read Buoy's sign-in from the app's WebView storage (${d.message}). Nothing was changed. Pass keepBuoy: false to reinstall anyway.`)}}}await simctl(["terminate",e.udid,r]).catch(()=>void 0);await simctl(["uninstall",e.udid,r]);try{await simctl(["install",e.udid,i],18e4)}catch(u){throw new Error(`The app was removed, but installing ${import_node_path8.default.basename(i)} failed: ${u.message}. Install it again by hand.`)}let l="";if(s&&a){try{const u=(await simctl(["get_app_container",e.udid,r,"data"])).trim();await copyBuoyFiles(s,import_node_path8.default.join(u,"Documents"));e.container=u;l=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(u){l=` Buoy's sign-in could not be restored (${u.message}): sign in to Buoy again in the app.`}}else if(c.length){try{const u=(await simctl(["get_app_container",e.udid,r,"data"])).trim();await simctl(["launch",e.udid,r]);const d=await iosWaitForLocalStorage(u);await simctl(["terminate",e.udid,r]).catch(()=>void 0);if(!d||!await iosWriteWebKeep(u,c))throw new Error("the app made no WebView storage");e.container=u;l=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(u){l=` Buoy's sign-in could not be restored (${u.message}): sign in to Buoy again in the app.`}}else if(t){l=" The old install had no Buoy sign-in to keep."}await simctl(["launch",e.udid,r]);return`Reinstalled ${r} from ${i} and launched it. The app's own data is gone, like a new user.${l}`}finally{if(s)await import_node_fs7.promises.rm(s,{recursive:true,force:true}).catch(()=>void 0)}}async function copyBuoyFiles(e,n){let t=false;for(const r of BUOY_KEEP){const i=import_node_path8.default.join(e,r);try{await import_node_fs7.promises.access(i)}catch{continue}const o=import_node_path8.default.join(n,r);await import_node_fs7.promises.mkdir(import_node_path8.default.dirname(o),{recursive:true});await import_node_fs7.promises.cp(i,o,{recursive:true,force:true});t=true}return t}async function reinstallAndroid(e,n,t,r){if(!/\.apk$/i.test(t))throw new Error("On Android, appPath must be an .apk file. Nothing was changed.");const i=await apkPackage(t);if(i!==n)throw new Error(`${import_node_path8.default.basename(t)} is ${i}, but this app is ${n}. Nothing was changed.`);const o=[];if(r){const c=await adbShell(e.serial,`run-as ${q(n)} find files/buoy-license files/react-buoy -maxdepth 1 -type f 2>/dev/null`).catch(()=>"");const l=c.split("\n").map(u=>u.trim()).filter(u=>u.startsWith("files/buoy-license/")||/react-buoy\/@react_buoy_(sync_device_id|install)\.json$/.test(u));for(const u of l){const d=await adbShell(e.serial,`run-as ${q(n)} base64 ${q(u)}`).catch(()=>"");if(d.trim())o.push({rel:u,data:d.replace(/\s+/g,"")})}}let s=[];if(r&&!o.length&&await androidHasWebViewStorage(e.serial,n)){try{s=await androidReadWebKeep(e.serial,n)}catch(c){throw new Error(`Couldn't read Buoy's sign-in from the app's WebView (${c.message}). Nothing was changed. Pass keepBuoy: false to reinstall anyway.`)}}await adb(e.serial,["install","-r","-d",t],18e4);await adbShell(e.serial,`pm clear ${q(n)}`);let a="";if(s.length){await hostLaunch(e);try{await androidWriteWebKeep(e.serial,n,s);a=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(c){a=` Buoy's sign-in could not be restored (${c.message}): sign in to Buoy again in the app.`}return`Reinstalled ${n} from ${t} and launched it. The app's data is gone, like a new user.${a}`}if(o.length){try{for(const c of o){const l=import_node_path8.default.posix.dirname(c.rel);await adbShell(e.serial,`echo ${q(c.data)} | run-as ${q(n)} sh -c ${q(`mkdir -p ${q(l)} && base64 -d > ${q(c.rel)}`)}`)}a=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(c){a=` Buoy's sign-in could not be restored (${c.message}): sign in to Buoy again in the app.`}}else if(r){a=" No Buoy sign-in could be read to keep (needs a debug build): sign in to Buoy again in the app."}await hostLaunch(e);return`Reinstalled ${n} from ${t} and launched it. The app's data is gone, like a new user.${a}`}async function reinstallPhone(e,n,t,r){if(!/\.app\/?$/i.test(t))throw new Error("On an iPhone, appPath must be a built .app folder (a device build). Nothing was changed.");const i=await appBundleInfo(t);if(i.bundleId!==n)throw new Error(`${import_node_path8.default.basename(t)} is ${i.bundleId}, but this app is ${n}. Nothing was changed.`);if(i.simulator)throw new Error(`${import_node_path8.default.basename(t)} is a simulator build, not a device build. Nothing was changed.`);const o=["Documents/buoy-license/buoy-gg-license.json","Documents/react-buoy/@react_buoy_sync_device_id.json","Documents/react-buoy/@react_buoy_install.json"];const s=r?await import_node_fs7.promises.mkdtemp(import_node_path8.default.join(import_node_os6.default.tmpdir(),"buoy-mcp-keep-")):null;try{const a=[];if(s){await import_node_fs7.promises.chmod(s,448);for(const l of o){let u;try{u=await readAppFile(e.udid,n,l)}catch(h){throw new Error(`Could not back up Buoy's ${import_node_path8.default.basename(l)} from the iPhone (${h.message}). Nothing was changed.`)}if(!u)continue;const d=import_node_path8.default.join(s,l.replace(/\//g,"__"));await import_node_fs7.promises.writeFile(d,u,{mode:384});a.push({rel:l,local:d})}}await phoneQuit(e.udid,n).catch(()=>false);await phoneUninstall(e.udid,n);try{await phoneInstall(e.udid,t)}catch(l){throw new Error(`The app was removed, but installing ${import_node_path8.default.basename(t)} failed: ${l.message}. Install it again from Xcode.`)}let c="";if(a.length){try{for(const d of a)await writeAppFile(e.udid,n,d.local,d.rel);const l=a.some(d=>d.rel.includes("buoy-license"));const u=a.some(d=>d.rel.includes("sync_device_id"));c=l?` Kept Buoy's sign-in${u?" and device id, so the same deviceId still works":""}.`:` Kept the device id; there was no Buoy sign-in to keep, so sign in to Buoy in the app.`}catch(l){c=` Buoy's sign-in could not be restored (${l.message}): sign in to Buoy again in the app.`}}else if(r)c=" The old install had no Buoy sign-in to keep.";await phoneLaunch(e.udid,n);return`Reinstalled ${n} on the iPhone and launched it. The app's own data is gone, like a new user.${c}`}finally{if(s)await import_node_fs7.promises.rm(s,{recursive:true,force:true}).catch(()=>void 0)}}async function bootSimulator(e){const n=JSON.parse(await simctl(["list","devices","available","-j"])).devices;const t=Object.entries(n).filter(([a])=>/iOS/.test(a)).flatMap(([,a])=>a);const r=e.trim().toLowerCase();const i=t.filter(a=>a.udid.toLowerCase()===r||a.name.toLowerCase()===r);const o=i.length?i:t.filter(a=>a.name.toLowerCase().includes(r));if(o.length===0)throw new Error(`No iOS Simulator matches "${e}". Run \`xcrun simctl list devices available\` to see them.`);if(o.length>1)throw new Error(`${o.length} simulators match "${e}": ${o.map(a=>`${a.name} (${a.udid})`).join(", ")}. Pass the udid.`);const s=o[0];if(s.state!=="Booted")await simctl(["boot",s.udid],12e4);await sh("open",["-a","Simulator","--args","-CurrentDeviceUDID",s.udid]).catch(()=>void 0);return s.state==="Booted"?`${s.name} (${s.udid}) was already booted.`:`Booted ${s.name} (${s.udid}).`}var import_node_child_process8,import_node_util7,import_node_fs7,import_node_os6,import_node_path8,import_node_crypto5,import_pngjs2,execFileAsync7,hosts,simctl,tailOf,finding,steadying,BUOY_KEEP;var init_hostDevice=__esm({"src/capture/hostDevice.ts"(){"use strict";import_node_child_process8=require("child_process");import_node_util7=require("util");import_node_fs7=require("fs");import_node_os6=__toESM(require("os"));import_node_path8=__toESM(require("path"));import_node_crypto5=require("crypto");import_pngjs2=__toESM(require_png());init_simctl();init_iosDevice();init_webViewKeep();init_adb();execFileAsync7=(0,import_node_util7.promisify)(import_node_child_process8.execFile);hosts=new Map;simctl=(e,n)=>sh("xcrun",["simctl",...e],n);tailOf=e=>e.split("-").pop()??"";finding=new Map;steadying=new Set;BUOY_KEEP=["buoy-license","react-buoy/@react_buoy_sync_device_id.json","react-buoy/@react_buoy_install.json"]}});async function hostTarget(e,n,t={},r={}){if(n==="All")throw new Error('Device control acts on one app. Pass its deviceId, not "All".');let i;let o=true;try{i=e.requireProDevice(n)}catch(c){const l=c instanceof Error?c.message:String(c);const u=l.startsWith(NOT_READY_MARK)&&/is not connected right now/.test(l)?/"([^"]+)"/.exec(l)?.[1]:void 0;const d=u?e.listDevices().some(h=>h.deviceId===u&&h.isPro):false;if(!r.allowOffline||!u||!d)throw c;i=u;o=false}const s=e.listDevices().find(c=>c.deviceId===i)?.platform;let a=await findHost(i,s,t);if(r.changesApp&&rememberedHost(i)===a)a=await verifyHost(i,a);return{id:i,host:a,online:o}}function hostLabel(e){if(e.platform==="ios")return`simulator "${e.name}"`;if(e.platform==="ios-device")return`iPhone "${e.name}"`;return`Android device ${e.serial}`}function has(e){if(!onPath.has(e))onPath.set(e,execFileAsync8("which",[e],{timeout:3e3}).then(()=>true,()=>false));return onPath.get(e)}async function hostSummary(e,n){let t=n;if(e.platform==="android"){const i=rememberedHost(e.deviceId);const o=i??(e.isConnected?await Promise.race([findHost(e.deviceId,"android").catch(()=>void 0),new Promise(a=>setTimeout(()=>a(void 0),3e3))]):void 0);const s=await has("adb");return{kind:"android",...o&&o.platform==="android"?{id:o.serial,name:o.packageName}:{},can:["screenshot","screen_recording","baseline diffs","quit/launch/reinstall","real lifecycle events","native_tap/type/swipe","native_inspect"],...!s?{missing:["adb (Android SDK platform-tools)"]}:!o?{missing:["proof of which phone runs it (needs a debug build reachable by adb)"]}:{}}}if(e.platform!=="ios")return{kind:e.platform??"unknown",can:[],missing:["host control works on iOS and Android apps"]};let r=rememberedHost(e.deviceId);if(!r&&!t&&e.isConnected){r=await Promise.race([findHost(e.deviceId,"ios").catch(()=>void 0),new Promise(i=>setTimeout(()=>i(void 0),4e3))])}if(!t&&r?.platform==="ios")t={name:r.name,udid:r.udid};if(r?.platform==="ios-device"){return{kind:"physical iPhone",id:r.udid,name:r.name,can:["screenshot","screen_recording (if this iPhone supports it)","baseline diffs","quit/launch/reinstall","open_url","native_tap/type/swipe/pinch (by query, testID, nativeTag or x/y; not label)","native_inspect (the app's side only)"]}}if(t){const i=await has("idb");return{kind:"ios simulator",id:t.udid,name:t.name,can:["screenshot","screen_recording","baseline diffs","quit/launch/reinstall/boot","real lifecycle events",...i?["native_tap/type/swipe/pinch","native_inspect"]:[]],...i?{}:{missing:["idb for real touches (brew install facebook/fb/idb-companion && pipx install fb-idb)"]}}}return void 0}var import_node_child_process9,import_node_util8,execFileAsync8,onPath;var init_hostKit=__esm({"src/tools/hostKit.ts"(){"use strict";init_SyncClient();import_node_child_process9=require("child_process");import_node_util8=require("util");init_hostDevice();execFileAsync8=(0,import_node_util8.promisify)(import_node_child_process9.execFile);onPath=new Map}});function json(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function fail(e){return{isError:true,content:[{type:"text",text:e}]}}function registerGenericTools(e,n){e.registerTool("list_devices",{description:"List the apps connected to Buoy: id, name, platform, whether it is connected and has MCP access, the simulator or phone it runs on with the host controls that work there (screenshot, recording, app control, real touches) and anything missing, and the Buoy tools it exposes. Start here. Pass details:true for every tool's action names.",inputSchema:{details:import_zod.z.boolean().optional().describe("Also list every action of every tool. Default false (tool names only); list_tool_actions gives one tool's actions."),includeDisconnected:import_zod.z.boolean().optional().describe("Also list apps that were seen before but are not connected now. Default false.")}},async(t={})=>{const r=await getUpdateNotice();let i=n.listDevices();for(let w=0;i.length===0&&w<10;w++){await new Promise(p=>setTimeout(p,200));i=n.listDevices()}if(i.length===0){return json({devices:[],hint:"No devices connected. Open the app with Buoy devtools running, then retry.",...r?{updateAvailable:r}:{}})}const o=t.includeDisconnected?0:i.filter(w=>!w.isConnected).length;if(!t.includeDisconnected)i=i.filter(w=>w.isConnected);if(i.length===0){return json({devices:[],hint:`No app is connected right now${o?` (${o} seen before; pass includeDisconnected:true to list them)`:""}. Open the app with Buoy devtools running, then retry.`,...r?{updateAvailable:r}:{}})}const s=await resolveSims(i.filter(w=>w.platform==="ios").map(w=>w.deviceId)).catch(()=>new Map);const a=i.filter(w=>w.isConnected);const c=a.some(w=>w.isPro);const l=a.some(w=>w.tier!=="locked");const u=a.filter(w=>w.collision);const d=await Promise.all(i.map(w=>w.isConnected?hostSummary(w,s.get(w.deviceId)).catch(()=>void 0):void 0));const h=i.map((w,p)=>{const g=s.get(w.deviceId);const m=d[p];return{deviceId:w.deviceId,deviceName:w.deviceName,platform:w.platform,isConnected:w.isConnected,isPro:w.isPro,tier:w.tier,access:n.accessState(w.deviceId),...g?{simulator:g}:{},...m?{host:m}:{},...w.collision?{collision:true}:{},tools:t.details?w.tools:w.tools.map(f=>f.toolId)}});return json({devices:h,...t.details?{}:{note:`Tool names only. Pass details:true, or list_tool_actions({toolId}), for action names.${o?` ${o} apps seen before but not connected now are left out (includeDisconnected:true lists them).`:""}`},...u.length>0?{warning:`${u.map(w=>`"${w.deviceId}"`).join(", ")}: more than one app is registered under this id, so actions sent to it land on an arbitrary device. Give each device its own externalSync.deviceId (or leave it unset for a per-install default) before mutating anything.`}:{},...c?{}:{hint:l?"The Buoy MCP is a Pro feature \u2014 the connected device is signed in on the free tier, so data/action tools are blocked. Upgrade to Buoy Pro in the app, or pass `licenseKey` to `<FloatingDevTools />` if it runs headless.":"The broker has not confirmed account access for the connected devices, so data/action tools are blocked. A locked status can mean missing configuration, pending/failed validation, or a missing account announcement after reconnect; it does not prove the user is signed out. Check app account status and broker compatibility."},...r?{updateAvailable:r}:{}})});e.registerTool("list_tool_actions",{description:"List the actions a tool exposes, and which connected devices offer it. Leave toolId out to list every tool's actions. Use the action names with call_action.",inputSchema:{toolId:import_zod.z.string().optional().describe('The tool id, e.g. "perf-monitor", "network", "react-query". Leave out for every tool.'),tool:import_zod.z.string().optional().describe("Same as toolId."),deviceId:import_zod.z.string().optional().describe("Only list what this device offers.")}},async({toolId:t,tool:r,deviceId:i})=>{const o=t??r;if(!o){const c=n.connectedDevices().filter(u=>!i||u.deviceId===i);if(c.length===0)return fail(i?`No connected device "${i}". Call list_devices.`:"No devices are connected. Call list_devices.");const l=c.map(u=>[`**${u.deviceName}** (${u.deviceId})`,...u.tools.map(d=>`- ${d.toolId}: ${d.actions.join(", ")}`)].join("\n"));return{content:[{type:"text",text:`${l.join("\n\n")}
|
|
42
56
|
|
|
43
|
-
Call one with call_action({toolId, action, params}).`}]}}const
|
|
57
|
+
Call one with call_action({toolId, action, params}).`}]}}const s=new Set(n.connectedDevices().map(c=>c.deviceId));const a=n.toolActions(o).filter(c=>s.has(c.deviceId)&&(!i||c.deviceId===i));if(a.length===0){const c=[...new Set(n.connectedDevices().flatMap(l=>l.tools.map(u=>u.toolId)))].sort();return fail(`No connected device exposes tool "${o}". Tool ids: ${c.join(", ")||"(none connected)"}. MCP tool names like "${o}" are not tool ids.`)}return json({toolId:o,offerings:a})});e.registerTool("get_snapshot",{description:"Read a tool's current state (its sync snapshot) from a device. Starts watching the tool and returns the next fresh snapshot.",inputSchema:{toolId:import_zod.z.string().optional().describe("The tool id to read state from."),tool:import_zod.z.string().optional().describe("Same as toolId."),deviceId:import_zod.z.string().optional().describe("The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out."),timeoutMs:import_zod.z.number().optional().describe("How long to wait for a fresh snapshot before falling back to the cached one.")}},async({toolId:t,tool:r,deviceId:i,timeoutMs:o})=>{try{const s=t??r;if(!s)return fail("get_snapshot needs toolId (see list_tool_actions).");const a=n.requireProDevice(i);const{payload:c,stale:l}=await n.getSnapshot(s,a,{timeoutMs:o});return json({toolId:s,deviceId:a,...l?{stale:l}:{},snapshot:c})}catch(s){return fail(errMsg(s))}});e.registerTool("call_action",{description:"Invoke any action a tool exposes (see list_tool_actions) and return its result. This is the generic escape hatch that works for every Buoy tool.",inputSchema:{toolId:import_zod.z.string().optional().describe('The tool id, e.g. "perf-monitor".'),tool:import_zod.z.string().optional().describe("Same as toolId."),action:import_zod.z.string().describe('The action name, e.g. "startRecording", "clearAll".'),params:import_zod.z.union([import_zod.z.record(import_zod.z.unknown()),import_zod.z.string()]).optional().describe("JSON params object for the action (shape depends on the action)."),args:import_zod.z.union([import_zod.z.record(import_zod.z.unknown()),import_zod.z.string()]).optional().describe("Same as params."),deviceId:import_zod.z.string().optional().describe('The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out. Or "All" to broadcast.'),timeoutMs:import_zod.z.number().optional().describe("Max time to wait for the device's result.")}},async({toolId:t,tool:r,action:i,params:o,args:s,deviceId:a,timeoutMs:c})=>{try{const l=t??r;if(!l)return fail("call_action needs toolId (see list_tool_actions).");const u=actionParams(o??s);const d=n.requireProDevice(a);const h=await n.callAction(l,i,u,d,{timeoutMs:c});return json({toolId:l,action:i,ok:true,result:h??null})}catch(l){return fail(errMsg(l))}})}function actionParams(e){if(e===void 0||typeof e==="object")return e;const n=e.trim();if(!n)return void 0;let t;try{t=JSON.parse(n)}catch{throw new Error('params is a string but not JSON. Pass an object, e.g. {"user": {...}}.')}if(!t||typeof t!=="object"||Array.isArray(t))throw new Error("params must be a JSON object.");return t}function errMsg(e){return e instanceof Error?e.message:String(e)}var import_zod;var init_generic=__esm({"src/tools/generic.ts"(){"use strict";import_zod=require("zod");init_checkForUpdate();init_simctl();init_hostKit()}});function clampLimit(e,n){return typeof e==="number"&&e>0?e:n}function staleHeader(e){return e?`${e}
|
|
44
58
|
|
|
45
|
-
`:""}function inactiveToolMessage(e){return`No ${e.toolId} result from the device. The ${e.toolId} tool may be inactive, or the app needs a newer Buoy (${e.mcpTool} requires the ${e.action} action).`}function withDevice(e,n){return async t=>{try{const r=e.requireProDevice(t.deviceId);return await n(t,r)}catch(r){return fail2(errMsg2(r))}}}function lastSyncAfterDrop(e,n,t){const r=n instanceof Error?n.message:String(n);if(!/is not connected right now/.test(r))return void 0;const i=/"([^"]+)"/.exec(r)?.[1];if(!i||!e.listDevices().some(a=>a.deviceId===i&&a.isPro))return void 0;const s=e.lastSync(i,t);if(!s)return void 0;const o=s.ageMs==null?"earlier":`${Math.round(s.ageMs/1e3)}s ago`;return{deviceId:i,payload:s.payload,stale:`\u26A0\uFE0F "${i}" is not connected, so this is the last data it sent (${o}). If it dropped right after an action, the app likely hit a fatal error (a red error screen): look for it below, then reload_app to recover.`}}var import_zod2,text,fail2,errMsg2,deviceIdInput;var init_packKit=__esm({"src/tools/packKit.ts"(){"use strict";import_zod2=require("zod");text=e=>({content:[{type:"text",text:e}]});fail2=e=>({isError:true,content:[{type:"text",text:e}]});errMsg2=e=>e instanceof Error?e.message:String(e);deviceIdInput=import_zod2.z.string().optional().describe("The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out.")}});var PERF_TOOL_ID;var init_perfMonitorTypes=__esm({"src/tools/packs/perfMonitorTypes.ts"(){"use strict";PERF_TOOL_ID="perf-monitor"}});function pick(e,n,t){return e??n??t}function buildAutomationConfig(e,n={}){const t=[];const r=(e.targetRoute||"").trim();if(!r)throw new Error("targetRoute is required (the screen to benchmark).");let i=(e.bounceRoute||"").trim();if(!i)i=r==="/"?"/_buoy_bounce":"/";if(i===r){throw new Error(`bounceRoute ("${i}") must differ from targetRoute \u2014 it's the screen we bounce to so the test screen fully remounts each run.`)}if(!Array.isArray(e.cases)||e.cases.length===0){throw new Error("At least one case is required.")}const s=e.cases.map((d,h)=>{const p=(d.name||"").trim()||`case ${h+1}`;return{id:`case-${h}`,name:p,params:d.params??{},route:d.route}});const o=clamp2(Math.round(pick(e.runsPerCase,n.runsPerCase,FALLBACK.runsPerCase)),1,10);const a=clamp2(Math.round(pick(e.coolDownMs,n.coolDownMs,FALLBACK.coolDownMs)),0,3e4);const c=clamp2(Math.round(pick(e.discardWarmupRuns,n.discardWarmupRuns,FALLBACK.discardWarmupRuns)),0,o-1);const u=e.shuffleCases??n.shuffleCases??s.length>3;if(s.length>3&&u===false){t.push("shuffleCases is off with >3 cases \u2014 later cases may be thermally throttled, biasing results. Consider enabling it.")}if(o===1){t.push("runsPerCase=1 \u2014 no median/variance; a single noisy run can mislead. 3+ is recommended.")}const l={targetRoute:r,bounceRoute:i,perCaseDurationMs:clamp2(Math.round(pick(e.perCaseDurationMs,n.perCaseDurationMs,FALLBACK.perCaseDurationMs)),1e3,6e4),settleMs:clamp2(Math.round(pick(e.settleMs,n.settleMs,FALLBACK.settleMs)),0,1e4),navTimeoutMs:clamp2(Math.round(pick(e.navTimeoutMs,n.navTimeoutMs,FALLBACK.navTimeoutMs)),1e3,3e4),cases:s,runsPerCase:o,coolDownMs:a,discardWarmupRuns:c,discardWarmupCase:e.discardWarmupCase??n.discardWarmupCase??true,shuffleCases:u,reloadBetweenCases:e.reloadBetweenCases??n.reloadBetweenCases??false,captureRenders:e.captureRenders??n.captureRenders??true};return{config:l,warnings:t}}function describeBenchmarkSettings(e){const n=c=>c>=1e3?`${(c/1e3).toFixed(c%1e3?1:0)}s`:`${c}ms`;const t=e.runsPerCase??1;const r=estimateBatchMs(e);const i=r/6e4;const s=i>=1?`~${i.toFixed(1)} min`:`~${Math.round(r/1e3)}s`;const o=[`**${n(e.perCaseDurationMs)} measured per page**`,t>1?`**${t} runs each** (median taken)`:`**1 run each** (no median \u2014 noisier)`,e.reloadBetweenCases?"**full reload between pages** (no state leaks across tests)":"no reload between pages",e.shuffleCases?"shuffled order (cancels thermal bias)":"fixed order",e.captureRenders!==false?"render capture on (per-component why-data)":"render capture off"];const a=e.settleMs+e.perCaseDurationMs+(e.coolDownMs??0)+1800;return`${o.join(", ")}. That's ~${n(a)} wall-clock per page; for ${e.cases.length} page(s) \xD7 ${t} run(s), **${s}** total.`}function estimateBatchMs(e){const n=1800;const t=e.settleMs+e.perCaseDurationMs+e.coolDownMs+n;let r=e.cases.length*(e.runsPerCase??1)*t;if(e.reloadBetweenCases)r+=e.cases.length*3e3;return r}function computeFlags(e){const n=[];const t=e.deviceMaxRefreshRate;if(e.uiFps!=null&&t&&e.uiFps<t*.95){n.push("UI thread drops frames")}else if(e.uiJank!=null&&e.uiJank>=2){n.push("UI jank spikes")}if(e.cpu!=null&&e.cpu>=90)n.push("CPU near cap");if(e.jsJank!=null&&e.jsJank>=5)n.push("JS thread stalls");return n}function computeWebFlags(e){const n=[];const t=e.deviceMaxRefreshRate;if(e.jsFps!=null&&t&&e.jsFps<t*.95){n.push("Low main-thread frame rate")}else if(e.longFrames!=null&&e.frames>0&&e.longFrames/e.frames>=.02){n.push("Frequent long frames")}const r=Math.max(e.frameGapMaxMs??0,e.edgeSilenceMs??0);if(r>=100)n.push(`Freeze of ${Math.round(r)} ms`);if(e.longTaskPct!=null&&e.longTaskPct>=20)n.push("Long tasks block the main thread");if(e.forcedLayoutMs!=null&&e.forcedLayoutMs>=50){n.push(`Forced layout in scripts (${Math.round(e.forcedLayoutMs)} ms)`)}if(e.styleLayoutMs!=null&&e.styleLayoutMs>=100){n.push(`Style and layout in slow frames (${Math.round(e.styleLayoutMs)} ms)`)}if(e.worstInteractionMs!=null&&e.worstInteractionMs>=200){n.push(`Slow response to input (${Math.round(e.worstInteractionMs)} ms)`)}if(e.layoutShift!=null&&e.layoutShift>=.1)n.push(`Layout shifts (${e.layoutShift})`);if(e.domGrowth!=null&&e.domGrowth>0){n.push(`DOM grew every run (+${e.domGrowth} nodes): check for a leak`)}return n}function domGrowthAcrossRuns(e){const n=e.filter(r=>!r.batchFailureReason&&!r.discardedWarmup).sort((r,i)=>(r.runIndex??0)-(i.runIndex??0)).map(r=>r.webRun?.domNodesStart).filter(r=>typeof r==="number");if(n.length<3)return null;for(let r=1;r<n.length;r++)if(n[r]<=n[r-1])return null;const t=n[n.length-1]-n[0];return t>=Math.max(50,n[0]*.05)?t:null}function pickBaseline(e,n){const t=e.find(i=>i.isBaseline);if(t)return t;const r=n?.[0]?.name;if(r){const i=e.filter(s=>s.caseName===r);if(i.length===1)return i[0]}return e[0]}function rankBatchFromIndex(e,n,t,r=[]){const i=e.filter(f=>f.batchId===n);const s=new Map(r.map(f=>[f.index,f.reason]));const o=Array.from(new Set(i.map(f=>f.batchIndex??0))).sort((f,b)=>f-b);const a=f=>{const b=i.filter(_=>(_.batchIndex??0)===f);if(b.length===0)return void 0;const v=b.filter(_=>!_.batchFailureReason&&!_.discardedWarmup);const y=v.filter(_=>_.webRun?.fps!=null);if(y.length>0&&y.length===v.length){const _=[...y].sort(($,k)=>$.webRun.fps-k.webRun.fps);return _[Math.floor((_.length-1)/2)]}if(v.length>0){return v.find(_=>_.isMedianRun===true)??v.find(_=>_.runIndex===0||_.runIndex===void 0)??v[0]}return b.find(_=>_.batchFailureReason)??b[0]};const c=f=>typeof f==="number"?f:null;const u=o.map(f=>{const b=a(f);const v=i.filter(P=>(P.batchIndex??0)===f);const y=v.length;const _=v.filter(P=>!P.batchFailureReason&&!P.discardedWarmup);const $=P=>P.webRun?P.webRun.fps??P.jsFpsAvg:P.uiFpsAvg;const k=_.map($).filter(P=>typeof P==="number");const T=b?.name??t?.[f]?.name??`case ${f+1}`;const A=i.some(P=>(P.batchIndex??0)===f&&P.isBaseline===true);const I=s.get(f)??b?.batchFailureReason;const R=v.every(P=>P.batchFailureReason||P.discardedWarmup);const M=Boolean(I)||!b||R;const S={batchIndex:f,caseName:T,params:b?.params??{},runs:y,failed:M,...b?.route?{route:b.route}:{},...A?{isBaseline:true}:{},failureReason:M?I??(R&&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:k.length?round(Math.min(...k),1):null,fpsMax:k.length?round(Math.max(...k),1):null,...b?.thermalState?{thermalState:b.thermalState}:{},renderCommits:c(b?.renderCommits),renderWasted:b?.renderWasted,topRenderers:b?.topRenderers??[]};const x=b?.webRun;if(!x)return{...S,flags:M?[]:computeFlags(S)};const E=[...x.longTasksSupported?[]:["long tasks"],...x.heapSupported?[]:["JS heap"],...x.loaf===null?["long animation frames"]:[]];const j={...S,platform:"web",uiFps:null,uiJank:null,jsJank:null,cpu:null,memMb:x.heapSupported?S.memMb:null,deviceMaxRefreshRate:Math.max(S.deviceMaxRefreshRate??0,x.refreshHz??0)||null,longTaskPct:x.longTaskPct,frameGapP95Ms:x.frameGapP95Ms,frameGapMaxMs:x.frameGapMaxMs,edgeSilenceMs:x.edgeSilenceMs??null,jsFps:x.fps??S.jsFps,longFrames:x.longFrames,...E.length?{missingMetrics:E}:{},loafBlockingMs:x.loaf?.blockingMs??null,styleLayoutMs:x.loaf?.styleLayoutMs??null,forcedLayoutMs:x.loaf?.forcedLayoutMs??null,topScripts:x.loaf?.topScripts??[],worstInteractionMs:x.interactions?.worstMs??null,layoutShift:x.layoutShift??null,domNodes:x.domNodesEnd??null,domGrowth:domGrowthAcrossRuns(v),pageLoad:x.pageLoad??null,refreshCalibrated:x.refreshCalibrated??null};return{...j,flags:M?[]:computeWebFlags({...j,frames:x.frames})}}).filter(f=>f.caseName!==WARMUP_CASE_NAME).map((f,b)=>({...f,batchIndex:b}));const l=pickBaseline(u,t);if(l){l.isBaseline=true;for(const f of u){if(f===l)continue;if(f.uiFps!=null&&l.uiFps!=null)f.deltaUiFps=round(f.uiFps-l.uiFps,1);if(f.jsFps!=null&&l.jsFps!=null)f.deltaJsFps=round(f.jsFps-l.jsFps,1)}}const d=u.filter(f=>!f.failed);const h=(f,b)=>{let v;let y=NaN;for(const _ of d){const $=f(_);if($==null)continue;if(v===void 0||b($,y)){v=_;y=$}}return v?.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=d.filter(f=>f.flags.length>0).map(f=>({caseName:f.caseName,flags:f.flags}));const w=d.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:l?.caseName??null,deviceMaxRefreshRate:d.find(f=>f.deviceMaxRefreshRate!=null)?.deviceMaxRefreshRate??null,rows:u,leaders:m,flagged:g,balanced:w}}function pageLoadLines(e){const n=e.filter(o=>!o.failed);if(n.length===0)return[];const t=n.map(o=>o.pageLoad?.navigationId);if(t.some(o=>o==null)||new Set(t).size!==t.length)return[];if(n.some(o=>(o.pageLoad?.pageAgeMs??Infinity)>3e4))return[];const r=o=>(o??"").replace(/\/+$/,"")||"/";const i=o=>{const a=o.pageLoad;if(!a?.loadPath||r(a.loadPath)!==r(o.route))return false;const c=new URLSearchParams(a.loadSearch??"");const u=[...c.keys()];if(new Set(u).size!==u.length)return false;const l=Object.entries(o.params);return u.length===l.length&&l.every(([d,h])=>c.get(d)===h)};if(n.some(o=>!i(o)))return[];const s=o=>o==null?"\u2014":String(Math.round(o));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(o=>{const a=o.pageLoad;return`| ${o.caseName} | ${s(a.ttfbMs)} | ${s(a.fcpMs)} | ${s(a.lcpMs)} | ${s(a.domContentLoadedMs)} | ${s(a.scriptKb)} | ${s(a.totalKb)} |`}),"",`_KB is bytes over the network. 0 can mean the file came from cache, so compare cold loads with cold loads._`]}function closeCallNote(e){const n=s=>s.platform==="web"?s.jsFps:s.uiFps;const t=e.filter(s=>!s.failed&&n(s)!=null&&s.fpsMin!=null&&s.fpsMax!=null).sort((s,o)=>(n(o)??0)-(n(s)??0));if(t.length<2)return null;const[r,i]=t;if((r.validRuns??0)<2||(i.validRuns??0)<2){return`**Too few runs to separate the top cases.** ${r.caseName} and ${i.caseName} each need 2+ valid runs before their FPS gap means anything.`}if((i.fpsMax??0)>=(r.fpsMin??0)||(n(r)??0)-(n(i)??0)<=2){return`**Too close to call:** ${r.caseName} (${r.fpsMin}\u2013${r.fpsMax} FPS) and ${i.caseName} (${i.fpsMin}\u2013${i.fpsMax} FPS) overlap or sit within 2 FPS. No clear winner between them; more runs may separate them.`}return null}function formatRankingMarkdown(e){const n=(h,p=1)=>h==null?"\u2014":h.toFixed(p);const t=h=>h==null?"":h>0?` (+${h.toFixed(1)})`:` (${h.toFixed(1)})`;const r=[];r.push(`### Benchmark batch \`${e.batchId}\``);if(e.rows.some(h=>h.platform==="web")){formatWebTable(e,r);return r.join("\n")}r.push(`**No single winner \u2014 weigh the trade-offs.** UI-thread health matters more than raw averages: a cheap run that drops UI frames is worse than a pricier one that holds them.`);r.push("");const i=e.rows.some(h=>h.thermalState);const s=i?" Thermal |":"";const o=i?"-------|":"";r.push(`| # | Case | UI FPS | JS FPS | CPU % | Mem MB | JS jank | UI jank |${s} Flags |`);r.push(`|---|------|-------:|-------:|------:|-------:|--------:|--------:|${o}-------|`);for(const h of e.rows){const p=i?` ${THERMAL_MARK[h.thermalState??"unknown"]??"\u2014"} |`:"";if(h.failed){r.push(`| ${h.batchIndex} | ${h.caseName} | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 |${p} \u274C FAILED (${h.failureReason}) |`);continue}const 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 a=closeCallNote(e.rows);if(a){r.push("");r.push(a)}const c=e.rows.filter(h=>h.thermalState==="serious"||h.thermalState==="critical");if(c.length){r.push("");r.push(`**\u{1F525} Thermally throttled: ${c.map(h=>h.caseName).join(", ")}.** A throttled device runs SLOWER at a LOWER cpu%, so these cases can look like the cheapest in the batch while actually delivering fewer frames \u2014 check their UI FPS and jank, and re-run them on a cool device before drawing any conclusion.`)}r.push("");const u=e.leaders;const l=[u.uiFps&&`UI FPS \u2192 **${u.uiFps}**`,u.jsFps&&`JS FPS \u2192 **${u.jsFps}**`,u.lowestCpu&&`lowest CPU \u2192 **${u.lowestCpu}**`,u.lowestMem&&`lowest mem \u2192 **${u.lowestMem}**`,u.fewestJank&&`fewest jank \u2192 **${u.fewestJank}**`].filter(Boolean).join(" \xB7 ");if(l)r.push(`**Per-metric best:** ${l}`);r.push(e.balanced.length?`**No configured risk flags:** ${e.balanced.join(", ")}. Check missing metrics and workload requirements before choosing.`:`**No configured risk flags:** no candidates listed. Review failures, available metrics and flags before choosing.`);if(e.flagged.length){r.push(`**\u26A0\uFE0F At-risk:** ${e.flagged.map(h=>`${h.caseName} (${h.flags.join("; ")})`).join(" \xB7 ")}`)}const d=e.rows.filter(h=>!h.failed&&(h.renderCommits!=null||h.topRenderers.length>0)).map(h=>{const p=h.topRenderers.map(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(d.length){r.push("");r.push("**Renders (median run)** \u2014 `wasted` = parent cascades + identity-only prop churn (removable). Cause per component: `propsUnstable` means a parent handed it a fresh function/object with unchanged values \u2014 fix upstream.");r.push(...d)}r.push("");r.push(`_Deltas vs baseline (\`${e.baselineName??"case #0"}\`). Don't pick on one metric \u2014 explain the trade-off (e.g. "A is cheapest but drops UI frames \u2192 jank risk; B costs more CPU but caps nothing")._`);return r.join("\n")}function compareReportStats(e,n){const t=(r,i)=>({a:{avg:round(r.avg,1),p95:round(r.p95,1)},b:{avg:round(i.avg,1),p95:round(i.p95,1)},deltaAvg:round(i.avg-r.avg,1)});return{a:e.name,b:n.name,uiFps:t(e.stats.uiFps,n.stats.uiFps),jsFps:t(e.stats.jsFps,n.stats.jsFps),cpuUsage:t(e.stats.cpuUsage,n.stats.cpuUsage),memoryUsage:t(e.stats.memoryUsage,n.stats.memoryUsage),jsJankFrames:{a:e.stats.jsJankFrames,b:n.stats.jsJankFrames,delta:n.stats.jsJankFrames-e.stats.jsJankFrames},uiJankFrames:{a:e.stats.uiJankFrames,b:n.stats.uiJankFrames,delta:n.stats.uiJankFrames-e.stats.uiJankFrames},...compareRenders(e.renders,n.renders)}}function compareWebReports(e,n){const t=(o,a,c)=>({a:o??null,b:a??null,delta:o!=null&&a!=null?round(a-o,1):null,better:c});const r=o=>o.webRun.heapSupported?round(o.stats.memoryUsage.max,1):null;const i=e.webRun;const s=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,s.fps??n.stats.jsFps.avg,"higher"),frameGapP95Ms:t(i.frameGapP95Ms,s.frameGapP95Ms,"lower"),frameGapMaxMs:t(i.frameGapMaxMs,s.frameGapMaxMs,"lower"),longFrames:t(i.longFrames,s.longFrames,"lower"),longTaskPct:t(i.longTaskPct,s.longTaskPct,"lower"),slowFrameBlockingMs:t(i.loaf?.blockingMs,s.loaf?.blockingMs,"lower"),styleLayoutPaintMs:t(i.loaf?.styleLayoutMs,s.loaf?.styleLayoutMs,"lower"),forcedLayoutMs:t(i.loaf?.forcedLayoutMs,s.loaf?.forcedLayoutMs,"lower"),worstInteractionMs:t(i.interactions?.worstMs,s.interactions?.worstMs,"lower"),layoutShift:t(i.layoutShift,s.layoutShift,"lower"),domNodes:t(i.domNodesEnd,s.domNodesEnd,"lower"),jsHeapMb:t(r(e),r(n),"lower"),topScripts:{a:i.loaf?.topScripts??[],b:s.loaf?.topScripts??[]},...compareRenders(e.renders,n.renders)}}function compareRenders(e,n){if(!e&&!n)return null;const t=r=>r??0;return{renders:{total:{a:t(e?.totalRenders),b:t(n?.totalRenders),delta:t(n?.totalRenders)-t(e?.totalRenders)},commits:{a:t(e?.totalCommits),b:t(n?.totalCommits),delta:t(n?.totalCommits)-t(e?.totalCommits)},wasted:{a:t(e?.wastedRenders),b:t(n?.wastedRenders),delta:t(n?.wastedRenders)-t(e?.wastedRenders)},causes:{a:e?.causes??{},b:n?.causes??{}}}}}function round(e,n){const t=Math.pow(10,n);return Math.round(e*t)/t}function formatWebTable(e,n){const t=(l,d=1)=>l==null?"\u2014":l.toFixed(d);const r=l=>l==null?"":l>0?` (+${l.toFixed(1)})`:` (${l.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 l of e.rows){const d=l.isBaseline?`${l.caseName} (baseline)`:l.caseName;if(l.failed){n.push(`| ${l.batchIndex} | ${d} | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u274C FAILED (${l.failureReason}) |`);continue}const h=l.flags.length?`\u26A0\uFE0F ${l.flags.join("; ")}`:"no flags";n.push(`| ${l.batchIndex} | ${d} | ${t(l.jsFps)}${r(l.deltaJsFps)} | ${t(l.frameGapP95Ms)} | ${t(l.frameGapMaxMs)} | ${t(l.longFrames,0)} | ${t(l.longTaskPct)} | ${t(l.memMb)} | ${h} |`)}const i=e.rows.filter(l=>!l.failed).map(l=>{const d=[l.loafBlockingMs!=null&&l.loafBlockingMs>0&&`slow frames blocked input ${l.loafBlockingMs} ms`,l.styleLayoutMs!=null&&l.styleLayoutMs>0&&`style + layout ${l.styleLayoutMs} ms`,l.forcedLayoutMs!=null&&l.forcedLayoutMs>0&&`forced layout ${l.forcedLayoutMs} ms`,l.worstInteractionMs!=null&&`slowest input ${l.worstInteractionMs} ms`,l.layoutShift!=null&&l.layoutShift>0&&`layout shift ${l.layoutShift}`,l.domNodes!=null&&`${l.domNodes} DOM nodes${l.domGrowth?` (+${l.domGrowth} over the runs)`:""}`,l.topScripts&&l.topScripts.length>0&&`top scripts: ${l.topScripts.slice(0,3).map(h=>`${h.name} ${h.ms} ms`).join(", ")}`].filter(Boolean);return d.length?`- **${l.caseName}**: ${d.join(" \xB7 ")}`:null}).filter(Boolean);if(i.length){n.push("");n.push(`**Why frames were slow** (Long Animation Frames, Event Timing, DOM size; slow frames that ran past a run's end are left out):`);n.push(...i)}const s=pageLoadLines(e.rows);if(s.length){n.push("");n.push(...s)}const o=closeCallNote(e.rows);if(o){n.push("");n.push(o)}const a=Array.from(new Set(e.rows.flatMap(l=>l.missingMetrics??[])));if(a.length){n.push("");n.push(`**Not measured in this browser:** ${a.join(", ")}. These show as \u2014 and can't win or lose.`)}if(e.rows.some(l=>l.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 u=[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(u)n.push(`**Per-metric leaders:** ${u}`);if(e.flagged.length){n.push(`**\u26A0\uFE0F At-risk:** ${e.flagged.map(l=>`${l.caseName} (${l.flags.join("; ")})`).join(" \xB7 ")}`)}n.push(e.balanced.length?`**No configured risk flags:** ${e.balanced.join(", ")}. Check missing metrics and workload requirements before choosing.`:`**No configured risk flags:** no candidates listed. Review failures, available metrics and flags before choosing.`);n.push("");n.push(`_Deltas vs baseline (\`${e.baselineName??"case #0"}\`). Confirm finalists on a real phone browser: desktop numbers don't predict mobile GPU, memory or heat._`)}var clamp2,WARMUP_CASE_NAME,THERMAL_MARK,FALLBACK;var init_perfRanking=__esm({"src/tools/packs/perfRanking.ts"(){"use strict";clamp2=(e,n,t)=>Math.max(n,Math.min(t,e));WARMUP_CASE_NAME="__batch_warmup__";THERMAL_MARK={nominal:"\u{1F7E2} nominal",fair:"\u{1F7E1} fair",serious:"\u{1F7E0} serious",critical:"\u{1F534} critical",unknown:"\u2014"};FALLBACK={perCaseDurationMs:5e3,settleMs:600,navTimeoutMs:5e3,runsPerCase:3,coolDownMs:2e3,discardWarmupRuns:0}}});async function readDeviceSettings(e,n){try{const t=await e.callAction(PERF_TOOL_ID,"getAutomationConfig",{},n);if(!t)return{};const{perCaseDurationMs:r,settleMs:i,navTimeoutMs:s,runsPerCase:o,coolDownMs:a,discardWarmupRuns:c,shuffleCases:u,reloadBetweenCases:l,captureRenders:d}=t;return{perCaseDurationMs:r,settleMs:i,navTimeoutMs:s,runsPerCase:o,coolDownMs:a,discardWarmupRuns:c,shuffleCases:u,reloadBetweenCases:l,captureRenders:d}}catch{return{}}}async function readPerfSnapshot(e,n){const{payload:t}=await e.getSnapshot(PERF_TOOL_ID,n,{timeoutMs:4e3});return t}function batchIdsIn(e){const n=new Set;for(const t of e??[])if(t.batchId)n.add(t.batchId);return n}function runCountFor(e,n){return(e??[]).filter(t=>t.batchId===n).length}function newestBatchId(e){let n=null;for(const t of e??[]){if(t.batchId&&(!n||t.createdAt>n.at))n={id:t.batchId,at:t.createdAt}}return n?.id??null}function failuresFromIndex(e,n){const t=new Map;for(const r of e??[]){if(r.batchId===n&&r.batchFailureReason&&!t.has(r.batchIndex??0)){t.set(r.batchIndex??0,r.batchFailureReason)}}return[...t.entries()].map(([r,i])=>({index:r,reason:i}))}function expectedRunsFor(e){const n=e.cases.length+(e.discardWarmupCase===true?1:0);return n*(e.runsPerCase??1)}function isRunnerBusy(e){return!!e&&e!=="idle"&&e!=="done"&&e!=="cancelled"}async function waitForRunnerSettled(e,n,t,r=SETTLE_WAIT_MS){const i=Date.now();while(Date.now()-i<r){const s=await readPerfSnapshot(e,n).catch(()=>null);if(s&&!isRunnerBusy(s.live?.automation?.phase))return true;await delay2(POLL_INTERVAL_MS)}t(`automation still busy after ${Math.round(r/1e3)}s`);return false}async function waitForBatchByIndex(e,n,t){const{preBatchIds:r,expectedRuns:i,maxWaitMs:s,log:o}=t;const a=t.reloadsBetweenCases?10:3;const c=Date.now();let u="";let l=false;let d=0;while(Date.now()-c<s){let m;try{m=await readPerfSnapshot(e,n)}catch{await delay2(POLL_INTERVAL_MS);continue}const g=m.index??[];const w=m.live?.automation?.phase??"idle";const f=m.live?.automationCompleted;if(f?.phase==="cancelled"&&!r.has(f.batchId)){return{batchId:f.batchId,failures:[],cancelled:true}}if(f?.phase==="done"&&!r.has(f.batchId)){return{batchId:f.batchId,failures:f.failures??failuresFromIndex(g,f.batchId)}}if(w!=="idle")l=true;if(w!==u){u=w;o(`automation phase: ${w}`)}const b=[...batchIdsIn(g)].find(v=>!r.has(v));if(b){const v=runCountFor(g,b);if(i>0&&v>=i){await waitForRunnerSettled(e,n,o);o(`batch ${b} complete (${v}/${i} runs saved)`);return{batchId:b,failures:failuresFromIndex(g,b)}}const y=(g??[]).filter(T=>T.batchId===b&&T.name!==WARMUP_CASE_NAME).length;const _=m.live?.pendingBatchId===b;const $=Boolean(m.live&&"pendingBatchId"in m.live);const k=!t.reloadsBetweenCases||$;if(w==="idle"&&l&&y>0&&!_&&k){if(++d>=a){o(`batch ${b} settled (${v} runs, automation idle)`);return{batchId:b,failures:failuresFromIndex(g,b)}}}else{d=0}}await delay2(POLL_INTERVAL_MS)}const h=await readPerfSnapshot(e,n).catch(()=>null);const p=h?[...batchIdsIn(h.index)].find(m=>!r.has(m)):void 0;if(p&&h)return{batchId:p,failures:failuresFromIndex(h.index,p),timedOut:true};throw new Error(`Batch did not start within ${Math.round(s/1e3)}s (last phase: ${u||"idle"}). Check get_automation_status \u2014 the device may not have navigated.`)}function registerPerfMonitorTools(e,n){e.registerTool("run_benchmark_batch",{description:"Run a perf-monitor benchmark batch and return per-metric leaders, risk flags and a comparison of available case results. Give it a target route and a matrix of cases (each a name + query params that select a variant on that route); it navigates, records, and benchmarks each case on the device, then ranks them. This blocks until the batch completes (can be minutes for large batches). The app must have the target route render its variants from the params.",inputSchema:{targetRoute:import_zod3.z.string().describe('The screen to benchmark, e.g. "/perf-test". Reads case params to pick a variant.'),cases:import_zod3.z.array(caseSchema).min(1).describe("The variants to compare. Case #0 is the baseline for deltas."),bounceRoute:import_zod3.z.string().optional().describe('Screen to bounce to between runs so the test screen fully remounts. Defaults to "/" (or a stub if target is "/").'),runsPerCase:import_zod3.z.number().optional().describe("Runs per case; the median becomes the canonical result. Default 3 (1\u201310)."),perCaseDurationMs:import_zod3.z.number().optional().describe("How long to record each run. Default 5000."),settleMs:import_zod3.z.number().optional().describe("Idle gap after navigation before recording. Default 600."),coolDownMs:import_zod3.z.number().optional().describe("Idle between runs/cases for thermal recovery. Default 2000."),navTimeoutMs:import_zod3.z.number().optional().describe("Max wait for navigation per run. Default 5000."),discardWarmupRuns:import_zod3.z.number().optional().describe("Discard first N runs of each case before taking the median. Default 0."),shuffleCases:import_zod3.z.boolean().optional().describe("Interleave and shuffle case order to reduce order-related bias. Default on for >3 cases."),reloadBetweenCases:import_zod3.z.boolean().optional().describe("Fully reload JS between cases (needs <AutomationResumer/> mounted). Default false."),captureRenders:import_zod3.z.boolean().optional().describe("Capture per-component render counts/durations during each run (needs @buoy-gg/highlight-updates installed; dev builds only). Adds instrumentation overhead that can vary with the workload. Default true."),deviceId:import_zod3.z.string().optional().describe("The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out."),maxWaitMs:import_zod3.z.number().optional().describe("Safety cap for how long to wait for completion. Defaults to ~3\xD7 the estimate + 60s.")}},async t=>{const r=i=>process.stderr.write(`[buoy-mcp] ${i}
|
|
46
|
-
`);try{const i=n.requireProDevice(t.deviceId);const
|
|
59
|
+
`:""}function inactiveToolMessage(e){return`No ${e.toolId} result from the device. The ${e.toolId} tool may be inactive, or the app needs a newer Buoy (${e.mcpTool} requires the ${e.action} action).`}function withDevice(e,n){return async t=>{try{const r=e.requireProDevice(t.deviceId);return await n(t,r)}catch(r){return fail2(errMsg2(r))}}}function lastSyncAfterDrop(e,n,t){const r=n instanceof Error?n.message:String(n);if(!/is not connected right now/.test(r))return void 0;const i=/"([^"]+)"/.exec(r)?.[1];if(!i||!e.listDevices().some(a=>a.deviceId===i&&a.isPro))return void 0;const o=e.lastSync(i,t);if(!o)return void 0;const s=o.ageMs==null?"earlier":`${Math.round(o.ageMs/1e3)}s ago`;return{deviceId:i,payload:o.payload,stale:`\u26A0\uFE0F "${i}" is not connected, so this is the last data it sent (${s}). If it dropped right after an action, the app likely hit a fatal error (a red error screen): look for it below, then reload_app to recover.`}}var import_zod2,text,fail2,errMsg2,deviceIdInput,coreTool;var init_packKit=__esm({"src/tools/packKit.ts"(){"use strict";import_zod2=require("zod");text=e=>({content:[{type:"text",text:e}]});fail2=e=>({isError:true,content:[{type:"text",text:e}]});errMsg2=e=>e instanceof Error?e.message:String(e);deviceIdInput=import_zod2.z.string().optional().describe("The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out.");coreTool=()=>process.env.BUOY_LOAD_CORE_TOOLS==="0"?void 0:{"anthropic/alwaysLoad":true}}});var PERF_TOOL_ID;var init_perfMonitorTypes=__esm({"src/tools/packs/perfMonitorTypes.ts"(){"use strict";PERF_TOOL_ID="perf-monitor"}});function pick(e,n,t){return e??n??t}function buildAutomationConfig(e,n={}){const t=[];const r=(e.targetRoute||"").trim();if(!r)throw new Error("targetRoute is required (the screen to benchmark).");let i=(e.bounceRoute||"").trim();if(!i)i=r==="/"?"/_buoy_bounce":"/";if(i===r){throw new Error(`bounceRoute ("${i}") must differ from targetRoute \u2014 it's the screen we bounce to so the test screen fully remounts each run.`)}if(!Array.isArray(e.cases)||e.cases.length===0){throw new Error("At least one case is required.")}const o=e.cases.map((d,h)=>{const w=(d.name||"").trim()||`case ${h+1}`;return{id:`case-${h}`,name:w,params:d.params??{},route:d.route}});const s=clamp2(Math.round(pick(e.runsPerCase,n.runsPerCase,FALLBACK.runsPerCase)),1,10);const a=clamp2(Math.round(pick(e.coolDownMs,n.coolDownMs,FALLBACK.coolDownMs)),0,3e4);const c=clamp2(Math.round(pick(e.discardWarmupRuns,n.discardWarmupRuns,FALLBACK.discardWarmupRuns)),0,s-1);const l=e.shuffleCases??n.shuffleCases??o.length>3;if(o.length>3&&l===false){t.push("shuffleCases is off with >3 cases \u2014 later cases may be thermally throttled, biasing results. Consider enabling it.")}if(s===1){t.push("runsPerCase=1 \u2014 no median/variance; a single noisy run can mislead. 3+ is recommended.")}const u={targetRoute:r,bounceRoute:i,perCaseDurationMs:clamp2(Math.round(pick(e.perCaseDurationMs,n.perCaseDurationMs,FALLBACK.perCaseDurationMs)),1e3,6e4),settleMs:clamp2(Math.round(pick(e.settleMs,n.settleMs,FALLBACK.settleMs)),0,1e4),navTimeoutMs:clamp2(Math.round(pick(e.navTimeoutMs,n.navTimeoutMs,FALLBACK.navTimeoutMs)),1e3,3e4),cases:o,runsPerCase:s,coolDownMs:a,discardWarmupRuns:c,discardWarmupCase:e.discardWarmupCase??n.discardWarmupCase??true,shuffleCases:l,reloadBetweenCases:e.reloadBetweenCases??n.reloadBetweenCases??false,captureRenders:e.captureRenders??n.captureRenders??true};return{config:u,warnings:t}}function describeBenchmarkSettings(e){const n=c=>c>=1e3?`${(c/1e3).toFixed(c%1e3?1:0)}s`:`${c}ms`;const t=e.runsPerCase??1;const r=estimateBatchMs(e);const i=r/6e4;const o=i>=1?`~${i.toFixed(1)} min`:`~${Math.round(r/1e3)}s`;const s=[`**${n(e.perCaseDurationMs)} measured per page**`,t>1?`**${t} runs each** (median taken)`:`**1 run each** (no median \u2014 noisier)`,e.reloadBetweenCases?"**full reload between pages** (no state leaks across tests)":"no reload between pages",e.shuffleCases?"shuffled order (cancels thermal bias)":"fixed order",e.captureRenders!==false?"render capture on (per-component why-data)":"render capture off"];const a=e.settleMs+e.perCaseDurationMs+(e.coolDownMs??0)+1800;return`${s.join(", ")}. That's ~${n(a)} wall-clock per page; for ${e.cases.length} page(s) \xD7 ${t} run(s), **${o}** total.`}function estimateBatchMs(e){const n=1800;const t=e.settleMs+e.perCaseDurationMs+e.coolDownMs+n;let r=e.cases.length*(e.runsPerCase??1)*t;if(e.reloadBetweenCases)r+=e.cases.length*3e3;return r}function computeFlags(e){const n=[];const t=e.deviceMaxRefreshRate;if(e.uiFps!=null&&t&&e.uiFps<t*.95){n.push("UI thread drops frames")}else if(e.uiJank!=null&&e.uiJank>=2){n.push("UI jank spikes")}if(e.cpu!=null&&e.cpu>=90)n.push("CPU near cap");if(e.jsJank!=null&&e.jsJank>=5)n.push("JS thread stalls");return n}function computeWebFlags(e){const n=[];const t=e.deviceMaxRefreshRate;if(e.jsFps!=null&&t&&e.jsFps<t*.95){n.push("Low main-thread frame rate")}else if(e.longFrames!=null&&e.frames>0&&e.longFrames/e.frames>=.02){n.push("Frequent long frames")}const r=Math.max(e.frameGapMaxMs??0,e.edgeSilenceMs??0);if(r>=100)n.push(`Freeze of ${Math.round(r)} ms`);if(e.longTaskPct!=null&&e.longTaskPct>=20)n.push("Long tasks block the main thread");if(e.forcedLayoutMs!=null&&e.forcedLayoutMs>=50){n.push(`Forced layout in scripts (${Math.round(e.forcedLayoutMs)} ms)`)}if(e.styleLayoutMs!=null&&e.styleLayoutMs>=100){n.push(`Style and layout in slow frames (${Math.round(e.styleLayoutMs)} ms)`)}if(e.worstInteractionMs!=null&&e.worstInteractionMs>=200){n.push(`Slow response to input (${Math.round(e.worstInteractionMs)} ms)`)}if(e.layoutShift!=null&&e.layoutShift>=.1)n.push(`Layout shifts (${e.layoutShift})`);if(e.domGrowth!=null&&e.domGrowth>0){n.push(`DOM grew every run (+${e.domGrowth} nodes): check for a leak`)}return n}function domGrowthAcrossRuns(e){const n=e.filter(r=>!r.batchFailureReason&&!r.discardedWarmup).sort((r,i)=>(r.runIndex??0)-(i.runIndex??0)).map(r=>r.webRun?.domNodesStart).filter(r=>typeof r==="number");if(n.length<3)return null;for(let r=1;r<n.length;r++)if(n[r]<=n[r-1])return null;const t=n[n.length-1]-n[0];return t>=Math.max(50,n[0]*.05)?t:null}function pickBaseline(e,n){const t=e.find(i=>i.isBaseline);if(t)return t;const r=n?.[0]?.name;if(r){const i=e.filter(o=>o.caseName===r);if(i.length===1)return i[0]}return e[0]}function rankBatchFromIndex(e,n,t,r=[]){const i=e.filter(f=>f.batchId===n);const o=new Map(r.map(f=>[f.index,f.reason]));const s=Array.from(new Set(i.map(f=>f.batchIndex??0))).sort((f,b)=>f-b);const a=f=>{const b=i.filter($=>($.batchIndex??0)===f);if(b.length===0)return void 0;const v=b.filter($=>!$.batchFailureReason&&!$.discardedWarmup);const y=v.filter($=>$.webRun?.fps!=null);if(y.length>0&&y.length===v.length){const $=[...y].sort((T,_)=>T.webRun.fps-_.webRun.fps);return $[Math.floor(($.length-1)/2)]}if(v.length>0){return v.find($=>$.isMedianRun===true)??v.find($=>$.runIndex===0||$.runIndex===void 0)??v[0]}return b.find($=>$.batchFailureReason)??b[0]};const c=f=>typeof f==="number"?f:null;const l=s.map(f=>{const b=a(f);const v=i.filter(R=>(R.batchIndex??0)===f);const y=v.length;const $=v.filter(R=>!R.batchFailureReason&&!R.discardedWarmup);const T=R=>R.webRun?R.webRun.fps??R.jsFpsAvg:R.uiFpsAvg;const _=$.map(T).filter(R=>typeof R==="number");const x=b?.name??t?.[f]?.name??`case ${f+1}`;const I=i.some(R=>(R.batchIndex??0)===f&&R.isBaseline===true);const D=o.get(f)??b?.batchFailureReason;const E=v.every(R=>R.batchFailureReason||R.discardedWarmup);const S=Boolean(D)||!b||E;const k={batchIndex:f,caseName:x,params:b?.params??{},runs:y,failed:S,...b?.route?{route:b.route}:{},...I?{isBaseline:true}:{},failureReason:S?D??(E&&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:_.length?round(Math.min(..._),1):null,fpsMax:_.length?round(Math.max(..._),1):null,...b?.thermalState?{thermalState:b.thermalState}:{},renderCommits:c(b?.renderCommits),renderWasted:b?.renderWasted,topRenderers:b?.topRenderers??[]};const M=b?.webRun;if(!M)return{...k,flags:S?[]:computeFlags(k)};const A=[...M.longTasksSupported?[]:["long tasks"],...M.heapSupported?[]:["JS heap"],...M.loaf===null?["long animation frames"]:[]];const P={...k,platform:"web",uiFps:null,uiJank:null,jsJank:null,cpu:null,memMb:M.heapSupported?k.memMb:null,deviceMaxRefreshRate:Math.max(k.deviceMaxRefreshRate??0,M.refreshHz??0)||null,longTaskPct:M.longTaskPct,frameGapP95Ms:M.frameGapP95Ms,frameGapMaxMs:M.frameGapMaxMs,edgeSilenceMs:M.edgeSilenceMs??null,jsFps:M.fps??k.jsFps,longFrames:M.longFrames,...A.length?{missingMetrics:A}:{},loafBlockingMs:M.loaf?.blockingMs??null,styleLayoutMs:M.loaf?.styleLayoutMs??null,forcedLayoutMs:M.loaf?.forcedLayoutMs??null,topScripts:M.loaf?.topScripts??[],worstInteractionMs:M.interactions?.worstMs??null,layoutShift:M.layoutShift??null,domNodes:M.domNodesEnd??null,domGrowth:domGrowthAcrossRuns(v),pageLoad:M.pageLoad??null,refreshCalibrated:M.refreshCalibrated??null};return{...P,flags:S?[]:computeWebFlags({...P,frames:M.frames})}}).filter(f=>f.caseName!==WARMUP_CASE_NAME).map((f,b)=>({...f,batchIndex:b}));const u=pickBaseline(l,t);if(u){u.isBaseline=true;for(const f of l){if(f===u)continue;if(f.uiFps!=null&&u.uiFps!=null)f.deltaUiFps=round(f.uiFps-u.uiFps,1);if(f.jsFps!=null&&u.jsFps!=null)f.deltaJsFps=round(f.jsFps-u.jsFps,1)}}const d=l.filter(f=>!f.failed);const h=(f,b)=>{let v;let y=NaN;for(const $ of d){const T=f($);if(T==null)continue;if(v===void 0||b(T,y)){v=$;y=T}}return v?.caseName};const w=f=>f.platform==="web"?f.longFrames??null:f.jsJank==null&&f.uiJank==null?null:(f.jsJank??0)+(f.uiJank??0);const p={uiFps:h(f=>f.uiFps,(f,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(w,(f,b)=>f<b),fewestLongTasks:h(f=>f.longTaskPct??null,(f,b)=>f<b)};const g=d.filter(f=>f.flags.length>0).map(f=>({caseName:f.caseName,flags:f.flags}));const m=d.filter(f=>f.flags.length===0).sort((f,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:u?.caseName??null,deviceMaxRefreshRate:d.find(f=>f.deviceMaxRefreshRate!=null)?.deviceMaxRefreshRate??null,rows:l,leaders:p,flagged:g,balanced:m}}function pageLoadLines(e){const n=e.filter(s=>!s.failed);if(n.length===0)return[];const t=n.map(s=>s.pageLoad?.navigationId);if(t.some(s=>s==null)||new Set(t).size!==t.length)return[];if(n.some(s=>(s.pageLoad?.pageAgeMs??Infinity)>3e4))return[];const r=s=>(s??"").replace(/\/+$/,"")||"/";const i=s=>{const a=s.pageLoad;if(!a?.loadPath||r(a.loadPath)!==r(s.route))return false;const c=new URLSearchParams(a.loadSearch??"");const l=[...c.keys()];if(new Set(l).size!==l.length)return false;const u=Object.entries(s.params);return l.length===u.length&&u.every(([d,h])=>c.get(d)===h)};if(n.some(s=>!i(s)))return[];const o=s=>s==null?"\u2014":String(Math.round(s));return[`**Page load** (each case started on a fresh page load):`,"",`| Case | TTFB ms | FCP ms | LCP ms | DOM ready ms | Script KB | Total KB |`,`|------|--------:|-------:|-------:|-------------:|----------:|---------:|`,...n.map(s=>{const a=s.pageLoad;return`| ${s.caseName} | ${o(a.ttfbMs)} | ${o(a.fcpMs)} | ${o(a.lcpMs)} | ${o(a.domContentLoadedMs)} | ${o(a.scriptKb)} | ${o(a.totalKb)} |`}),"",`_KB is bytes over the network. 0 can mean the file came from cache, so compare cold loads with cold loads._`]}function closeCallNote(e){const n=o=>o.platform==="web"?o.jsFps:o.uiFps;const t=e.filter(o=>!o.failed&&n(o)!=null&&o.fpsMin!=null&&o.fpsMax!=null).sort((o,s)=>(n(s)??0)-(n(o)??0));if(t.length<2)return null;const[r,i]=t;if((r.validRuns??0)<2||(i.validRuns??0)<2){return`**Too few runs to separate the top cases.** ${r.caseName} and ${i.caseName} each need 2+ valid runs before their FPS gap means anything.`}if((i.fpsMax??0)>=(r.fpsMin??0)||(n(r)??0)-(n(i)??0)<=2){return`**Too close to call:** ${r.caseName} (${r.fpsMin}\u2013${r.fpsMax} FPS) and ${i.caseName} (${i.fpsMin}\u2013${i.fpsMax} FPS) overlap or sit within 2 FPS. No clear winner between them; more runs may separate them.`}return null}function formatRankingMarkdown(e){const n=(h,w=1)=>h==null?"\u2014":h.toFixed(w);const t=h=>h==null?"":h>0?` (+${h.toFixed(1)})`:` (${h.toFixed(1)})`;const r=[];r.push(`### Benchmark batch \`${e.batchId}\``);if(e.rows.some(h=>h.platform==="web")){formatWebTable(e,r);return r.join("\n")}r.push(`**No single winner \u2014 weigh the trade-offs.** UI-thread health matters more than raw averages: a cheap run that drops UI frames is worse than a pricier one that holds them.`);r.push("");const i=e.rows.some(h=>h.thermalState);const o=i?" Thermal |":"";const s=i?"-------|":"";r.push(`| # | Case | UI FPS | JS FPS | CPU % | Mem MB | JS jank | UI jank |${o} Flags |`);r.push(`|---|------|-------:|-------:|------:|-------:|--------:|--------:|${s}-------|`);for(const h of e.rows){const w=i?` ${THERMAL_MARK[h.thermalState??"unknown"]??"\u2014"} |`:"";if(h.failed){r.push(`| ${h.batchIndex} | ${h.caseName} | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 |${w} \u274C FAILED (${h.failureReason}) |`);continue}const p=h.flags.length?`\u26A0\uFE0F ${h.flags.join("; ")}`:"no flags";r.push(`| ${h.batchIndex} | ${h.caseName} | ${n(h.uiFps)}${t(h.deltaUiFps)} | ${n(h.jsFps)}${t(h.deltaJsFps)} | ${n(h.cpu)} | ${n(h.memMb)} | ${n(h.jsJank,0)} | ${n(h.uiJank,0)} |${w} ${p} |`)}const a=closeCallNote(e.rows);if(a){r.push("");r.push(a)}const c=e.rows.filter(h=>h.thermalState==="serious"||h.thermalState==="critical");if(c.length){r.push("");r.push(`**\u{1F525} Thermally throttled: ${c.map(h=>h.caseName).join(", ")}.** A throttled device runs SLOWER at a LOWER cpu%, so these cases can look like the cheapest in the batch while actually delivering fewer frames \u2014 check their UI FPS and jank, and re-run them on a cool device before drawing any conclusion.`)}r.push("");const l=e.leaders;const u=[l.uiFps&&`UI FPS \u2192 **${l.uiFps}**`,l.jsFps&&`JS FPS \u2192 **${l.jsFps}**`,l.lowestCpu&&`lowest CPU \u2192 **${l.lowestCpu}**`,l.lowestMem&&`lowest mem \u2192 **${l.lowestMem}**`,l.fewestJank&&`fewest jank \u2192 **${l.fewestJank}**`].filter(Boolean).join(" \xB7 ");if(u)r.push(`**Per-metric best:** ${u}`);r.push(e.balanced.length?`**No configured risk flags:** ${e.balanced.join(", ")}. Check missing metrics and workload requirements before choosing.`:`**No configured risk flags:** no candidates listed. Review failures, available metrics and flags before choosing.`);if(e.flagged.length){r.push(`**\u26A0\uFE0F At-risk:** ${e.flagged.map(h=>`${h.caseName} (${h.flags.join("; ")})`).join(" \xB7 ")}`)}const d=e.rows.filter(h=>!h.failed&&(h.renderCommits!=null||h.topRenderers.length>0)).map(h=>{const w=h.topRenderers.map(m=>`${m.name} \xD7${m.renders} (${m.totalMs}ms${m.cause?`, ${m.cause}`:""})`).join(", ");const p=h.renderCommits!=null?`${h.renderCommits} commits`:"";const g=h.renderWasted!=null?`${h.renderWasted} wasted`:"";return`- **${h.caseName}** \u2014 ${[p,g,w].filter(Boolean).join(": ")}`});if(d.length){r.push("");r.push("**Renders (median run)** \u2014 `wasted` = parent cascades + identity-only prop churn (removable). Cause per component: `propsUnstable` means a parent handed it a fresh function/object with unchanged values \u2014 fix upstream.");r.push(...d)}r.push("");r.push(`_Deltas vs baseline (\`${e.baselineName??"case #0"}\`). Don't pick on one metric \u2014 explain the trade-off (e.g. "A is cheapest but drops UI frames \u2192 jank risk; B costs more CPU but caps nothing")._`);return r.join("\n")}function compareReportStats(e,n){const t=(r,i)=>({a:{avg:round(r.avg,1),p95:round(r.p95,1)},b:{avg:round(i.avg,1),p95:round(i.p95,1)},deltaAvg:round(i.avg-r.avg,1)});return{a:e.name,b:n.name,uiFps:t(e.stats.uiFps,n.stats.uiFps),jsFps:t(e.stats.jsFps,n.stats.jsFps),cpuUsage:t(e.stats.cpuUsage,n.stats.cpuUsage),memoryUsage:t(e.stats.memoryUsage,n.stats.memoryUsage),jsJankFrames:{a:e.stats.jsJankFrames,b:n.stats.jsJankFrames,delta:n.stats.jsJankFrames-e.stats.jsJankFrames},uiJankFrames:{a:e.stats.uiJankFrames,b:n.stats.uiJankFrames,delta:n.stats.uiJankFrames-e.stats.uiJankFrames},...compareRenders(e.renders,n.renders)}}function compareWebReports(e,n){const t=(s,a,c)=>({a:s??null,b:a??null,delta:s!=null&&a!=null?round(a-s,1):null,better:c});const r=s=>s.webRun.heapSupported?round(s.stats.memoryUsage.max,1):null;const i=e.webRun;const o=n.webRun;return{a:e.name,b:n.name,platform:"web",note:"Browser runs: FPS is the main thread's whole-run requestAnimationFrame rate; long tasks % is not CPU. null = this browser couldn't measure it.",fps:t(i.fps??e.stats.jsFps.avg,o.fps??n.stats.jsFps.avg,"higher"),frameGapP95Ms:t(i.frameGapP95Ms,o.frameGapP95Ms,"lower"),frameGapMaxMs:t(i.frameGapMaxMs,o.frameGapMaxMs,"lower"),longFrames:t(i.longFrames,o.longFrames,"lower"),longTaskPct:t(i.longTaskPct,o.longTaskPct,"lower"),slowFrameBlockingMs:t(i.loaf?.blockingMs,o.loaf?.blockingMs,"lower"),styleLayoutPaintMs:t(i.loaf?.styleLayoutMs,o.loaf?.styleLayoutMs,"lower"),forcedLayoutMs:t(i.loaf?.forcedLayoutMs,o.loaf?.forcedLayoutMs,"lower"),worstInteractionMs:t(i.interactions?.worstMs,o.interactions?.worstMs,"lower"),layoutShift:t(i.layoutShift,o.layoutShift,"lower"),domNodes:t(i.domNodesEnd,o.domNodesEnd,"lower"),jsHeapMb:t(r(e),r(n),"lower"),topScripts:{a:i.loaf?.topScripts??[],b:o.loaf?.topScripts??[]},...compareRenders(e.renders,n.renders)}}function compareRenders(e,n){if(!e&&!n)return null;const t=r=>r??0;return{renders:{total:{a:t(e?.totalRenders),b:t(n?.totalRenders),delta:t(n?.totalRenders)-t(e?.totalRenders)},commits:{a:t(e?.totalCommits),b:t(n?.totalCommits),delta:t(n?.totalCommits)-t(e?.totalCommits)},wasted:{a:t(e?.wastedRenders),b:t(n?.wastedRenders),delta:t(n?.wastedRenders)-t(e?.wastedRenders)},causes:{a:e?.causes??{},b:n?.causes??{}}}}}function round(e,n){const t=Math.pow(10,n);return Math.round(e*t)/t}function formatWebTable(e,n){const t=(u,d=1)=>u==null?"\u2014":u.toFixed(d);const r=u=>u==null?"":u>0?` (+${u.toFixed(1)})`:` (${u.toFixed(1)})`;n.push(`**How to read this.** This is a browser run. FPS is the main thread's frame rate (requestAnimationFrame); it can't see frames dropped later by the GPU or compositor. Long tasks % is time the main thread was blocked by tasks over 50 ms, not CPU use. For Chrome's own dropped-frame count, use run_web_benchmark.`);n.push("");n.push(`| # | Case | FPS | p95 frame gap ms | Worst gap ms | Long frames | Long tasks % | JS heap MB | Flags |`);n.push(`|---|------|----:|-----------------:|-------------:|------------:|-------------:|--------:|-------|`);for(const u of e.rows){const d=u.isBaseline?`${u.caseName} (baseline)`:u.caseName;if(u.failed){n.push(`| ${u.batchIndex} | ${d} | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u274C FAILED (${u.failureReason}) |`);continue}const h=u.flags.length?`\u26A0\uFE0F ${u.flags.join("; ")}`:"no flags";n.push(`| ${u.batchIndex} | ${d} | ${t(u.jsFps)}${r(u.deltaJsFps)} | ${t(u.frameGapP95Ms)} | ${t(u.frameGapMaxMs)} | ${t(u.longFrames,0)} | ${t(u.longTaskPct)} | ${t(u.memMb)} | ${h} |`)}const i=e.rows.filter(u=>!u.failed).map(u=>{const d=[u.loafBlockingMs!=null&&u.loafBlockingMs>0&&`slow frames blocked input ${u.loafBlockingMs} ms`,u.styleLayoutMs!=null&&u.styleLayoutMs>0&&`style + layout ${u.styleLayoutMs} ms`,u.forcedLayoutMs!=null&&u.forcedLayoutMs>0&&`forced layout ${u.forcedLayoutMs} ms`,u.worstInteractionMs!=null&&`slowest input ${u.worstInteractionMs} ms`,u.layoutShift!=null&&u.layoutShift>0&&`layout shift ${u.layoutShift}`,u.domNodes!=null&&`${u.domNodes} DOM nodes${u.domGrowth?` (+${u.domGrowth} over the runs)`:""}`,u.topScripts&&u.topScripts.length>0&&`top scripts: ${u.topScripts.slice(0,3).map(h=>`${h.name} ${h.ms} ms`).join(", ")}`].filter(Boolean);return d.length?`- **${u.caseName}**: ${d.join(" \xB7 ")}`:null}).filter(Boolean);if(i.length){n.push("");n.push(`**Why frames were slow** (Long Animation Frames, Event Timing, DOM size; slow frames that ran past a run's end are left out):`);n.push(...i)}const o=pageLoadLines(e.rows);if(o.length){n.push("");n.push(...o)}const s=closeCallNote(e.rows);if(s){n.push("");n.push(s)}const a=Array.from(new Set(e.rows.flatMap(u=>u.missingMetrics??[])));if(a.length){n.push("");n.push(`**Not measured in this browser:** ${a.join(", ")}. These show as \u2014 and can't win or lose.`)}if(e.rows.some(u=>u.refreshCalibrated===false)){n.push("");n.push(`**Refresh rate not checked on an idle screen:** the batch couldn't reach its bounce screen first, so the screen rate (and frame budgets) may read low.`)}if(e.deviceMaxRefreshRate){n.push("");n.push(`Screen rate: ${e.deviceMaxRefreshRate} Hz. A frame gap over ${(1500/e.deviceMaxRefreshRate).toFixed(1)} ms missed at least one frame.`)}n.push("");const c=e.leaders;const l=[c.jsFps&&`FPS \u2192 **${c.jsFps}**`,c.fewestJank&&`fewest long frames \u2192 **${c.fewestJank}**`,c.fewestLongTasks&&`fewest long tasks \u2192 **${c.fewestLongTasks}**`,c.lowestMem&&`lowest heap \u2192 **${c.lowestMem}**`].filter(Boolean).join(" \xB7 ");if(l)n.push(`**Per-metric leaders:** ${l}`);if(e.flagged.length){n.push(`**\u26A0\uFE0F At-risk:** ${e.flagged.map(u=>`${u.caseName} (${u.flags.join("; ")})`).join(" \xB7 ")}`)}n.push(e.balanced.length?`**No configured risk flags:** ${e.balanced.join(", ")}. Check missing metrics and workload requirements before choosing.`:`**No configured risk flags:** no candidates listed. Review failures, available metrics and flags before choosing.`);n.push("");n.push(`_Deltas vs baseline (\`${e.baselineName??"case #0"}\`). Confirm finalists on a real phone browser: desktop numbers don't predict mobile GPU, memory or heat._`)}var clamp2,WARMUP_CASE_NAME,THERMAL_MARK,FALLBACK;var init_perfRanking=__esm({"src/tools/packs/perfRanking.ts"(){"use strict";clamp2=(e,n,t)=>Math.max(n,Math.min(t,e));WARMUP_CASE_NAME="__batch_warmup__";THERMAL_MARK={nominal:"\u{1F7E2} nominal",fair:"\u{1F7E1} fair",serious:"\u{1F7E0} serious",critical:"\u{1F534} critical",unknown:"\u2014"};FALLBACK={perCaseDurationMs:5e3,settleMs:600,navTimeoutMs:5e3,runsPerCase:3,coolDownMs:2e3,discardWarmupRuns:0}}});async function readDeviceSettings(e,n){try{const t=await e.callAction(PERF_TOOL_ID,"getAutomationConfig",{},n);if(!t)return{};const{perCaseDurationMs:r,settleMs:i,navTimeoutMs:o,runsPerCase:s,coolDownMs:a,discardWarmupRuns:c,shuffleCases:l,reloadBetweenCases:u,captureRenders:d}=t;return{perCaseDurationMs:r,settleMs:i,navTimeoutMs:o,runsPerCase:s,coolDownMs:a,discardWarmupRuns:c,shuffleCases:l,reloadBetweenCases:u,captureRenders:d}}catch{return{}}}async function readPerfSnapshot(e,n){const{payload:t}=await e.getSnapshot(PERF_TOOL_ID,n,{timeoutMs:4e3});return t}function batchIdsIn(e){const n=new Set;for(const t of e??[])if(t.batchId)n.add(t.batchId);return n}function runCountFor(e,n){return(e??[]).filter(t=>t.batchId===n).length}function newestBatchId(e){let n=null;for(const t of e??[]){if(t.batchId&&(!n||t.createdAt>n.at))n={id:t.batchId,at:t.createdAt}}return n?.id??null}function failuresFromIndex(e,n){const t=new Map;for(const r of e??[]){if(r.batchId===n&&r.batchFailureReason&&!t.has(r.batchIndex??0)){t.set(r.batchIndex??0,r.batchFailureReason)}}return[...t.entries()].map(([r,i])=>({index:r,reason:i}))}function expectedRunsFor(e){const n=e.cases.length+(e.discardWarmupCase===true?1:0);return n*(e.runsPerCase??1)}function isRunnerBusy(e){return!!e&&e!=="idle"&&e!=="done"&&e!=="cancelled"}async function waitForRunnerSettled(e,n,t,r=SETTLE_WAIT_MS){const i=Date.now();while(Date.now()-i<r){const o=await readPerfSnapshot(e,n).catch(()=>null);if(o&&!isRunnerBusy(o.live?.automation?.phase))return true;await delay2(POLL_INTERVAL_MS)}t(`automation still busy after ${Math.round(r/1e3)}s`);return false}async function waitForBatchByIndex(e,n,t){const{preBatchIds:r,expectedRuns:i,maxWaitMs:o,log:s}=t;const a=t.reloadsBetweenCases?10:3;const c=Date.now();let l="";let u=false;let d=0;while(Date.now()-c<o){let p;try{p=await readPerfSnapshot(e,n)}catch{await delay2(POLL_INTERVAL_MS);continue}const g=p.index??[];const m=p.live?.automation?.phase??"idle";const f=p.live?.automationCompleted;if(f?.phase==="cancelled"&&!r.has(f.batchId)){return{batchId:f.batchId,failures:[],cancelled:true}}if(f?.phase==="done"&&!r.has(f.batchId)){return{batchId:f.batchId,failures:f.failures??failuresFromIndex(g,f.batchId)}}if(m!=="idle")u=true;if(m!==l){l=m;s(`automation phase: ${m}`)}const b=[...batchIdsIn(g)].find(v=>!r.has(v));if(b){const v=runCountFor(g,b);if(i>0&&v>=i){await waitForRunnerSettled(e,n,s);s(`batch ${b} complete (${v}/${i} runs saved)`);return{batchId:b,failures:failuresFromIndex(g,b)}}const y=(g??[]).filter(x=>x.batchId===b&&x.name!==WARMUP_CASE_NAME).length;const $=p.live?.pendingBatchId===b;const T=Boolean(p.live&&"pendingBatchId"in p.live);const _=!t.reloadsBetweenCases||T;if(m==="idle"&&u&&y>0&&!$&&_){if(++d>=a){s(`batch ${b} settled (${v} runs, automation idle)`);return{batchId:b,failures:failuresFromIndex(g,b)}}}else{d=0}}await delay2(POLL_INTERVAL_MS)}const h=await readPerfSnapshot(e,n).catch(()=>null);const w=h?[...batchIdsIn(h.index)].find(p=>!r.has(p)):void 0;if(w&&h)return{batchId:w,failures:failuresFromIndex(h.index,w),timedOut:true};throw new Error(`Batch did not start within ${Math.round(o/1e3)}s (last phase: ${l||"idle"}). Check get_automation_status \u2014 the device may not have navigated.`)}function registerPerfMonitorTools(e,n){e.registerTool("run_benchmark_batch",{description:"Run a perf-monitor benchmark batch and return per-metric leaders, risk flags and a comparison of available case results. Give it a target route and a matrix of cases (each a name + query params that select a variant on that route); it navigates, records, and benchmarks each case on the device, then ranks them. This blocks until the batch completes (can be minutes for large batches). The app must have the target route render its variants from the params.",inputSchema:{targetRoute:import_zod3.z.string().describe('The screen to benchmark, e.g. "/perf-test". Reads case params to pick a variant.'),cases:import_zod3.z.array(caseSchema).min(1).describe("The variants to compare. Case #0 is the baseline for deltas."),bounceRoute:import_zod3.z.string().optional().describe('Screen to bounce to between runs so the test screen fully remounts. Defaults to "/" (or a stub if target is "/").'),runsPerCase:import_zod3.z.number().optional().describe("Runs per case; the median becomes the canonical result. Default 3 (1\u201310)."),perCaseDurationMs:import_zod3.z.number().optional().describe("How long to record each run. Default 5000."),settleMs:import_zod3.z.number().optional().describe("Idle gap after navigation before recording. Default 600."),coolDownMs:import_zod3.z.number().optional().describe("Idle between runs/cases for thermal recovery. Default 2000."),navTimeoutMs:import_zod3.z.number().optional().describe("Max wait for navigation per run. Default 5000."),discardWarmupRuns:import_zod3.z.number().optional().describe("Discard first N runs of each case before taking the median. Default 0."),shuffleCases:import_zod3.z.boolean().optional().describe("Interleave and shuffle case order to reduce order-related bias. Default on for >3 cases."),reloadBetweenCases:import_zod3.z.boolean().optional().describe("Fully reload JS between cases (needs <AutomationResumer/> mounted). Default false."),captureRenders:import_zod3.z.boolean().optional().describe("Capture per-component render counts/durations during each run (needs @buoy-gg/highlight-updates installed; dev builds only). Adds instrumentation overhead that can vary with the workload. Default true."),deviceId:import_zod3.z.string().optional().describe("The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out."),maxWaitMs:import_zod3.z.number().optional().describe("Safety cap for how long to wait for completion. Defaults to ~3\xD7 the estimate + 60s.")}},async t=>{const r=i=>process.stderr.write(`[buoy-mcp] ${i}
|
|
60
|
+
`);try{const i=n.requireProDevice(t.deviceId);const o=await readDeviceSettings(n,i);const{config:s,warnings:a}=buildAutomationConfig(t,o);const c=estimateBatchMs(s);const l=t.maxWaitMs??c*3+6e4;const u=expectedRunsFor(s);if(!await waitForRunnerSettled(n,i,r)){return fail2("Another benchmark batch is still running on this device. Wait for it to finish, or cancel it (call_action perf-monitor cancelAutomation), then retry.")}await n.callAction(PERF_TOOL_ID,"acknowledgeAutomation",{},i).catch(()=>{});await n.callAction(PERF_TOOL_ID,"setEnabled",{enabled:true},i).catch(()=>{});await n.callAction(PERF_TOOL_ID,"refreshIndex",{},i).catch(()=>{});const d=await readPerfSnapshot(n,i);const h=batchIdsIn(d.index);r(`starting batch: ${s.cases.length} cases \xD7 ${s.runsPerCase} runs (~${Math.round(c/1e3)}s estimated) on ${i}`);await n.callAction(PERF_TOOL_ID,"startAutomation",{config:s},i);const w=await waitForBatchByIndex(n,i,{preBatchIds:h,expectedRuns:u,maxWaitMs:l,log:r,reloadsBetweenCases:s.reloadBetweenCases===true});if(w.cancelled){await n.callAction(PERF_TOOL_ID,"acknowledgeAutomation",{},i).catch(()=>{});return fail2(`Batch ${w.batchId} was cancelled before completing.`)}await n.callAction(PERF_TOOL_ID,"refreshIndex",{},i).catch(()=>{});const p=await readPerfSnapshot(n,i);const g=rankBatchFromIndex(p.index??[],w.batchId,s.cases,w.failures);await n.callAction(PERF_TOOL_ID,"acknowledgeAutomation",{},i).catch(()=>{});await n.callAction(PERF_TOOL_ID,"setEnabled",{enabled:false},i).catch(()=>{});if(g.rows.length===0){const b=n.connectedDevices().some($=>$.deviceId===i);const v=p.live?.pendingBatchId===w.batchId;const y=!b?`The device disconnected during the batch (a browser tab that closes, reloads or sleeps drops off). Reconnect it and run again.`:v?`The batch reloaded the app between cases and never resumed. Check that <AutomationResumer/> is mounted (the web host mounts it), or pass reloadBetweenCases: false.`:w.timedOut?`No runs were saved before the wait cap (${Math.round(l/1e3)}s). On web, a hidden or background tab pauses the run: keep the tab in front. Check get_automation_status for the device's phase.`:`The batch finished without saving any runs. Check get_automation_status and the device console.`;return fail2(`Benchmark batch ${w.batchId||"(no id)"} saved no runs. ${y}`)}const m=formatRankingMarkdown(g);const f={batchId:w.batchId,leaders:g.leaders,balanced:g.balanced,flagged:g.flagged,rows:g.rows,failures:w.failures,warnings:a,estimateMs:c,...w.timedOut?{note:"Wait cap hit \u2014 results may be partial (some runs may still be saving)."}:{}};return text(`${m}
|
|
47
61
|
|
|
48
62
|
\`\`\`json
|
|
49
63
|
${JSON.stringify(f,null,2)}
|
|
50
|
-
\`\`\``)}catch(i){return fail2(errMsg2(i))}});e.registerTool("get_automation_status",{description:"Get the perf-monitor automation batch status (current phase + last completed batch) without waiting.",inputSchema:{deviceId:import_zod3.z.string().optional().describe("The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out.")}},async({deviceId:t})=>{try{const r=n.requireProDevice(t);const i=await readPerfSnapshot(n,r);return json2({deviceId:r,automation:i.live?.automation??{phase:"idle"},automationCompleted:i.live?.automationCompleted??null})}catch(r){return fail2(errMsg2(r))}});e.registerTool("wait_for_automation",{description:"Block until the in-flight perf-monitor batch finishes, then return its ranked comparison. Use this if a batch was started another way (e.g. on the device).",inputSchema:{deviceId:deviceIdInput,maxWaitMs:import_zod3.z.number().optional().describe("Max time to wait. Default 600000 (10 min).")}},async({deviceId:t,maxWaitMs:r})=>{const i=
|
|
51
|
-
`);const
|
|
64
|
+
\`\`\``)}catch(i){return fail2(errMsg2(i))}});e.registerTool("get_automation_status",{description:"Get the perf-monitor automation batch status (current phase + last completed batch) without waiting.",inputSchema:{deviceId:import_zod3.z.string().optional().describe("The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out.")}},async({deviceId:t})=>{try{const r=n.requireProDevice(t);const i=await readPerfSnapshot(n,r);return json2({deviceId:r,automation:i.live?.automation??{phase:"idle"},automationCompleted:i.live?.automationCompleted??null})}catch(r){return fail2(errMsg2(r))}});e.registerTool("wait_for_automation",{description:"Block until the in-flight perf-monitor batch finishes, then return its ranked comparison. Use this if a batch was started another way (e.g. on the device).",inputSchema:{deviceId:deviceIdInput,maxWaitMs:import_zod3.z.number().optional().describe("Max time to wait. Default 600000 (10 min).")}},async({deviceId:t,maxWaitMs:r})=>{const i=s=>process.stderr.write(`[buoy-mcp] ${s}
|
|
65
|
+
`);const o=r??6e5;try{const s=n.requireProDevice(t);const a=Date.now();let c=false;let l=0;let u=-1;let d=null;while(Date.now()-a<o){let p;try{p=await readPerfSnapshot(n,s)}catch{await delay2(POLL_INTERVAL_MS);continue}const g=p.live?.automationCompleted;if(g?.phase==="cancelled")return fail2(`Batch ${g.batchId} was cancelled.`);if(g?.phase==="done"){d={batchId:g.batchId,failures:g.failures??failuresFromIndex(p.index,g.batchId)};break}const m=p.live?.automation?.phase??"idle";if(m!=="idle")c=true;const f=newestBatchId(p.index);if(m==="idle"&&f){const b=runCountFor(p.index,f);if(b===u){if(c&&++l>=3){d={batchId:f,failures:failuresFromIndex(p.index,f)};break}if(!c&&Date.now()-a>4e3){d={batchId:f,failures:failuresFromIndex(p.index,f)};break}}else{l=0;u=b}}else{l=0}await delay2(POLL_INTERVAL_MS)}if(!d)return fail2("No automation batch completed within the wait window.");await n.callAction(PERF_TOOL_ID,"refreshIndex",{},s).catch(()=>{});const h=await readPerfSnapshot(n,s);const w=rankBatchFromIndex(h.index??[],d.batchId,void 0,d.failures);if(w.rows.length===0){await n.callAction(PERF_TOOL_ID,"acknowledgeAutomation",{},s).catch(()=>{});return fail2(`Batch ${d.batchId} saved no measured runs (only a warmup, or nothing). Check get_automation_status and run it again.`)}await n.callAction(PERF_TOOL_ID,"acknowledgeAutomation",{},s).catch(()=>{});return text(`${formatRankingMarkdown(w)}
|
|
52
66
|
|
|
53
67
|
\`\`\`json
|
|
54
|
-
${JSON.stringify(
|
|
55
|
-
\`\`\``)}catch(
|
|
68
|
+
${JSON.stringify(w,null,2)}
|
|
69
|
+
\`\`\``)}catch(s){return fail2(errMsg2(s))}});e.registerTool("get_batch_report",{description:"Re-rank a previously-run benchmark batch by its batchId (from the saved recordings index).",inputSchema:{batchId:import_zod3.z.string().describe("The batch id to report on."),deviceId:deviceIdInput}},async({batchId:t,deviceId:r})=>{try{const i=n.requireProDevice(r);await n.callAction(PERF_TOOL_ID,"refreshIndex",{},i).catch(()=>{});const o=await readPerfSnapshot(n,i);const s=(o.index??[]).filter(c=>c.batchId===t);if(s.length===0)return fail2(`No saved runs found for batch "${t}".`);const a=rankBatchFromIndex(o.index??[],t);if(a.rows.length===0)return fail2(`Batch "${t}" has no measured runs, only a warmup.`);return text(`${formatRankingMarkdown(a)}
|
|
56
70
|
|
|
57
71
|
\`\`\`json
|
|
58
72
|
${JSON.stringify(a,null,2)}
|
|
59
|
-
\`\`\``)}catch(i){return fail2(errMsg2(i))}});e.registerTool("compare_reports",{description:"Compare two saved benchmark runs head-to-head. Native runs: avg + p95 for FPS/CPU/memory, jank. Browser runs: FPS, frame gaps, long tasks, slow-frame scripts, input, DOM and heap (no CPU). Both: render counts \u2014 total, commits, and wasted (parent cascades + identity-only prop churn) \u2014 each with deltas. Use comparable workloads and inspect available metrics together. A wasted-render delta alone does not prove a fix.",inputSchema:{reportIdA:import_zod3.z.string().describe("First (baseline) report id."),reportIdB:import_zod3.z.string().describe("Second report id to compare against the baseline."),deviceId:deviceIdInput}},async({reportIdA:t,reportIdB:r,deviceId:i})=>{try{const
|
|
73
|
+
\`\`\``)}catch(i){return fail2(errMsg2(i))}});e.registerTool("compare_reports",{description:"Compare two saved benchmark runs head-to-head. Native runs: avg + p95 for FPS/CPU/memory, jank. Browser runs: FPS, frame gaps, long tasks, slow-frame scripts, input, DOM and heap (no CPU). Both: render counts \u2014 total, commits, and wasted (parent cascades + identity-only prop churn) \u2014 each with deltas. Use comparable workloads and inspect available metrics together. A wasted-render delta alone does not prove a fix.",inputSchema:{reportIdA:import_zod3.z.string().describe("First (baseline) report id."),reportIdB:import_zod3.z.string().describe("Second report id to compare against the baseline."),deviceId:deviceIdInput}},async({reportIdA:t,reportIdB:r,deviceId:i})=>{try{const o=n.requireProDevice(i);const[s,a]=await Promise.all([n.callAction(PERF_TOOL_ID,"loadReport",{id:t},o),n.callAction(PERF_TOOL_ID,"loadReport",{id:r},o)]);if(!s)return fail2(`Report "${t}" not found.`);if(!a)return fail2(`Report "${r}" not found.`);const c=s.metadata.webRun;const l=a.metadata.webRun;if(c&&l){return json2(compareWebReports({name:s.metadata.name,stats:s.stats,webRun:c,renders:s.renders},{name:a.metadata.name,stats:a.stats,webRun:l,renders:a.renders}))}if(c||l){return json2({...compareReportStats({name:s.metadata.name,stats:s.stats,renders:s.renders},{name:a.metadata.name,stats:a.stats,renders:a.renders}),note:"One report has browser details and one doesn't (an older save, or a different platform). Only the stats both share are compared. On web, UI FPS and JS FPS are the same main-thread number and CPU is long-task time, not CPU. Re-run the older case to compare frame gaps, long tasks and input."})}return json2(compareReportStats({name:s.metadata.name,stats:s.stats,renders:s.renders},{name:a.metadata.name,stats:a.stats,renders:a.renders}))}catch(o){return fail2(errMsg2(o))}});e.registerTool("get_benchmark_settings",{description:"Read the device's saved benchmark settings (per-page duration, runs, cooldown, reload, shuffle) in plain English with a time estimate. Call this before run_benchmark_batch so you can tell the user what the run will do \u2014 run_benchmark_batch inherits these unless you override them.",inputSchema:{pages:import_zod3.z.number().optional().describe("How many pages/variants you plan to test, for a total-time estimate. Default 1."),deviceId:deviceIdInput}},async({pages:t,deviceId:r})=>{try{const i=n.requireProDevice(r);const o=await readDeviceSettings(n,i);const s=Math.max(1,Math.round(t??1));const{config:a}=buildAutomationConfig({targetRoute:"/_preview",cases:Array.from({length:s},(l,u)=>({name:`page ${u+1}`}))},o);const c=Object.keys(o).length>0?"this device's saved settings":"default profile (none saved)";return text(`**Benchmark settings (${c}):** ${describeBenchmarkSettings(a)}
|
|
60
74
|
|
|
61
75
|
\`\`\`json
|
|
62
|
-
${JSON.stringify(
|
|
63
|
-
\`\`\``)}catch(i){return fail2(errMsg2(i))}});e.registerTool("set_benchmark_settings",{description:`PERSIST benchmark settings on the device so they stick across runs. Only use when the user explicitly wants to save a change ("always", "save this"). For a one-off, pass overrides to run_benchmark_batch instead \u2014 don't change their saved profile.`,inputSchema:{perCaseDurationMs:import_zod3.z.number().optional().describe("Recording length per page (ms)."),settleMs:import_zod3.z.number().optional().describe("Idle after navigation before recording (ms)."),coolDownMs:import_zod3.z.number().optional().describe("Idle between runs/cases (ms)."),navTimeoutMs:import_zod3.z.number().optional().describe("Max wait for navigation per run (ms)."),runsPerCase:import_zod3.z.number().optional().describe("Runs per page; median is the canonical result (1\u201310)."),discardWarmupRuns:import_zod3.z.number().optional().describe("Discard first N runs of each page before the median."),shuffleCases:import_zod3.z.boolean().optional().describe("Interleave and shuffle case order to reduce order-related bias."),reloadBetweenCases:import_zod3.z.boolean().optional().describe("Fully reload JS between pages (needs <AutomationResumer/> mounted)."),captureRenders:import_zod3.z.boolean().optional().describe("Capture per-component render counts/durations during each run."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(PERF_TOOL_ID,"getAutomationConfig",{},r)??{};const
|
|
76
|
+
${JSON.stringify(o,null,2)}
|
|
77
|
+
\`\`\``)}catch(i){return fail2(errMsg2(i))}});e.registerTool("set_benchmark_settings",{description:`PERSIST benchmark settings on the device so they stick across runs. Only use when the user explicitly wants to save a change ("always", "save this"). For a one-off, pass overrides to run_benchmark_batch instead \u2014 don't change their saved profile.`,inputSchema:{perCaseDurationMs:import_zod3.z.number().optional().describe("Recording length per page (ms)."),settleMs:import_zod3.z.number().optional().describe("Idle after navigation before recording (ms)."),coolDownMs:import_zod3.z.number().optional().describe("Idle between runs/cases (ms)."),navTimeoutMs:import_zod3.z.number().optional().describe("Max wait for navigation per run (ms)."),runsPerCase:import_zod3.z.number().optional().describe("Runs per page; median is the canonical result (1\u201310)."),discardWarmupRuns:import_zod3.z.number().optional().describe("Discard first N runs of each page before the median."),shuffleCases:import_zod3.z.boolean().optional().describe("Interleave and shuffle case order to reduce order-related bias."),reloadBetweenCases:import_zod3.z.boolean().optional().describe("Fully reload JS between pages (needs <AutomationResumer/> mounted)."),captureRenders:import_zod3.z.boolean().optional().describe("Capture per-component render counts/durations during each run."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(PERF_TOOL_ID,"getAutomationConfig",{},r)??{};const o=["perCaseDurationMs","settleMs","coolDownMs","navTimeoutMs","runsPerCase","discardWarmupRuns","shuffleCases","reloadBetweenCases","captureRenders"];const s={};for(const d of o){const h=t[d];if(h!==void 0)s[d]=h}if(Object.keys(s).length===0){return fail2("No settings provided to save. Pass at least one field (e.g. perCaseDurationMs).")}const a={...i,...s};const c=await n.callAction(PERF_TOOL_ID,"setAutomationConfig",{config:a},r);const l=await readDeviceSettings(n,r);const{config:u}=buildAutomationConfig({targetRoute:"/_preview",cases:[{name:"page 1"}]},l);return text(`Saved. **New benchmark settings:** ${describeBenchmarkSettings(u)}
|
|
64
78
|
|
|
65
79
|
\`\`\`json
|
|
66
|
-
${JSON.stringify(c??
|
|
67
|
-
\`\`\``)}catch(r){return fail2(errMsg2(r))}})}var import_zod3,POLL_INTERVAL_MS,delay2,json2,caseSchema,SETTLE_WAIT_MS;var init_perfMonitor=__esm({"src/tools/packs/perfMonitor.ts"(){"use strict";import_zod3=require("zod");init_packKit();init_perfMonitorTypes();init_perfRanking();POLL_INTERVAL_MS=1500;delay2=e=>new Promise(n=>setTimeout(n,e));json2=e=>({content:[{type:"text",text:JSON.stringify(e,null,2)}]});caseSchema=import_zod3.z.object({name:import_zod3.z.string().describe("Display name for this variant (becomes the saved run's name)."),params:import_zod3.z.record(import_zod3.z.string()).optional().describe('Query params applied to the route for this case, e.g. { "renderer": "v2", "count": "100" }.'),route:import_zod3.z.string().optional().describe("Optional per-case route override; defaults to targetRoute.")});SETTLE_WAIT_MS=1e4}});function expandSources(e){if(!e||e.length===0)return void 0;return[...new Set(e.flatMap(n=>SOURCE_ALIASES[n]??[n]))]}function registerEventsTools(e,n){e.registerTool("get_events",{description:"Read retained events from connected Buoy sources. Filter with sources, such as ['network'], ['redux'], ['react-query'], ['storage'] or ['route']. Returns compact summaries by default; use includeData:true for available payload details. Coverage depends on integrations and retention. An empty timeline does not prove an event never happened. Use get_network_requests for request IDs and get_snapshot for available current tool state.",inputSchema:{limit:import_zod4.z.number().optional().describe("Most-recent N events to include. Default 25."),sources:import_zod4.z.array(import_zod4.z.string()).optional().describe('Only these sources. Coarse names accepted: "network", "redux", "react-query", "storage", "route", "render", "zustand", "jotai", "capacitor" (Capacitor plugin calls). Omit for all.'),status:import_zod4.z.enum(["all","errors","success","pending"]).optional().describe("Filter by status. Default all."),includeData:import_zod4.z.boolean().optional().describe("Include each event's full raw payload (HEAVY \u2014 network bodies, state trees). Default false (compact)."),format:import_zod4.z.enum(["markdown","json","text","mermaid"]).optional().describe("Output format. Default markdown."),preset:import_zod4.z.enum(["llm","bugReport","json","errors","minimal","mermaid"]).optional().describe("Start from a named Copy-Settings preset (then your other args override it)."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i={};const
|
|
80
|
+
${JSON.stringify(c??l,null,2)}
|
|
81
|
+
\`\`\``)}catch(r){return fail2(errMsg2(r))}})}var import_zod3,POLL_INTERVAL_MS,delay2,json2,caseSchema,SETTLE_WAIT_MS;var init_perfMonitor=__esm({"src/tools/packs/perfMonitor.ts"(){"use strict";import_zod3=require("zod");init_packKit();init_perfMonitorTypes();init_perfRanking();POLL_INTERVAL_MS=1500;delay2=e=>new Promise(n=>setTimeout(n,e));json2=e=>({content:[{type:"text",text:JSON.stringify(e,null,2)}]});caseSchema=import_zod3.z.object({name:import_zod3.z.string().describe("Display name for this variant (becomes the saved run's name)."),params:import_zod3.z.record(import_zod3.z.string()).optional().describe('Query params applied to the route for this case, e.g. { "renderer": "v2", "count": "100" }.'),route:import_zod3.z.string().optional().describe("Optional per-case route override; defaults to targetRoute.")});SETTLE_WAIT_MS=1e4}});function expandSources(e){if(!e||e.length===0)return void 0;return[...new Set(e.flatMap(n=>SOURCE_ALIASES[n]??[n]))]}function registerEventsTools(e,n){e.registerTool("get_events",{description:"Read retained events from connected Buoy sources. Filter with sources, such as ['network'], ['redux'], ['react-query'], ['storage'] or ['route']. Returns compact summaries by default; use includeData:true for available payload details. Coverage depends on integrations and retention. An empty timeline does not prove an event never happened. Use get_network_requests for request IDs and get_snapshot for available current tool state.",inputSchema:{limit:import_zod4.z.number().optional().describe("Most-recent N events to include. Default 25."),sources:import_zod4.z.array(import_zod4.z.string()).optional().describe('Only these sources. Coarse names accepted: "network", "redux", "react-query", "storage", "route", "render", "zustand", "jotai", "capacitor" (Capacitor plugin calls). Omit for all.'),status:import_zod4.z.enum(["all","errors","success","pending"]).optional().describe("Filter by status. Default all."),includeData:import_zod4.z.boolean().optional().describe("Include each event's full raw payload (HEAVY \u2014 network bodies, state trees). Default false (compact)."),format:import_zod4.z.enum(["markdown","json","text","mermaid"]).optional().describe("Output format. Default markdown."),preset:import_zod4.z.enum(["llm","bugReport","json","errors","minimal","mermaid"]).optional().describe("Start from a named Copy-Settings preset (then your other args override it)."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i={};const o=expandSources(t.sources);if(o)i.filterSources=o;if(t.status)i.filterMode=t.status;if(t.includeData!==void 0)i.includeEventData=t.includeData;if(t.format)i.format=t.format==="text"?"plaintext":t.format;const s=await n.callAction(EVENTS_TOOL_ID,"exportEvents",{preset:t.preset,settings:i,limit:t.limit??25},r);if(!s||typeof s.output!=="string"){return fail2("No events result from the device. The events tool may be inactive, or the app needs a newer Buoy (get_events requires the exportEvents action).")}const a=s.includedData?"":" \u2014 compact view; pass includeData:true, a specific source, or a bigger limit for full payloads";const c=`
|
|
68
82
|
|
|
69
|
-
_Showing ${
|
|
70
|
-
\u2026 cut: showing ${n} of ${t.length} chars (pass maxChars to see more)`}function parseSnapshot(e){if(Array.isArray(e))return{events:e,saved:[]};if(e&&typeof e==="object"){const n=e;return{events:Array.isArray(n.events)?n.events:[],saved:Array.isArray(n.saved)?n.saved:[]}}return{events:[],saved:[]}}function statusIcon(e){if(e.error)return"\u274C";if(e.status===void 0)return"\u23F3";if(e.status>=400)return"\u274C";if(e.status>=300)return"\u21AA\uFE0F";return"\u2705"}function statusLabel(e){if(e.status!==void 0&&e.status>0)return String(e.status);if(e.error){const n=e.error.replace(/^HTTP\s+\d+:\s*/i,"").trim();if(!n||n==="undefined"||n==="no error"){return"ERR"}return`ERR ${e.error}`}if(e.status===void 0)return"pending";return String(e.status)}function formatBytes(e){if(!e)return"";if(e<1024)return`${e}B`;if(e<1024*1024)return`${Math.round(e/1024)}KB`;return`${(e/(1024*1024)).toFixed(1)}MB`}function matchesStatus(e,n){if(!n||n==="all")return true;const t=!!e.error||e.status!==void 0&&e.status>=400;if(n==="errors")return t;if(n==="pending")return e.status===void 0&&!e.error;if(n==="success")return!t&&e.status!==void 0;return true}function truncate(e,n=600){if(e===null||e===void 0)return"(none)";const t=typeof e==="string"?e:JSON.stringify(e);return t.length>n?`${t.slice(0,n)}\u2026(+${t.length-n} chars)`:t}async function resolveBodies(e,n,t,r=MAX_BODY_FETCHES){const i=n.filter(c=>c.id&&(c.requestBodyOmitted===true&&c.requestData===void 0||c.responseBodyOmitted===true&&c.responseData===void 0));const
|
|
83
|
+
_Showing ${s.returned} of ${s.totalAvailable} captured event(s)${a}._`;return text((s.output||"(no events captured)")+c)}catch(r){return fail2(errMsg2(r))}})}var import_zod4,EVENTS_TOOL_ID,SOURCE_ALIASES;var init_events=__esm({"src/tools/packs/events.ts"(){"use strict";import_zod4=require("zod");init_packKit();EVENTS_TOOL_ID="events";SOURCE_ALIASES={storage:["storage-async","storage-mmkv"],"react-query":["react-query","react-query-query","react-query-mutation"]}}});function redactHeaders(e){if(!e||typeof e!=="object")return null;return Object.fromEntries(Object.entries(e).map(([n,t])=>[n,SECRET_HEADER.test(n)?"[redacted]":t]))}function parseBody(e){if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return e}}function bodyShape(e){if(Array.isArray(e))return`array(${e.length})`;if(e&&typeof e==="object")return`{${Object.entries(e).slice(0,20).map(([n,t])=>`${n}: ${Array.isArray(t)?`array(${t.length})`:t===null?"null":typeof t}`).join(", ")}}`;return typeof e}function bodyText(e,n){if(e==null)return"(none)";const t=scrubSecrets(typeof e==="string"?e:JSON.stringify(e,null,1));return t.length<=n?t:`${t.slice(0,n)}
|
|
84
|
+
\u2026 cut: showing ${n} of ${t.length} chars (pass maxChars to see more)`}function parseSnapshot(e){if(Array.isArray(e))return{events:e,saved:[]};if(e&&typeof e==="object"){const n=e;return{events:Array.isArray(n.events)?n.events:[],saved:Array.isArray(n.saved)?n.saved:[]}}return{events:[],saved:[]}}function statusIcon(e){if(e.error)return"\u274C";if(e.status===void 0)return"\u23F3";if(e.status>=400)return"\u274C";if(e.status>=300)return"\u21AA\uFE0F";return"\u2705"}function statusLabel(e){if(e.status!==void 0&&e.status>0)return String(e.status);if(e.error){const n=e.error.replace(/^HTTP\s+\d+:\s*/i,"").trim();if(!n||n==="undefined"||n==="no error"){return"ERR"}return`ERR ${e.error}`}if(e.status===void 0)return"pending";return String(e.status)}function formatBytes(e){if(!e)return"";if(e<1024)return`${e}B`;if(e<1024*1024)return`${Math.round(e/1024)}KB`;return`${(e/(1024*1024)).toFixed(1)}MB`}function matchesStatus(e,n){if(!n||n==="all")return true;const t=!!e.error||e.status!==void 0&&e.status>=400;if(n==="errors")return t;if(n==="pending")return e.status===void 0&&!e.error;if(n==="success")return!t&&e.status!==void 0;return true}function truncate(e,n=600){if(e===null||e===void 0)return"(none)";const t=typeof e==="string"?e:JSON.stringify(e);return t.length>n?`${t.slice(0,n)}\u2026(+${t.length-n} chars)`:t}async function resolveBodies(e,n,t,r=MAX_BODY_FETCHES){const i=n.filter(c=>c.id&&(c.requestBodyOmitted===true&&c.requestData===void 0||c.responseBodyOmitted===true&&c.responseData===void 0));const o=new Map;if(i.length===0)return{bodies:o,skipped:0};const s=i.slice(0,r);const a=await Promise.allSettled(s.map(c=>e.callAction(NETWORK_TOOL_ID,"getEventBody",{id:c.id},t)));a.forEach((c,l)=>{const u=s[l].id;const d=c.status==="fulfilled"?c.value:null;o.set(u,d?{...d}:{unresolved:true})});return{bodies:o,skipped:i.length-s.length}}async function captureDiagnosis(e,n){let t=null;try{t=await e.callAction(NETWORK_TOOL_ID,"getCaptureStatus",{},n)}catch{return"Capture status is unavailable. An empty result does not establish whether requests occurred."}if(!t||t.capturing!==false){return"No requests are available in this result. Check capture setup, supported transports and hook timing before concluding that no request occurred."}return"Capture is disabled. Open the Network panel on the device or in Buoy Desktop, trigger a supported request and read again. An empty result does not establish whether requests occurred. Capture depends on installed hooks, supported transports and recording timing."}function skippedNote(e){return e>0?`
|
|
71
85
|
|
|
72
|
-
_${e} more withheld ${e===1?"body was":"bodies were"} not fetched (cap ${MAX_BODY_FETCHES} per listing, they are large). Get one in full with its id._`:""}function bodyLines(e,n){const t=e.id?n.get(e.id):void 0;const r=(i,s
|
|
86
|
+
_${e} more withheld ${e===1?"body was":"bodies were"} not fetched (cap ${MAX_BODY_FETCHES} per listing, they are large). Get one in full with its id._`:""}function bodyLines(e,n){const t=e.id?n.get(e.id):void 0;const r=(i,o,s)=>{const a=i??o;if(a!==void 0&&a!==null)return truncate(a);if(!s)return"(none)";return t?.unresolved?"(withheld \u2014 the device did not answer getEventBody)":"(none)"};return`
|
|
73
87
|
\u2514\u2500 request: ${r(e.requestData,t?.requestData,e.requestBodyOmitted)}
|
|
74
|
-
\u2514\u2500 response: ${r(e.responseData,t?.responseData,e.responseBodyOmitted)}`}function formatRow(e,n,t){const r=n.path||n.url;const i=[`${n.duration!==void 0?`${Math.round(n.duration)}ms`:"\u2014"}`,formatBytes(n.responseSize),n.host??"",n.requestClient??""].filter(Boolean);const
|
|
75
|
-
\u2514\u2500 ${i.join(" \xB7 ")}`}function registerNetworkTools(e,n){e.registerTool("network_conditions",{description:"Read or set the device's network conditions. Offline blocks new intercepted HTTP requests; slow adds 500 ms and verySlow adds 2000 ms before dispatch. Normal clears conditions. State resets on JS reload. Check app and server observations to verify the effect.",inputSchema:{action:import_zod5.z.enum(["get","set"]).describe("Read the effective profile or select one."),profile:import_zod5.z.enum(["normal","offline","slow","verySlow"]).optional().describe("Required for set."),deviceId:deviceIdInput}},async t=>{try{if(t.action==="set"&&!t.profile)return fail2("Set requires a profile.");const r=n.resolveDevice(t.deviceId);const i=await n.callAction(NETWORK_TOOL_ID,t.action==="get"?"getNetworkConditions":"setNetworkConditions",t.action==="set"?{profile:t.profile}:void 0,r);if(!i||typeof i!=="object"||!("profile"in i))return fail2("The device did not report its effective network conditions.");return text(JSON.stringify(i))}catch(r){return fail2(errMsg2(r))}});e.registerTool("get_network_requests",{description:"List captured HTTP requests with IDs, available status/timing/size fields and pinned or saved markers. Capture depends on supported transports, installed hooks and recording timing; requests made before capture starts may be absent. Use IDs for network actions and flagged to inspect retained records. A flag does not establish who created it or the cause of a problem. Filter by status or URL pattern. includeBodies:true requests available truncated bodies, which can be missing or withheld. Requires the network integration and Buoy Pro.",inputSchema:{limit:import_zod5.z.number().optional().describe("Most-recent N requests. Default 25."),pattern:import_zod5.z.string().optional().describe("Only requests whose URL contains this substring (case-insensitive)."),status:import_zod5.z.enum(["all","errors","success","pending"]).optional().describe("Filter by outcome. Default all."),flagged:import_zod5.z.enum(["pinned","saved","any"]).optional().describe("Read KEPT requests instead of the live list: 'pinned' (held at the top of the developer's list), 'saved' (their favorites), 'any' (either). These are separate from the live list; restart retention depends on successful persistence."),includeBodies:import_zod5.z.boolean().optional().describe("Include truncated request/response bodies. Default false (compact)."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:i,stale:
|
|
88
|
+
\u2514\u2500 response: ${r(e.responseData,t?.responseData,e.responseBodyOmitted)}`}function formatRow(e,n,t){const r=n.path||n.url;const i=[`${n.duration!==void 0?`${Math.round(n.duration)}ms`:"\u2014"}`,formatBytes(n.responseSize),n.host??"",n.requestClient??""].filter(Boolean);const o=n.operationName?` (${n.operationName})`:"";return`${e}. \`${n.id}\` ${statusIcon(n)} ${statusLabel(n)} ${n.method} ${r}${o}${t?` ${t}`:""}
|
|
89
|
+
\u2514\u2500 ${i.join(" \xB7 ")}`}function registerNetworkTools(e,n){e.registerTool("network_conditions",{description:"Read or set the device's network conditions. Offline blocks new intercepted HTTP requests; slow adds 500 ms and verySlow adds 2000 ms before dispatch. Normal clears conditions. State resets on JS reload. Check app and server observations to verify the effect.",inputSchema:{action:import_zod5.z.enum(["get","set"]).describe("Read the effective profile or select one."),profile:import_zod5.z.enum(["normal","offline","slow","verySlow"]).optional().describe("Required for set."),deviceId:deviceIdInput}},async t=>{try{if(t.action==="set"&&!t.profile)return fail2("Set requires a profile.");const r=n.resolveDevice(t.deviceId);const i=await n.callAction(NETWORK_TOOL_ID,t.action==="get"?"getNetworkConditions":"setNetworkConditions",t.action==="set"?{profile:t.profile}:void 0,r);if(!i||typeof i!=="object"||!("profile"in i))return fail2("The device did not report its effective network conditions.");return text(JSON.stringify(i))}catch(r){return fail2(errMsg2(r))}});e.registerTool("get_network_requests",{description:"List captured HTTP requests with IDs, available status/timing/size fields and pinned or saved markers. Capture depends on supported transports, installed hooks and recording timing; requests made before capture starts may be absent. Use IDs for network actions and flagged to inspect retained records. A flag does not establish who created it or the cause of a problem. Filter by status or URL pattern. includeBodies:true requests available truncated bodies, which can be missing or withheld. Requires the network integration and Buoy Pro.",inputSchema:{limit:import_zod5.z.number().optional().describe("Most-recent N requests. Default 25."),pattern:import_zod5.z.string().optional().describe("Only requests whose URL contains this substring (case-insensitive)."),status:import_zod5.z.enum(["all","errors","success","pending"]).optional().describe("Filter by outcome. Default all."),flagged:import_zod5.z.enum(["pinned","saved","any"]).optional().describe("Read KEPT requests instead of the live list: 'pinned' (held at the top of the developer's list), 'saved' (their favorites), 'any' (either). These are separate from the live list; restart retention depends on successful persistence."),includeBodies:import_zod5.z.boolean().optional().describe("Include truncated request/response bodies. Default false (compact)."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:i,stale:o}=await n.getSnapshot(NETWORK_TOOL_ID,r);const{events:s,saved:a}=parseSnapshot(i);const c=typeof t.limit==="number"&&t.limit>0?t.limit:25;const l=t.pattern?.toLowerCase();const u=new Set;const d=new Set;for(const m of a){if(m.pinned)u.add(m.event?.id);if(m.saved)d.add(m.event?.id);if(m.pinned)u.add(m.liveId);if(m.saved)d.add(m.liveId)}if(t.flagged){const m=a.filter(y=>t.flagged==="pinned"?y.pinned:t.flagged==="saved"?y.saved:y.pinned||y.saved);const f=m.filter(y=>y.event&&matchesStatus(y.event,t.status)).filter(y=>!l||(y.event.url??"").toLowerCase().includes(l)).slice(0,c);if(f.length===0){return text(staleHeader(o)+`No ${t.flagged==="any"?"pinned or saved":t.flagged} requests on ${r}.
|
|
76
90
|
|
|
77
|
-
The developer pins/saves a request from the Network tool (long-press a row, or the pin/bookmark buttons in the request detail header), or you can with network_action.`)}const b=t.includeBodies?await resolveBodies(n,f.map(y=>y.event),r):{bodies:new Map,skipped:0};const v=f.map((y
|
|
78
|
-
\u2514\u2500 key \`${y.key}\`${
|
|
91
|
+
The developer pins/saves a request from the Network tool (long-press a row, or the pin/bookmark buttons in the request detail header), or you can with network_action.`)}const b=t.includeBodies?await resolveBodies(n,f.map(y=>y.event),r):{bodies:new Map,skipped:0};const v=f.map((y,$)=>{const T=[y.pinned?"\u{1F4CC} pinned":"",y.saved?"\u{1F516} saved":""].filter(Boolean).join(" ");const _=y.event.id?.startsWith("saved:")?" \xB7 from an earlier app run":"";const x=y.bodyTruncated?" \xB7 body truncated":"";let I=formatRow($+1,y.event,T);I+=`
|
|
92
|
+
\u2514\u2500 key \`${y.key}\`${_}${x}`;if(t.includeBodies)I+=bodyLines(y.event,b.bodies);return I}).join("\n");return text(staleHeader(o)+`**Kept requests on ${r}** \u2014 ${f.length} of ${m.length}
|
|
79
93
|
|
|
80
94
|
${v}
|
|
81
95
|
|
|
82
|
-
_These are snapshots: they survive Clear, the 500-request cap and app restarts. Remove one with network_action({action:"remove", key}). Ids starting \`saved:\` are from an earlier run of the app._${skippedNote(b.skipped)}`)}const h=
|
|
96
|
+
_These are snapshots: they survive Clear, the 500-request cap and app restarts. Remove one with network_action({action:"remove", key}). Ids starting \`saved:\` are from an earlier run of the app._${skippedNote(b.skipped)}`)}const h=s.filter(m=>matchesStatus(m,t.status)).filter(m=>!l||(m.url??"").toLowerCase().includes(l)).slice(0,c);if(h.length===0){const m=s.length===0?await captureDiagnosis(n,r):"No request matched the filter.";return text(staleHeader(o)+`No requests on ${r}. ${m}`)}const w=t.includeBodies?await resolveBodies(n,h,r):{bodies:new Map,skipped:0};const p=h.map((m,f)=>{const b=[u.has(m.id)?"\u{1F4CC}":"",d.has(m.id)?"\u{1F516}":""].filter(Boolean).join("");let v=formatRow(f+1,m,b);if(t.includeBodies)v+=bodyLines(m,w.bodies);return v}).join("\n");const g=a.length>0?` \xB7 ${a.length} kept (flagged:'any' to list)`:"";return text(staleHeader(o)+`**Network requests on ${r}** \u2014 ${h.length} of ${s.length}${g}
|
|
83
97
|
|
|
84
|
-
${
|
|
98
|
+
${p}
|
|
85
99
|
|
|
86
|
-
_\u{1F4CC} pinned \xB7 \u{1F516} saved. Full status, headers and body for one: get_network_request({id:"${h[0].id}"}). Pin or save one: network_action({action:"pin", id:"${h[0].id}"})._${skippedNote(
|
|
100
|
+
_\u{1F4CC} pinned \xB7 \u{1F516} saved. Full status, headers and body for one: get_network_request({id:"${h[0].id}"}). Pin or save one: network_action({action:"pin", id:"${h[0].id}"})._${skippedNote(w.skipped)}`)}catch(r){return fail2(errMsg2(r))}});e.registerTool("get_network_request",{description:"Read ONE captured request by its id (from get_network_requests): method, URL, status, whether a mock produced it, request and response headers (secrets redacted) and the full bodies up to maxChars, plus a one-line shape of the response (array lengths included) so counts don't depend on reading a long body. Use this instead of re-listing requests with includeBodies when you need one response.",inputSchema:{id:import_zod5.z.string().describe("The request id from get_network_requests."),maxChars:import_zod5.z.number().optional().describe("Most body characters to show per body. Default 12000."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(NETWORK_TOOL_ID,"getEventBody",{id:t.id},r);if(!i)return fail2(`No request "${t.id}" on ${r}. It may have been cleared or aged out; list again with get_network_requests.`);const o=typeof t.maxChars==="number"&&t.maxChars>0?t.maxChars:12e3;const s=parseBody(i.responseData);const a=[`**${i.method??"?"} ${i.url??"?"}** \u2192 ${i.status??"no status"}${i.override?" (answered by a network override, not the server)":""}`,`Response shape: ${bodyShape(s)}`,`
|
|
87
101
|
**Response body:**
|
|
88
|
-
${bodyText(o
|
|
102
|
+
${bodyText(s,o)}`,`
|
|
89
103
|
**Request body:**
|
|
90
|
-
${bodyText(parseBody(i.requestData),Math.min(
|
|
91
|
-
**Response headers:** ${JSON.stringify(redactHeaders(i.responseHeaders))}`,`**Request headers:** ${JSON.stringify(redactHeaders(i.requestHeaders))}`];return text(a.join("\n"))}catch(r){return fail2(errMsg2(r))}});e.registerTool("network_action",{description:"Pin or save captured requests as retained records, or remove records and clear lists. Bodies may be truncated or omitted by storage budgets. Records are kept separately from the live list; availability after restart depends on successful device persistence. Get request IDs from get_network_requests. remove uses a retained-record key from flagged results. An action acknowledgement does not confirm a durable storage write.",inputSchema:{action:import_zod5.z.enum(["pin","unpin","save","unsave","remove","clearPinned","clearSaved","clearRequests"]).describe("pin/unpin/save/unsave act on one request by `id`. remove drops one kept record by `key`. clearPinned/clearSaved drop all of that kind. clearRequests wipes the live capture list (kept requests survive)."),id:import_zod5.z.string().optional().describe("Request id for pin/unpin/save/unsave \u2014 from get_network_requests."),key:import_zod5.z.string().optional().describe("Kept-record key for `remove` \u2014 from get_network_requests({flagged:'any'})."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=["pin","unpin","save","unsave"].includes(t.action);if(i&&!t.id){return fail2(`"${t.action}" needs an \`id\`. List requests with get_network_requests to get one.`)}if(t.action==="remove"&&!t.key){return fail2('"remove" needs a `key` (not a request id). Get it from get_network_requests({flagged:"any"}).')}switch(t.action){case"pin":case"unpin":{const
|
|
104
|
+
${bodyText(parseBody(i.requestData),Math.min(o,4e3))}`,`
|
|
105
|
+
**Response headers:** ${JSON.stringify(redactHeaders(i.responseHeaders))}`,`**Request headers:** ${JSON.stringify(redactHeaders(i.requestHeaders))}`];return text(a.join("\n"))}catch(r){return fail2(errMsg2(r))}});e.registerTool("network_action",{description:"Pin or save captured requests as retained records, or remove records and clear lists. Bodies may be truncated or omitted by storage budgets. Records are kept separately from the live list; availability after restart depends on successful device persistence. Get request IDs from get_network_requests. remove uses a retained-record key from flagged results. An action acknowledgement does not confirm a durable storage write.",inputSchema:{action:import_zod5.z.enum(["pin","unpin","save","unsave","remove","clearPinned","clearSaved","clearRequests"]).describe("pin/unpin/save/unsave act on one request by `id`. remove drops one kept record by `key`. clearPinned/clearSaved drop all of that kind. clearRequests wipes the live capture list (kept requests survive)."),id:import_zod5.z.string().optional().describe("Request id for pin/unpin/save/unsave \u2014 from get_network_requests."),key:import_zod5.z.string().optional().describe("Kept-record key for `remove` \u2014 from get_network_requests({flagged:'any'})."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=["pin","unpin","save","unsave"].includes(t.action);if(i&&!t.id){return fail2(`"${t.action}" needs an \`id\`. List requests with get_network_requests to get one.`)}if(t.action==="remove"&&!t.key){return fail2('"remove" needs a `key` (not a request id). Get it from get_network_requests({flagged:"any"}).')}switch(t.action){case"pin":case"unpin":{const o=await n.callAction(NETWORK_TOOL_ID,"setPinned",{id:t.id,pinned:t.action==="pin"},r);if(o===null)return fail2(`No request "${t.id}" on ${r}. It may have been cleared or aged out \u2014 re-list with get_network_requests.`);const s=typeof o==="object"&&o!==null&&o.reason==="pin-cap";if(s)return fail2(`Pin limit reached on ${r}. Unpin something first (network_action({action:"clearPinned"}) drops them all).`);return text(`${t.action==="pin"?"\u{1F4CC} Pinned":"Unpinned"} \`${t.id}\` on ${r}.`)}case"save":case"unsave":{const o=await n.callAction(NETWORK_TOOL_ID,"setSaved",{id:t.id,saved:t.action==="save"},r);if(o===null)return fail2(`No request "${t.id}" on ${r}. It may have been cleared or aged out \u2014 re-list with get_network_requests.`);const s=typeof o==="object"&&o!==null&&o.reason==="saved-cap";if(s)return fail2(`Saved-request limit reached on ${r}. Remove one first, or network_action({action:"clearSaved"}).`);return text(`${t.action==="save"?"\u{1F516} Saved":"Unsaved"} \`${t.id}\` on ${r}.`)}case"remove":await n.callAction(NETWORK_TOOL_ID,"removeSavedRecord",{key:t.key},r);return text(`Removed kept record \`${t.key}\` on ${r}.`);case"clearPinned":await n.callAction(NETWORK_TOOL_ID,"clearPinnedRequests",{},r);return text(`Unpinned all requests on ${r} (saved ones kept).`);case"clearSaved":await n.callAction(NETWORK_TOOL_ID,"clearSavedRequests",{},r);return text(`Cleared saved requests on ${r} (pinned ones kept).`);case"clearRequests":await n.callAction(NETWORK_TOOL_ID,"clearEvents",{},r);return text(`Clear request sent to ${r}. Re-list to confirm the live capture list; this action does not clear retained records.`)}}catch(r){return fail2(errMsg2(r))}});e.registerTool("network_override",{description:"Configure response, failure or delay rules for supported requests intercepted by the app integration. Coverage depends on transport, hooks and rule-loading timing; early startup requests may bypass a rule. Inspect existing rules before editing, trigger the intended request and check observed results. Simulated offline behavior does not disconnect the device. Remove rules created for this task afterward or restore prior settings; preserve unrelated rules. Requires Buoy Pro and network override support.",inputSchema:{action:import_zod5.z.enum(["list","add","remove","clear","enable","disable","debug"]).describe("add creates a rule (or replaces one when `id` is given). remove drops one by `id`. clear drops all. enable/disable flip ONE rule when `id` is given, otherwise the master switch \u2014 rules are kept either way. list shows every rule with its hit counts; pass `id` to dump one rule in full, body included. debug reports why a rule is or isn't firing."),urlPattern:import_zod5.z.string().optional().describe("For `add`: glob matched against the WHOLE request URL, query string included. `*` is the only wildcard, e.g. '*pokeapi.co*' or 'https://api.example.com/v1/users*'. Careful with an exact URL copied from get_network_requests \u2014 if the client cache-busts or pages, the next call won't match it and the rule sits at 0 hits. Prefer `fromRequestId`, which handles that for you."),fromRequestId:import_zod5.z.string().optional().describe("For `add`: build the rule from a captured request id (from get_network_requests) \u2014 the same 'Override this request' the developer gets in the UI. Seeds the pattern (query string replaced with `*` so it keeps matching), the method, the status, and the REAL response body, so you can change two fields of a payload you just saw instead of authoring one from scratch. Anything you pass explicitly overrides the prefill."),methods:import_zod5.z.array(import_zod5.z.string()).optional().describe("For `add`: restrict to these HTTP methods. Omit for any."),kind:import_zod5.z.enum(["respond","fail","delay"]).optional().describe("respond = return your status/body, never hitting the network (default). fail = a transport failure, as if the device were offline. delay = let the real request run, just late."),status:import_zod5.z.number().optional().describe("For kind 'respond': HTTP status, 200\u2013599 (default 200). Outside that range fetch itself throws, so use kind 'fail' for connection errors rather than status 0."),body:import_zod5.z.union([import_zod5.z.string(),import_zod5.z.record(import_zod5.z.unknown()),import_zod5.z.array(import_zod5.z.unknown())]).optional().describe("For kind 'respond': the response body. Pass JSON directly (an object or array) or a raw string; content-type is inferred."),bodyPatch:import_zod5.z.record(import_zod5.z.unknown()).optional().describe('For `add` with `fromRequestId` (or a rule `id`): fields deep-merged INTO the real captured response \u2014 the way to change one field of a big payload without pasting it back. Send only what changes, e.g. {"name":"test123"}. Ignored when `body` is given.'),statusText:import_zod5.z.string().optional().describe("For kind 'respond': the status line's text, e.g. 'Service Unavailable'. Cosmetic \u2014 React Native's XMLHttpRequest has no statusText field, so the app never sees it; it only makes the developer's rule list read correctly."),headers:import_zod5.z.record(import_zod5.z.string()).optional().describe("For kind 'respond': response headers to send."),failKind:import_zod5.z.enum(["network","timeout"]).optional().describe("For kind 'fail': 'network' (default) or 'timeout'."),delayMs:import_zod5.z.number().optional().describe("Latency before the outcome, in ms. Works with every kind."),times:import_zod5.z.number().optional().describe("Auto-disable the rule after N matches. Use 1 for 'make the next call fail' so it can't linger."),alternate:import_zod5.z.boolean().optional().describe("Apply to every OTHER matching request, forever: the first goes through, the second is overridden, and so on. This is how you test retry logic and flaky endpoints \u2014 a rule that is always on or always off can't reach those paths."),name:import_zod5.z.string().optional().describe("Label shown in the developer's UI."),enabled:import_zod5.z.boolean().optional().describe("For `add`: whether the rule is enabled. Default true; pass false to stage it switched off. Useful for staging a rule you'll arm later with enable({id})."),id:import_zod5.z.string().optional().describe("Rule id. Required for `remove`. For `add` it replaces that rule. For `enable`/`disable` it targets ONE rule instead of the master switch. For `list` it dumps that rule in full."),url:import_zod5.z.string().optional().describe("For `debug`: a concrete URL to test the rules against, so the report says which rule would match it and why."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);switch(t.action){case"add":{if(!t.urlPattern&&!t.fromRequestId){return fail2("`add` needs a `urlPattern` or a `fromRequestId`. Take an id from get_network_requests to override a request you just saw, or pass a glob like '*pokeapi.co*'.")}const i=await n.callAction(NETWORK_TOOL_ID,"upsertOverrideRule",{fromRequestId:t.fromRequestId,rule:{id:t.id,name:t.name,urlPattern:t.urlPattern,methods:t.methods,kind:t.kind,status:t.status,statusText:t.statusText,body:t.body,bodyPatch:t.bodyPatch,headers:t.headers,failKind:t.failKind,delayMs:t.delayMs,times:t.times,alternate:t.alternate,enabled:t.enabled!==false}},r);const o=i;if(!o?.ok){return fail2(o?.error??`Could not add the rule on ${r}.`)}const s=o.rule?.urlPattern??t.urlPattern;const a=o.rule?.enabled===false?`
|
|
92
106
|
|
|
93
|
-
It is switched OFF \u2014 arm it with network_override({action:"enable", id:"${
|
|
107
|
+
It is switched OFF \u2014 arm it with network_override({action:"enable", id:"${o.rule?.id}"}).`:"";return text(`Override added on ${r} \u2014 \`${o.rule?.id}\` matching \`${s}\`.${a}
|
|
94
108
|
|
|
95
|
-
Trigger the request now (navigate / tap_element), then check it with get_network_requests or describe_screen. Remove it with network_override({action:"remove", id:"${
|
|
109
|
+
Trigger the request now (navigate / tap_element), then check it with get_network_requests or describe_screen. Remove it with network_override({action:"remove", id:"${o.rule?.id}"}) when you're done.`)}case"remove":{if(!t.id){return fail2('`remove` needs an `id`. List them with network_override({action:"list"}).')}await n.callAction(NETWORK_TOOL_ID,"deleteOverrideRule",{id:t.id},r);return text(`Removed override \`${t.id}\` on ${r}.`)}case"clear":await n.callAction(NETWORK_TOOL_ID,"clearOverrideRules",{},r);return text(`Removed all override rules on ${r}. Other interception or simulation settings may still apply.`);case"enable":case"disable":{const i=t.action==="enable";if(t.id){await n.callAction(NETWORK_TOOL_ID,"setOverrideRuleEnabled",{id:t.id,enabled:i},r);return text(`Rule \`${t.id}\` was requested ${i?"ON":"OFF"} on ${r}. The other rules and the master switch are unchanged.`)}await n.callAction(NETWORK_TOOL_ID,"setOverridesEnabled",{enabled:i},r);return text(i?`Overrides enabled in settings for ${r}.`:`Overrides switched OFF for ${r}. Rules are kept \u2014 re-enable with network_override({action:"enable"}).`)}case"list":{const i=await n.callAction(NETWORK_TOOL_ID,"listOverrideRules",{},r);const o=i?.rules??[];if(t.id){const a=o.find(c=>c.id===t.id);if(!a){return fail2(`No override rule \`${t.id}\` on ${r}. List them with network_override({action:"list"}).`)}return text(`**Override rule \`${a.id}\`** on ${r}${masterNote(i)}
|
|
96
110
|
|
|
97
111
|
\`\`\`json
|
|
98
112
|
${JSON.stringify(a,null,2)}
|
|
99
|
-
\`\`\``)}if(
|
|
113
|
+
\`\`\``)}if(o.length===0){return text(`No override rules on ${r}.
|
|
100
114
|
|
|
101
|
-
Add one with network_override({action:"add", urlPattern:"https://api.example.com/test*", status:500}) to force an error state.`)}const o
|
|
102
|
-
\u2514\u2500 \`${a.urlPattern}\` \xB7 ${
|
|
115
|
+
Add one with network_override({action:"add", urlPattern:"https://api.example.com/test*", status:500}) to force an error state.`)}const s=o.map((a,c)=>{const l=a.kind==="respond"?`\u2192 ${a.status??200}${a.statusText?` ${a.statusText}`:""}`:a.kind==="fail"?`\u2192 ${a.failKind==="timeout"?"timeout":"network error"}`:"\u2192 real response";const u=[a.methods?.length?a.methods.join("/"):"any method",l,a.kind==="respond"&&a.body?`body ${a.body.length}B`:"",a.headers&&Object.keys(a.headers).length?`${Object.keys(a.headers).length} header(s)`:"",a.delayMs?`${a.delayMs}ms delay`:"",a.alternate?"every other request":"",typeof a.times==="number"?`${a.times}\xD7 then off`:"",`${a.hits} hit${a.hits===1?"":"s"}`,a.seen!=null&&a.seen!==a.hits?`${a.seen} matched`:"",a.enabled?"":"DISABLED"].filter(Boolean);return`${c+1}. \`${a.id}\`${a.name?` ${a.name}`:""}
|
|
116
|
+
\u2514\u2500 \`${a.urlPattern}\` \xB7 ${u.join(" \xB7 ")}`});return text(`**Override rules on ${r}**${masterNote(i)}
|
|
103
117
|
|
|
104
|
-
${
|
|
118
|
+
${s.join("\n")}
|
|
105
119
|
|
|
106
|
-
Full detail incl. body: network_override({action:"list", id:"${
|
|
120
|
+
Full detail incl. body: network_override({action:"list", id:"${o[0]?.id}"}).`)}case"debug":{const i=await n.callAction(NETWORK_TOOL_ID,"debugOverrides",{url:t.url},r);if(!i){return fail2(`${r} did not answer the diagnostics call \u2014 the network tool may not be mounted.`)}return text(`**Override diagnostics on ${r}**${t.url?` for \`${t.url}\``:""}
|
|
107
121
|
|
|
108
122
|
\`\`\`json
|
|
109
123
|
${JSON.stringify(i,null,2)}
|
|
110
124
|
\`\`\`
|
|
111
125
|
|
|
112
|
-
A rule that never fires is usually one of: the master switch is off, the interceptor isn't installed (nothing is subscribed to the network tool), or the pattern doesn't match the FULL url including its query string.`)}}}catch(r){return fail2(errMsg2(r))}})}var import_zod5,NETWORK_TOOL_ID,SECRET_HEADER,masterNote,MAX_BODY_FETCHES;var init_network=__esm({"src/tools/packs/network.ts"(){"use strict";import_zod5=require("zod");init_packKit();init_secrets();NETWORK_TOOL_ID="network";SECRET_HEADER=/authorization|cookie|token|api[-_]?key|secret|session/i;masterNote=e=>{if(e?.enabled!==false)return"";return e.autoPaused?' \u2014 AUTO-PAUSED after the app failed to settle on launch with overrides active; nothing is firing. Re-arm with network_override({action:"enable"}).':" \u2014 MASTER SWITCH IS OFF, nothing is firing"};MAX_BODY_FETCHES=8}});async function callQueryAction(e,n,t,r){try{return await e.callAction(RQ_TOOL_ID,n,t,r)}catch(i){const
|
|
113
|
-
data: ${JSON.stringify(
|
|
126
|
+
A rule that never fires is usually one of: the master switch is off, the interceptor isn't installed (nothing is subscribed to the network tool), or the pattern doesn't match the FULL url including its query string.`)}}}catch(r){return fail2(errMsg2(r))}})}var import_zod5,NETWORK_TOOL_ID,SECRET_HEADER,masterNote,MAX_BODY_FETCHES;var init_network=__esm({"src/tools/packs/network.ts"(){"use strict";import_zod5=require("zod");init_packKit();init_secrets();NETWORK_TOOL_ID="network";SECRET_HEADER=/authorization|cookie|token|api[-_]?key|secret|session/i;masterNote=e=>{if(e?.enabled!==false)return"";return e.autoPaused?' \u2014 AUTO-PAUSED after the app failed to settle on launch with overrides active; nothing is firing. Re-arm with network_override({action:"enable"}).':" \u2014 MASTER SWITCH IS OFF, nothing is firing"};MAX_BODY_FETCHES=8}});async function callQueryAction(e,n,t,r){try{return await e.callAction(RQ_TOOL_ID,n,t,r)}catch(i){const o=errMsg2(i);if(!/unknown tool/i.test(o))throw i;return await e.callAction(RQ_TOOL_ID_LEGACY,n,t,r)}}function relTime(e){if(!e)return"\u2014";const n=Math.round((Date.now()-e)/1e3);if(n<60)return`${n}s ago`;if(n<3600)return`${Math.round(n/60)}m ago`;if(n<86400)return`${Math.round(n/3600)}h ago`;return`${Math.round(n/86400)}d ago`}function registerReactQueryTools(e,n){e.registerTool("get_react_query",{description:"Read queries reported by the connected React Query integration, including available status, observer counts, timestamps and errors. includeData:true requests cached payloads; staleOnly:true filters stale queries. Use each returned hash with react_query_action. History depends on retained events.",inputSchema:{includeData:import_zod6.z.boolean().optional().describe("Include each query's full cached data payload (HEAVY). Default false."),staleOnly:import_zod6.z.boolean().optional().describe("Only stale queries. Default false."),limit:import_zod6.z.number().optional().describe("Most-recently-updated N queries. Default 25."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await callQueryAction(n,"listQueries",{includeData:t.includeData??false,staleOnly:t.staleOnly??false,limit:t.limit??25},r);if(!i||!Array.isArray(i.queries)){return fail2("No react-query result from the device. The react-query tool may be inactive, or the app needs a newer Buoy (get_react_query requires the listQueries action).")}if(i.queries.length===0){return text(`React Query cache is empty (0 of ${i.total} queries${t.staleOnly?" match staleOnly":""}).`)}const o=i.queries.map((l,u)=>{const d=STATUS_ICON[l.status]??"\u2022";const h=`${u+1}. ${d} ${l.status} \xB7 \`${l.queryHash}\` \xB7 ${l.observers} obs \xB7 ${relTime(l.updatedAt)}`;const w=l.error?` \u2014 \u26A0\uFE0F ${l.error}`:"";const p=i.includedData?`
|
|
127
|
+
data: ${JSON.stringify(l.data)}`:"";return h+w+p});const s=i.queries.filter(l=>l.isStale).length;const a=`**React Query cache \u2014 ${i.total} queries (showing ${i.returned}, ${s} stale):**`;const c=i.includedData?"":"\n\n_Compact view. Pass includeData:true for cached payloads, staleOnly:true to narrow. Act on one with react_query_action using the `hash` in backticks._";return text(`${a}
|
|
114
128
|
|
|
115
|
-
${
|
|
116
|
-
${c.map(
|
|
117
|
-
${JSON.stringify(a.currentState)}`);let c=a.currentState;for(const
|
|
118
|
-
${JSON.stringify(a.currentState)}`:` \xB7 keys: ${(a.keys??[]).join(", ")||"\u2014"}`;return`${c+1}. **${a.name}** \xB7 ${a.changes} changes${
|
|
129
|
+
${o.join("\n")}${c}`)}catch(r){return fail2(errMsg2(r))}});e.registerTool("react_query_action",{description:"Mutate the app's React Query cache: invalidate / refetch / reset / remove a single query (by queryHash, from get_react_query), or clear the entire query cache. Use this to fix stale data, force a refetch, or reset state during debugging.",inputSchema:{action:import_zod6.z.enum(["invalidate","refetch","reset","remove","clear","list"]).describe("invalidate/refetch/reset/remove one query (by queryHash or queryKey); clear empties the whole cache; list shows the queries."),queryHash:import_zod6.z.string().optional().describe("The target query's hash (from get_react_query, shown in backticks)."),queryKey:import_zod6.z.union([import_zod6.z.array(import_zod6.z.unknown()),import_zod6.z.string()]).optional().describe('Or the query key, e.g. ["offers"]. Acts on every query whose key starts with it.'),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);if(t.action==="clear"){await callQueryAction(n,"clearQueryCache",{},r);return text("Requested clearing of the connected React Query cache. Read it again to confirm.")}const i=t.action==="list"||!t.queryHash&&t.queryKey!==void 0;const o=i?await callQueryAction(n,"listQueries",{includeData:false,staleOnly:false,limit:5e3},r):null;if(t.action==="list"){const c=o?.queries??[];return text(c.length?`**Queries (${c.length}):**
|
|
130
|
+
${c.map(l=>`- \`${l.queryHash}\` \xB7 ${l.status}`).join("\n")}`:"React Query cache is empty.")}let s=t.queryHash?[t.queryHash]:[];if(!s.length&&t.queryKey!==void 0){s=matchQueryKey(t.queryKey,o?.queries??[]);if(!s.length){const c=o&&o.total>o.returned?` (searched ${o.returned} of ${o.total} queries)`:"";return fail2(`No query has a key starting with ${JSON.stringify(t.queryKey)}${c}. Call get_react_query to see the keys.`)}}if(!s.length){return fail2(`'${t.action}' needs a queryHash or queryKey. Call get_react_query first and use a row's hash (in backticks).`)}for(const c of s)await callQueryAction(n,t.action,{queryHash:c},r);const a=o&&o.total>o.returned?` Note: only ${o.returned} of ${o.total} queries were searched, so some matches may have been missed.`:"";return text(`Requested ${t.action} on ${s.map(c=>`\`${c}\``).join(", ")}.${a}`)}catch(r){return fail2(errMsg2(r))}})}function matchQueryKey(e,n){let t;if(Array.isArray(e))t=e;else{try{const r=JSON.parse(e);t=Array.isArray(r)?r:[r]}catch{t=[e]}}return n.filter(r=>{let i=r.queryKey;if(!Array.isArray(i)){try{i=JSON.parse(r.queryHash)}catch{return false}}return Array.isArray(i)&&t.length<=i.length&&t.every((o,s)=>sameJson(o,i[s]))}).map(r=>r.queryHash)}function sameJson(e,n){if(e&&n&&typeof e==="object"&&typeof n==="object"&&!Array.isArray(e)&&!Array.isArray(n)){return Object.entries(e).every(([t,r])=>sameJson(r,n[t]))}return JSON.stringify(e)===JSON.stringify(n)}var import_zod6,RQ_TOOL_ID,RQ_TOOL_ID_LEGACY,STATUS_ICON;var init_reactQuery=__esm({"src/tools/packs/reactQuery.ts"(){"use strict";import_zod6=require("zod");init_packKit();RQ_TOOL_ID="query";RQ_TOOL_ID_LEGACY="react-query";STATUS_ICON={fresh:"\u{1F7E2}",stale:"\u{1F7E1}",fetching:"\u{1F504}",error:"\u{1F534}",inactive:"\u26AA\uFE0F",paused:"\u23F8\uFE0F",disabled:"\u{1F6AB}"}}});function registerZustandTools(e,n){e.registerTool("get_zustand_state",{description:'Read registered Zustand stores, available state keys, change counts and persistence metadata. includeValues:true requests values. Pass store (and optionally path, like "member.crowns") to read just one store or one value. Use get_events with sources:["zustand"] for retained changes.',inputSchema:{store:import_zod7.z.string().optional().describe("Read only this store (name from the list), with its values."),path:import_zod7.z.string().optional().describe('With store: read one value by dot path, e.g. "member.crowns" or "lines.0.id".'),includeValues:import_zod7.z.boolean().optional().describe("Include each store's full current state object (HEAVY). Default false (keys only)."),limit:import_zod7.z.number().optional().describe("First N stores. Default all."),deviceId:deviceIdInput}},withDevice(n,async(t,r)=>{if(t.store){const a=await n.callAction(ZUSTAND_TOOL_ID,"getStoreState",{storeName:t.store},r);if(!a?.found)return fail2(`No Zustand store named "${t.store}". Call get_zustand_state without store to list them.`);if(!t.path)return text(`**${t.store}**
|
|
131
|
+
${JSON.stringify(a.currentState)}`);let c=a.currentState;for(const l of t.path.split(".").filter(Boolean)){if(c==null||typeof c!=="object"||!(l in c)){return fail2(`"${t.path}" is not in store "${t.store}" (stopped at "${l}"). Read the store without path to see its shape.`)}c=c[l]}return text(`**${t.store}** \xB7 ${t.path} = ${JSON.stringify(c)}`)}const i=await n.callAction(ZUSTAND_TOOL_ID,"listStores",{includeValues:t.includeValues??false,limit:t.limit},r);if(!i||!Array.isArray(i.stores)){return fail2(inactiveToolMessage({toolId:ZUSTAND_TOOL_ID,mcpTool:"get_zustand_state",action:"listStores"}))}if(i.stores.length===0){return text("No Zustand stores are registered (call watchStores to register them).")}const o=i.stores.map((a,c)=>{const l=a.isPersisted?` \xB7 persisted${a.persistName?` (${a.persistName})`:""}`:"";const u=i.includedValues?`
|
|
132
|
+
${JSON.stringify(a.currentState)}`:` \xB7 keys: ${(a.keys??[]).join(", ")||"\u2014"}`;return`${c+1}. **${a.name}** \xB7 ${a.changes} changes${l}${u}`});const s=i.includedValues?"":"\n\n_Compact view (keys only). Pass includeValues:true for full state. Mutate with zustand_action({store, state})._";return text(`**Zustand stores \u2014 ${i.total} (showing ${i.returned}):**
|
|
119
133
|
|
|
120
|
-
${
|
|
134
|
+
${o.join("\n")}${s}`)}));e.registerTool("zustand_action",{description:"Change a Zustand store by name (from get_zustand_state). Merges by default: send only the fields to change, including nested ones ({member:{crowns:5}} keeps member's other fields), and the store's action functions stay. Pass replace:true only to reset the whole store; that drops the store's functions and can break the app.",inputSchema:{store:import_zod7.z.string().optional().describe("Store name to target (from get_zustand_state). Leave out to list the stores."),state:import_zod7.z.record(import_zod7.z.string(),import_zod7.z.unknown()).optional().describe("The fields to change."),replace:import_zod7.z.boolean().optional().describe("Default false (merge). true replaces the whole state and deletes the store's action functions."),deviceId:deviceIdInput}},withDevice(n,async(t,r)=>{if(!t.store||!t.state){const s=await n.callAction(ZUSTAND_TOOL_ID,"listStores",{includeValues:false},r);const a=s?.stores??[];const c=a.map(u=>`- **${u.name}** \xB7 keys: ${(u.keys??[]).join(", ")||"\u2014"}`).join("\n")||"(no stores registered)";const l=!t.store?"a store":"state (the fields to change)";return text(`Nothing changed: zustand_action needs ${l}. Stores:
|
|
121
135
|
${c}
|
|
122
136
|
|
|
123
|
-
Example: zustand_action({store: "${a[0]?.name??"cart"}", state: {...}})`)}const i=await n.callAction(ZUSTAND_TOOL_ID,"setState",{storeName:t.store,state:t.state,replace:t.replace??false},r);if(i&&i.ok===false)return fail2(`The app refused the change to "${t.store}": ${(i.error??"no reason given").replace(/\.$/,"")}.`);const
|
|
124
|
-
${JSON.stringify(a.currentValue)}`:"";return`${c+1}. **${a.label}** \xB7 ${a.changes} changes \xB7 ${
|
|
137
|
+
Example: zustand_action({store: "${a[0]?.name??"cart"}", state: {...}})`)}const i=await n.callAction(ZUSTAND_TOOL_ID,"setState",{storeName:t.store,state:t.state,replace:t.replace??false},r);if(i&&i.ok===false)return fail2(`The app refused the change to "${t.store}": ${(i.error??"no reason given").replace(/\.$/,"")}.`);const o=[...i?.keyed??[],...i?.unchecked??[]];return text(`Updated Zustand store "${t.store}" (${t.replace===true?"replaced the whole state":"merged"}).${o.length?` Note: ${o.join(" ")}`:""}`)}))}var import_zod7,ZUSTAND_TOOL_ID;var init_zustand=__esm({"src/tools/packs/zustand.ts"(){"use strict";import_zod7=require("zod");init_packKit();ZUSTAND_TOOL_ID="zustand"}});function registerJotaiTools(e,n){e.registerTool("get_jotai_state",{description:'Read watched Jotai atoms and their available labels, change counts and writable status. includeValues:true requests values. Use get_events with sources:["jotai"] for retained changes.',inputSchema:{includeValues:import_zod8.z.boolean().optional().describe("Include each atom's current value (HEAVY). Default false."),limit:import_zod8.z.number().optional().describe("First N atoms. Default all."),deviceId:deviceIdInput}},withDevice(n,async(t,r)=>{const i=await n.callAction(JOTAI_TOOL_ID,"listAtoms",{includeValues:t.includeValues??false,limit:t.limit},r);if(!i||!Array.isArray(i.atoms)){return fail2(inactiveToolMessage({toolId:JOTAI_TOOL_ID,mcpTool:"get_jotai_state",action:"listAtoms"}))}if(i.atoms.length===0){return text("No Jotai atoms are being watched (call watchAtoms to register them).")}const o=i.atoms.map((a,c)=>{const l=a.writable?"writable":"read-only";const u=i.includedValues?`
|
|
138
|
+
${JSON.stringify(a.currentValue)}`:"";return`${c+1}. **${a.label}** \xB7 ${a.changes} changes \xB7 ${l}${u}`});const s=i.includedValues?"":"\n\n_Compact view. Pass includeValues:true for current values. Set a writable atom with jotai_action({atom, value})._";return text(`**Jotai atoms \u2014 ${i.total} (showing ${i.returned}):**
|
|
125
139
|
|
|
126
|
-
${
|
|
140
|
+
${o.join("\n")}${s}`)}));e.registerTool("jotai_action",{description:"Set the value of a writable Jotai atom (by label, from get_jotai_state). Read-only/derived atoms cannot be set (you'll get a clear error). Use for tweaking state during debugging.",inputSchema:{atom:import_zod8.z.string().describe("Atom label to set (from get_jotai_state; must be writable)."),value:import_zod8.z.unknown().describe("The new value (any JSON \u2014 number, string, object, etc.)."),deviceId:deviceIdInput}},withDevice(n,async(t,r)=>{await n.callAction(JOTAI_TOOL_ID,"setAtom",{label:t.atom,value:t.value},r);return text(`Requested update of Jotai atom "${t.atom}" to ${JSON.stringify(t.value)}.`)}))}var import_zod8,JOTAI_TOOL_ID;var init_jotai=__esm({"src/tools/packs/jotai.ts"(){"use strict";import_zod8=require("zod");init_packKit();JOTAI_TOOL_ID="jotai"}});function noStoreMessage(e){switch(e){case"no-react-redux":return"react-redux is not installed in the app \u2014 the Redux tool requires it (npm install react-redux).";case"no-provider":return"No Redux Provider above <FloatingDevTools />. Move <FloatingDevTools /> inside your <Provider store={store}> and retry.";case"not-instrumented":default:return"Redux store not instrumented yet. On current Buoy versions the store binds automatically at app startup \u2014 this usually means the app is running an older @buoy-gg/core (upgrade it), or the Redux tool hasn't been opened once (older versions only). Apps can also bind explicitly with registerReduxStore(store) from @buoy-gg/redux."}}function registerReduxTools(e,n){e.registerTool("get_redux_state",{description:'Read available state from the connected Redux integration. Lists top-level slices by default; includeValues:true requests state values. Use get_events with sources:["redux"] for retained action history.',inputSchema:{includeValues:import_zod9.z.boolean().optional().describe("Include the full current state tree (HEAVY). Default false (slice names only)."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(REDUX_TOOL_ID,"getState",{includeValues:t.includeValues??false},r);if(!i){return fail2("No redux result from the device. The redux tool may be inactive, or the app needs a newer Buoy (get_redux_state requires the getState action).")}if(!i.available)return fail2(noStoreMessage(i.reason));const o=i.slices.length?i.slices.join(", "):"(none)";const s=i.capture==="top-level-only"?TOP_LEVEL_ONLY_NOTE:"";if(t.includeValues){return text(`**Redux store \u2014 slices: ${o}**
|
|
127
141
|
|
|
128
142
|
\`\`\`json
|
|
129
143
|
${JSON.stringify(i.state,null,2)}
|
|
130
|
-
\`\`\`${
|
|
144
|
+
\`\`\`${s}`)}return text(`**Redux store \u2014 slices: ${o}**
|
|
131
145
|
|
|
132
|
-
_Compact view. Pass includeValues:true for the full state tree. Dispatch with redux_dispatch({type, payload})._${
|
|
133
|
-
${
|
|
134
|
-
${
|
|
135
|
-
${m.join("\n")}`)}if(a.length===0){return text(`No storage keys${i?` matching "${t.pattern}"`:""} in any backend.`)}const p=t.includeValues?"":"\n\n_Keys only. Pass includeValues:true for values, or a pattern to filter. Modify AsyncStorage with storage_action._";return text(`${a.join("\n\n")}${p}`)}catch(r){return fail2(errMsg2(r))}});e.registerTool("storage_action",{description:"Modify the app's AsyncStorage: set a key, remove a key, or clear supported app AsyncStorage keys (Buoy's own devtool keys are preserved). Values are stored as strings \u2014 JSON-encode objects yourself.",inputSchema:{action:import_zod10.z.enum(["set","remove","clear"]).describe("set/remove a key, or clear supported app AsyncStorage keys."),key:import_zod10.z.string().optional().describe("The key (required for set and remove)."),value:import_zod10.z.string().optional().describe("The string value to store (required for set; JSON-encode objects)."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);if(t.action==="clear"){await n.callAction(STORAGE_TOOL_ID,"clearAppStorage",{},r);return text("Requested clearing of supported app AsyncStorage keys. Read storage again to confirm.")}if(!t.key){return fail2(`'${t.action}' needs a key.`)}if(t.action==="remove"){await n.callAction(STORAGE_TOOL_ID,"async.removeItem",{key:t.key},r);return text(`Requested removal of storage key "${t.key}".`)}if(t.value===void 0){return fail2("'set' needs a value (a string).")}await n.callAction(STORAGE_TOOL_ID,"async.setItem",{key:t.key,value:t.value},r);return text(`Requested update of storage key "${t.key}".`)}catch(r){return fail2(errMsg2(r))}})}var import_zod10,STORAGE_TOOL_ID;var init_storage=__esm({"src/tools/packs/storage.ts"(){"use strict";import_zod10=require("zod");init_packKit();STORAGE_TOOL_ID="storage"}});async function observeAfterAction(e,n,t){let r="";for(let s=0;s<(t?6:1);s++){await delay3(s===0?300:250);try{const o=await e.callAction("route-events","getCurrentRoute",{},n,{timeoutMs:3e3,silent:true});r=String(o?.pathname??o?.path??"")}catch{break}if(!t||r.replace(/\(.*?\)\//g,"").replace(/\/$/,"")===t.replace(/\/$/,"")||r.endsWith(t))break}let i="";try{const s=await e.callAction(TOOL_ID,"describeScreen",{},n,{timeoutMs:5e3,silent:true});const o=s?.elements??[];const a=new Set(o.filter(l=>l.name!=="Text").map(l=>l.text??l.label).filter(Boolean));const c=o.filter(l=>{const d=l.text??l.label;if(l.name==="Text"&&(!d||/^[\s\uE000-\uF8FF]*$/.test(d)))return false;if(l.name==="Text"&&a.has(d))return false;return true});const u=c.slice(0,OBSERVE_MAX);i=u.map(formatElement).join("\n");if(c.length>u.length)i+=`
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
Now on ${r?`\`${r}\``:"an unknown route"}. Screen (\u2022 = tappable):
|
|
139
|
-
${i}`}function formatElement(e){let n=e.interactive?"\u2022 ":" ";n+=e.name;const t=e.text??e.label;if(t)n+=` "${t}"`;if(e.role)n+=` <${e.role}>`;if(e.control)n+=` {${e.control}${e.value!==void 0?`=${JSON.stringify(e.value)}`:""}}`;if(e.longPressable)n+=" {long-press}";if(e.testID)n+=` [testID=${e.testID}]`;if(e.tap)n+=` (tap: ${e.tap.x},${e.tap.y})`;if(e.nativeTag!=null)n+=` #${e.nativeTag}`;return n}function registerInteractTools(e,n){e.registerTool("describe_screen",{description:"List elements exposed by the app React-fiber inspection integration, with available names, text, roles, testIDs, positions and native tags. This is not a complete native accessibility tree or a visual screenshot. Use the returned controls to select a target for tap_element; refresh after navigation or state changes. Empty results can reflect unavailable inspection. Requires Buoy Pro and the highlight-updates interaction integration.",inputSchema:{interactiveOnly:import_zod11.z.boolean().optional().describe("Only return tappable (onPress) elements. Default false (include labels/text for context)."),includeBuoy:import_zod11.z.boolean().optional().describe("Also list Buoy's own overlay \u2014 the dial, tool sheets, Ask Buoy's chat. Default false: the screen described is the app's. Exact testIDs inside Buoy (buoy-\u2026) can still be tapped without this."),includeHidden:import_zod11.z.boolean().optional().describe("Also list screens that are mounted but not showing (other tabs, screens under the current one). Default false: only what is on screen."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(TOOL_ID,"describeScreen",{includeBuoy:t.includeBuoy,includeHidden:t.includeHidden},r);const s=i?.elements??[];const o=t.interactiveOnly?s.filter(l=>l.interactive):s;if(o.length===0){return text2("No elements found on screen. If the app just navigated, wait a moment and retry; make sure highlight-updates is enabled in the app.")}const a=i.hiddenBuoy?` Buoy's own overlay (${i.hiddenBuoy} element${i.hiddenBuoy===1?"":"s"}) is left out \u2014 pass includeBuoy:true to see it.`:"";const c=i.hiddenScreens?` ${i.hiddenScreens} screen${i.hiddenScreens===1?" that isn't":"s that aren't"} showing (other tabs, screens underneath) left out \u2014 pass includeHidden:true to see them.`:"";const u=`Screen ${i.screen.width}\xD7${i.screen.height} \u2014 ${o.length} element${o.length===1?"":"s"} (\u2022 = tappable). Tap with tap_element({ testID | query | nativeTag }).${a}${c}`;return text2(`${u}
|
|
140
|
-
|
|
141
|
-
${o.map(formatElement).join("\n")}`)}catch(r){return fail3(errMsg3(r))}});e.registerTool("tap_element",{description:"Invoke a supported element handler in JavaScript: onPress/onLongPress, onValueChange or onChangeText. This does not reproduce native hit testing, keyboard entry or a physical gesture. Select an exposed element by nativeTag, testID or fuzzy query; inspect the matched target and resulting behavior. value sets a supported toggle or slider, text invokes a text-input handler, and longPress selects onLongPress. Can attempt to scroll an off-screen target into view. Use describe_screen for current controls and run_flow for sequences. Requires Buoy Pro and the app interaction integration.",inputSchema:{nativeTag:import_zod11.z.number().optional().describe("Exact nativeTag from describe_screen (most precise)."),testID:import_zod11.z.string().optional().describe("Exact testID of the element."),query:import_zod11.z.string().optional().describe('Fuzzy match against testID / label / visible text / component name \u2014 e.g. "Sign in".'),value:import_zod11.z.union([import_zod11.z.number(),import_zod11.z.boolean()]).optional().describe("For a toggle: true/false (omit to flip). For a slider: the numeric value (omit to jump to the far end)."),text:import_zod11.z.string().optional().describe("For a text input: the string to set via onChangeText."),longPress:import_zod11.z.boolean().optional().describe("Invoke the element's onLongPress instead of onPress. Fails with a clear reason if the element has no onLongPress handler."),scrollIntoView:import_zod11.z.boolean().optional().describe("Attempt to scroll an off-screen target into view. Default true; inspect the action result."),includeBuoy:import_zod11.z.boolean().optional().describe("Let a fuzzy `query` match Buoy's own overlay. Default false \u2014 an exact nativeTag/testID always may."),includeHidden:import_zod11.z.boolean().optional().describe("Also match elements on screens that are mounted but not showing. Default false."),observe:observeInput,deviceId:deviceIdInput}},async t=>{try{if(t.nativeTag==null&&!t.testID&&!t.query){return fail3("Provide one of: nativeTag, testID, or query (from describe_screen).")}const r=n.requireProDevice(t.deviceId);const i=await n.callAction(TOOL_ID,"tapElement",{nativeTag:t.nativeTag,testID:t.testID,query:t.query,value:t.value,text:t.text===void 0?void 0:fillSecrets(t.text),longPress:t.longPress,scrollIntoView:t.scrollIntoView,includeBuoy:t.includeBuoy,includeHidden:t.includeHidden},r);tapCount+=1;const s=tapCount>=FLOW_TIP_EVERY&&tapCount%FLOW_TIP_EVERY===0?FLOW_TIP:"";if(i?.tapped&&i.matched){const a=i.matched;const c=a.text??a.label??a.name;const u=a.testID?` [testID=${a.testID}]`:a.nativeTag!=null?` #${a.nativeTag}`:"";const l=i.scrolled?" (scrolled into view)":"";const d=a.via==="onValueChange"?`Set "${c}"${u} \u2192 ${JSON.stringify(a.value)}`:a.via==="onChangeText"?`Typed ${JSON.stringify(a.value)} into "${c}"${u}`:a.via==="onLongPress"?`Long-pressed "${c}"${u}`:`Tapped "${c}"${u}`;const h=i.effect;const p=!h?"":h.commits>0?` ${h.commits} re-render${h.commits===1?"":"s"} followed.`:` No re-render followed within ${h.observedMs}ms \u2014 the handler ran but the app did not react. The element may sit on a screen beneath the current one, or be inert; do not treat this as done.`;const m=i.alsoMatched?.length?`
|
|
142
|
-
Also matched equally well (the choice was a coin toss \u2014 re-tap by #nativeTag if this was wrong):
|
|
143
|
-
`+i.alsoMatched.map(w=>`- ${w.name}${w.text?` "${w.text}"`:""}${w.testID?` [testID=${w.testID}]`:""}${w.nativeTag!=null?` #${w.nativeTag}`:""}`).join("\n"):"";const g=t.observe==="none"?"":await observeAfterAction(n,r);return text2(`${d}${l}.${p}${m}${g}${s}`)}let o=i?.reason??"Tap failed.";if(i?.candidates?.length){o+="\n\nTappable candidates:\n"+i.candidates.map(a=>`- ${a.name}${a.text?` "${a.text}"`:""}${a.testID?` [testID=${a.testID}]`:""}${a.nativeTag!=null?` #${a.nativeTag}`:""}`).join("\n")}return fail3(o)}catch(r){return fail3(errMsg3(r))}})}var import_zod11,TOOL_ID,text2,fail3,errMsg3,delay3,OBSERVE_MAX,observeInput,tapCount,FLOW_TIP_EVERY,FLOW_TIP;var init_interact=__esm({"src/tools/packs/interact.ts"(){"use strict";init_secrets();import_zod11=require("zod");init_packKit();TOOL_ID="highlight-updates";text2=e=>({content:[{type:"text",text:e}]});fail3=e=>({isError:true,content:[{type:"text",text:e}]});errMsg3=e=>e instanceof Error?e.message:String(e);delay3=e=>new Promise(n=>setTimeout(n,e));OBSERVE_MAX=40;observeInput=import_zod11.z.enum(["screen","none"]).optional().describe('What to return after the action. Default "screen": the current route and what is on screen, so no follow-up describe_screen is needed. "none" skips it.');tapCount=0;FLOW_TIP_EVERY=3;FLOW_TIP="\n\nTip: driving several steps? `run_flow` does a whole tap/type/wait/assert sequence in ONE call and reports the final screen plus the network and console output it produced."}});function flattenRoutes(e,n=[]){for(const t of e??[]){if(t.path)n.push(t.path);if(t.children?.length)flattenRoutes(t.children,n)}return n}function registerRoutesTools(e,n){e.registerTool("get_routes",{description:'Read reported current navigation state and stack. includeSitemap:true includes available configured route paths; it does not establish complete application route coverage. Use get_events with sources:["route"] for retained navigation history.',inputSchema:{includeSitemap:import_zod12.z.boolean().optional().describe("Also list available configured route paths (can be long). Default false."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:i,stale:s}=await n.getSnapshot(ROUTES_TOOL_ID,r);const o=Array.isArray(i)?{events:i}:i??{};const a=Array.isArray(o.stack)?o.stack:[];const c=a.find(h=>h.isFocused)??a[a.length-1];const u=c?.pathname??"(unknown)";const l=[`**Current route:** \`${u}\``];if(a.length){const h=a.map((p,m)=>`${m+1}. \`${p.pathname??p.name??"?"}\`${p.isFocused?" \u2190 focused":""}`);l.push(`
|
|
144
|
-
**Navigation stack** (top last):
|
|
145
|
-
${h.join("\n")}`)}const d=flattenRoutes(o.sitemap?.routes);if(t.includeSitemap){const h=d.slice(0,200);l.push(`
|
|
146
|
-
**Sitemap (${d.length} routes${h.length<d.length?`, showing ${h.length}`:""}):**
|
|
147
|
-
${h.map(p=>`- \`${p}\``).join("\n")}`)}else{l.push(`
|
|
148
|
-
**Sitemap:** ${d.length} routes _(pass includeSitemap:true to list them)_`)}l.push("\n_Navigate with navigate({ path })._");return text(staleHeader(s)+l.join("\n"))}catch(r){return fail2(errMsg2(r))}});e.registerTool("navigate",{description:"Navigate the app to a route path (e.g. '/pokemon/25' or '/settings'). Use a concrete path \u2014 resolve any dynamic segments (like [id]) to real values first. See get_routes with includeSitemap:true for valid paths. Pushes by default (back still works); pass replace:true to leave the current screen instead of stacking on top of it (e.g. resetting to '/').",inputSchema:{path:import_zod12.z.string().describe("The concrete path to navigate to, e.g. '/pokemon/25'."),replace:import_zod12.z.boolean().optional().describe("Replace the current screen instead of pushing (use when resetting, e.g. to '/')."),observe:import_zod12.z.enum(["screen","none"]).optional().describe('What to return after navigating. Default "screen": the route it landed on and what is on screen. "none" skips it.'),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);await n.callAction(ROUTES_TOOL_ID,"navigate",{path:t.path,replace:t.replace===true},r);const i=t.observe==="none"?"":await observeAfterAction(n,r,t.path);return text(`Navigated to \`${t.path}\`${t.replace?" (replaced current screen)":""}.${i}`)}catch(r){return fail2(errMsg2(r))}})}var import_zod12,ROUTES_TOOL_ID;var init_routes=__esm({"src/tools/packs/routes.ts"(){"use strict";import_zod12=require("zod");init_packKit();init_interact();ROUTES_TOOL_ID="route-events"}});function hhmmss(e){const n=new Date(e);const t=(r,i=2)=>String(r).padStart(i,"0");return`${t(n.getHours())}:${t(n.getMinutes())}:${t(n.getSeconds())}.${t(n.getMilliseconds(),3)}`}function registerConsoleTools(e,n){e.registerTool("get_console",{description:"Read retained captured console output as a compact tail of timestamps, levels and messages. Filter by minimum level or a case-insensitive message substring. Fatal JavaScript errors may be included when supported hooks captured them; post-crash availability is not guaranteed. Missing entries do not establish that no error occurred. Use get_snapshot for available full entry details. Requires configured console capture and Buoy Pro.",inputSchema:{level:import_zod13.z.enum(["verbose","info","warning","error"]).optional().describe("Minimum level to include (severity threshold). e.g. 'warning' = warnings + errors. Default all."),limit:import_zod13.z.number().optional().describe("Most-recent N entries. Default 50."),pattern:import_zod13.z.string().optional().describe("Only entries whose message contains this substring (case-insensitive)."),deviceId:deviceIdInput}},async t=>{let r;let i;try{const s=n.requireProDevice(t.deviceId);({payload:r,stale:i}=await n.getSnapshot(CONSOLE_TOOL_ID,s))}catch(s){const o=lastSyncAfterDrop(n,s,CONSOLE_TOOL_ID);if(!o)return fail2(errMsg2(s));({payload:r,stale:i}=o)}{const s=staleHeader(i);const o=Array.isArray(r)?{entries:r}:r??{};const a=Array.isArray(o.entries)?o.entries:[];const c=t.level?SEVERITY[t.level]:0;const u=t.pattern?.toLowerCase();const l=a.filter(f=>SEVERITY[f.level]>=c&&(!u||(f.message??"").toLowerCase().includes(u)));const d=[...l].sort((f,b)=>f.id-b.id);const h=clampLimit(t.limit,50);const p=d.slice(-h);if(p.length===0){return text(`${s}No console entries${t.level?` at level \u2265 ${t.level}`:""}${u?` matching "${t.pattern}"`:""} (${a.length} total captured).`)}const m=p.map(f=>`${hhmmss(f.timestamp)} [${TAG[f.level]??f.level}] ${f.message}`);const g=t.level?`, level \u2265 ${t.level}`:"";const w=`**Console \u2014 ${a.length} entries (showing ${p.length}${g}):**`;return text(`${s}${w}
|
|
149
|
-
|
|
150
|
-
\`\`\`
|
|
151
|
-
${m.join("\n")}
|
|
152
|
-
\`\`\`
|
|
153
|
-
|
|
154
|
-
_Tail of recent logs. Use get_snapshot for available console entry details._`)}})}var import_zod13,CONSOLE_TOOL_ID,SEVERITY,TAG;var init_console=__esm({"src/tools/packs/console.ts"(){"use strict";import_zod13=require("zod");init_packKit();CONSOLE_TOOL_ID="console";SEVERITY={verbose:0,info:1,warning:2,error:3};TAG={verbose:"\xB7",info:"info",warning:"warn",error:"ERR"}}});function hhmmss2(e){const n=new Date(e);const t=r=>String(r).padStart(2,"0");return`${t(n.getHours())}:${t(n.getMinutes())}:${t(n.getSeconds())}`}function bytes(e){if(e<1024)return`${e}B`;if(e<1024*1024)return`${(e/1024).toFixed(1)}KB`;return`${(e/(1024*1024)).toFixed(2)}MB`}function units(e,n){if(n==="bytes")return bytes(e);if(e>=1e6)return`${(e/1e6).toFixed(1)}M`;if(e>=1e3)return`${(e/1e3).toFixed(1)}k`;return String(e)}function statusNote(e){switch(e){case"attached":return"";case"sdk-not-found":return"\n\n\u26A0\uFE0F The tool never found @sentry/react-native \u2014 nothing is being captured. The app must pass `getClient` to SentryRoot, or the SDK isn't installed.";case"no-client":return"\n\n\u26A0\uFE0F The SDK is present but no client appeared \u2014 is Sentry.init() being called?";default:return"\n\n\u23F3 Still looking for the app's Sentry client."}}function registerSentryTools(e,n){e.registerTool("get_sentry_envelopes",{description:"Inspect retained captured Sentry envelopes and available item types, sizes, spans and payload details. Coverage depends on supported hooks. Local capture does not prove successful delivery, ingestion or billing impact. Filter by item type to investigate the available evidence.",inputSchema:{type:import_zod14.z.string().optional().describe("Only envelopes containing this item type, e.g. 'event' for errors or 'transaction' for traces."),limit:import_zod14.z.number().optional().describe("Most-recent N envelopes. Default 25."),deviceId:import_zod14.z.string().optional().describe("The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out.")}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:i,stale:s}=await n.getSnapshot(SENTRY_TOOL_ID,r);const o=s?`${s}
|
|
155
|
-
|
|
156
|
-
`:"";const a=i??{};const c=Array.isArray(a.envelopes)?a.envelopes:[];const u=t.type?c.filter(m=>m.items.some(g=>g.type===t.type)):c;const l=typeof t.limit==="number"&&t.limit>0?t.limit:25;const d=u.slice(-l);if(d.length===0){return text3(`${o}No Sentry envelopes${t.type?` containing a '${t.type}' item`:""} (${c.length} captured this session).${statusNote(a.status)}`)}const h=d.map(m=>{const g=m.items.map(v=>v.type).join("+");const w=m.items.reduce((v,y)=>v+(y.spanCount??0),0);const f=w>0?` \xB7 ${w} span${w===1?"":"s"}`:"";const b=`${m.id}. ${hhmmss2(m.timestamp)} [${g}] ${bytes(m.totalBytes)}${f}`;return`${b}
|
|
157
|
-
\u2514\u2500 ${m.items[0]?.summary??"envelope"}`});const p=`**Sentry \u2014 ${c.length} envelope${c.length===1?"":"s"} sent (showing ${d.length}${t.type?`, type '${t.type}'`:""}):**`;return text3(`${o}${p}${statusNote(a.status)}
|
|
158
|
-
|
|
159
|
-
${h.join("\n")}
|
|
160
|
-
|
|
161
|
-
_Full payloads (exception, breadcrumbs, contexts) via get_snapshot('sentry'). Billing units via get_sentry_cost._`)}catch(r){return fail4(errMsg4(r))}});e.registerTool("get_sentry_cost",{description:"Inspect captured session usage and the tool's configured monthly extrapolation and quota assumptions. These estimates do not establish Sentry ingestion, current plan limits or an actual bill. Check the account's current terms and usage before making cost decisions.",inputSchema:{deviceId:import_zod14.z.string().optional().describe("The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out.")}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:i,stale:s}=await n.getSnapshot(SENTRY_TOOL_ID,r);const o=s?`${s}
|
|
162
|
-
|
|
163
|
-
`:"";const a=i??{};const c=a.usage;if(!c?.session){return text3(`${o}No usage is available in this capture.${statusNote(a.status)}`)}const u=c.session;const l=c.projectedMonthly;const d=Object.keys(u);const h=d.map(w=>{const f=CATEGORY_FORMAT[w];const b=units(u[w],f);if(!l)return`- ${w}: ${b} this session`;const v=l[w];const y=FREE_QUOTA[w];const _=y>0?Math.round(v/y*100):null;const $=_===null?" (no configured reference quota)":` \u2014 ${_}% of the configured reference quota of ${units(y,f)}`;return`- ${w}: ${b} this session \u2192 ~${units(v,f)}/mo${$}`});const p=c.windowMs?` over ${Math.round(c.windowMs/1e3)}s`:"";const m=c.topContributors?.length?`
|
|
164
|
-
|
|
165
|
-
**What produced it:**
|
|
166
|
-
${c.topContributors.map(w=>`- ${w.label} \u2014 ${w.units} ${w.category}`).join("\n")}`:"";const g=l?"\n\n_The monthly figure extrapolates one session on one device \u2014 it catches a config that is orders of magnitude off, it is not a forecast._":"\n\n_Session too short to project a month from._";return text3(`${o}**Sentry usage estimate \u2014 ${a.envelopes?.length??0} envelopes${p}:**
|
|
167
|
-
|
|
168
|
-
${h.join("\n")}${m}${g}`)}catch(r){return fail4(errMsg4(r))}});e.registerTool("get_sentry_drops",{description:"Why events never reached Sentry. Answers 'I called captureException but the event isn't in Sentry' \u2014 the single most common Sentry problem \u2014 by naming the layer that discarded it: a beforeSend callback returning null, a sample-rate roll, dedupe or another event processor, React Native tracing discarding an empty transaction, or a native rate limit.",inputSchema:{limit:import_zod14.z.number().optional().describe("Most-recent N drop records. Default 30."),deviceId:import_zod14.z.string().optional().describe("The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out.")}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:i,stale:s}=await n.getSnapshot(SENTRY_TOOL_ID,r);const o=s?`${s}
|
|
169
|
-
|
|
170
|
-
`:"";const a=i??{};const c=a.drops?.summary??[];const u=a.drops?.recent??[];if(c.length===0){return text3(`${o}No drops are reported in the available capture.${statusNote(a.status)}
|
|
171
|
-
|
|
172
|
-
_If an event is missing from sentry.io, check capture coverage, transport errors, the DSN/project, inbound filters and quota. Local capture does not confirm delivery._`)}const l=typeof t.limit==="number"&&t.limit>0?t.limit:30;const d=u.slice(-l);const h=c.map(m=>`- ${m.reason}: ${m.units} unit${m.units===1?"":"s"} across ${m.records} record${m.records===1?"":"s"}`);const p=d.map(m=>`${hhmmss2(m.timestamp)} [${m.reason}] ${m.category}${m.quantity>1?` \xD7${m.quantity}`:""} \u2014 ${m.detail} (${m.source})`);return text3(`${o}**Sentry drops \u2014 by reason:**
|
|
173
|
-
|
|
174
|
-
${h.join("\n")}
|
|
175
|
-
|
|
176
|
-
**Recent (${d.length}):**
|
|
177
|
-
|
|
178
|
-
\`\`\`
|
|
179
|
-
${p.join("\n")}
|
|
180
|
-
\`\`\`
|
|
181
|
-
|
|
182
|
-
_"observed" means the tool watched it happen; "reported" means the SDK counted it afterwards. Native drops only appear when the SDK runs with debug enabled._`)}catch(r){return fail4(errMsg4(r))}});e.registerTool("sentry_action",{description:"Act on the Sentry inspector. 'clear' drops every captured envelope and drop record \u2014 use it to get a clean window before driving a flow you want to measure.",inputSchema:{action:import_zod14.z.enum(["clear"]).describe("The action to perform."),deviceId:import_zod14.z.string().optional().describe("The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out.")}},async t=>{try{const r=n.requireProDevice(t.deviceId);await n.callAction(SENTRY_TOOL_ID,"clearEnvelopes",{},r);return text3("Cleared the Sentry inspector \u2014 envelopes and drop records. Drive your flow, then read get_sentry_envelopes or get_sentry_cost.")}catch(r){return fail4(errMsg4(r))}})}var import_zod14,SENTRY_TOOL_ID,text3,fail4,errMsg4,FREE_QUOTA,CATEGORY_FORMAT;var init_sentry=__esm({"src/tools/packs/sentry.ts"(){"use strict";import_zod14=require("zod");SENTRY_TOOL_ID="sentry";text3=e=>({content:[{type:"text",text:e}]});fail4=e=>({isError:true,content:[{type:"text",text:e}]});errMsg4=e=>e instanceof Error?e.message:String(e);FREE_QUOTA={errors:5e3,spans:5e6,replays:50,logBytes:5*1024**3,attachmentBytes:1*1024**3};CATEGORY_FORMAT={errors:"count",spans:"count",replays:"count",logBytes:"bytes",attachmentBytes:"bytes"}}});function kb(e){return e<1024?`${e} B`:`${(e/1024).toFixed(1)} KB`}function formatOutcome(e){const n=Object.entries(e.results).map(([r,i])=>{const s=i.skipped.slice(0,3).map(a=>`
|
|
183
|
-
\xB7 ${a.id}: ${a.reason}`).join("");const o=i.warnings.slice(0,3).map(a=>`
|
|
184
|
-
\u26A0 ${a}`).join("");return` ${i.ok?"\u2713":"\u2715"} ${r} \u2014 applied ${i.applied}${i.skipped.length?`, skipped ${i.skipped.length}`:""}${s}${o}`});const t=e.route;if(t){n.push(t.status==="navigated"?` \u2713 route \u2014 navigated to ${t.href}`:t.status==="deferred"?` \u21BB route \u2014 ${t.href} will be opened after the reload`:` \u2715 route \u2014 ${t.error??t.status}`)}return`Restored "${e.snapshotName}" (${e.mode}${e.willReload?", app reloading":""}):
|
|
185
|
-
${n.join("\n")}`}function registerTimeMachineTools(e,n){e.registerTool("get_time_machine",{description:"List the app's Time Machine state snapshots (restore points) and which state sources (storage/redux/zustand/jotai/react-query) can currently be captured/restored. Each snapshot also records the route it was captured on (shown as `route`), which a restore can navigate back to. Use time_machine_action to capture a snapshot before driving a flow, then restore supported sources to repeat the flow. Uncaptured and backend state can still differ.",inputSchema:{deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:i,stale:s}=await n.getSnapshot(TIME_MACHINE_TOOL_ID,r);const o=i??{};const a=o.snapshots??[];const c=o.providers??[];const u=c.map(h=>{const p=h.canCapture?h.canRestore?"capture+restore":"capture only":"unavailable";return`- ${h.label} (${h.id}): ${p}${h.detail?` \u2014 ${h.detail}`:""}`});if(o.route){u.push(o.route.available?`- Route (route): capture+restore \u2014 recorded with every snapshot; pass restoreRoute:true to return to it${o.route.current?` (now ${o.route.current})`:""}`:"- Route (route): unavailable \u2014 no Expo Router on this device, snapshots record no route")}const l=a.map(h=>{const p=Object.values(h.sources).reduce((w,f)=>w+f.warnings.length,0);const m=h.baseline?"baseline: clear supported providers and request reload":`${kb(h.sizeBytes)} \xB7 ${Object.keys(h.sources).join(", ")}`;const g=h.route?` \xB7 route ${h.route.href}`:"";return`- \`${h.id}\` **${h.name}** \u2014 ${new Date(h.createdAt).toISOString()} \xB7 ${m}${g}${p?` \xB7 \u26A0 ${p}`:""}`});const d=[`**Time Machine \u2014 ${a.length} snapshot(s):**`,l.length?l.join("\n"):"_none yet \u2014 capture one with time_machine_action_",`**Sources:**
|
|
186
|
-
${u.join("\n")||"_no providers registered_"}`];if(o.lastOutcome)d.push(`**Last restore:**
|
|
187
|
-
${formatOutcome(o.lastOutcome)}`);return text(staleHeader(s)+d.join("\n\n"))}catch(r){return fail2(errMsg2(r))}});e.registerTool("time_machine_action",{description:"Manage snapshots of supported registered state sources: capture, preview, restore, capture_baseline, delete or rename. Preview affected items before restoring. Live mode replaces supported state in place; reload mode restores supported persisted storage and requests a JS reload. Baselines clear providers that support clearing and request a reload; they do not reset backend state or reproduce a complete reinstall. restoreRoute:true requests the captured route when available. Inspect per-source applied/skipped results and reload outcomes.",inputSchema:{action:import_zod15.z.enum(["capture","capture_baseline","preview","restore","delete","rename"]).describe("What to do."),id:import_zod15.z.string().optional().describe("Snapshot id (required for restore/delete/rename; from get_time_machine)."),name:import_zod15.z.string().optional().describe("Snapshot name (for capture and rename)."),mode:import_zod15.z.enum(["live","reload"]).optional().describe("Restore mode. Default 'live'."),excludeKeys:import_zod15.z.array(import_zod15.z.string()).optional().describe('Restore only: item keys to LEAVE UNTOUCHED, as "sourceId::itemKey" (itemKey = the key shown by the preview action, e.g. "query::[\\"pokemon\\"]" or "storage::async:@cart").'),restoreRoute:import_zod15.z.boolean().optional().describe("Restore only: also navigate back to the route the snapshot was captured on (shown as `route` by get_time_machine). With mode 'reload' the navigation happens automatically on the next boot. Default false \u2014 state is restored but the app stays on the current screen."),sourceIds:import_zod15.z.array(import_zod15.z.string()).optional().describe("Capture/restore only these source ids (default all)."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=(s,o)=>n.callAction(TIME_MACHINE_TOOL_ID,s,o,r);switch(t.action){case"capture":{const s=await i("capture",{name:t.name??"",sourceIds:t.sourceIds});const o=s.snapshot;const a=Object.entries(o.sources).flatMap(([c,u])=>u.warnings.map(l=>`
|
|
188
|
-
\u26A0 ${c}: ${l}`)).join("");return text(`Captured \`${o.id}\` "${o.name}" \u2014 ${kb(o.sizeBytes)} \xB7 ${Object.keys(o.sources).join(", ")}${a}`)}case"capture_baseline":{const s=await i("captureBaseline",{});return text(`Captured baseline \`${s.snapshot.id}\` \u2014 restoring it wipes app storage and reloads.`)}case"preview":{if(!t.id)return fail2("preview requires `id` (from get_time_machine).");const s=await i("preview",{id:t.id});const o=[];let a=0;for(const u of s.sources){const l={};for(const p of u.items){l[p.verdict]=(l[p.verdict]??0)+1}const d=(l.added??0)+(l.removed??0)+(l.changed??0)+(l["too-large"]??0);a+=d;const h=Object.entries(l).filter(([p])=>p!=="unchanged").map(([p,m])=>`${m} ${p}`);o.push(`- **${u.label}**: ${h.length?h.join(", "):"no changes"}${u.error?` \u2014 \u26A0 ${u.error}`:""}`);for(const p of u.items.filter(m=>m.verdict!=="unchanged").slice(0,8)){o.push(` ${p.verdict==="added"?"+":p.verdict==="removed"?"\u2212":p.verdict==="wont-apply"?"\u2298":"\u2248"} ${p.label}${p.reason?` (${p.reason})`:""}`)}for(const p of u.notes)o.push(` \xB7 ${p}`)}const c=a===0?"**Restore would change NOTHING** (states identical or nothing applicable).":`**Restore would apply ${a} change(s):**`;return text(`${c}
|
|
189
|
-
${o.join("\n")}`)}case"restore":{if(!t.id)return fail2("restore requires `id` (from get_time_machine).");const s=await i("restore",{id:t.id,mode:t.mode??"live",excludeKeys:t.excludeKeys,restoreRoute:t.restoreRoute});return text(formatOutcome(s))}case"delete":{if(!t.id)return fail2("delete requires `id`.");await i("delete",{id:t.id});return text(`Deleted snapshot \`${t.id}\`.`)}case"rename":{if(!t.id||!t.name)return fail2("rename requires `id` and `name`.");await i("rename",{id:t.id,name:t.name});return text(`Renamed \`${t.id}\` to "${t.name}".`)}}}catch(r){return fail2(errMsg2(r))}})}var import_zod15,TIME_MACHINE_TOOL_ID;var init_timeMachine=__esm({"src/tools/packs/timeMachine.ts"(){"use strict";import_zod15=require("zod");init_packKit();TIME_MACHINE_TOOL_ID="time-machine"}});function duration(e){const n=e<0?"-":"+";let t=Math.abs(Math.round(e/1e3));if(t===0)return"0s";const r=[];for(const[i,s]of[["d",86400],["h",3600],["m",60],["s",1]]){if(t>=s){r.push(`${Math.floor(t/s)}${i}`);t%=s}if(r.length===2)break}return n+r.join(" ")}function describe(e){const n=[e.active?`**App clock: ${e.virtualIso}** (${e.mode}${e.rate!==1?`, ${e.rate}\xD7`:""}), ${duration(e.offsetMs)} from real time ${new Date(e.realNow).toISOString()}`:`**App clock: real time** (${e.virtualIso})`,`Time zone: ${e.timeZone} (the override never changes it)`,`Pending app timers: ${e.timers.timeouts} timeouts, ${e.timers.intervals} intervals`];if(e.lastJump){n.push(`Last change: ${duration(e.lastJump.byMs)}${e.lastJump.firedTimers?`, ran ${e.lastJump.firedTimers} due timer(s)`:""}`)}n.push(...describeTokens(e));n.push(`Settings: persist=${e.settings.persist} showChip=${e.settings.showChip} fireTimersOnJump=${e.settings.fireTimersOnJump}`);return n.join("\n")}function describeTokens(e){const n=e.tokens;if(!n)return[];if(!n.available)return["Sign-in tokens: unavailable (the app has no @buoy-gg/network)."];if(n.tokens.length===0)return["Sign-in tokens: none seen yet (they appear once the app sends a signed-in request)."];const t=["Sign-in tokens (read from captured requests; raw tokens are never shown):"];for(const i of n.tokens){const s=i.expiresAt!==void 0?i.expiresAt-e.virtualNow:void 0;const o=i.serverExpiresAt!==void 0?i.serverExpiresAt-e.realNow:void 0;const a=i.neverExpires?"never expires":s===void 0?"expiry unknown":s>0?`expires in ${duration(s).slice(1)} on the app's clock`:`expired ${duration(-s).slice(1)} ago on the app's clock`;const c=o!==void 0&&s!==void 0&&Math.abs(o-s)>2e3?o>0?`; the server accepts it for ${duration(o).slice(1)} more`:"; the server no longer accepts it":"";const u=[i.hint??i.formatLabel,i.expirySource?`expiry from ${i.expirySource}`:null,i.issuedBy?`issued by ${i.issuedBy}`:null,i.claims.sub?`sub ${i.claims.sub}`:null,`${i.uses} request(s)`,i.refreshes?`${i.refreshes} refresh(es)`:null,i.expiredSends?`SENT ${i.expiredSends}\xD7 AFTER EXPIRY`:null,i.rejected?`rejected ${i.rejected}\xD7`:null,i.looping?`REFRESH LOOP (${i.recentRefreshes} new tokens in 20s)`:null].filter(Boolean);t.push(`- [${i.id}] ${i.label} \u2192 ${i.host}: ${a}${c} (${u.join(", ")})`)}const r=n.check;if(r){const i=r.status==="refreshed"?`refreshed${r.kind==="401"&&r.forcedAt?" after the forced 401":""}${r.newIssuedBy?` via ${r.newIssuedBy}`:""}${r.newLifetimeMs?`; new token lasts ${duration(r.newLifetimeMs).slice(1)}`:""}`:r.status==="loop"?`REFRESH LOOP: ${r.newTokens} new tokens since the check started`:r.kind==="401"&&r.forcedAt===void 0?"waiting: the next request to that API will get a 401 (the app must send one)":`waiting for a new token (${duration(e.realNow-r.startedAt).slice(1)} so far)`;const s=r.staleAfterFailure?`; the app re-sent the old token ${r.staleAfterFailure}\xD7 after the 401`:"";t.push(`Refresh check (${r.kind==="401"?"forced 401":"jump to expiry"}): ${i}${s}`)}return t}function registerClockTools(e,n){e.registerTool("get_clock",{description:"Read the app's clock as the Clock tool (@buoy-gg/clock) sees it: the time the app reads now, whether it is overridden (running, frozen or sped up), how far it is from real time, and the pending app timers a jump ahead could run. Also lists the app's sign-in tokens seen in its traffic (JWT, PASETO, opaque tokens with an expiry from the login response, session cookies): time left on the app's clock and the server's, who issued them, refreshes, sends after expiry, refresh loops, and the result of a running refresh check. Check this before calling a date, countdown, expiry or sign-out a bug.",inputSchema:{deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(CLOCK_TOOL_ID,"getState",{},r);return text(describe(i))}catch(r){return fail2(errMsg2(r))}});e.registerTool("clock_action",{description:"Override the app's clock. set_time moves it to `time` (ISO 8601, 'YYYY-MM-DD HH:MM' in the device's zone, epoch ms, or relative like '+30d'), optionally frozen. shift jumps by `by` ('+1d', '-2h30m', '90s'); a forward shift also runs app setTimeout/setInterval callbacks that come due inside the jump, once each. freeze/resume stop and restart it, set_rate runs it faster (60 = a minute per second), reset returns to real time. To test token refresh: jump_to_token_expiry moves the app's clock to `leadMs` (default 10000) before a token expires, for apps that refresh before expiry; fail_next_request answers the next request to that token's API with a 401 once, for apps that refresh after a 401. Both start a refresh check; read get_clock after the app sends a request to see whether a new token arrived. stop_token_check ends it and withdraws an unfired 401. Moves Date.now(), new Date() and no-argument Intl formatting; performance.now(), animations, native timers, the time zone and the backend's clock stay real. Screens that already computed a time keep it until they re-read the clock or the app reloads; the override survives reload_app.",inputSchema:{action:import_zod16.z.enum(["set_time","shift","freeze","resume","set_rate","reset","settings","jump_to_token_expiry","fail_next_request","stop_token_check"]).describe("What to do."),time:import_zod16.z.union([import_zod16.z.string(),import_zod16.z.number()]).optional().describe("set_time (required) / freeze (optional): target time."),by:import_zod16.z.union([import_zod16.z.string(),import_zod16.z.number()]).optional().describe("shift (required): signed duration like '+1d', '-2h30m', '90s', or ms."),freeze:import_zod16.z.boolean().optional().describe("set_time: stop the clock at `time`. Default false."),fireTimers:import_zod16.z.boolean().optional().describe("shift: run app timers that come due inside a forward jump. Default on."),rate:import_zod16.z.number().optional().describe("set_rate (required): speed multiplier, 0.1-86400; 1 is normal."),persist:import_zod16.z.boolean().optional().describe("settings: keep the override across reloads."),showChip:import_zod16.z.boolean().optional().describe("settings: show the floating clock chip while overridden."),fireTimersOnJump:import_zod16.z.boolean().optional().describe("settings: default for shift's fireTimers."),token:import_zod16.z.string().optional().describe("jump_to_token_expiry / fail_next_request: token id from get_clock. Default: the most recently used token."),leadMs:import_zod16.z.number().optional().describe("jump_to_token_expiry: land this many ms before expiry. Default 10000."),status:import_zod16.z.number().optional().describe("fail_next_request: 401 (default) or 403."),times:import_zod16.z.number().optional().describe("fail_next_request: how many requests to fail, 1-10. Default 1."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=(o,a={})=>n.callAction(CLOCK_TOOL_ID,o,a,r);let s;switch(t.action){case"set_time":if(t.time===void 0)return fail2("set_time requires `time`.");s=await i("setTime",{time:t.time,freeze:t.freeze??false});break;case"shift":if(t.by===void 0)return fail2("shift requires `by`, e.g. '+1d'.");s=await i("shift",{by:t.by,...t.fireTimers!==void 0?{fireTimers:t.fireTimers}:{}});break;case"freeze":s=await i("freeze",t.time!==void 0?{time:t.time}:{});break;case"resume":s=await i("resume");break;case"set_rate":if(t.rate===void 0)return fail2("set_rate requires `rate`.");s=await i("setRate",{rate:t.rate});break;case"reset":s=await i("reset");break;case"settings":s=await i("updateSettings",{...t.persist!==void 0?{persist:t.persist}:{},...t.showChip!==void 0?{showChip:t.showChip}:{},...t.fireTimersOnJump!==void 0?{fireTimersOnJump:t.fireTimersOnJump}:{}});break;case"jump_to_token_expiry":s=await i("jumpToTokenExpiry",{...t.token?{token:t.token}:{},...t.leadMs!==void 0?{leadMs:t.leadMs}:{}});break;case"fail_next_request":s=await i("failNextRequest",{...t.token?{token:t.token}:{},...t.status!==void 0?{status:t.status}:{},...t.times!==void 0?{times:t.times}:{}});break;case"stop_token_check":s=await i("stopTokenCheck");break}return text(describe(s))}catch(r){return fail2(errMsg2(r))}})}var import_zod16,CLOCK_TOOL_ID;var init_clock=__esm({"src/tools/packs/clock.ts"(){"use strict";import_zod16=require("zod");init_packKit();CLOCK_TOOL_ID="clock"}});function describe2(e,n=12){const t=[];t.push(e.overriddenCount>0?`**${e.overriddenCount} permission(s) overridden** on ${e.platform}. The app sees the override; the OS state is unchanged.`:`**No overrides** on ${e.platform}: the app sees the real OS state.`);t.push(`Libraries found: ${e.libraries.length?e.libraries.join(", "):"none yet"}`);if(e.permissions.length===0){t.push("No permission APIs found yet. Rows appear for Expo modules in the app and for anything the app asks for.")}for(const i of e.permissions){const s=[i.override?`override **${i.override}**`:"not overridden",`system ${i.real??"unknown"}`,i.calls?`asked ${i.calls}\xD7`:"not asked yet",i.sources.length?`via ${i.sources.join(", ")}`:null,`can be: ${i.states.join(", ")}`].filter(Boolean);t.push(`- ${i.id} (${i.label}): ${s.join("; ")}`);if(i.warning)t.push(` \u26A0 ${i.warning}`)}const r=e.settings;t.push(`Settings: requestAnswer=${r.requestAnswer} notifyApp=${r.notifyApp} interceptSettings=${r.interceptSettings} enforce=${r.enforce} persist=${r.persist} showChip=${r.showChip}`);if(e.log.length){t.push("Recent calls (newest first):");for(const i of e.log.slice(0,n)){const s=new Date(i.at).toISOString().slice(11,19);const o=i.error??i.returned??"no answer";t.push(`- ${s} ${i.source}.${i.method} \u2192 ${o}${i.overridden?" (override)":""}${i.real&&i.real!==i.returned?`, system ${i.real}`:""}${i.answer?`, answered ${i.answer}`:""}`)}}if(e.host.bundleId){t.push(`Host: ${e.host.isSimulator?"simulator/emulator":e.host.isSimulator===false?"physical device":"unknown device"} "${e.host.deviceName??"?"}", app ${e.host.bundleId}`)}return t.join("\n")}async function run(e,n){const{stdout:t}=await execFileAsync8(e,n,{timeout:2e4});return t}async function findSimulator(e,n){if(n)return n;const t=JSON.parse(await run("xcrun",["simctl","list","devices","booted","-j"]));const r=Object.values(t.devices).flat();const i=r.filter(s=>s.name===e.host.deviceName);if(i.length===1)return i[0].udid;if(!e.host.deviceName&&r.length===1)return r[0].udid;throw new Error(i.length===0?`No booted simulator is named "${e.host.deviceName??"?"}". Pass \`udid\`.`:`${i.length} booted simulators are named "${e.host.deviceName}". Pass \`udid\`.`)}async function findAdbSerial(e){if(e)return e;const n=await run("adb",["devices"]);const t=n.split("\n").slice(1).map(r=>r.trim().split(/\s+/)).filter(r=>r[1]==="device").map(r=>r[0]);if(t.length===1)return t[0];throw new Error(t.length===0?"No Android device is connected to adb.":"Several Android devices are connected. Pass `serial`.")}async function systemPermission(e,n,t,r){const i=e.host.bundleId;if(!i)throw new Error("The app did not report its bundle id (needs expo-application).");if(e.platform==="ios"){if(e.host.isSimulator===false)throw new Error("A physical iPhone can't be changed from the host. Use the app's Settings page.");const c=t==="all"?"all":SIMCTL_SERVICE[t];if(!c){throw new Error(`simctl has no privacy service for ${t}. Override it in the app instead (permission_action set).`)}const u=await findSimulator(e,r.udid);await run("xcrun",["simctl","privacy",u,n,c,i]);return`simctl privacy ${n} ${c} for ${i} on ${u}.${n==="grant"?"":" iOS ends the app's process when a permission is revoked or reset; relaunch it."}`}const s=await findAdbSerial(r.serial);const o=t==="all"?Object.values(ANDROID_PERMISSIONS).flat():ANDROID_PERMISSIONS[t];if(!o)throw new Error(`No Android permission is known for ${t}.`);const a=[];for(const c of o){const u=`android.permission.${c}`;try{if(n==="grant")await run("adb",["-s",s,"shell","pm","grant",i,u]);else{await run("adb",["-s",s,"shell","pm","revoke",i,u]);if(n==="reset"){await run("adb",["-s",s,"shell","pm","clear-permission-flags",i,u,"user-set","user-fixed"])}}a.push(c)}catch{}}if(a.length===0)throw new Error(`None of ${o.join(", ")} could be changed. Is it declared in the app's manifest?`);return`adb ${n} ${a.join(", ")} for ${i} on ${s}.${n==="grant"?"":" Android restarts the app's process when a permission is revoked."}`}function registerPermissionsTools(e,n){e.registerTool("get_permissions",{description:"Read the app's permissions as the Permissions tool (@buoy-gg/permissions) sees them: each permission the app can reach (location, camera, notifications, photos\u2026), what the OS says, any override, which libraries asked (Expo modules, PermissionsAndroid, react-native-permissions), the states this platform allows, and the recent permission calls with what each one returned. Check this before calling a permission screen, prompt or Settings flow a bug.",inputSchema:{logLimit:import_zod17.z.number().optional().describe("How many recent calls to list. Default 12."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(PERMISSIONS_TOOL_ID,"getState",{},r);return text(describe2(i,t.logLimit??12))}catch(r){return fail2(errMsg2(r))}});e.registerTool("permission_action",{description:"Override what the app sees when it asks for a permission, without changing the OS. set makes `permission` read as `state` (undetermined = not asked, granted, limited = approximate location / selected photos or contacts / provisional notifications, denied, blocked = Android 'don't ask again', restricted = iOS parental controls); iOS has no blocked (a refusal is final, so denied reads as blocked) and Android has no restricted. clear returns one permission to the OS answer, reset clears all. While overridden, the real system prompt never shows: a request from undetermined (or Android denied) is answered by `answer` (ask = Buoy shows a prompt on the device and waits for a tap; allow, limited or deny answer at once) and moves the state the way the OS would. Linking.openSettings and app-settings: open Buoy's stand-in for Settings. By default a change sends the app background \u2192 active, like a return from Settings, so screens that re-check on foreground update; permission hooks that read only on mount update on their next read. With enforce on (default), calls that need access (current position, launch camera, media library reads) fail with the native module's error while refused. request_real shows the real system prompt once so the OS grants what the override pretends. The override survives reload_app.",inputSchema:{action:import_zod17.z.enum(["set","clear","reset","answer","settings","request_real","return_from_settings","clear_log"]).describe("What to do."),permission:import_zod17.z.string().optional().describe(`set / clear / request_real (required): ${PERMISSION_IDS.join(", ")}, or android:<android.permission.NAME>.`),state:import_zod17.z.enum(["undetermined","granted","limited","denied","blocked","restricted"]).optional().describe("set (required): the state the app sees."),answer:import_zod17.z.enum(["ask","allow","limited","deny"]).optional().describe("answer (required): how a request from 'not asked' is answered while overridden."),notifyApp:import_zod17.z.boolean().optional().describe("settings: send background \u2192 active after each change. Default on."),interceptSettings:import_zod17.z.boolean().optional().describe("settings: stand in for Settings while overridden. Default on."),enforce:import_zod17.z.boolean().optional().describe("settings: fail calls that need a refused permission. Default on."),persist:import_zod17.z.boolean().optional().describe("settings: keep overrides across reloads. Default on."),showChip:import_zod17.z.boolean().optional().describe("settings: show the floating chip while overridden. Default on."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=(o,a={})=>n.callAction(PERMISSIONS_TOOL_ID,o,a,r);let s;switch(t.action){case"set":if(!t.permission||!t.state)return fail2("set requires `permission` and `state`.");s=await i("setOverride",{permission:t.permission,state:t.state});break;case"clear":if(!t.permission)return fail2("clear requires `permission`.");s=await i("clearOverride",{permission:t.permission});break;case"reset":s=await i("resetAll");break;case"answer":if(!t.answer)return fail2("answer requires `answer`: ask, allow, limited or deny.");s=await i("updateSettings",{requestAnswer:t.answer});break;case"settings":s=await i("updateSettings",{...t.notifyApp!==void 0?{notifyApp:t.notifyApp}:{},...t.interceptSettings!==void 0?{interceptSettings:t.interceptSettings}:{},...t.enforce!==void 0?{enforce:t.enforce}:{},...t.persist!==void 0?{persist:t.persist}:{},...t.showChip!==void 0?{showChip:t.showChip}:{}});break;case"request_real":if(!t.permission)return fail2("request_real requires `permission`.");s=await i("requestReal",{permission:t.permission});break;case"return_from_settings":s=await i("simulateReturnFromSettings");break;case"clear_log":s=await i("clearLog");break}return text(describe2(s))}catch(r){return fail2(errMsg2(r))}});e.registerTool("system_permission",{description:"Change the REAL OS permission for the connected app from this machine, for what an in-app override can't fake (native code that checks the OS itself, like reading a position or opening the camera). iOS Simulator uses `xcrun simctl privacy` (grant, revoke, reset; reset returns to 'not asked' so the real prompt shows again). There is no simctl service for notifications or tracking. Android uses `adb shell pm grant/revoke`; reset also clears 'don't ask again'. Revoking or resetting ends the app's process on both platforms, so relaunch it afterwards. Physical iPhones can't be changed this way.",inputSchema:{action:import_zod17.z.enum(["grant","revoke","reset"]).describe("grant, revoke, or reset to not asked."),permission:import_zod17.z.string().describe(`${PERMISSION_IDS.join(", ")}, or all.`),udid:import_zod17.z.string().optional().describe("iOS: the simulator udid, when its name is ambiguous."),serial:import_zod17.z.string().optional().describe("Android: the adb serial, when several devices are connected."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(PERMISSIONS_TOOL_ID,"getState",{},r);const s=await systemPermission(i,t.action,t.permission,{udid:t.udid,serial:t.serial});return text(s)}catch(r){return fail2(errMsg2(r))}})}var import_node_child_process9,import_node_util8,import_zod17,PERMISSIONS_TOOL_ID,execFileAsync8,PERMISSION_IDS,SIMCTL_SERVICE,ANDROID_PERMISSIONS;var init_permissions=__esm({"src/tools/packs/permissions.ts"(){"use strict";import_node_child_process9=require("child_process");import_node_util8=require("util");import_zod17=require("zod");init_packKit();PERMISSIONS_TOOL_ID="permissions";execFileAsync8=(0,import_node_util8.promisify)(import_node_child_process9.execFile);PERMISSION_IDS=["location","locationBackground","camera","microphone","notifications","photos","contacts","calendar","reminders","tracking","motion","bluetooth"];SIMCTL_SERVICE={location:"location",locationBackground:"location-always",camera:"camera",microphone:"microphone",photos:"photos",contacts:"contacts",calendar:"calendar",reminders:"reminders",motion:"motion"};ANDROID_PERMISSIONS={location:["ACCESS_FINE_LOCATION","ACCESS_COARSE_LOCATION"],locationBackground:["ACCESS_BACKGROUND_LOCATION"],camera:["CAMERA"],microphone:["RECORD_AUDIO"],notifications:["POST_NOTIFICATIONS"],photos:["READ_MEDIA_IMAGES","READ_MEDIA_VIDEO"],contacts:["READ_CONTACTS","WRITE_CONTACTS"],calendar:["READ_CALENDAR","WRITE_CALENDAR"],motion:["ACTIVITY_RECOGNITION"],bluetooth:["BLUETOOTH_SCAN","BLUETOOTH_CONNECT"]}}});function listeners(e){if(e==null)return"can't count";return e===0?"none":String(e)}function describe3(e){const n=[];if(e.away){const r=Math.round((Date.now()-e.away.startedAt)/1e3);n.push(`**Simulated: ${e.away.kind==="background"?"in the background":"interrupted (inactive)"}** for ${r}s`+(e.away.returnAt?`, returns in ${Math.max(0,Math.round((e.away.returnAt-Date.now())/1e3))}s`:", until return")+`. Real OS state: ${e.realAppState}.`)}else{n.push(`App state: active (real OS state: ${e.realAppState}).`)}if(e.power){n.push(`Simulated battery: ${Math.round(e.power.level*100)}%, ${e.power.state}${e.power.lowPowerMode?", low power mode":""} (reached ${e.power.reached.join(", ")})`+(e.power.realGetters.length?`; still real: ${e.power.realGetters.join(", ")}`:""))}if(e.scheme)n.push(`Simulated color scheme: ${e.scheme.scheme} (${e.scheme.mode}).`);n.push(`App listeners: app state ${listeners(e.listeners.appState)}, memory warning ${listeners(e.listeners.memoryWarning)}, deep link ${listeners(e.listeners.deepLink)}`+(e.platform==="android"?`, window focus ${listeners(e.listeners.focus)}`:"")+(e.batteryLibraries.length?`, battery ${listeners(e.listeners.battery)} (${e.batteryLibraries.join(", ")})`:", battery: no battery library installed")+".");if(e.report){const r=e.report;n.push(`
|
|
190
|
-
**Report: ${r.label}**${r.collectingUntil!=null?" (still collecting)":""}`);if(r.unavailable)n.push(r.unavailable);if(r.finding)n.push(`Finding: ${r.finding}`);if(r.note)n.push(`Note: ${r.note}`);const i=Object.entries(r.counts).map(([s,o])=>`${o} ${s}`).join(", ");if(!r.unavailable)n.push(`Counts: ${i||"nothing happened"}`);for(const s of r.events.slice(0,25)){n.push(`- +${(s.at/1e3).toFixed(1)}s ${s.whileAway?"[away] ":""}${s.source}: ${s.title}${s.subtitle?` (${s.subtitle})`:""}${s.status==="error"?" ERROR":""}`)}}if(e.relaunch){const r=e.relaunch;n.push(r.restored==null&&r.after==null?`
|
|
191
|
-
Relaunch: checking where the app landed (was on ${r.before??"unknown"}).`:`
|
|
192
|
-
Relaunch: ${r.restored?`restored ${r.after}`:`landed on ${r.after??"unknown"}, was on ${r.before??"unknown"}`}${r.tookMs!=null?` (${(r.tookMs/1e3).toFixed(1)}s)`:""}.`)}if(typeof e.handled==="boolean")n.push(`Back press handled by the app: ${e.handled}.`);if(e.log.length)n.push(`
|
|
193
|
-
Recent: ${e.log.slice(0,5).map(r=>r.text).join(" \xB7 ")}`);const t=e.recipes.filter(r=>!r.unavailable).map(r=>r.id);n.push(`Recipes: ${t.join(", ")}`);return n.join("\n")}async function simctl2(e){const{stdout:n}=await execFileAsync9("xcrun",["simctl",...e],{timeout:2e4});return n}async function hostColorScheme(e,n){if(e.platform==="ios"){await simctl2(["ui",e.udid,"appearance",n]);return`Simulator appearance set to ${n} (affects every app on this simulator).`}if(e.platform==="ios-device")throw new Error("A physical iPhone's appearance can't be changed from the computer. Leave `real` off to simulate it.");await adb(e.serial,["shell","cmd","uimode","night",n==="dark"?"yes":"no"]);return`Android night mode set to ${n==="dark"?"on":"off"} (affects every app on this device).`}function registerLifecycleTools(e,n){e.registerTool("get_lifecycle",{description:"Read the Lifecycle tool (@buoy-gg/lifecycle): the app's simulated and real app state, how many of the APP's own listeners each lifecycle signal has (app state, memory warning, deep link, battery), the report of what the app did during and after the last simulation (requests, query refetches, route changes, store writes, with a finding such as requests made while in the background), and the relaunch check (did the app reopen where it was). Read it after lifecycle_action; reports keep collecting for a few seconds after the app returns.",inputSchema:{deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(LIFECYCLE_TOOL_ID,"getState",{},r);return text(describe3(i))}catch(r){return fail2(errMsg2(r))}});e.registerTool("lifecycle_action",{description:"Put the app through lifecycle events and interruptions. background sends it to the background (iOS: inactive then background; Android: blur then background), interrupt makes it inactive like the app switcher or a call, return brings it back; `duration` ('5s', '31m') returns by itself, and skipWait with a duration moves the app clock instead of waiting (needs @buoy-gg/clock), which tests session timeouts in one call. memory_warning, open_url (`url`), press_back (Android; never exits the app, reports whether a screen handled it), color_scheme (`scheme`), battery (`level` 0-1, `lowPowerMode`, `state`; needs expo-battery, react-native-device-info or @capacitor/device), reset_battery, relaunch (restarts the app's JS, then checks where it landed), recipe (`id`, see get_lifecycle), clear_report, reset (end every simulation). Simulations reach the app's JS listeners only: nothing is suspended and the next real OS event wins. With `real: true` (iOS Simulator or Android), background/return/relaunch/color_scheme/open_url cause the real OS event instead (relaunch then kills the process, a real cold start). App control, iOS Simulator or Android, no lifecycle package needed: quit closes the app, launch opens it (works while it is closed), reinstall (`appPath`: a simulator .app or an .apk) wipes its data like a new user and keeps Buoy's sign-in on iOS, boot_simulator (`simulator`) starts an iOS Simulator. Read get_lifecycle afterwards for the report.",inputSchema:{action:import_zod18.z.enum(["background","interrupt","return","memory_warning","open_url","press_back","color_scheme","battery","reset_battery","relaunch","recipe","clear_report","reset","settings","quit","launch","reinstall","boot_simulator"]).describe("What to do."),duration:import_zod18.z.union([import_zod18.z.string(),import_zod18.z.number()]).optional().describe("background / interrupt: return by itself after this long ('5s', '5m', ms). Omit to stay until return."),skipWait:import_zod18.z.boolean().optional().describe("background / interrupt: move the app clock forward by `duration` and return at once. Needs @buoy-gg/clock."),url:import_zod18.z.string().optional().describe("open_url (required): the link, with its scheme."),scheme:import_zod18.z.enum(["light","dark","system"]).optional().describe("color_scheme (required). 'system' ends the simulated scheme."),mode:import_zod18.z.enum(["js","native"]).optional().describe("color_scheme: 'js' emits the change to JS listeners (default); 'native' overrides the app's native appearance too."),level:import_zod18.z.number().optional().describe("battery: 0 to 1 (or a percentage above 1)."),lowPowerMode:import_zod18.z.boolean().optional().describe("battery: low power mode on or off."),state:import_zod18.z.enum(["unplugged","charging","full","unknown"]).optional().describe("battery: charging state."),id:import_zod18.z.string().optional().describe("recipe (required): a recipe id from get_lifecycle, e.g. 'away-31m'."),showChip:import_zod18.z.boolean().optional().describe("settings: show the floating status chip while simulating."),reportWindow:import_zod18.z.union([import_zod18.z.string(),import_zod18.z.number()]).optional().describe("settings: how long reports keep collecting after the app returns ('5s')."),real:import_zod18.z.boolean().optional().describe("Cause the real OS event on the iOS Simulator or Android device (background, return, relaunch, color_scheme, open_url)."),appPath:import_zod18.z.string().optional().describe("reinstall (required): the built app, a simulator .app folder or an Android .apk."),keepBuoySignIn:import_zod18.z.boolean().optional().describe("reinstall, iOS: keep Buoy's sign-in and device id. Default true."),simulator:import_zod18.z.string().optional().describe('boot_simulator (required): simulator name or udid, e.g. "iPhone 17 Pro".'),udid:import_zod18.z.string().optional().describe("The simulator udid, when it can't be found by itself."),serial:import_zod18.z.string().optional().describe("Android: the adb serial, when several devices are connected."),deviceId:deviceIdInput}},async t=>{try{if(t.action==="boot_simulator"){if(!t.simulator&&!t.udid)return fail2('boot_simulator requires `simulator` (a name like "iPhone 17 Pro" or a udid).');if(!n.listDevices().some(a=>a.isPro))return fail2("boot_simulator needs a Buoy Pro app seen in this session. Open the app once first.");return text(await bootSimulator(t.simulator??t.udid))}const r=["quit","launch","reinstall"];if(t.real||r.includes(t.action)){const a=t.action==="launch"||t.action==="quit";const c=["quit","relaunch","reinstall"].includes(t.action);const{id:u,host:l,online:d}=await hostTarget(n,t.deviceId,{udid:t.udid,serial:t.serial},{allowOffline:a,changesApp:c});const h=(v,y={})=>n.callAction(LIFECYCLE_TOOL_ID,v,y,u);const p=d?await h("getState").catch(()=>null):null;const m=p?.host?.bundleId;if(m&&l.platform==="ios"&&!l.bundleId)l.bundleId=m;let g;switch(t.action){case"quit":g=`${await hostQuit(l)} Buoy disconnects until it is launched again (lifecycle_action launch).`;break;case"launch":g=`${await hostLaunch(l)} A dev build loads its bundle first; give it a few seconds to connect.`;break;case"reinstall":if(!t.appPath)return fail2("reinstall requires `appPath`: the built simulator .app folder or Android .apk.");g=await hostReinstall(l,t.appPath,t.keepBuoySignIn??true);break;case"background":g=`${await hostBackground(l)} Use return with real: true.`;break;case"return":await hostLaunch(l);g="Brought back to the foreground for real.";break;case"relaunch":if(d)await h("prepareRelaunch").catch(()=>void 0);await hostQuit(l);await hostLaunch(l);g="Killed the process and launched it again (a real cold start). Read get_lifecycle in a few seconds for where it landed; a dev build reloads its bundle first.";break;case"color_scheme":if(!t.scheme)return fail2("color_scheme requires `scheme`.");if(t.scheme==="system")return fail2("With real: true, pass light or dark; the device has no system value to go back to.");g=await hostColorScheme(l,t.scheme);break;case"open_url":if(!t.url)return fail2("open_url requires `url`.");g=await hostOpenUrl(l,t.url);break;default:return fail2(`${t.action} has no real (host-side) version. iOS has no command-line memory warning; leave \`real\` off to simulate it.`)}await sleep(1200);const w=` (${hostLabel(l)})`;const f=["return","color_scheme","open_url"].includes(t.action);const b=f&&p?await n.callAction(LIFECYCLE_TOOL_ID,"getState",{},u,{timeoutMs:5e3}).catch(()=>null):null;return text(`${g}${w}${b?`
|
|
194
|
-
|
|
195
|
-
${describe3(b)}`:""}`)}const i=n.requireProDevice(t.deviceId);const s=(a,c={})=>n.callAction(LIFECYCLE_TOOL_ID,a,c,i);let o;switch(t.action){case"background":o=await s("background",{duration:t.duration,skipWait:t.skipWait});break;case"interrupt":o=await s("interrupt",{duration:t.duration,skipWait:t.skipWait});break;case"return":o=await s("returnToApp");break;case"memory_warning":o=await s("memoryWarning");break;case"open_url":if(!t.url)return fail2("open_url requires `url`.");o=await s("openUrl",{url:t.url});break;case"press_back":o=await s("pressBack");break;case"color_scheme":if(!t.scheme)return fail2("color_scheme requires `scheme`.");o=await s("setColorScheme",{scheme:t.scheme,mode:t.mode??"js"});break;case"battery":o=await s("setPower",{...t.level!==void 0?{level:t.level}:{},...t.lowPowerMode!==void 0?{lowPowerMode:t.lowPowerMode}:{},...t.state?{state:t.state}:{}});break;case"reset_battery":o=await s("resetPower");break;case"relaunch":o=await s("relaunch");return text(`Relaunching: the app's JS restarts now. Read get_lifecycle in a few seconds for where it landed.
|
|
196
|
-
|
|
197
|
-
${describe3(o)}`);case"recipe":if(!t.id)return fail2("recipe requires `id`; get_lifecycle lists them.");o=await s("runRecipe",{id:t.id});break;case"clear_report":o=await s("clearReport");break;case"reset":o=await s("reset");break;case"settings":o=await s("updateSettings",{...t.showChip!==void 0?{showChip:t.showChip}:{},...t.reportWindow!==void 0?{reportWindow:t.reportWindow}:{}});break;default:return fail2(`Unknown action ${t.action}.`)}return text(describe3(o))}catch(r){return fail2(errMsg2(r))}})}var import_node_child_process10,import_node_util9,import_zod18,LIFECYCLE_TOOL_ID,execFileAsync9,sleep;var init_lifecycle=__esm({"src/tools/packs/lifecycle.ts"(){"use strict";import_node_child_process10=require("child_process");import_node_util9=require("util");import_zod18=require("zod");init_packKit();init_hostDevice();init_adb();init_hostKit();LIFECYCLE_TOOL_ID="lifecycle";execFileAsync9=(0,import_node_util9.promisify)(import_node_child_process10.execFile);sleep=e=>new Promise(n=>setTimeout(n,e))}});function meters(e){if(e==null||!Number.isFinite(e))return"?";return e<1e3?`${Math.round(e)} m`:`${(e/1e3).toFixed(e<1e4?1:0)} km`}function coord(e){return`${e.latitude.toFixed(5)}, ${e.longitude.toFixed(5)}`}function describe4(e){const n=e.override;const t=[];if(!e.active){t.push("**Location: real** (no override; the app gets the device's own location)")}else{const s=e.current.fix;const o=s?coord(s):`no fix (${e.current.reason})`;if(n.mode==="route"&&n.route&&e.progress){t.push(`**Location: route "${n.route.name??n.route.id??"custom"}"** ${n.playing?"moving":e.progress.finished?"arrived":"paused"} at ${(n.route.speed*3.6).toFixed(1)} km/h, ${meters(e.progress.along)} of ${meters(e.progress.length)}${n.route.loop?" (loops)":""} \u2192 ${o}`)}else if(n.mode==="fixed"){t.push(`**Location: pinned** ${n.place.label?`"${n.place.label}" `:""}\u2192 ${o}`)}else{t.push(`**Location: real position**, with overrides below`)}if(s){t.push(`Reported: \xB1${meters(s.accuracy)}${s.heading!=null?`, heading ${Math.round(s.heading)}\xB0`:""}${s.speed!=null?`, ${s.speed.toFixed(1)} m/s`:""}${n.jitter?`, drifting up to ${meters(n.jitter)}`:""}`)}if(!n.signal)t.push("GPS signal: OFF (updates stop, requests fail)");if(!n.services)t.push("Location services: OFF (the app is told they are disabled)")}if(e.permission){const s=e.permission;t.push(s.status==="granted"?`Permission: granted (${s.background?"always":"while in use"}, ${s.precision==="reduced"?"approximate":"precise"})`:`Permission: ${s.status.toUpperCase()} (the app's location requests fail)`)}if(e.current.precision==="reduced")t.push("Precise location is OFF in the permission: positions snap to ~3 km.");t.push(`Libraries overridden: ${e.libraries.length?e.libraries.join(", "):"none found in this app"}`);const r=e.watches.filter(s=>s.kind==="position");t.push(`Live watches: ${r.length?r.map(s=>`${s.library}#${s.id} (${s.updates} updates)`).join(", "):"none"}`);for(const s of e.tasks){if(s.kind==="geofencing"){t.push(`Geofencing task "${s.name}" (${s.intercepted?"simulated":"native"}, ${s.runs} runs):`);for(const o of s.regions){t.push(`- ${o.identifier}${o.label?` (${o.label})`:""}: ${o.state}, radius ${meters(o.radius)}${o.distance!=null?`, ${meters(o.distance)} from center`:""} (${coord(o)})`)}}else{t.push(`Background location task "${s.name}" (${s.intercepted?"simulated":"native"}, ${s.runs} runs)`)}}const i=e.log.slice(-10);if(i.length){t.push("Recent:");for(const s of i)t.push(`- [${s.kind}] ${s.text}${s.detail?` (${s.detail})`:""}`)}if(e.places.length)t.push(`App places: ${e.places.map(s=>s.label??coord(s)).join(", ")}`);if(e.routes.length)t.push(`App routes: ${e.routes.map(s=>s.id??s.name).join(", ")}`);t.push(`Presets: ${e.presets.map(s=>s.id).join(", ")}`);return t.join("\n")}async function bootedSimulators(){const{stdout:e}=await execFileAsync10("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const n=JSON.parse(e);return Object.values(n.devices).flat().filter(t=>t.state==="Booted").map(({udid:t,name:r})=>({udid:t,name:r}))}async function resolveSimulator(e){if(process.platform!=="darwin")throw new Error("sim_location needs macOS with Xcode's iOS Simulator.");const n=await bootedSimulators();if(e){if(!n.some(t=>t.udid===e))throw new Error(`Simulator ${e} is not booted.`);return e}if(n.length===1)return n[0].udid;if(n.length===0)throw new Error("No iOS Simulator is booted.");throw new Error(`${n.length} simulators are booted; pass \`udid\`: ${n.map(t=>`${t.name} (${t.udid})`).join(", ")}`)}function registerLocationTools(e,n){e.registerTool("get_location",{description:"Read where the app thinks it is, as the Location tool (@buoy-gg/location) sees it: real or overridden (pinned place, route with progress and speed), the position the app gets right now, GPS signal and location-services switches, which location libraries are overridden, the app's live location watches, its geofencing regions with inside/outside state and distance, background location tasks, and recent location events (requests, geofence enters and exits, errors). Check this before calling a distance, nearby list, geofence or location permission flow a bug.",inputSchema:{deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(LOCATION_TOOL_ID,"getState",{},r);return text(describe4(i))}catch(r){return fail2(errMsg2(r))}});e.registerTool("location_action",{description:"Override where the app thinks it is. set_location pins it to `latitude`+`longitude`, a `query` ('lat, lon' or a Google/Apple Maps link) or a `place` name from get_location. start_route moves it along `points` ([{latitude, longitude}, ...]), a `route` (a preset: walk, run, drive, highway, tunnel, loop; or an app route id), or in a straight line `to` a place, at `speed` m/s; heading and speed follow the route. pause_route / resume_route / seek_route (`meters` or `fraction`) / set_speed control it, and stop_route ends it and stays where it got to. enter_region / exit_region move just inside or outside a monitored geofence `identifier`, which runs the app's geofencing task. conditions sets the signal quality in one step: `conditions` good (\xB15 m), weak (\xB165 m, drifting up to 50 m), no-signal or off. signal (on=false) stops updates and fails requests; services (on=false) reports location services disabled. tune sets `accuracy` and `jitter` (drift) in meters. use_real returns to the real position but keeps signal/services switches; reset ends every override. Works for expo-location (including background tasks and geofencing), @react-native-community/geolocation and react-native-geolocation-service. Permission comes from the device or the Permissions tool: a denied permission still fails. Native maps' own blue dot follows the device's real location; use sim_location for that. The override survives reload_app.",inputSchema:{action:import_zod19.z.enum(["set_location","start_route","pause_route","resume_route","stop_route","seek_route","set_speed","enter_region","exit_region","conditions","signal","services","tune","use_real","reset","settings","clear_log"]).describe("What to do."),latitude:import_zod19.z.number().optional().describe("set_location: latitude, -90 to 90."),longitude:import_zod19.z.number().optional().describe("set_location: longitude, -180 to 180."),label:import_zod19.z.string().optional().describe("set_location: a name to show for the place."),query:import_zod19.z.string().optional().describe("set_location: 'lat, lon' text or a Google/Apple Maps link."),place:import_zod19.z.string().optional().describe("set_location: a place name from get_location (app places and built-ins)."),points:import_zod19.z.array(import_zod19.z.object({latitude:import_zod19.z.number(),longitude:import_zod19.z.number()})).optional().describe("start_route: two or more points to travel through."),route:import_zod19.z.string().optional().describe("start_route: a preset id (walk, run, drive, highway, tunnel, loop) or an app route id."),to:import_zod19.z.string().optional().describe("start_route: travel in a straight line to this place name or 'lat, lon'."),speed:import_zod19.z.number().optional().describe("start_route / set_speed: meters per second (1.4 walk, 13.4 city, 30 highway)."),heading:import_zod19.z.number().optional().describe("start_route with a preset: direction to head, degrees from north. tune: heading reported while pinned."),loop:import_zod19.z.boolean().optional().describe("start_route with points: start over after the last point."),meters:import_zod19.z.number().optional().describe("seek_route: meters from the route's start."),fraction:import_zod19.z.number().optional().describe("seek_route: 0 to 1 along the route."),identifier:import_zod19.z.string().optional().describe("enter_region / exit_region (required): the region's identifier from get_location."),task:import_zod19.z.string().optional().describe("enter_region / exit_region: the geofencing task name, when two tasks share an identifier."),conditions:import_zod19.z.enum(["good","weak","no-signal","off"]).optional().describe("conditions (required): good, weak, no-signal or off."),on:import_zod19.z.boolean().optional().describe("signal / services (required): true = working, false = off."),accuracy:import_zod19.z.number().optional().describe("tune: reported accuracy radius in meters."),jitter:import_zod19.z.number().optional().describe("tune: GPS drift in meters (0 = none)."),interval:import_zod19.z.number().optional().describe("tune: ms between updates to live watches (default 1000)."),persist:import_zod19.z.boolean().optional().describe("settings: keep the override across reloads."),showChip:import_zod19.z.boolean().optional().describe("settings: show the floating location chip while overridden."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=(a,c={})=>n.callAction(LOCATION_TOOL_ID,a,c,r);const s=(...a)=>{const c={};for(const u of a)if(t[u]!==void 0)c[u]=t[u];return c};let o;switch(t.action){case"set_location":o=await i("setLocation",s("latitude","longitude","label","query","place"));break;case"start_route":o=await i("startRoute",s("points","route","to","speed","heading","loop"));break;case"pause_route":o=await i("pauseRoute");break;case"resume_route":o=await i("resumeRoute");break;case"stop_route":o=await i("stopRoute");break;case"seek_route":o=await i("seekRoute",s("meters","fraction"));break;case"set_speed":if(t.speed===void 0)return fail2("set_speed requires `speed` in m/s.");o=await i("setSpeed",{speed:t.speed});break;case"enter_region":case"exit_region":if(!t.identifier)return fail2(`${t.action} requires \`identifier\`; get_location lists the regions.`);o=await i(t.action==="enter_region"?"enterRegion":"exitRegion",s("identifier","task"));break;case"conditions":if(!t.conditions)return fail2("conditions requires `conditions`: good, weak, no-signal or off.");o=await i("setConditions",{conditions:t.conditions});break;case"signal":if(t.on===void 0)return fail2("signal requires `on`.");o=await i("setSignal",{on:t.on});break;case"services":if(t.on===void 0)return fail2("services requires `on`.");o=await i("setServices",{on:t.on});break;case"tune":o=await i("tune",s("accuracy","jitter","heading","interval"));break;case"use_real":o=await i("useRealLocation");break;case"reset":o=await i("reset");break;case"settings":o=await i("updateSettings",s("persist","showChip"));break;case"clear_log":o=await i("clearLog");break}return text(describe4(o))}catch(r){return fail2(errMsg2(r))}});e.registerTool("sim_location",{description:"Set the iOS Simulator's own location with `xcrun simctl location` (runs on this Mac, not in the app). Unlike location_action, this reaches native code: map views' blue dot (react-native-maps, expo-maps, Mapbox), native geofence monitoring, other SDKs. set pins `latitude`+`longitude`; route moves through `points` at `speed` m/s (updates every `interval` s); clear stops it. Needs no Buoy in the app. The in-app Location tool, when on, still decides what the app's JS location calls return. Pass `udid` when more than one simulator is booted.",inputSchema:{action:import_zod19.z.enum(["set","route","clear"]).describe("What to do."),latitude:import_zod19.z.number().optional().describe("set: latitude."),longitude:import_zod19.z.number().optional().describe("set: longitude."),points:import_zod19.z.array(import_zod19.z.object({latitude:import_zod19.z.number(),longitude:import_zod19.z.number()})).optional().describe("route: two or more waypoints."),speed:import_zod19.z.number().optional().describe("route: meters per second. Default 20."),interval:import_zod19.z.number().optional().describe("route: seconds between updates. Default 1."),udid:import_zod19.z.string().optional().describe("The simulator's UDID. Required when several are booted.")}},async t=>{try{const r=await resolveSimulator(t.udid);const i=(...s)=>execFileAsync10("xcrun",["simctl","location",r,...s],{timeout:15e3});switch(t.action){case"set":if(t.latitude===void 0||t.longitude===void 0)return fail2("set requires `latitude` and `longitude`.");await i("set",`${t.latitude},${t.longitude}`);return text(`Simulator ${r} location set to ${t.latitude}, ${t.longitude}.`);case"route":{const s=t.points??[];if(s.length<2)return fail2("route requires two or more `points`.");const o=[`--speed=${t.speed??20}`,`--interval=${t.interval??1}`];await i("start",...o,...s.map(a=>`${a.latitude},${a.longitude}`));return text(`Simulator ${r} is moving through ${s.length} points at ${t.speed??20} m/s.`)}case"clear":await i("clear");return text(`Simulator ${r} location cleared.`)}}catch(r){return fail2(errMsg2(r))}})}var import_node_child_process11,import_node_util10,import_zod19,execFileAsync10,LOCATION_TOOL_ID;var init_location=__esm({"src/tools/packs/location.ts"(){"use strict";import_node_child_process11=require("child_process");import_node_util10=require("util");import_zod19=require("zod");init_packKit();execFileAsync10=(0,import_node_util10.promisify)(import_node_child_process11.execFile);LOCATION_TOOL_ID="location"}});function varSpec(e){const n=e.options?.length?` one of ${e.options.join("|")}`:"";const t=e.default!==void 0?` (default ${String(e.default)})`:"";return`${e.key}: ${e.type}${n}${t}`}function summarize(e){const n=e.vars?.length?`
|
|
198
|
-
variables: ${e.vars.map(varSpec).join("; ")}`:"";const t=e.stepLines?.length?`
|
|
199
|
-
${e.stepLines.map(s=>` \xB7 ${s.label} [${s.durability}]`).join("\n")}`:"";const r=[`v${e.version}`,e.author,e.usage?.runs?`${e.usage.runs} run(s)`:null,e.authoredAgainst?`authored against ${e.authoredAgainst}`:null,e.unsavedToRepo?"unsaved to repo":null].filter(Boolean).join(" \xB7 ");const i=e.expectedOutcome?`
|
|
200
|
-
expected: ${e.expectedOutcome}`:"";return`- \`${e.id}\` **${e.name}** \u2014 ${r}${n}${i}${t}`}function renderSection(e,n,t){if(!n.length)return`**${e} (0):**
|
|
201
|
-
_none_`;if(!t.length){return`**${e} (${n.length}):**
|
|
202
|
-
${n.map(summarize).join("\n")}`}const r=[`**${e} (${n.length}):**`];for(const s of t){const o=n.filter(a=>(a.folder??"").toLowerCase()===s.toLowerCase());if(!o.length)continue;r.push(`_${s} (${o.length})_
|
|
203
|
-
${o.map(summarize).join("\n")}`)}const i=n.filter(s=>!s.folder);if(i.length){r.push(`_Ungrouped (${i.length})_
|
|
204
|
-
${i.map(summarize).join("\n")}`)}return r.join("\n")}function formatActive(e){const n=Object.entries(e.varValues).map(([t,r])=>`${t}=${String(r)}`).join(", ");return[`**${e.name}** (\`${e.scenarioId}\` v${e.version}) \u2014 active since ${new Date(e.runAt).toISOString()}`,n?`variables: ${n}`:null,`effects:
|
|
205
|
-
${e.effects.map(t=>` \xB7 ${t.label} [${t.kind}]`).join("\n")}`].filter(Boolean).join("\n")}function registerScenariosTools(e,n){e.registerTool("get_scenarios",{description:"List saved scenarios, configured steps, available durability labels and the reported active scenario. Inspect these settings when app behavior may be simulated. A scenario covers its supported steps, not every source of app or backend state.",inputSchema:{deviceId:import_zod20.z.string().optional().describe("Target device id (auto-selected if one is connected).")}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:i,stale:s}=await n.getSnapshot(SCENARIOS_TOOL_ID,r);const o=i??{};const a=o.code??[];const c=o.device??[];const u=o.drafts??[];const l=o.folders??[];const d=[];d.push(o.active?`\u26A0\uFE0F **SIMULATED \u2014 a scenario is active.** The app is showing bent state right now.
|
|
206
|
-
${formatActive(o.active)}`:"**No scenario active** \u2014 the app is showing real data.");if(l.length){d.push(`**Folders:** ${l.join(" \xB7 ")} \u2014 the flows this team organizes by. Scenarios below are grouped under them; file new ones into an existing folder with \`scenario_action setFolder\` rather than inventing a name.`)}d.push(renderSection("Shipped with this app",a,l));d.push(renderSection("Saved on this device",c,l));if(u.length){d.push(`**Drafts awaiting review on the device (${u.length}):** these are INERT and cannot run until a human accepts them on the device.
|
|
207
|
-
${u.map(summarize).join("\n")}`)}return text4(staleHeader(s)+d.join("\n\n"))}catch(r){return fail5(errMsg5(r))}});e.registerTool("scenario_action",{description:"Preview, run, deactivate, save, organize or delete a scenario. Preview unfamiliar scenarios before running; inspect applied steps, failures and unrestored effects afterward. Storage changes need suitable undo steps. Saved scenarios are drafts requiring acceptance on the device before running. Reuse existing folders when appropriate. A completed scenario does not guarantee a deterministic app or backend state; overrides and cache edits have different coverage and lifetimes.",inputSchema:{action:import_zod20.z.enum(["preview","run","deactivate","save","setFolder","delete"]).describe("What to do."),folder:import_zod20.z.string().optional().describe("Folder name for action 'setFolder' \u2014 omit to un-file the scenario. Matching an existing folder case-insensitively files it there rather than creating a second one."),id:import_zod20.z.string().optional().describe("Scenario id (required for preview/run/delete; from get_scenarios)."),params:import_zod20.z.record(import_zod20.z.union([import_zod20.z.string(),import_zod20.z.number(),import_zod20.z.boolean()])).optional().describe("Variable values for preview/run, e.g. {storeId:'220'}. Declared defaults fill in the rest."),scenario:import_zod20.z.object({id:import_zod20.z.string().describe("Stable kebab-case id."),name:import_zod20.z.string().describe("Human name; may contain {{variable}} placeholders."),description:import_zod20.z.string().optional(),expectedOutcome:import_zod20.z.string().optional().describe("What SHOULD happen once applied \u2014 this is how a tester tells a bug from expected behavior without asking a developer. Write it."),author:import_zod20.z.string().optional(),authoredAgainst:import_zod20.z.string().optional().describe("App version this was written against."),folder:import_zod20.z.string().optional().describe('The flow this belongs to \u2014 "Checkout", "Login". Reuse a folder from get_scenarios; a scenario nobody can find is a scenario nobody runs.'),tags:import_zod20.z.array(import_zod20.z.string()).optional(),vars:import_zod20.z.array(import_zod20.z.object({key:import_zod20.z.string(),label:import_zod20.z.string().optional(),type:import_zod20.z.enum(["string","number","boolean","enum"]),options:import_zod20.z.array(import_zod20.z.union([import_zod20.z.string(),import_zod20.z.number(),import_zod20.z.boolean()])).optional(),default:import_zod20.z.union([import_zod20.z.string(),import_zod20.z.number(),import_zod20.z.boolean()]).optional()})).optional().describe("Declare a variable for every value a tester might want to change (a store id, a user, a status code) instead of freezing it into the steps."),steps:import_zod20.z.array(import_zod20.z.object({id:import_zod20.z.string().optional(),tool:import_zod20.z.string().describe("Tool id: network | storage | impersonate | route-events | query | time-machine"),action:import_zod20.z.string().describe("Action name on that tool, e.g. upsertOverrideRule, async.setItem, startImpersonation, navigate."),params:import_zod20.z.unknown().optional(),label:import_zod20.z.string().optional()})).describe("Steps, in order."),undoSteps:import_zod20.z.array(import_zod20.z.object({id:import_zod20.z.string().optional(),tool:import_zod20.z.string(),action:import_zod20.z.string(),params:import_zod20.z.unknown().optional(),label:import_zod20.z.string().optional()})).optional().describe("How to reverse effects that have no automatic inverse. Supply these whenever a step writes or removes storage, or deactivation will honestly report the key as unrestored.")}).optional().describe("The scenario to save (action 'save')."),deviceId:import_zod20.z.string().optional().describe("Target device id (auto-selected if one is connected).")}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=(s,o)=>n.callAction(SCENARIOS_TOOL_ID,s,o,r);switch(t.action){case"preview":{if(!t.id)return fail5("preview requires `id` (from get_scenarios).");const s=await i("preview",{id:t.id,params:t.params??{}});const o=[`**Dry run \u2014 \`${t.id}\`** (nothing has been changed)`,`variables: ${Object.entries(s.values).map(([a,c])=>`${a}=${String(c)}`).join(", ")||"none"}`,`**Would do:**
|
|
208
|
-
${s.willDo.map(a=>` \xB7 ${a.label} [${a.durability}]`).join("\n")}`];if(s.expectedOutcome)o.push(`**Expected outcome:** ${s.expectedOutcome}`);if(s.conflict){o.push(`\u26A0\uFE0F **Conflict:** "${s.conflict.activeName}" is active and touches the same target(s): ${s.conflict.overlaps.join(", ")}. Running will SWAP \u2014 it deactivates first.`)}if(s.warnings?.length)o.push(`**Warnings:**
|
|
209
|
-
${s.warnings.map(a=>` \xB7 ${a}`).join("\n")}`);o.push(s.ok?"Pre-flight checks passed. Review the intended effects before running.":`\u274C **Cannot run:**
|
|
210
|
-
${s.errors.map(a=>` \xB7 ${a}`).join("\n")}`);return text4(o.join("\n\n"))}case"run":{if(!t.id)return fail5("run requires `id` (from get_scenarios).");const s=await i("run",{id:t.id,params:t.params??{}});if(s.preflightErrors?.length){return fail5(`Pre-flight refused to run \`${t.id}\` \u2014 nothing was changed:
|
|
211
|
-
${s.preflightErrors.map(a=>` \xB7 ${a}`).join("\n")}`)}const o=(s.steps??[]).map(a=>{const c=a.skipped?"\u2013":a.ok?"\u2713":"\u2717";const u=a.error?`
|
|
212
|
-
${a.error}`:"";return` ${c} ${a.label} (${a.ms}ms)${u}`}).join("\n");if(!s.ok){return fail5(`Run FAILED \u2014 it stopped at the failing step and nothing after it ran. The steps before it DID apply:
|
|
213
|
-
${o}
|
|
214
|
-
|
|
215
|
-
The device is now in a partial state. Deactivate to reverse what landed, or fix the step and run again.`)}return text4([`\u2705 **Scenario active \u2014 ${s.name??t.id}**`,o,`**Reported effects:**
|
|
216
|
-
${(s.effects??[]).map(a=>` \xB7 ${a.label} [${a.kind}]`).join("\n")}`,"The device shows a SIMULATED banner while this is active. Deactivate when done, and account for these effects when interpreting observations."].join("\n\n"))}case"deactivate":{const s=await i("deactivate",{});const o=s.report;const a=[`Removed ${o.removedRules} override rule(s)`,o.stoppedImpersonation?"Ended impersonation":null,o.undoStepsRan?`Ran ${o.undoStepsRan} undo step(s)`:null].filter(Boolean);const c=o.unrestoredState??[];const u=(o.unrestoredStorageKeys.length?`
|
|
217
|
-
|
|
218
|
-
\u26A0\uFE0F **NOT restored:** ${o.unrestoredStorageKeys.join(", ")} \u2014 a storage write has no automatic inverse. The app still holds these values.`:"")+(c.length?`
|
|
219
|
-
|
|
220
|
-
\u26A0\uFE0F **Stores NOT restored:** ${c.join(", ")} \u2014 a state write has no automatic inverse. These stores still hold what the scenario wrote.`:"");const l=o.errors.length?`
|
|
221
|
-
|
|
222
|
-
Errors: ${o.errors.join("; ")}`:"";return text4(`**Deactivated.**
|
|
223
|
-
${a.map(d=>` \xB7 ${d}`).join("\n")}${u}${l}`)}case"save":{if(!t.scenario)return fail5("save requires `scenario`.");const s=await i("save",{scenario:t.scenario});if(!s.ok){return fail5(`Save rejected:
|
|
224
|
-
${(s.errors??[s.error??"unknown error"]).map(o=>` \xB7 ${o}`).join("\n")}`)}return text4(`Saved \`${s.id}\` **as a draft**.
|
|
225
|
-
|
|
226
|
-
It is INERT and cannot run yet. Ask the user to open Scenarios on the device, review what it will do, and tap **Accept to library** \u2014 a scenario never becomes runnable on someone's device without them seeing it first.`)}case"setFolder":{if(!t.id)return fail5("setFolder requires `id` (from get_scenarios).");const s=await i("setFolder",{id:t.id,folder:t.folder});return text4(s.folder?`Filed \`${s.id}\` under **${s.folder}**.`:`Removed \`${s.id}\` from its folder \u2014 it now shows under Ungrouped.`)}case"delete":{if(!t.id)return fail5("delete requires `id`.");await i("delete",{id:t.id});return text4(`Deleted \`${t.id}\` from the device library.`)}}}catch(r){return fail5(errMsg5(r))}})}var import_zod20,SCENARIOS_TOOL_ID,text4,fail5,errMsg5;var init_scenarios=__esm({"src/tools/packs/scenarios.ts"(){"use strict";import_zod20=require("zod");init_packKit();SCENARIOS_TOOL_ID="scenarios";text4=e=>({content:[{type:"text",text:e}]});fail5=e=>({isError:true,content:[{type:"text",text:e}]});errMsg5=e=>e instanceof Error?e.message:String(e)}});function pickDescribeScreenMatch(e,n,t){if(t!=null){const s=e.find(o=>o.nativeTag===t);if(s)return s}const r=(n??"").trim().toLowerCase();if(!r)return void 0;let i;for(const s of e){const o=[s.testID,s.label,s.text,s.name].filter(Boolean).map(u=>u.toLowerCase());let a=0;for(const u of o){if(u===r)a=Math.max(a,100);else if(u.startsWith(r))a=Math.max(a,50);else if(u.includes(r))a=Math.max(a,25)}const c=s.tap;if(c&&c.x>=0&&c.x<=1&&c.y>=0&&c.y<=1)a+=20;else if(c)a-=40;if(a<=0)continue;if(!i||a>i.score)i={el:s,score:a}}return i?.el}function frameToRect(e,n){return{x:e.x*n.width,y:e.y*n.height,width:e.width*n.width,height:e.height*n.height}}var init_screenshotLocate=__esm({"src/tools/packs/screenshotLocate.ts"(){"use strict"}});function pixelmatch(e,n,t,r,i,s={}){const{threshold:o=.1,alpha:a=.1,aaColor:c=[255,255,0],diffColor:u=[255,0,0],checkerboard:l=true,includeAA:d,diffColorAlt:h,diffMask:p}=s;if(!isPixelData(e)||!isPixelData(n)||t&&!isPixelData(t))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(e.length!==n.length||t&&t.length!==e.length)throw new Error(`Image sizes do not match. Image 1 size: ${e.length}, image 2 size: ${n.length}`);if(e.length!==r*i*4)throw new Error(`Image data size does not match width/height. Expecting ${r*i*4}. Got ${e.length}`);const m=r*i;const g=new Uint32Array(e.buffer,e.byteOffset,m);const w=new Uint32Array(n.buffer,n.byteOffset,m);let f=true;for(let S=0;S<m;S++){if(g[S]!==w[S]){f=false;break}}if(f){if(t&&!p){for(let S=0,x=0;S<m;S++,x+=4)drawGrayPixel(e,x,a,t)}return 0}const b=35215*o*o;const[v,y,_]=c;const[$,k,T]=u;const[A,I,R]=h||u;let M=0;for(let S=0,x=0;S<m;S++,x+=4){const E=g[S]===w[S]?0:colorDelta(e,n,x,x,l);if(Math.abs(E)>b){const j=S%r;const P=S/r|0;const B=!d&&(antialiased(e,j,P,r,i,g,w,l)||antialiased(n,j,P,r,i,w,g,l));if(B){if(t&&!p)drawPixel(t,x,v,y,_)}else{if(t){if(E<0){drawPixel(t,x,A,I,R)}else{drawPixel(t,x,$,k,T)}}M++}}else if(t&&!p){drawGrayPixel(e,x,a,t)}}return M}function isPixelData(e){return ArrayBuffer.isView(e)&&e.BYTES_PER_ELEMENT===1}function antialiased(e,n,t,r,i,s,o,a){const c=Math.max(n-1,0);const u=Math.max(t-1,0);const l=Math.min(n+1,r-1);const d=Math.min(t+1,i-1);const h=(t*r+n)*4;const p=e[h];const m=e[h+1];const g=e[h+2];const w=e[h+3];let f=n===c||n===l||t===u||t===d?1:0;let b=0;let v=0;let y=0;let _=0;let $=0;let k=0;for(let T=c;T<=l;T++){for(let A=u;A<=d;A++){if(T===n&&A===t)continue;const I=brightnessDelta(e,h,(A*r+T)*4,p,m,g,w,a);if(I===0){f++;if(f>2)return false}else if(I<b){b=I;y=T;_=A}else if(I>v){v=I;$=T;k=A}}}if(b===0||v===0)return false;return hasManySiblings(s,y,_,r,i)&&hasManySiblings(o,y,_,r,i)||hasManySiblings(s,$,k,r,i)&&hasManySiblings(o,$,k,r,i)}function hasManySiblings(e,n,t,r,i){const s=Math.max(n-1,0);const o=Math.max(t-1,0);const a=Math.min(n+1,r-1);const c=Math.min(t+1,i-1);const u=e[t*r+n];let l=n===s||n===a||t===o||t===c?1:0;for(let d=s;d<=a;d++){for(let h=o;h<=c;h++){if(d===n&&h===t)continue;l+=+(u===e[h*r+d]);if(l>2)return true}}return false}function colorDelta(e,n,t,r,i){const s=e[t];const o=e[t+1];const a=e[t+2];const c=e[t+3];const u=n[r];const l=n[r+1];const d=n[r+2];const h=n[r+3];let p=s-u;let m=o-l;let g=a-d;const w=c-h;if(c<255||h<255){let _=255,$=255,k=255;if(i){_=48+159*(t%2);$=48+159*((t/1.618033988749895|0)%2);k=48+159*((t/2.618033988749895|0)%2)}p=(s*c-u*h-_*w)/255;m=(o*c-l*h-$*w)/255;g=(a*c-d*h-k*w)/255}const f=p*.29889531+m*.58662247+g*.11448223;const b=p*.59597799-m*.2741761-g*.32180189;const v=p*.21147017-m*.52261711+g*.31114694;const y=.5053*f*f+.299*b*b+.1957*v*v;return f>0?-y:y}function brightnessDelta(e,n,t,r,i,s,o,a){const c=e[t];const u=e[t+1];const l=e[t+2];const d=e[t+3];let h=r-c;let p=i-u;let m=s-l;const g=o-d;if(!h&&!p&&!m&&!g)return 0;if(o<255||d<255){let w=255,f=255,b=255;if(a){w=48+159*(n%2);f=48+159*((n/1.618033988749895|0)%2);b=48+159*((n/2.618033988749895|0)%2)}h=(r*o-c*d-w*g)/255;p=(i*o-u*d-f*g)/255;m=(s*o-l*d-b*g)/255}return h*.29889531+p*.58662247+m*.11448223}function drawPixel(e,n,t,r,i){e[n]=t;e[n+1]=r;e[n+2]=i;e[n+3]=255}function drawGrayPixel(e,n,t,r){const i=255+(e[n]*.29889531+e[n+1]*.58662247+e[n+2]*.11448223-255)*t*e[n+3]/255;drawPixel(r,n,i,i,i)}var init_pixelmatch=__esm({"../../node_modules/pixelmatch/index.js"(){"use strict"}});function decodePng(e){return import_pngjs3.PNG.sync.read(e)}function diffScreens(e,n,t={}){const r=decodePng(e);const i=decodePng(n);if(r.width!==i.width||r.height!==i.height){throw new Error(`The screenshots are different sizes (${r.width}\xD7${r.height} vs ${i.width}\xD7${i.height}). Compare on the same device and orientation, or save a new baseline.`)}const{width:s,height:o}=r;const a=Math.round(o*(t.ignoreTop??0));for(const p of[r,i])p.data.fill(0,0,a*s*4);for(const p of t.masks??[]){const m=Math.max(0,Math.floor(p.x*s));const g=Math.min(s,Math.ceil((p.x+p.width)*s));const w=Math.max(0,Math.floor(p.y*o));const f=Math.min(o,Math.ceil((p.y+p.height)*o));for(const b of[r,i])for(let v=w;v<f;v++)b.data.fill(0,(v*s+m)*4,(v*s+g)*4)}const c=t.threshold??.1;const u=new import_pngjs3.PNG({width:s,height:o});const l=pixelmatch(r.data,i.data,u.data,s,o,{threshold:c,includeAA:false,diffMask:true});const d=new import_pngjs3.PNG({width:s,height:o});pixelmatch(r.data,i.data,d.data,s,o,{threshold:c,includeAA:false,alpha:.25,diffColor:[230,30,40]});const h=s*(o-a);return{width:s,height:o,changedPixels:l,percent:h?l/h*100:0,boxes:changedBoxes(u.data,s,o),diffPng:import_pngjs3.PNG.sync.write(d)}}function changedBoxes(e,n,t){const r=Math.max(8,Math.round(n/48));const i=Math.ceil(n/r);const s=Math.ceil(t/r);const o=new Uint32Array(i*s);for(let l=0;l<t;l++){for(let d=0;d<n;d++){if(e[(l*n+d)*4+3]>0)o[Math.floor(l/r)*i+Math.floor(d/r)]++}}const a=1;const c=new Uint8Array(i*s);const u=[];for(let l=0;l<o.length;l++){if(c[l]||o[l]<a)continue;const d={x0:Infinity,y0:Infinity,x1:-1,y1:-1,pixels:0};const h=[l];c[l]=1;while(h.length){const p=h.pop();const m=p%i;const g=Math.floor(p/i);d.x0=Math.min(d.x0,m);d.y0=Math.min(d.y0,g);d.x1=Math.max(d.x1,m);d.y1=Math.max(d.y1,g);d.pixels+=o[p];for(let w=-2;w<=2;w++){for(let f=-2;f<=2;f++){const b=m+f;const v=g+w;if(b<0||v<0||b>=i||v>=s)continue;const y=v*i+b;if(!c[y]&&o[y]>=a){c[y]=1;h.push(y)}}}}u.push(d)}return u.sort((l,d)=>d.pixels-l.pixels).slice(0,8).map(l=>({x:l.x0*r/n,y:l.y0*r/t,width:Math.min(n,(l.x1+1)*r-l.x0*r)/n,height:Math.min(t,(l.y1+1)*r-l.y0*r)/t,pixels:l.pixels}))}function describeSpot(e){const n=e.x+e.width/2;const t=e.y+e.height/2;const r=t<.33?"top":t<.66?"middle":"bottom";const i=n<.33?" left":n<.66?"":" right";return`${r}${i}`}var import_pngjs3;var init_imageDiff=__esm({"src/capture/imageDiff.ts"(){"use strict";import_pngjs3=__toESM(require_png());init_pixelmatch()}});function reasonMessage(e,n){switch(e.reason){case"no-renders":return"No components matched via highlight tracking or the live fiber walk. Pass a testID / name from describe_screen, then retry.";case"no-match":return n?`Nothing matched "${n}".`:"No query or nativeTag given \u2014 pass one, or a testID/name to search for.";case"no-measurement":return"Found the component but couldn't measure it \u2014 it may have just unmounted. Re-navigate to it and retry.";default:return e.reason?`Locate failed: ${e.reason}`:"Couldn't locate that component."}}function candidatesText(e){if(!e||e.length===0)return"";const n=e.map(t=>{const r=t.testID||t.nativeID;return`- ${t.componentName||t.viewType}${r?` (${r})`:""} \u2014 nativeTag ${t.nativeTag}, rendered \xD7${t.renderCount}`});return`
|
|
227
|
-
|
|
228
|
-
Closest matches (retry with a more precise query, or pass nativeTag directly):
|
|
229
|
-
${n.join("\n")}`}function registerScreenshotTools(e,n){e.registerTool("screenshot_component",{description:"Screenshot the app. Leave query and nativeTag out for the whole screen (iOS Simulator or Android, shrunk to keep it cheap). Give a query or nativeTag to crop one React Native component (iOS Simulator only); it can scroll the component into view. Prefer describe_screen for reading text and finding controls: a picture costs far more tokens. Needs the MCP server on the same computer as the simulator or adb device.",inputSchema:{query:import_zod21.z.string().optional().describe('Fuzzy match against testID, nativeID, accessibilityLabel, component name, or view type \u2014 e.g. "submit-button".'),nativeTag:import_zod21.z.number().optional().describe("An exact nativeTag (from a previous call's candidates) to skip fuzzy matching."),scrollIntoView:import_zod21.z.boolean().optional().describe("Attempt to scroll an off-screen component into view before capture. Default true; inspect the result."),serial:import_zod21.z.string().optional().describe("Android: the adb serial, when several devices are connected."),baseline:import_zod21.z.string().optional().describe('Whole screen only: a name like "home". The first call saves the screen as that baseline (in .buoy/baselines); later calls compare against it and report what changed, with a diff picture.'),updateBaseline:import_zod21.z.boolean().optional().describe("With baseline: save the current screen as the new baseline instead of comparing."),steady:import_zod21.z.boolean().optional().describe("With baseline: freeze the app's clock at the baseline's moment while capturing, so countdowns and times match (needs @buoy-gg/clock). Default true when the app has the clock tool."),threshold:import_zod21.z.number().min(0).max(1).optional().describe("With baseline: per-pixel color tolerance, 0 to 1. Default 0.1."),ignore:import_zod21.z.array(import_zod21.z.string()).optional().describe('With baseline: leave these out of the comparison, by testID (e.g. ["live-map", "ad-banner"]), for parts that change on their own.'),ignoreAreas:import_zod21.z.array(import_zod21.z.object({x:import_zod21.z.number(),y:import_zod21.z.number(),width:import_zod21.z.number(),height:import_zod21.z.number()})).optional().describe("With baseline: areas to leave out, as fractions of the screen (0 to 1)."),deviceId:deviceIdInput}},async t=>{try{if(t.baseline){if(t.query||t.nativeTag!=null)return fail6("baseline works on the whole screen: leave query and nativeTag out.");return await baselineShot(n,t.baseline,{deviceId:t.deviceId,serial:t.serial,update:t.updateBaseline,threshold:t.threshold,steady:t.steady,ignore:t.ignore,ignoreAreas:t.ignoreAreas})}if(!t.query&&t.nativeTag==null){const{id:y,host:_,online:$}=await hostTarget(n,t.deviceId,{serial:t.serial},{allowOffline:true});let k=Buffer.alloc(0);const T=await maskSecrets(n,y,$,async()=>k=await hostPng(_));const A={length:T.covered};const I=await toSmallImage(T.png);const R=_.platform==="ios-device"&&isAllBlack(k)?` ${BLACK_PHONE_NOTE}`:"";return{content:[{type:"image",data:I.data,mimeType:I.mimeType},{type:"text",text:`Whole screen of ${hostLabel(_)}, ${I.width}\xD7${I.height}px.${A.length?` ${A.length} element(s) showing a secret were blacked out.`:""}${R}`}]}}const r=n.requireProDevice(t.deviceId);await n.callAction(TOOL_ID2,"setSilentTracking",{enabled:true},r).catch(()=>{});let i=t.nativeTag;const s=i==null&&t.query?await exactTag(n,r,t.query):null;if(s)i=s.tag;const o=await n.callAction(TOOL_ID2,"locateComponent",{query:i==null?t.query:void 0,nativeTag:i,scrollIntoView:t.scrollIntoView??true,margin:MARGIN_PT},r);let a=o;if(!a.matched&&(a.reason==="no-renders"||a.reason==="no-match")){const y=await n.callAction(TOOL_ID2,"describeScreen",{},r).catch(()=>null);const _=y?.elements?pickDescribeScreenMatch(y.elements,t.query,i):void 0;if(_?.frame&&y?.screen){a={matched:true,live:true,rect:frameToRect(_.frame,y.screen),screen:y.screen,nativeTag:_.nativeTag??void 0,componentName:_.name,testID:_.testID}}else if(a.reason==="no-renders"){a={matched:false,reason:"no-match",candidates:a.candidates}}}if(!a.matched||!a.rect||!a.screen){return fail6(reasonMessage(a,t.query)+candidatesText(a.candidates))}if(i==null&&t.query){const y=t.query.toLowerCase();const _=a.candidates?.find(I=>I.nativeTag===a.nativeTag);const $=await n.callAction(TOOL_ID2,"describeScreen",{},r,{timeoutMs:4e3}).catch(()=>null);const k=$?.elements?.find(I=>I.nativeTag===a.nativeTag);const T=[a.testID,a.nativeID,a.componentName,_?.testID,_?.nativeID,_?.componentName,k?.testID,k?.nativeID,k?.text,k?.label].filter(Boolean).map(I=>String(I).toLowerCase());const A=T.some(I=>I.includes(y)||I.length>3&&y.includes(I));if(!A){return fail6(`"${t.query}" is not on the current screen (the closest component was ${a.componentName??"unknown"}${a.testID?` [${a.testID}]`:""}). Navigate to it first, or pass a testID from describe_screen.`+candidatesText(a.candidates))}}const{host:c}=await hostTarget(n,r);if(c.platform!=="ios")return fail6("Cropping one component works on the iOS Simulator. Leave query out for a whole-screen picture.");let u={ok:false};const l=await maskSecrets(n,r,true,async()=>{u=await captureIosFramebuffer(c.udid);return u.ok&&u.srcPath?import_node_fs8.promises.readFile(u.srcPath):Buffer.alloc(0)});if(l.covered&&u.ok&&u.srcPath)await import_node_fs8.promises.writeFile(u.srcPath,l.png);if(!u.ok||!u.srcPath||!u.width||!u.height){return fail6(u.error??"Screenshot capture failed.")}const d=u.width/a.screen.width;const h=a.rect;const p=CAPTURE_PADDING_PT;const m=await cropToBuffer(u.srcPath,{width:u.width,height:u.height},{x:(h.x-p)*d,y:(h.y-p)*d,width:(h.width+p*2)*d,height:(h.height+p*2)*d});if(!m.ok||!m.buffer){return fail6(m.error??"Crop failed.")}const g=a.componentName||s?.name||"component";const w=a.testID??s?.testID;const f=w?` (testID: "${w}")`:"";const b=a.inView===false?"\n\nNote: the component is partly off-screen even after scrolling, so the crop is clamped to the screen edge.":"";const v=`Captured "${g}"${f} \u2014 ${m.width}\xD7${m.height}px.${b}`;return{content:[{type:"image",data:m.buffer.toString("base64"),mimeType:"image/png"},{type:"text",text:v}]}}catch(r){return fail6(errMsg6(r))}})}async function maskSecrets(e,n,t,r){const i=typeof r==="function"?r:async()=>r;const s=secretValues();if(!s.length)return{png:await i(),covered:0};const o=t?await secretBoxes(e,n,s):null;const a=await i();const c=t?await secretBoxes(e,n,s):null;if(o===null||c===null){if(t||typedSecretValues().length){throw new Error("Buoy can't read the app's screen to hide secrets right now, so no picture was taken. Try again in a moment.")}return{png:a,covered:0}}const u=[...o,...c];if(!a.length)return{png:a,covered:0};return{png:u.length?blackOut(a,u):a,covered:Math.max(o.length,c.length)}}async function secretBoxes(e,n,t){const r=await e.callAction(TOOL_ID2,"describeScreen",{includeHidden:false,includeBuoy:true,fullText:true},n,{timeoutMs:4e3}).catch(()=>null);if(!r?.screen)return null;const i=typedSecretValues().length>0;const s=[];for(const o of r.elements??[]){const a=o.value;const c=[o.text,o.label,a].filter(h=>h!=null&&h!=="").map(String);const u=c.some(h=>t.some(p=>showsSecret(h,p)));const l=i&&o.control==="text"&&a===void 0;if(!u&&!l)continue;const d=o.frame?.width&&o.frame.height?fractionFrame(o,r.screen):void 0;if(!d)return null;s.push({...d,pixels:0})}return s}function showsSecret(e,n){const t=e.replace(/\s+/g," ");const r=n.replace(/\s+/g," ").trim();if(t.includes(r))return true;const i=t.replace(/(…|\.\.\.)$/,"");for(let s=r.length-1;s>=MIN_SECRET_LENGTH;s--)if(i.endsWith(r.slice(0,s)))return true;return false}function blackOut(e,n){const t=import_pngjs4.PNG.sync.read(e);for(const r of n){const i=Math.max(0,Math.floor((r.x-.01)*t.width));const s=Math.min(t.width,Math.ceil((r.x+r.width+.01)*t.width));const o=Math.max(0,Math.floor((r.y-.005)*t.height));const a=Math.min(t.height,Math.ceil((r.y+r.height+.005)*t.height));for(let c=o;c<a;c++){for(let u=i;u<s;u++){const l=(c*t.width+u)*4;t.data[l]=t.data[l+1]=t.data[l+2]=0;t.data[l+3]=255}}}return import_pngjs4.PNG.sync.write(t)}async function exactTag(e,n,t){const r=await e.callAction(TOOL_ID2,"describeScreen",{},n,{timeoutMs:4e3}).catch(()=>null);const i=r?.elements??[];const s=u=>({tag:u.nativeTag,name:u.name,testID:u.testID});const o=i.filter(u=>u.testID===t&&u.nativeTag!=null);if(o.length===1)return s(o[0]);const a=t.trim().toLowerCase();const c=i.filter(u=>(u.text??u.label??"").trim().toLowerCase()===a&&u.nativeTag!=null);return c.length===1?s(c[0]):null}function baselinePath(e){const n=e.trim().replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"")||"screen";return import_node_path9.default.join(process.env.BUOY_PROJECT_ROOT||process.cwd(),".buoy","baselines",`${n}.png`)}function fractionFrame(e,n){if(e.frame&&e.frame.width&&e.frame.height){const t=e.frame.x+e.frame.width>1.5||e.frame.y+e.frame.height>1.5;return t?{x:e.frame.x/n.width,y:e.frame.y/n.height,width:e.frame.width/n.width,height:e.frame.height/n.height}:{...e.frame}}if(e.tap)return{x:e.tap.x-.01,y:e.tap.y-.01,width:.02,height:.02};return void 0}function elementsIn(e,n){const t=[];for(const r of n){const i=r.frame;if(!i)continue;const s=Math.max(0,Math.min(e.x+e.width,i.x+i.width)-Math.max(e.x,i.x));const o=Math.max(0,Math.min(e.y+e.height,i.y+i.height)-Math.max(e.y,i.y));const a=i.width*i.height;if(!a||s*o/a<.5)continue;t.push({label:labelOf(r),area:a,words:!!r.words})}return[...new Set(t.sort((r,i)=>Number(i.words)-Number(r.words)||r.area-i.area).map(r=>r.label))].slice(0,3)}function textChanges(e,n){const t=d=>d.testID?`id:${d.testID}`:`${d.name??""}@${d.frame?`${Math.round(d.frame.x*40)},${Math.round(d.frame.y*40)}`:"?"}`;const r=new Map(e.filter(d=>d.words).map(d=>[t(d),d]));const i=new Map(n.filter(d=>d.words).map(d=>[t(d),d]));const s=new Set([...r.values()].map(d=>d.words));const o=new Set([...i.values()].map(d=>d.words));const a=[];for(const[d,h]of i){const p=r.get(d);if(p){if(p.words!==h.words)a.push(`changed: ${labelOf({...h,words:void 0})} "${p.words}" \u2192 "${h.words}"`)}else if(!s.has(h.words))a.push(`appeared: ${labelOf(h)}`)}for(const[d,h]of r)if(!i.has(d)&&!o.has(h.words))a.push(`gone: ${labelOf(h)}`);const c=[...r.entries()].filter(([d,h])=>!i.has(d)&&!o.has(h.words)).map(([,d])=>d);const u=[...i.entries()].filter(([d,h])=>!r.has(d)&&!s.has(h.words)).map(([,d])=>d);const l=(d,h)=>!!d&&!!h&&d.x<h.x+h.width&&h.x<d.x+d.width&&d.y<h.y+h.height&&h.y<d.y+d.height;for(const d of u){const h=c.find(m=>m.name===d.name&&l(m.frame,d.frame));if(!h)continue;c.splice(c.indexOf(h),1);const p=new Set([`appeared: ${labelOf(d)}`,`gone: ${labelOf(h)}`]);for(let m=a.length-1;m>=0;m--)if(p.has(a[m]))a.splice(m,1);a.push(`changed: ${labelOf({...d,words:void 0})} "${h.words}" \u2192 "${d.words}"`)}return a.slice(0,12)}async function readScreen(e,n){try{const[t,r,i]=await Promise.all([e.callAction("highlight-updates","describeScreen",{includeBuoy:true},n,{timeoutMs:4e3}),e.callAction("highlight-updates","describeScreen",{},n,{timeoutMs:4e3}),e.callAction("route-events","getCurrentRoute",{},n,{timeoutMs:2e3}).catch(()=>null)]);const s=r?.screen??t?.screen;if(!s)return null;const o=new Set((r?.elements??[]).map(l=>l.nativeTag));const a=[];for(const l of t?.elements??[]){if(o.has(l.nativeTag))continue;const d=fractionFrame(l,s);if(d)a.push({x:d.x-.01,y:d.y-.01,width:d.width+.02,height:d.height+.02,pixels:0})}const c=(r?.elements??[]).map(l=>{const d=scrubSecrets((l.text??l.label??"").replace(/[\s\u200b\u00a0]+/g," ").trim());return{name:l.name,words:d||void 0,testID:l.testID?scrubSecrets(l.testID):void 0,frame:fractionFrame(l,s)}});const u=i?.path??i?.pathname;return{elements:c,masks:a,route:u?scrubSecrets(u):void 0}}catch{return null}}async function withFrozenClock(e,n,t,r){let i;let s;let o;try{await e.callAction("clock","freeze",{time:t},n);await new Promise(c=>setTimeout(c,1300));i=await r()}catch(c){s=c}finally{try{await e.callAction("clock","reset",{},n)}catch(c){o=c}}const a=o?` WARNING: putting the app's clock back failed (${errMsg6(o)}); run clock_action reset.`:"";if(s)throw new Error(`${errMsg6(s)}${a}`);return{result:i,note:` The app's clock was frozen at ${new Date(t).toISOString()} for the capture.${a}`}}async function baselineShot(...e){return(await runBaseline(...e)).result}async function runBaseline(e,n,t){const{id:r,host:i}=await hostTarget(e,t.deviceId,{serial:t.serial});const s=baselinePath(n);const o=s.replace(/\.png$/,".json");const a=import_node_path9.default.relative(process.env.BUOY_PROJECT_ROOT||process.cwd(),s);let c=null;try{c=await import_node_fs8.promises.readFile(s)}catch{}const u=!c||!!t.update;const l=u?{}:JSON.parse(await import_node_fs8.promises.readFile(o,"utf8").catch(()=>"{}"));const d=hostLabel(i);const h=e.connectedDevices().find(D=>D.deviceId===r)?.tools.some(D=>D.toolId==="clock")??false;const p=t.steady??h;let m="";const g=async()=>{const{result:D,steadied:z}=await withSteadyStatusBar(i,async()=>({png:(await maskSecrets(e,r,true,()=>hostPng(i))).png,screen:await readScreen(e,r)}));return{...D,steadied:z}};let w;if(p&&h){const D=await e.callAction("clock","getState",{},r).catch(()=>null);if(D?.mode==="real"){const z=u||!l.steadyTime?Math.floor(Date.now()/6e4)*6e4:l.steadyTime;l.steadyTime=z;const L=await withFrozenClock(e,r,z,g);w=L.result;m+=L.note}else{w=await g();m+=" The app's clock was already overridden, so it was left as it was."}}else{w=await g();if(p&&!h)m+=" (steady needs the Clock tool in the app; times on screen may differ.)"}const f={width:w.png.readUInt32BE(16),height:w.png.readUInt32BE(20)};if(u){await import_node_fs8.promises.mkdir(import_node_path9.default.dirname(s),{recursive:true});await import_node_fs8.promises.writeFile(s,w.png);const D={...l,device:d,size:f,route:w.screen?.route,elements:w.screen?.elements};await import_node_fs8.promises.writeFile(o,JSON.stringify(D,null,1));const z=await toSmallImage(w.png);const L=`${c?"Replaced":"Saved"} baseline "${n}"`;return{outcome:{saved:true,changed:false,percent:0,texts:0,summary:`${L} (first run)`},result:{content:[{type:"image",data:z.data,mimeType:z.mimeType},{type:"text",text:`${c?"Replaced":"Saved"} baseline "${n}" (${a}) from ${d}${w.screen?.route?` on ${w.screen.route}`:""}. Call again with the same baseline to compare.${m}`}]}}}const b=[];if(l.device&&l.device!==d)b.push(`The baseline was saved on ${l.device}; this is ${d}.`);if(l.route&&w.screen?.route&&l.route!==w.screen.route)b.push(`The baseline was on ${l.route}; the app is now on ${w.screen.route}.`);const v=[...t.ignoreAreas??[]];const y=new Set(t.ignore??[]);const _=new Set(y);for(const D of[...l.elements??[],...w.screen?.elements??[]]){if(!D.testID||!y.has(D.testID)||!D.frame)continue;_.delete(D.testID);v.push({x:D.frame.x-.005,y:D.frame.y-.005,width:D.frame.width+.01,height:D.frame.height+.01})}if(_.size)b.push(`Not on screen, so not left out: ${[..._].join(", ")}.`);const $=i.platform==="android"?[]:[{x:.28,y:0,width:.44,height:.055}];const k=diffScreens(c,w.png,{threshold:t.threshold,masks:[...w.screen?.masks??[],...v,...$],ignoreTop:w.steadied?0:.065});const T=D=>!!D&&v.some(z=>D.x+D.width/2>=z.x&&D.x+D.width/2<=z.x+z.width&&D.y+D.height/2>=z.y&&D.y+D.height/2<=z.y+z.height);const A=D=>(!D.testID||!y.has(D.testID))&&!T(D.frame);const I=l.elements&&w.screen?textChanges(l.elements.filter(A),w.screen.elements.filter(A)):[];const R=[w.steadied?"":"status bar",w.screen?.masks.length?"Buoy's overlay":"",v.length?"the parts you asked to ignore":""].filter(Boolean);const M=R.join(" and ");const S=M?`; ${M} left out`:"";const x=b.length?`
|
|
230
|
-
|
|
231
|
-
\u26A0\uFE0F ${b.join(" ")}`:"";if(k.changedPixels===0&&I.length===0){return{outcome:{saved:false,changed:false,percent:0,texts:0,summary:`no change from baseline "${n}"`},result:text(`No change from baseline "${n}" (${a}${S}).${m}${x}`)}}const E=k.boxes.map((D,z)=>{const L=w.screen?elementsIn(D,w.screen.elements):[];const J=`${describeSpot(D)} (x ${D.x.toFixed(2)}, y ${D.y.toFixed(2)}, ${D.width.toFixed(2)}\xD7${D.height.toFixed(2)})`;return`${z+1}. ${J}${L.length?`: ${L.join(", ")}`:""}`});const j=await toSmallImage(k.diffPng);const P=k.percent<.01&&k.changedPixels>0?"<0.01":k.percent.toFixed(2);const B=E[0]?`; ${E[0].replace(/^1\. /,"")}`:"";const F=I[0]?`; ${I[0]}`:"";const C=k.changedPixels===0?`no pixel change from baseline "${n}", but text changed`:`${P}% changed from baseline "${n}"`;const O={saved:false,changed:true,percent:k.percent,texts:I.length,summary:`${C}${B}${F}`};return{outcome:O,result:{content:[{type:"image",data:j.data,mimeType:j.mimeType},{type:"text",text:`**Changed from baseline "${n}": ${k.percent<.01&&k.changedPixels>0?"<0.01":k.percent.toFixed(2)}% of the screen** (${k.changedPixels} px${S}). Changes are red in the picture.${m}`+(E.length?`
|
|
232
|
-
|
|
233
|
-
Where:
|
|
234
|
-
${E.join("\n")}`:"")+(I.length?`
|
|
235
|
-
|
|
236
|
-
Text:
|
|
237
|
-
${I.map(D=>`- ${D}`).join("\n")}`:"")+`${x}
|
|
238
|
-
|
|
239
|
-
If this change is expected, save it with updateBaseline: true.`}]}}}var import_zod21,import_node_fs8,import_node_path9,import_pngjs4,TOOL_ID2,MARGIN_PT,CAPTURE_PADDING_PT,fail6,errMsg6,labelOf;var init_screenshot=__esm({"src/tools/packs/screenshot.ts"(){"use strict";import_zod21=require("zod");init_packKit();init_simctl();init_screenshotLocate();init_hostDevice();init_imageDiff();import_node_fs8=require("fs");import_node_path9=__toESM(require("path"));init_hostKit();init_secrets();init_iosDevice();import_pngjs4=__toESM(require_png());TOOL_ID2="highlight-updates";MARGIN_PT=12;CAPTURE_PADDING_PT=6;fail6=e=>({isError:true,content:[{type:"text",text:e}]});errMsg6=e=>e instanceof Error?e.message:String(e);labelOf=e=>`${e.name??"View"}${e.words?` "${e.words.length>40?`${e.words.slice(0,40)}\u2026`:e.words}"`:""}${e.testID?` [${e.testID}]`:""}`}});var camera_exports={};__export(camera_exports,{cliPath:()=>cliPath,describeDevices:()=>describeDevices,describeDiagnosis:()=>describeDiagnosis,describeInputs:()=>describeInputs,proRequired:()=>proRequired,readEntitlement:()=>readEntitlement,run:()=>run2});function candidates(){const e=process.env.BUOY_SIMCAM_DIR;const n=[...e?[import_node_path10.default.join(e,"buoycam")]:[],"/Applications/Buoy.app/Contents/Resources/simcam/buoycam",import_node_path10.default.join(import_node_os7.default.homedir(),"Applications/Buoy.app/Contents/Resources/simcam/buoycam")];let t=__dirname;for(let r=0;r<8;r++){n.push(import_node_path10.default.join(t,"apps/desktop/resources/simcam/buoycam"));const i=import_node_path10.default.dirname(t);if(i===t)break;t=i}return n}function cliPath(){if(resolved)return resolved;resolved=candidates().find(e=>(0,import_node_fs9.existsSync)(e))??null;return resolved}async function run2(e){const n=cliPath();if(!n){return{ok:false,error:"The simulator camera components were not found. They ship with the Buoy desktop app \u2014 install it, or set BUOY_SIMCAM_DIR to the directory holding `buoycam`."}}try{const{stdout:t}=await execFileAsync11(n,[...e,"--json"],{timeout:3e4});return{ok:true,data:JSON.parse(t)}}catch(t){const r=t.stdout??"";try{return{ok:false,data:JSON.parse(r)}}catch{return{ok:false,error:t.message||"the simulator camera CLI failed"}}}}function describeDiagnosis(e){const n=e.filter(s=>s.level==="fail");const t=e.filter(s=>s.level==="warn");if(n.length===0&&t.length===0){return"The simulator camera is healthy \u2014 every check passed."}const r=[];for(const s of[...n,...t]){r.push(`- **${s.name}** (${s.level}): ${s.detail}`);if(s.fix)r.push(` ${s.fix}`)}const i=n.length>0?`${n.length} problem${n.length===1?"":"s"} found.`:`No hard failures, but ${t.length} thing${t.length===1?"":"s"} worth knowing.`;return[i,"",...r].join("\n")}function describeDevices(e,n){if(e.length===0){return"No booted simulators.\n\n_Boot one first \u2014 `xcrun simctl boot <udid>`, or open Simulator.app. The camera attaches to a simulator, so nothing else here works until one is running._"}const t=[e.length===1?"1 booted simulator:":`${e.length} booted simulators:`,...e.map(r=>`- **${r.name}** (${r.runtime}) \u2014 \`${r.udid}\``)];if(e.length>1&&n===null){t.push("","_More than one is booted, so pass `udid` to list a specific one's apps \u2014 and to every other camera tool that takes one._");return t.join("\n")}if(n===null){t.push("","_Could not read the installed apps._");return t.join("\n")}if(n.length===0){t.push("","No apps installed on it.");return t.join("\n")}t.push("",`${n.length} installed app${n.length===1?"":"s"}:`,...n.map(r=>`- ${r.name} \u2014 \`${r.bundleId}\``),"","_Pass one of these bundle ids to `camera_launch` to relaunch it with the camera attached._");return t.join("\n")}function describeInputs(e,n){const t=[];t.push(e.length?'**Mac cameras** (for `kind: "camera"`):':"**Mac cameras**: none found.");if(e.length){t.push(...e.map(r=>`- ${r.name} \u2014 \`${r.uniqueId}\``))}else{t.push("_If this Mac has a webcam, Buoy has not been granted Camera permission (System Settings \u2192 Privacy & Security \u2192 Camera)._")}t.push("");t.push(n.length?'**Capturable windows** (for `kind: "screen"`, `value: "window:<id>"`):':"**Capturable windows**: none found.");if(n.length){t.push(...n.map(r=>`- ${r.app}${r.title?` \u2014 ${r.title}`:""} \u2014 \`window:${r.id}\``))}else{t.push("_Screen Recording permission is almost certainly missing (System Settings \u2192 Privacy & Security \u2192 Screen & System Audio Recording)._")}return t.join("\n")}function entitlementPaths(){const e=process.env.BUOY_ENTITLEMENT_FILE;if(e)return[e];return[import_node_path10.default.join(import_node_os7.default.homedir(),"Library/Application Support/Buoy/entitlement.json"),import_node_path10.default.join(import_node_os7.default.homedir(),"Library/Application Support/buoy-desktop/entitlement.json")]}function readEntitlement(){for(const e of entitlementPaths()){try{if(!(0,import_node_fs9.existsSync)(e))continue;const n=JSON.parse((0,import_node_fs9.readFileSync)(e,"utf8"));return{tier:n.tier==="pro"||n.tier==="free"?n.tier:"locked",isPro:n.isPro===true&&n.hasDesktopAccess===true&&typeof n.validUntil==="number"&&Number.isFinite(n.validUntil)&&Date.now()<n.validUntil&&typeof n.proValidUntil==="number"&&Number.isFinite(n.proValidUntil)&&Date.now()<n.proValidUntil}}catch{}}return{tier:"locked",isPro:false}}function proRequired(e){return`\`${e}\` is a Buoy Pro feature.
|
|
240
|
-
|
|
241
|
-
The simulator camera itself is free \u2014 the Mac camera, image, video, test-pattern and QR sources all work in the Buoy desktop panel with a Free account. Pro adds the screen region, the non-QR symbologies (PDF417, Aztec, DataMatrix, Code 128), and driving any of it from an agent.
|
|
242
|
-
|
|
243
|
-
_Tell the user to enter a licence in Buoy Desktop, or see https://buoy.gg/pricing. Don't try to work around it \u2014 use the desktop panel by hand instead._`}var import_node_child_process12,import_node_util11,import_node_fs9,import_node_os7,import_node_path10,execFileAsync11,resolved;var init_camera=__esm({"src/capture/camera.ts"(){"use strict";import_node_child_process12=require("child_process");import_node_util11=require("util");import_node_fs9=require("fs");import_node_os7=__toESM(require("os"));import_node_path10=__toESM(require("path"));execFileAsync11=(0,import_node_util11.promisify)(import_node_child_process12.execFile);resolved=null}});function registerCameraTools(e){e.registerTool("camera_source",{description:"Give the iOS Simulator a camera, and choose what it shows. Use this before testing anything that opens a camera \u2014 a QR or barcode scanner, document capture, an avatar picker. `barcode` generates the code from text, so testing a scanner needs no printed code and no second device; pdf417 is the barcode on a driver's licence. `screen` points the phone's camera at this Mac's screen. Needs no Buoy integration in the app under test.",inputSchema:{kind:import_zod22.z.enum(["barcode","image","video","camera","screen","pattern"]).describe("What the camera should show."),value:import_zod22.z.string().optional().describe("Text for `barcode`, a file path for `image`/`video`, a camera uniqueId for `camera` (see `camera_inputs`), or one of `behind` / `display` / `window:<id>` / `region:<id>[:<gutter>]` for `screen`."),format:import_zod22.z.enum(["qr","pdf417","aztec","code128"]).optional().describe("Barcode symbology; defaults to qr.")}},async n=>{const t=gate("camera_source");if(t)return t;const r=["source",n.kind];if(n.value)r.push(n.value);if(n.format)r.push("--format",n.format);const i=await run2(r);if(!i.ok){return fail7(i.error??i.data?.error??"could not set the camera source")}const s=n.kind==="barcode"?`a ${n.format??"qr"} code reading "${n.value}"`:n.kind==="screen"?`this Mac's screen (${n.value??"behind the simulator window"})`:n.value??n.kind;return text5(`The simulator camera is now showing ${s}, at ${i.data?.fps??0} fps.
|
|
244
|
-
|
|
245
|
-
_Apps already running do not pick up a camera they started without \u2014 use \`camera_launch\` to relaunch one, or \`camera_zero_setup\` so that anything the simulator launches gets it._`)});e.registerTool("camera_status",{description:"Check what the simulator camera is doing and what it is currently decoding. Use this to confirm a scanner test is actually seeing a code before concluding the app is broken.",inputSchema:{}},async()=>{const n=gate("camera_status");if(n)return n;const t=await run2(["status"]);if(!t.ok||!t.data){return fail7(t.error??"could not read the simulator camera status")}const{publishing:r,fps:i,codes:s}=t.data;if(!r){return text5("The simulator camera is not publishing anything.\n\n_Set a source with `camera_source` first._")}return text5([`Publishing at ${i} fps.`,s.length?`Currently decoding: ${s.map(o=>`\`${o}\``).join(", ")}`:"No barcode in the current frame.","","_A code shown here is what the app receives. If the app is not reacting to it, the problem is in the app, not the camera \u2014 `camera_diagnose` will say whether the app is even reading the feed._"].join("\n"))});e.registerTool("camera_launch",{description:"Relaunch a simulator app with the camera attached. A camera can only be attached when a process starts, so an app that is already running cannot be given one \u2014 this terminates and relaunches it.",inputSchema:{bundleId:import_zod22.z.string().describe("The app's bundle identifier."),udid:import_zod22.z.string().optional().describe("Simulator udid, if more than one is booted.")}},async n=>{const t=gate("camera_launch");if(t)return t;const r=["launch",n.bundleId];if(n.udid)r.push("--udid",n.udid);const i=await run2(r);if(!i.ok){return fail7(i.error??i.data?.error??"could not launch the app")}return text5(`Relaunched \`${n.bundleId}\` with the camera attached${i.data?.pid?` (pid ${i.data.pid})`:""}.`)});e.registerTool("camera_diagnose",{description:"Work out why the simulator camera is not working. Checks that the pieces are present, a simulator is booted, something is publishing, SOMETHING IS READING IT, the library is loaded in the target app, no other tool owns the injection, and no camera library in the project disables simulator cameras at compile time.",inputSchema:{bundleId:import_zod22.z.string().optional().describe("Check a specific app \u2014 whether the library is actually loaded in it.")}},async n=>{const t=["diagnose"];if(n.bundleId)t.push(n.bundleId);const r=await run2(t);if(!r.data?.checks){return fail7(r.error??"could not run the simulator camera diagnosis")}const i=readEntitlement();const s=i.isPro?"":"\n\n_This install is on the **free** tier, so the other `camera_*` tools are blocked. The camera still works by hand in the Buoy desktop panel._";return text5(describeDiagnosis(r.data.checks)+s)});e.registerTool("camera_stop",{description:"Turn the simulator camera off and stop publishing frames. The camera stays on until stopped \u2014 across app relaunches and after a test finishes \u2014 so call this when done, or the next thing that opens a camera will still see the last source.",inputSchema:{}},async()=>{const n=gate("camera_stop");if(n)return n;const t=await run2(["stop"]);if(!t.ok){return fail7(t.error??t.data?.error??"could not stop the camera")}return text5("The simulator camera is off.")});e.registerTool("camera_devices",{description:"List booted simulators and the apps installed on one. Use this to find the bundle id `camera_launch` needs, or the udid to pass when more than one simulator is booted. Lists every app on the simulator, not just Buoy-integrated ones \u2014 the camera works on any of them.",inputSchema:{udid:import_zod22.z.string().optional().describe("Which simulator's apps to list. Only needed when several are booted.")}},async n=>{const t=gate("camera_devices");if(t)return t;const r=await run2(["devices"]);if(!r.ok||!r.data){return fail7(r.error??"could not list booted simulators")}const i=r.data.devices??[];let s=null;if(i.length===1||n.udid){const o=await run2(["apps",...n.udid?["--udid",n.udid]:[]]);s=o.ok?o.data?.apps??[]:null}return text5(describeDevices(i,s))});e.registerTool("camera_inputs",{description:"List what this Mac can point the simulator camera at: its webcams (the uniqueId for `camera_source` with kind `camera`) and the windows the screen source can film (the id for `window:<id>`). Call this before choosing a `camera` or windowed `screen` source \u2014 those ids cannot be guessed.",inputSchema:{}},async()=>{const n=gate("camera_inputs");if(n)return n;const[t,r]=await Promise.all([run2(["cameras"]),run2(["windows"])]);if(!t.ok&&!r.ok){return fail7(t.error??r.error??"could not list the Mac's cameras or windows")}return text5(describeInputs(t.data?.cameras??[],r.data?.windows??[]))});e.registerTool("camera_zero_setup",{description:"Make every app the simulator launches get a camera, however it was launched \u2014 `expo start`, `react-native run-ios`, Xcode, a test runner. Use this when you are not the one starting the app, so `camera_launch` is not an option. It loads Buoy's library into every process in that simulator, SpringBoard included, so turn it off when finished.",inputSchema:{action:import_zod22.z.enum(["on","off","status"]).describe("Turn it on, off, or report the current state."),udid:import_zod22.z.string().optional().describe("Which simulator. Only needed when several are booted.")}},async n=>{const t=gate("camera_zero_setup");if(t)return t;const r=await run2(["zero-setup",n.action,...n.udid?["--udid",n.udid]:[]]);if(!r.ok){return fail7(r.error??r.data?.error??"could not change zero-setup mode")}const i=r.data??{};if(n.action==="status"){if(!i.enabled)return text5("Zero-setup mode is **off**.");return text5(i.foreign?`Zero-setup is on, but **another tool owns it** (\`${i.path}\`). Quit that tool before turning Buoy's on.`:"Zero-setup mode is **on** \u2014 anything this simulator launches gets the camera.")}if(n.action==="on"){return text5("Zero-setup mode is **on**. Anything this simulator launches from now on gets the camera \u2014 start your app however you normally would.\n\n_This loads the library into every process in the simulator. Turn it off with `camera_zero_setup` action `off` when you are done._")}return text5("Zero-setup mode is **off**.")})}var import_zod22,text5,gate,fail7;var init_camera2=__esm({"src/tools/packs/camera.ts"(){"use strict";import_zod22=require("zod");init_camera();text5=e=>({content:[{type:"text",text:e}]});gate=e=>readEntitlement().isPro?null:fail7(proRequired(e));fail7=e=>({isError:true,content:[{type:"text",text:e}]})}});var START_PROBE_JS,END_PROBE_JS,COLLECT_PROBE_JS,MEASURE_REFRESH_JS;var init_inPageProbe=__esm({"src/webBench/inPageProbe.ts"(){"use strict";START_PROBE_JS=`(() => {
|
|
246
|
-
const supported = (t) => {
|
|
247
|
-
try { return (PerformanceObserver.supportedEntryTypes || []).includes(t); } catch { return false; }
|
|
248
|
-
};
|
|
249
|
-
const frames = [], longTasks = [], loaf = [], shifts = [], events = [], observers = [];
|
|
250
|
-
const watch = (type, cb, extra) => {
|
|
251
|
-
if (!supported(type)) return false;
|
|
252
|
-
const o = new PerformanceObserver((l) => l.getEntries().forEach(cb));
|
|
253
|
-
o.observe(Object.assign({ type, buffered: false }, extra || {}));
|
|
254
|
-
observers.push([o, cb]);
|
|
255
|
-
return true;
|
|
256
|
-
};
|
|
257
|
-
const hasLong = watch("longtask", (e) => longTasks.push({ start: e.startTime, end: e.startTime + e.duration }));
|
|
258
|
-
const hasLoaf = watch("long-animation-frame", (e) => loaf.push({
|
|
259
|
-
startTime: e.startTime,
|
|
260
|
-
duration: e.duration,
|
|
261
|
-
blockingDuration: e.blockingDuration || 0,
|
|
262
|
-
styleAndLayoutStart: e.styleAndLayoutStart || 0,
|
|
263
|
-
scripts: (e.scripts || []).map((s) => {
|
|
264
|
-
const file = s.sourceURL ? s.sourceURL.split("?")[0].split("/").pop() : "";
|
|
265
|
-
const where = s.sourceFunctionName ? s.sourceFunctionName + (file ? " @ " + file : "") : file;
|
|
266
|
-
// Invokers like "FrameRequestCallback" say how a script ran, not which
|
|
267
|
-
// one; add the function and file when the browser gives them.
|
|
268
|
-
const name = s.invoker ? (where ? s.invoker + " \u2192 " + where : s.invoker) : where || "(anonymous)";
|
|
269
|
-
return { duration: s.duration, name, forced: s.forcedStyleAndLayoutDuration || 0 };
|
|
270
|
-
}),
|
|
271
|
-
}));
|
|
272
|
-
// 16 ms is Event Timing's smallest threshold; the default (104) hides most taps.
|
|
273
|
-
const hasEvents = watch("event", (e) => {
|
|
274
|
-
if (e.interactionId) events.push({
|
|
275
|
-
name: e.name, startTime: e.startTime, duration: e.duration,
|
|
276
|
-
processingStart: e.processingStart, processingEnd: e.processingEnd, interactionId: e.interactionId,
|
|
277
|
-
});
|
|
278
|
-
}, { durationThreshold: 16 });
|
|
279
|
-
// Click proof: which step selectors each real click landed inside, read
|
|
280
|
-
// at the moment of the click (capture phase, before the page's handlers).
|
|
281
|
-
const clickTargets = Array.isArray(window.__buoyBenchClickTargets) ? window.__buoyBenchClickTargets : [];
|
|
282
|
-
const clicks = [], keys = [];
|
|
283
|
-
// Only real (trusted) input counts as proof; a click the page fakes in
|
|
284
|
-
// script doesn't. Input after the run's end doesn't count either.
|
|
285
|
-
const onClick = (e) => {
|
|
286
|
-
if (!e.isTrusted || ended) return;
|
|
287
|
-
const t = e.target;
|
|
288
|
-
const hit = clickTargets.filter((sel) => { try { return t && t.closest && t.closest(sel); } catch { return false; } });
|
|
289
|
-
clicks.push({ t: performance.now(), hit });
|
|
290
|
-
};
|
|
291
|
-
const onKey = (e) => {
|
|
292
|
-
if (!e.isTrusted || ended) return;
|
|
293
|
-
keys.push({ t: performance.now(), key: e.key, ctrl: e.ctrlKey, shift: e.shiftKey, alt: e.altKey, meta: e.metaKey });
|
|
294
|
-
};
|
|
295
|
-
// Expect steps, judged inside end() so no page work can slip in between
|
|
296
|
-
// the end of the run and the check.
|
|
297
|
-
const expects = Array.isArray(window.__buoyBenchExpects) ? window.__buoyBenchExpects : [];
|
|
298
|
-
let expectResults = null;
|
|
299
|
-
document.addEventListener("click", onClick, true);
|
|
300
|
-
document.addEventListener("keydown", onKey, true);
|
|
301
|
-
const hasShift = watch("layout-shift", (e) => shifts.push({ startTime: e.startTime, value: e.value, hadRecentInput: e.hadRecentInput }));
|
|
302
|
-
let hidden = document.visibilityState === "hidden";
|
|
303
|
-
const onVis = () => { if (document.visibilityState === "hidden") hidden = true; };
|
|
304
|
-
document.addEventListener("visibilitychange", onVis);
|
|
305
|
-
// Latched: a resize or zoom that's undone before stop still changed the work.
|
|
306
|
-
let resized = false;
|
|
307
|
-
const onResize = () => { resized = true; };
|
|
308
|
-
window.addEventListener("resize", onResize);
|
|
309
|
-
// A pixel-ratio change (moving to another screen) may not fire resize.
|
|
310
|
-
let dprQuery = null;
|
|
311
|
-
try {
|
|
312
|
-
dprQuery = matchMedia("(resolution: " + window.devicePixelRatio + "dppx)");
|
|
313
|
-
dprQuery.addEventListener("change", onResize);
|
|
314
|
-
} catch {}
|
|
315
|
-
let raf = 0;
|
|
316
|
-
const tick = (t) => { frames.push(t); raf = requestAnimationFrame(tick); };
|
|
317
|
-
raf = requestAnimationFrame(tick);
|
|
318
|
-
const start = performance.now();
|
|
319
|
-
// Trace markers: the driver counts Chrome's frames between these two.
|
|
320
|
-
try { performance.mark("__buoy_bench_start"); } catch {}
|
|
321
|
-
const domStart = document.getElementsByTagName("*").length;
|
|
322
|
-
let ended = 0;
|
|
323
|
-
window.__buoyBench = {
|
|
324
|
-
// Two steps so the driver can read Chrome's counters between them:
|
|
325
|
-
// end() freezes the end time at once; collect() then waits up to two
|
|
326
|
-
// frames (capped at 300 ms) so an input's entry, which only arrives after
|
|
327
|
-
// its paint, isn't lost. Entries after the end are filtered out later.
|
|
328
|
-
end: () => {
|
|
329
|
-
if (ended) return ended;
|
|
330
|
-
ended = performance.now();
|
|
331
|
-
try { performance.mark("__buoy_bench_end"); } catch {}
|
|
332
|
-
cancelAnimationFrame(raf);
|
|
333
|
-
expectResults = expects.map((x) => {
|
|
334
|
-
const n = document.querySelector(x.selector);
|
|
335
|
-
const full = n ? (n.textContent || "") : null;
|
|
336
|
-
// Match against the full text here; only a short snippet goes back.
|
|
337
|
-
return { selector: x.selector, text: x.text == null ? null : x.text, found: !!n, matched: full != null && (x.text == null || full.includes(x.text)), content: full == null ? null : full.slice(0, 200) };
|
|
338
|
-
});
|
|
339
|
-
return ended;
|
|
340
|
-
},
|
|
341
|
-
collect: () => new Promise((resolve) => {
|
|
342
|
-
const end = window.__buoyBench.end();
|
|
343
|
-
let done = false;
|
|
344
|
-
const finish = () => {
|
|
345
|
-
if (done) return;
|
|
346
|
-
done = true;
|
|
347
|
-
document.removeEventListener("visibilitychange", onVis);
|
|
348
|
-
window.removeEventListener("resize", onResize);
|
|
349
|
-
document.removeEventListener("click", onClick, true);
|
|
350
|
-
document.removeEventListener("keydown", onKey, true);
|
|
351
|
-
try { dprQuery && dprQuery.removeEventListener("change", onResize); } catch {}
|
|
352
|
-
for (const [o, cb] of observers) { o.takeRecords().forEach(cb); o.disconnect(); }
|
|
353
|
-
resolve({
|
|
354
|
-
start, end, frames,
|
|
355
|
-
longTasks: hasLong ? longTasks : null,
|
|
356
|
-
loaf: hasLoaf ? loaf : null,
|
|
357
|
-
shifts: hasShift ? shifts : null,
|
|
358
|
-
events: hasEvents ? events : null,
|
|
359
|
-
clicks,
|
|
360
|
-
keys,
|
|
361
|
-
expectResults,
|
|
362
|
-
domStart,
|
|
363
|
-
domEnd: document.getElementsByTagName("*").length,
|
|
364
|
-
hidden,
|
|
365
|
-
resized,
|
|
366
|
-
});
|
|
367
|
-
};
|
|
368
|
-
requestAnimationFrame(() => requestAnimationFrame(finish));
|
|
369
|
-
setTimeout(finish, 300);
|
|
370
|
-
}),
|
|
371
|
-
};
|
|
372
|
-
return true;
|
|
373
|
-
})()`;END_PROBE_JS=`(() => (window.__buoyBench ? window.__buoyBench.end() : null))()`;COLLECT_PROBE_JS=`(() => (window.__buoyBench ? window.__buoyBench.collect() : null))()`;MEASURE_REFRESH_JS=`new Promise((resolve) => {
|
|
374
|
-
let n = 0, t0 = 0;
|
|
375
|
-
const tick = (t) => {
|
|
376
|
-
if (!t0) t0 = t;
|
|
377
|
-
n++;
|
|
378
|
-
if (t - t0 >= 1000) resolve(((n - 1) / (t - t0)) * 1000);
|
|
379
|
-
else requestAnimationFrame(tick);
|
|
380
|
-
};
|
|
381
|
-
requestAnimationFrame(tick);
|
|
382
|
-
})`}});var webBench_exports={};__export(webBench_exports,{GPU_RENDERER_JS:()=>GPU_RENDERER_JS,PLAYWRIGHT_MISSING:()=>PLAYWRIGHT_MISSING,aggregateCase:()=>aggregateCase,caseUrl:()=>caseUrl,cdpDeltas:()=>cdpDeltas,checkBudgets:()=>checkBudgets,closeCall:()=>closeCall,closeWithin:()=>closeWithin,expectFailureFrom:()=>expectFailureFrom,formatWebBenchMarkdown:()=>formatWebBenchMarkdown,isSoftwareGpu:()=>isSoftwareGpu,keyMatches:()=>keyMatches,loadChromium:()=>loadChromium,locateStepTargets:()=>locateStepTargets,mergeInteractions:()=>mergeInteractions,missedInput:()=>missedInput,oneLine:()=>oneLine,percentile:()=>percentile,runWebBench:()=>runWebBench,shuffled:()=>shuffled,snapRefreshRate:()=>snapRefreshRate,summarizeFrameTrace:()=>summarizeFrameTrace,summarizeProbe:()=>summarizeProbe,takeHostLock:()=>takeHostLock,tiedPairs:()=>tiedPairs,validateWebBenchOptions:()=>validateWebBenchOptions,waitForHostLock:()=>waitForHostLock,webBenchFlags:()=>webBenchFlags,withDeadline:()=>withDeadline});function checkBudgets(e,n,t=[]){const r=e.median;const i=[];const s=[];const o=(d,h,p)=>{if(h==null)return;if(p==null)s.push(d);else if(p>h)i.push(`${d} ${p} > ${h}`)};o("droppedPct",n.droppedPct,e.droppedMin!=null?r?.droppedPct:null);const a=e.runs.filter(d=>!d.failed&&d.fps!=null);const c=t.some(d=>"click"in d||"press"in d||"type"in d);const u=a.map(d=>d.interactions==null||!d.inputCaptureComplete?null:d.worstInteractionMs??16);o("inputMs",n.inputMs,c&&u.length&&u.every(d=>d!=null)?Math.max(...u):null);const l=a.map(d=>Math.max(d.frameGapMaxMs??0,d.edgeSilenceMs??0));o("freezeMs",n.freezeMs,l.length?Math.max(...l):null);o("mainThreadPct",n.mainThreadPct,r?.mainThreadPct);o("jsHeapMb",n.jsHeapMb,r?.heapMb);return{meets:Boolean(r)&&i.length===0&&s.length===0,over:i,unknown:s}}function isSoftwareGpu(e){return/swiftshader|llvmpipe|softpipe|software|microsoft basic render/i.test(e)}function percentile(e,n){if(e.length===0)return null;const t=[...e].sort((i,s)=>i-s);const r=Math.ceil(n/100*t.length)-1;return t[Math.min(t.length-1,Math.max(0,r))]}function snapRefreshRate(e){for(const n of COMMON_RATES)if(Math.abs(e-n)/n<=.08)return n;return Math.max(1,Math.round(e))}function shuffled(e,n){let t=n>>>0;const r=()=>{t=t+1831565813>>>0;let s=t;s=Math.imul(s^s>>>15,s|1);s^=s+Math.imul(s^s>>>7,s|61);return((s^s>>>14)>>>0)/4294967296};const i=[...e];for(let s=i.length-1;s>0;s--){const o=Math.floor(r()*(s+1));[i[s],i[o]]=[i[o],i[s]]}return i}function caseUrl(e,n,t){const r=new URL(e);const i=n.path??t;if(i)r.pathname=i.startsWith("/")?i:`${r.pathname.replace(/\/$/,"")}/${i}`;for(const[s,o]of Object.entries(n.params??{}))r.searchParams.set(s,o);return r.toString()}function summarizeFrameTrace(e){const n=p=>e.find(m=>m.name===p&&m.ts!=null);const t=n("__buoy_bench_start");const r=n("__buoy_bench_end");if(!t||!r||r.ts<=t.ts)return null;if(t.pid!==r.pid)return null;const i=t.pid;const s={STATE_PRESENTED_ALL:0,STATE_PRESENTED_PARTIAL:1,STATE_DROPPED:2};const o=new Map;for(const p of e){if(p.name!=="PipelineReporter"||p.ph!=="b")continue;if(i!=null&&p.pid!==i)continue;if(p.ts==null||p.ts<t.ts||p.ts>r.ts)continue;const m=p.args?.frame_reporter;if(!m||m.frame_sequence==null)continue;const g=m.state;if(!FRAME_STATES.includes(g))continue;const w=`${m.layer_tree_host_id??""}:${m.frame_source??""}:${m.frame_sequence}`;const f=Boolean(m.affects_smoothness)&&g!=="STATE_PRESENTED_ALL";const b=o.get(w);if(!b)o.set(w,{state:g,fault:f});else{if(s[g]>s[b.state])b.state=g;b.fault=b.fault||f}}let a=0;let c=0;let u=0;let l=0;for(const p of o.values()){if(p.state==="STATE_PRESENTED_ALL")a++;else if(p.state==="STATE_PRESENTED_PARTIAL")c++;else u++;if(p.fault)l++}const d=a+c+u;if(d===0)return null;const h=(r.ts-t.ts)/1e6;return{full:a,partial:c,dropped:u,faults:l,shownFps:r1((a+c)/h),droppedPct:r1(l/d*100)}}function keyMatches(e,n){const t=e.split("+");const r=t[t.length-1];const i=new Set(t.slice(0,-1).map(a=>a.toLowerCase()));if(n.key!==r)return false;const s=r.toLowerCase();const o={ctrl:i.has("control")||s==="control",alt:i.has("alt")||s==="alt",meta:i.has("meta")||i.has("command")||s==="meta",shift:i.has("shift")||s==="shift"};if(Boolean(n.ctrl)!==o.ctrl||Boolean(n.alt)!==o.alt||Boolean(n.meta)!==o.meta)return false;if(!o.shift&&n.shift&&r.length!==1)return false;if(o.shift&&!n.shift)return false;return true}function mergeInteractions(e){const n=[];for(const t of e){const r=t.startTime+t.duration;const i=n.find(o=>o.interactionId===t.interactionId&&Math.abs(o.startTime+o.duration-r)<=8);if(!i){n.push({...t});continue}const s=i.startTime+i.duration;i.startTime=Math.min(i.startTime,t.startTime);i.processingStart=Math.min(i.processingStart,t.processingStart);i.processingEnd=Math.max(i.processingEnd,t.processingEnd);i.duration=Math.max(s,r)-i.startTime;if(t.processingEnd-t.processingStart>0)i.name=t.name}return n}function summarizeProbe(e,n){const{start:t,end:r}=e;const i=Math.max(1,r-t);const s=[];for(let k=1;k<e.frames.length;k++)s.push(e.frames[k]-e.frames[k-1]);const o=1e3/n;const a=percentile(s,95);let c=null;if(e.longTasks){let k=0;for(const T of e.longTasks){const A=Math.min(T.end,r)-Math.max(T.start,t);if(A>0)k+=A}c=r1(Math.min(100,k/i*100))}let u=null;let l=null;let d=null;let h=[];let p=0;if(e.loaf){let k=0;let T=0;let A=0;const I=new Map;for(const R of e.loaf){if(R.startTime>=t&&R.startTime<=r&&R.startTime+R.duration>r)p++;if(R.startTime<t||R.startTime+R.duration>r)continue;k+=R.blockingDuration;if(R.styleAndLayoutStart>R.startTime)T+=Math.max(0,R.startTime+R.duration-R.styleAndLayoutStart);for(const M of R.scripts){A+=M.forced;const S=I.get(M.name)??{ms:0,count:0};S.ms+=M.duration;S.count++;I.set(M.name,S)}}u=r1(k);l=r1(T);d=r1(A);h=[...I.entries()].map(([R,M])=>({name:R,ms:r1(M.ms),count:M.count})).sort((R,M)=>M.ms-R.ms).slice(0,5)}let m=null;if(e.shifts){let k=0;for(const T of e.shifts)if(!T.hadRecentInput&&T.startTime>=t&&T.startTime<=r)k+=T.value;m=Math.round(k*1e3)/1e3}let g=null;let w=null;if(e.events){const k=mergeInteractions(e.events.filter(T=>T.startTime>=t&&T.startTime<=r));g=new Set(k.map(T=>T.interactionId)).size;for(const T of k)if(!w||T.duration>w.duration)w=T}const f=w;const b=e.frames;const v=[...(e.clicks??[]).map(k=>k.t),...(e.keys??[]).map(k=>k.t)];const y=v.length?Math.max(...v):null;const _=y==null||b.filter(k=>k>y).length>=2;const $=b.length===0?i:Math.max(0,b[0]-t,r-b[b.length-1]);return{edgeSilenceMs:r1($),frameGapCount:s.length,inputCaptureComplete:_,resized:Boolean(e.resized),interactions:g,worstInteractionMs:f?r1(f.duration):null,worstInputDelayMs:f?r1(Math.max(0,f.processingStart-f.startTime)):null,worstProcessingMs:f?r1(Math.max(0,f.processingEnd-f.processingStart)):null,worstPresentationMs:f?r1(Math.max(0,f.startTime+f.duration-f.processingEnd)):null,fps:r1(e.frames.length/i*1e3),frameGapP95Ms:a==null?null:r1(a),frameGapMaxMs:s.length?r1(Math.max(...s)):null,longFrames:s.filter(k=>k>o*1.5).length,longTaskPct:c,loafBlockingMs:u,styleLayoutMs:l,forcedLayoutMs:d,topScripts:h,loafCutOff:p,layoutShift:m,domNodesStart:e.domStart,domNodesEnd:e.domEnd}}function cdpDeltas(e,n,t){const r=a=>a in e&&a in n?n[a]-e[a]:null;const i=a=>{const c=r(a);return c==null?null:r1(c*1e3)};const s=i("TaskDuration");const o=i("Timestamp")??t;return{mainThreadPct:s==null?null:r1(s/Math.max(1,o)*100),scriptMs:i("ScriptDuration"),styleMs:i("RecalcStyleDuration"),layoutMs:i("LayoutDuration"),layoutCount:r("LayoutCount"),styleCount:r("RecalcStyleCount"),heapMb:"JSHeapUsedSize"in n?r1(n.JSHeapUsedSize/(1024*1024)):null}}function webBenchFlags(e,n){const t=[];if(e.droppedPct!=null&&e.droppedPct>=5)t.push(`${e.droppedPct}% of frames dropped or partial`);if(e.fps!=null&&e.fps<n*.95)t.push("Low main-thread frame rate");if(e.frameGapCount&&e.longFrames/e.frameGapCount>=.02)t.push("Frequent long frames");const r=Math.max(e.frameGapMaxMs??0,e.edgeSilenceMs??0);if(r>=100)t.push(`Freeze of ${Math.round(r)} ms`);if(e.mainThreadPct!=null&&e.mainThreadPct>=80)t.push("Main thread near full");if(e.longTaskPct!=null&&e.longTaskPct>=20)t.push("Long tasks block the main thread");if(e.forcedLayoutMs!=null&&e.forcedLayoutMs>=50)t.push(`Forced layout in scripts (${Math.round(e.forcedLayoutMs)} ms)`);if(e.layoutShift!=null&&e.layoutShift>=.1)t.push(`Layout shifts (${e.layoutShift})`);if(e.worstInteractionMs!=null&&e.worstInteractionMs>=200){t.push(`Slow response to input (${Math.round(e.worstInteractionMs)} ms)`)}return t}function aggregateCase(e,n){const t=e.filter(c=>!c.failed&&c.fps!=null);const r=[...t].sort((c,u)=>(c.fps??0)-(u.fps??0));const i=t.filter(c=>c.droppedPct!=null).length;const s=t.length>0&&i===t.length;const o=s?[...t].sort((c,u)=>c.droppedPct-u.droppedPct):r;const a=o.length?o[Math.floor((o.length-1)/2)]:null;return{caseName:e[0]?.caseName??"",cpu:e[0]?.cpu??1,validRuns:t.length,plannedRuns:e.length,isBaseline:false,deltaDroppedPct:null,tracedRuns:i,...(()=>{const c=s?t.map(l=>l.droppedPct):[];const u=t.map(l=>l.worstInteractionMs).filter(l=>l!=null);return{droppedMin:c.length?Math.min(...c):null,droppedMax:c.length?Math.max(...c):null,inputMin:u.length?Math.min(...u):null,inputMax:u.length?Math.max(...u):null}})(),runs:e,median:a,fpsMin:r.length?r[0].fps:null,fpsMax:r.length?r[r.length-1].fps:null,flags:a?webBenchFlags(s?a:{...a,droppedPct:null},n):[]}}async function loadChromium(e){const n=(0,import_node_module.createRequire)((0,import_node_path11.join)(e,"noop.js"));for(const t of["playwright","playwright-core"]){let r;try{r=n.resolve(t)}catch{continue}const i=await import((0,import_node_url.pathToFileURL)(r).href);const s=i.chromium??i.default?.chromium;if(s)return s}throw new Error(`${PLAYWRIGHT_MISSING}
|
|
383
|
-
(Searched from ${e}. Pass projectRoot to look elsewhere.)`)}async function withDeadline(e,n,t){let r;const i=new Promise(s=>{r=setTimeout(()=>s("timeout"),n)});try{const s=await Promise.race([e,i]);if(s==="timeout"){e.catch(()=>{});return await t()}return s}finally{clearTimeout(r)}}function gitCommit(e){try{return(0,import_node_child_process13.execFileSync)("git",["rev-parse","HEAD"],{cwd:e,stdio:["ignore","pipe","ignore"],timeout:3e3}).toString().trim()}catch{return null}}function gitDirty(e){try{const n=(0,import_node_child_process13.execFileSync)("git",["status","--porcelain"],{cwd:e,stdio:["ignore","pipe","ignore"],timeout:5e3});return n.toString().trim().length>0}catch{return null}}async function closeWithin(e,n){if(!e)return true;return withDeadline(e.close().then(()=>true,()=>false),n,async()=>false)}function validateWebBenchOptions(e){if(!e.cases?.length)throw new Error("Give at least one case.");const n=new Set;for(const o of e.cases){if(!o.name?.trim())throw new Error("Every case needs a name.");if(n.has(o.name))throw new Error(`Two cases are named "${o.name}". Give each case its own name.`);n.add(o.name)}const t=(o,a,c,u)=>{if(o==null)return;if(!Number.isInteger(o)||o<c||o>u)throw new Error(`${a} must be a whole number from ${c} to ${u}.`)};const r=(o,a,c)=>{if(o==null)return;if(!Number.isFinite(o)||o<c)throw new Error(`${a} must be a number of at least ${c}.`)};const i=(o,a,c,u)=>{if(o==null)return;if(!Number.isFinite(o)||o<c||o>u)throw new Error(`${a} must be from ${c} to ${u}.`)};t(e.runsPerCase,"runsPerCase",1,10);i(e.durationMs,"durationMs",500,12e4);i(e.settleMs,"settleMs",0,6e4);i(e.refreshHz,"refreshHz",1,500);const s=e.cpuSlowdown??[];for(const o of s)i(o,"each cpuSlowdown rate",1,20);if(new Set(s).size!==s.length)throw new Error("cpuSlowdown has the same rate twice.");if(e.viewport){t(e.viewport.width,"viewport.width",200,8e3);t(e.viewport.height,"viewport.height",200,8e3);i(e.viewport.deviceScaleFactor,"viewport.deviceScaleFactor",.5,4)}t(e.extraRoundsWhenClose,"extraRoundsWhenClose",0,10);i(e.maxBatchMs,"maxBatchMs",1e4,6*60*6e4);for(const[o,a]of Object.entries(e.budgets??{}))i(a,`budgets.${o}`,0,1e9);for(const o of e.steps??[]){if("wait"in o)i(o.wait,"a wait step",0,6e4);if("scroll"in o)i(o.scroll,"a scroll step",-1e5,1e5)}new URL(e.url)}function oneLine(e){return e.replace(/\u001b\[[0-9;]*m/g,"").split("\n")[0].trim().slice(0,160)}async function locateStepTargets(e,n){const t=new Map;for(const r of n){if("expect"in r)continue;const i="click"in r?r.click:"type"in r?r.type.selector:null;if(!i||t.has(i))continue;const s=await e.$(i);const o=s?await s.boundingBox():null;if(!o)throw new Error(`step target ${i} isn't on the page (or isn't visible)`);t.set(i,{x:o.x+o.width/2,y:o.y+o.height/2})}return t}async function runSteps(e,n,t){for(const r of n){if("click"in r){const i=t.get(r.click);await e.mouse.click(i.x,i.y)}else if("press"in r)await e.keyboard.press(r.press);else if("type"in r){const i=t.get(r.type.selector);await e.mouse.click(i.x,i.y);await e.keyboard.type(r.type.text)}else if("scroll"in r)await e.mouse.wheel(0,r.scroll);else if("wait"in r)await sleep2(r.wait)}}function missedInput(e,n,t=[]){const r=[...n].sort((l,d)=>l.t-d.t);const i=[...t].sort((l,d)=>l.t-d.t);let s=0;let o=0;let a=-Infinity;const c=l=>{while(s<r.length){const d=r[s++];if(d.t>=a&&d.hit.includes(l)){a=d.t;return true}}return false};const u=l=>{while(o<i.length){const d=i[o++];if(d.t>=a&&keyMatches(l,d)){a=d.t;return true}}return false};for(const[l,d]of e.entries()){if("click"in d&&!c(d.click)){return`step ${l+1} (click ${d.click}) has no real click on its target, in order (moved, covered, or ignored)`}if("type"in d){if(!c(d.type.selector))return`step ${l+1} (type into ${d.type.selector}) has no real click on its target`;for(const h of d.type.text){if(!u(h))return`step ${l+1} (type "${d.type.text}") didn't deliver the key "${h}"`}}if("press"in d&&!u(d.press))return`step ${l+1} (press ${d.press}) didn't deliver that key`}return null}async function expectsAlreadyTrue(e,n){for(const t of n){if(!("expect"in t))continue;const{selector:r,text:i}=t.expect;const s=await e.evaluate(`(() => { const n = document.querySelector(${JSON.stringify(r)}); if (!n) return false; ${i==null?"return true;":`return (n.textContent || "").includes(${JSON.stringify(i)});`} })()`);if(s)return i==null?r:`${r} contains "${i}"`}return null}async function checkTargetsStill(e,n){for(const[t,r]of n){const i=await e.$(t);const s=i?await i.boundingBox():null;if(!s)return`step target ${t} was gone after the run`;const o=s.x+s.width/2;const a=s.y+s.height/2;if(Math.abs(o-r.x)>4||Math.abs(a-r.y)>4){return`step target ${t} moved during the run, so a click may have missed it`}}return null}function expectFailureFrom(e){for(const n of e){if(!n.found)return`expected ${n.selector} at the end of the run, but it isn't there`;const t=n.matched??(n.text==null||(n.content??"").includes(n.text));if(!t){return`expected ${n.selector} to contain "${n.text}" at the end of the run, got "${(n.content??"").slice(0,60)}"`}}return null}async function readMetrics(e){const{metrics:n}=await e.send("Performance.getMetrics");return Object.fromEntries(n.map(t=>[t.name,t.value]))}async function runWebBench(e,n=()=>{}){validateWebBenchOptions(e);const t=await waitForHostLock(e.lockWaitMs??20*6e4,n);const r={browserLeftRunning:false};try{return await runWebBenchLocked(e,n,r)}finally{t(r.browserLeftRunning)}}async function waitForHostLock(e,n=()=>{},t=2e3){const r=Date.now()+Math.max(0,e);let i=false;for(;;){try{return takeHostLock()}catch(s){const o=s?.message??String(s);const a=/Another web benchmark|already running/.test(o);if(!a||Date.now()+t>r)throw s;if(!i){n("another web benchmark is running; waiting for it to finish");i=true}await new Promise(c=>setTimeout(c,t))}}}function takeHostLock(){if(lockedHere){throw new Error("A web benchmark is already running in this process (or left a stuck browser). Wait, or restart the MCP server.")}const e=`${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;const n=JSON.stringify({pid:process.pid,token:e,startedAt:new Date().toISOString()});const t=()=>{const s=`${LOCK_FILE}.${e.replace(/[^\w]/g,"")}.tmp`;try{(0,import_node_fs10.writeFileSync)(s,n);(0,import_node_fs10.linkSync)(s,LOCK_FILE);return true}catch{return false}finally{try{(0,import_node_fs10.unlinkSync)(s)}catch{}}};const r=()=>{try{return JSON.parse((0,import_node_fs10.readFileSync)(LOCK_FILE,"utf8"))}catch{return null}};const i=s=>{if(!s)return false;try{process.kill(s,0);return true}catch{return false}};if(!t()){const s=r();if(!s)throw new Error("Another web benchmark is starting. Wait for it to finish.");if(i(s.pid)){throw new Error(`Another web benchmark is running (pid ${s.pid}, since ${s.startedAt}). Two at once would skew both; wait for it to finish.`)}const o=`${LOCK_FILE}.cleanup`;let a=null;try{if(Date.now()-(0,import_node_fs10.statSync)(o).mtimeMs>3e4){const c=`${o}.${e.replace(/[^\w]/g,"")}.old`;(0,import_node_fs10.renameSync)(o,c);if(Date.now()-(0,import_node_fs10.statSync)(c).mtimeMs>3e4)(0,import_node_fs10.unlinkSync)(c);else{try{(0,import_node_fs10.linkSync)(c,o)}catch{}(0,import_node_fs10.unlinkSync)(c)}}}catch{}try{a=(0,import_node_fs10.openSync)(o,"wx")}catch{throw new Error("Another web benchmark is clearing an old lock. Try again in a moment.")}try{const c=r();if(c?.token===s.token)(0,import_node_fs10.unlinkSync)(LOCK_FILE);if(!t())throw new Error("Another web benchmark just started. Wait for it to finish.")}finally{(0,import_node_fs10.closeSync)(a);try{(0,import_node_fs10.unlinkSync)(o)}catch{}}}lockedHere=true;return(s=false)=>{if(s)return;lockedHere=false;if(r()?.token===e){try{(0,import_node_fs10.unlinkSync)(LOCK_FILE)}catch{}}}}async function runWebBenchLocked(e,n,t){const r=e.runsPerCase??3;const i=Math.max(500,e.durationMs??5e3);const s=Math.max(0,e.settleMs??1e3);const o=e.frameTrace!==false;const a=(e.cpuSlowdown?.length?e.cpuSlowdown:[1]).map(S=>Math.max(1,S));let c=e.refreshHz??60;const u={width:e.viewport?.width??1280,height:e.viewport?.height??800,deviceScaleFactor:e.viewport?.deviceScaleFactor??1};const l=[];const d=[];let h=null;if(r<2)l.push("runsPerCase=1 gives no spread; use 3 or more before choosing.");const p=await loadChromium(e.projectRoot??process.cwd());const m=await p.launch({headless:!e.headed,args:["--enable-gpu"]});const g=[];const w=[];const f=Date.now();const b=new Date(f).toISOString();const v=e.maxBatchMs??30*6e4;let y=false;let _=false;const $={commit:gitCommit(e.projectRoot??process.cwd()),dirty:gitDirty(e.projectRoot??process.cwd())};try{const S={viewport:{width:u.width,height:u.height},deviceScaleFactor:u.deviceScaleFactor};const x=await withDeadline(m.newContext(S),3e4,async()=>{t.browserLeftRunning=true;throw new Error("Chromium didn't open a page in 30 s. Restart the MCP server and try again.")});const E=3e4+15e3+s+i+6e4;const j=async(C,O,D,z)=>{const L={};return withDeadline(B(L,C,O,D,z),E,async()=>{L.cancelled=true;if(!L.ctx)y=true;else if(!await closeWithin(L.ctx,1e4))y=true;return{...P(C.name,O,D),failed:`run took over ${Math.round(E/1e3)} s (the page may be stuck in a loop)`}})};const P=(C,O,D)=>({caseName:C,cpu:O,round:D,fps:null,frameGapP95Ms:null,frameGapMaxMs:null,longFrames:0,longTaskPct:null,loafBlockingMs:null,styleLayoutMs:null,forcedLayoutMs:null,topScripts:[],layoutShift:null,domNodesStart:null,domNodesEnd:null,mainThreadPct:null,scriptMs:null,styleMs:null,layoutMs:null,layoutCount:null,styleCount:null,heapMb:null,pageErrors:[]});const B=async(C,O,D,z,L)=>{const J=await m.newContext(S);C.ctx=J;if(C.cancelled){await closeWithin(J,1e4);throw new Error("run was cancelled during setup")}const N=await J.newPage();const K=[];N.on("pageerror",U=>K.push(String(U?.message??U)));const W={...P(O.name,D,z),pageErrors:K};try{const U=await J.newCDPSession(N);await U.send("Performance.enable",{timeDomain:"timeTicks"});if(D>1)await U.send("Emulation.setCPUThrottlingRate",{rate:D});const te=await N.goto(caseUrl(e.url,O,e.path),{waitUntil:"load",timeout:3e4});if(te&&te.status()>=400)return{...W,failed:`HTTP ${te.status()}`};if(e.readySelector)await N.waitForSelector(e.readySelector,{state:"attached",timeout:15e3});await sleep2(s);const oe=L||o;if(oe){await U.send("Tracing.start",{transferMode:"ReturnAsStream",categories:(L?FULL_TRACE_CATEGORIES:FRAME_TRACE_CATEGORIES).join(",")})}const ne=e.steps?.length?await locateStepTargets(N,e.steps):new Map;if(e.steps?.length){const X=await expectsAlreadyTrue(N,e.steps);if(X)return{...W,failed:`expect ${X} already held before the steps, so it can't prove they worked`};const Q=[...ne.keys()];const Y=e.steps.flatMap(Z=>"expect"in Z?[Z.expect]:[]);await N.evaluate(`window.__buoyBenchClickTargets = ${JSON.stringify(Q)}; window.__buoyBenchExpects = ${JSON.stringify(Y)}; true`)}const re=await readMetrics(U);await N.evaluate(START_PROBE_JS);const ae=Date.now();if(e.steps?.length)await runSteps(N,e.steps,ne);const ce=i-(Date.now()-ae);if(ce>0)await sleep2(ce);await N.evaluate(END_PROBE_JS);const ie=await readMetrics(U);const le=Date.now()-ae;const V=await N.evaluate(COLLECT_PROBE_JS);let H=null;if(oe){const X=new Promise(G=>U.on("Tracing.tracingComplete",ee=>G(ee.stream)));await U.send("Tracing.end");const Q=await X;const Y=L?(0,import_node_fs10.openSync)(L,"w"):null;const Z=[];let se=0;try{for(;;){const G=await U.send("IO.read",{handle:Q});const ee=G.base64Encoded?Buffer.from(G.data,"base64").toString("utf8"):G.data;se+=ee.length;if(Y!=null)(0,import_node_fs10.writeSync)(Y,ee);if(se<=MAX_TRACE_CHARS)Z.push(ee);else Z.length=0;if(G.eof)break}}finally{await U.send("IO.close",{handle:Q}).catch(()=>{});if(Y!=null)(0,import_node_fs10.closeSync)(Y)}if(L)d.push(L);if(se>MAX_TRACE_CHARS){l.push(`Trace for ${O.name} was over ${Math.round(MAX_TRACE_CHARS/1e6)} MB, so its frames weren't counted. A page that busy shows its problem in the table already.`)}else{try{const G=JSON.parse(Z.join(""));H=summarizeFrameTrace(Array.isArray(G)?G:G.traceEvents??[])}catch{H=null}}}if(!V)return{...W,failed:"probe returned nothing (page navigated away?)"};if(V.hidden)return{...W,failed:"page was hidden during the run"};if(V.resized)return{...W,failed:"the window size or zoom changed during the run"};if(K.length&&!e.allowPageErrors){return{...W,failed:`page error: ${oneLine(K[0])}`}}if(e.steps?.length){const X=missedInput(e.steps,V.clicks??[],V.keys??[]);if(X)return{...W,failed:X};const Q=expectFailureFrom(V.expectResults??[]);if(Q)return{...W,failed:Q};const Y=await checkTargetsStill(N,ne);if(Y)return{...W,failed:Y}}const ue="Timestamp"in re&&"Timestamp"in ie?r1((ie.Timestamp-re.Timestamp)*1e3):null;return{...W,...summarizeProbe(V,c),...cdpDeltas(re,ie,le),probeSpanMs:r1(V.end-V.start),cdpSpanMs:ue,shownFps:H?.shownFps??null,droppedFrames:H?.faults??null,frameCounts:H?{full:H.full,partial:H.partial,dropped:H.dropped,faults:H.faults}:null,droppedPct:H?.droppedPct??null}}catch(U){return{...W,failed:oneLine(U?.message??String(U))}}finally{await closeWithin(N,5e3);if(!await closeWithin(J,1e4))y=true}};{const C=await withDeadline(x.newPage(),15e3,async()=>{throw new Error("Chromium didn't open the GPU check page in 15 s.")});try{h=await withDeadline(C.evaluate(GPU_RENDERER_JS),5e3,async()=>null)??null}catch{h=null}finally{await closeWithin(C,5e3)}if(h)n(`GPU ${h}`);if(h&&isSoftwareGpu(h)){l.push(`Chrome is drawing with a software GPU (${h}). Canvas, WebGL and Skia pages run several times slower than on a real screen, so their numbers mean little. Try headed: true, or a machine with a GPU.`)}}if(e.refreshHz==null){const C=await withDeadline(x.newPage(),15e3,async()=>{throw new Error("Chromium didn't open the calibration page in 15 s.")});try{await withDeadline(C.goto("about:blank"),15e3,async()=>null);const O=await withDeadline(C.evaluate(MEASURE_REFRESH_JS),5e3,async()=>{throw new Error("idle rate check timed out")});c=snapRefreshRate(O);n(`idle frame rate ${O.toFixed(1)} \u2192 ${c} Hz`)}catch{l.push("Couldn't measure the idle frame rate; frame budgets assume 60 Hz.")}finally{await closeWithin(C,5e3)}}n("warmup load");await j(e.cases[0],1,-1);const F=async(C,O,D,z)=>{if(y){g.push({...P(C.name,O,D),failed:"an earlier run left the browser stuck; batch stopped"});return}if(Date.now()-f>v){g.push({...P(C.name,O,D),failed:"batch time limit reached; run skipped"});return}n(z);w.push({cpu:O,round:D,caseName:C.name});g.push(await j(C,O,D))};for(const C of a){for(let O=0;O<r;O++){const D=shuffled(e.cases,2654435769^O*7919+C);for(const z of D)await F(z,C,O,`cpu ${C}x \xB7 round ${O+1}/${r} \xB7 ${z.name}`)}for(let O=0;O<(e.extraRoundsWhenClose??0);O++){const D=e.cases.map(N=>aggregateCase(g.filter(K=>K.cpu===C&&K.caseName===N.name),c));for(const N of D)N.control=e.cases.find(K=>K.name===N.caseName)?.control===true;const z=new Set([...tiedPairs(D).flat(),...D.filter(N=>!N.control&&N.validRuns<2&&N.plannedRuns>0).map(N=>N.caseName)]);if(z.size===0)break;const L=r+O;const J=shuffled(e.cases.filter(N=>z.has(N.name)),20973^L*7919+C);for(const N of J)await F(N,C,L,`cpu ${C}x \xB7 extra round ${O+1} (close call) \xB7 ${N.name}`)}}if(e.traceDir){(0,import_node_fs10.mkdirSync)(e.traceDir,{recursive:true});for(const[C,O]of e.cases.entries()){const D=(0,import_node_path11.join)(e.traceDir,`${String(C+1).padStart(2,"0")}-${O.name.replace(/[^\w.-]+/g,"_")}.json`);if(y||Date.now()-f>v){l.push(`Trace run for ${O.name} skipped (batch time limit or a stuck browser).`);continue}n(`trace \xB7 ${O.name}`);const z=await j(O,a[0],-1,D);if(z.failed)l.push(`Trace run for ${O.name} failed: ${z.failed}`)}}await closeWithin(x,1e4)}finally{const S=await closeWithin(m,15e3);t.browserLeftRunning=!S;if(!S){_=true;l.push("Chromium didn't close in 15 s and may still be running. The benchmark lock stays held; restart the MCP server before the next batch.")}}const k=[];for(const S of a){for(const x of e.cases){k.push(aggregateCase(g.filter(E=>E.cpu===S&&E.caseName===x.name),c))}}for(const S of k)S.control=e.cases.find(x=>x.name===S.caseName)?.control===true;for(const S of a){const x=k.filter(B=>B.cpu===S);const E=x.find(B=>!B.control);if(!E)continue;E.isBaseline=true;const j=B=>B.droppedMin!=null?B.median?.droppedPct??null:null;const P=j(E);for(const B of x.filter(F=>F!==E&&!F.control)){const F=j(B);B.deltaDroppedPct=P!=null&&F!=null?r1(F-P):null}}if(e.allowPageErrors&&g.some(S=>S.pageErrors.length)){l.push("Some runs threw page errors (kept because allowPageErrors is on).")}if(y)l.push("A browser context wouldn't close, so the batch stopped early. Restart and run again.");if(e.budgets)for(const S of k)S.budget=checkBudgets(S,e.budgets,e.steps??[]);const T=k.filter(S=>S.median).length;const A=k.every(S=>S.validRuns===S.plannedRuns);const I=T===0?"failed":T<k.length||!A?"partial":"ok";const R=k.filter(S=>S.median&&S.validRuns>0&&S.validRuns<S.plannedRuns);for(const S of R){const x=Array.from(new Set(S.runs.filter(E=>E.failed).map(E=>E.failed)));l.push(`${S.caseName} (CPU ${S.cpu}x): ${S.plannedRuns-S.validRuns} of ${S.plannedRuns} runs failed: ${x.join("; ")}`)}for(const S of k){const x=S.median;if(x?.probeSpanMs&&x.cdpSpanMs&&Math.abs(x.cdpSpanMs-x.probeSpanMs)/x.probeSpanMs>.15){l.push(`${S.caseName} (CPU ${S.cpu}x): Chrome's counters cover ${Math.round(x.cdpSpanMs)} ms but frames cover ${Math.round(x.probeSpanMs)} ms, so its cost columns include extra time.`)}if(x?.probeSpanMs!=null&&x.probeSpanMs<i*.8){l.push(`${S.caseName} (CPU ${S.cpu}x) recorded ${Math.round(x.probeSpanMs)} ms, not the ${i} ms asked for.`)}}const M={status:I,hasSteps:Boolean(e.steps?.length),browserLeftRunning:_,replay:{startedAt:b,...$,runOrder:w},url:e.url,browser:`Chromium ${m.version()}${e.headed?"":" (headless)"}`,gpu:h,viewport:u,refreshHz:c,durationMs:i,runsPerCase:r,results:k,traces:d,warnings:l};if(e.outFile){try{(0,import_node_fs10.writeFileSync)(e.outFile,JSON.stringify({options:e,result:M},null,2))}catch(S){M.warnings.push(`Couldn't write outFile ${e.outFile}: ${oneLine(S?.message??String(S))}`)}}return M}function tiedPairs(e){const n=e.filter(s=>!s.control&&s.median&&s.validRuns>1);const t=n.filter(s=>s.droppedMin!=null);const r=[];if(t.length>=2&&t.length===n.length){const s=[...t].sort((o,a)=>o.median.droppedPct-a.median.droppedPct);for(let o=1;o<s.length;o++){const[a,c]=[s[o-1],s[o]];const u=c.median.droppedPct-a.median.droppedPct<=MIN_DROPPED_GAP_PP;if(c.droppedMin<=a.droppedMax||u)r.push([a.caseName,c.caseName])}return r}if(t.length>0)return r;const i=n.filter(s=>s.median.fps!=null).sort((s,o)=>o.median.fps-s.median.fps);for(let s=1;s<i.length;s++){const[o,a]=[i[s-1],i[s]];const c=o.median.fps-a.median.fps<=MIN_FPS_GAP;if((a.fpsMax??0)>=(o.fpsMin??0)||c)r.push([o.caseName,a.caseName])}return r}function closeCall(e){const n=e.filter(a=>!a.control&&a.median);const t=[];const r=n.filter(a=>a.validRuns<2);if(r.length)t.push(`**Too few runs to rank:** ${r.map(a=>a.caseName).join(", ")} (need 2 or more valid runs).`);const i=n.filter(a=>a.validRuns>1);const s=i.filter(a=>a.droppedMin!=null);if(s.length>0&&s.length<i.length){t.push(`**Not enough traced runs to compare smoothness:** ${i.filter(a=>!s.includes(a)).map(a=>`${a.caseName} (${a.tracedRuns}/${a.validRuns} traced)`).join(", ")}.`);return t.join("\n")}const o=new Map(i.map(a=>[a.caseName,a]));for(const[a,c]of tiedPairs(e)){const u=o.get(a);const l=o.get(c);t.push(s.length?`**Too close to call:** ${a} (${u.droppedMin}\u2013${u.droppedMax}% dropped) and ${c} (${l.droppedMin}\u2013${l.droppedMax}%) overlap or sit within ${MIN_DROPPED_GAP_PP} pp. No clear winner between them; more runs may separate them.`:`**Too close to call:** ${a} and ${c} overlap or sit within ${MIN_FPS_GAP} FPS. No clear winner between them; more runs may separate them.`)}return t.length?t.join("\n"):null}function formatWebBenchMarkdown(e){const n=(a,c=1)=>a==null?"\u2014":a.toFixed(c);const t=[];t.push(`### Web benchmark \xB7 ${e.url}`);t.push(`${e.browser}${e.gpu?` \xB7 GPU: ${e.gpu}${isSoftwareGpu(e.gpu)?" \u26A0\uFE0F software":""}`:""} \xB7 ${e.viewport.width}\xD7${e.viewport.height} @${e.viewport.deviceScaleFactor}x \xB7 ${e.runsPerCase} runs${e.results.some(a=>a.plannedRuns>e.runsPerCase)?" (more for close calls)":""} \xD7 ${e.durationMs/1e3}s per case, fresh browser context each run, case order shuffled each round.`);const r=e.results.map(a=>a.median?.probeSpanMs).filter(a=>a!=null);const i=e.results.map(a=>a.median?.cdpSpanMs).filter(a=>a!=null);const s=a=>`${(Math.min(...a)/1e3).toFixed(2)}\u2013${(Math.max(...a)/1e3).toFixed(2)} s`;if(r.length){t.push(`Recorded: frames over ${s(r)}${i.length?`; cost columns (Chrome's counters) over ${s(i)}`:""}, not the requested time.`)}if(e.replay?.dirty)t.push(`Note: the project had uncommitted changes, so commit ${e.replay.commit?.slice(0,10)??"?"} alone doesn't describe the code that ran.`);t.push("");t.push(`**How to read this.** Dropped % is the smoothness number: frames Chrome dropped or only partly produced that it says hurt smoothness, as a share of the frames it wanted, from its own verdicts in a trace. Rank on it first, and only across variants doing the same work. Shown FPS counts frames Chrome produced (headless Chrome displays nothing), so an animation that changes less often needs fewer; don't compare it across variants that update at different rates. Main-thread FPS and frame gaps come from requestAnimationFrame. Main thread % is Chrome's task time for the run. Desktop numbers, even with CPU slowdown, don't stand in for a real phone's GPU, memory or heat.`);const o=Array.from(new Set(e.results.map(a=>a.cpu)));for(const a of o){t.push("");t.push(a===1?`#### No CPU slowdown`:`#### CPU slowed ${a}x`);t.push("");t.push(`| Case | Runs | Shown FPS | Dropped % | Main-thread FPS (range) | p95 gap ms | Worst gap ms | Main thread % | Script ms | Style ms | Layout ms | Layouts | DOM nodes | JS heap MB | Flags |`);t.push(`|------|-----:|----------:|----------:|------------------------:|-----------:|-------------:|--------------:|----------:|---------:|----------:|--------:|----------:|--------:|-------|`);for(const h of e.results.filter(p=>p.cpu===a)){const p=h.median;if(!p){const w=h.runs.find(f=>f.failed)?.failed??"no valid runs";t.push(`| ${h.caseName} | 0/${h.plannedRuns} | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u274C FAILED (${w}) |`);continue}const m=h.fpsMin!=null&&h.fpsMax!=null&&h.validRuns>1?` (${n(h.fpsMin)}\u2013${n(h.fpsMax)})`:"";const g=h.flags.length?`\u26A0\uFE0F ${h.flags.join("; ")}`:"no flags";t.push(`| ${h.isBaseline?`${h.caseName} (baseline)`:h.control?`${h.caseName} (control)`:h.caseName} | ${h.validRuns}/${h.plannedRuns} | ${n(p.shownFps)} | ${h.droppedMin==null&&h.tracedRuns>0?`\u2014 (${h.tracedRuns}/${h.validRuns} traced)`:n(h.droppedMin==null?null:p.droppedPct)}${h.droppedMin!=null&&h.validRuns>1?` [${h.droppedMin}\u2013${h.droppedMax}]`:""}${h.deltaDroppedPct!=null?` (${h.deltaDroppedPct>0?"+":""}${h.deltaDroppedPct} pp)`:""} | ${n(p.fps)}${m} | ${n(p.frameGapP95Ms)} | ${n(p.frameGapMaxMs)} | ${n(p.mainThreadPct)} | ${n(p.scriptMs,0)} | ${n(p.styleMs,0)} | ${n(p.layoutMs,0)} | ${n(p.layoutCount,0)} | ${n(p.domNodesEnd,0)} | ${n(p.heapMb)} | ${g} |`)}const c=closeCall(e.results.filter(h=>h.cpu===a));if(c){t.push("");t.push(c)}const u=e.results.filter(h=>h.cpu===a&&h.budget);if(u.length){t.push("");t.push(`Budget:`);for(const h of u){const p=h.budget;const m=[...p.over,...p.unknown.map(w=>`${w} not measured`)].join("; ");const g=h.control?`${h.caseName} (control)`:h.caseName;t.push(`- **${g}**: ${p.meets?"meets every limit":`misses (${m||"no result"})`}`)}}const l=e.results.filter(h=>h.cpu===a&&h.median?.interactions!=null&&(e.hasSteps||h.median.interactions>0)).map(h=>{const p=h.median;const m=h.inputMin!=null&&h.inputMax!=null?` \xB7 slowest across all runs ${h.inputMax} ms (range ${h.inputMin}\u2013${h.inputMax})`:"";const g=h.runs.filter(f=>!f.failed&&f.fps!=null&&f.inputCaptureComplete===false).length;const w=g?` \xB7 \u26A0\uFE0F timing incomplete in ${g} run(s): the last input's paint came after the run ended, so its time is unknown (leave more time after the last step)`:"";if(!p.interactions)return`- **${h.caseName}**: middle run had no input entry (inputs under 16 ms aren't reported)${m}${w}`;return`- **${h.caseName}**: middle run: ${p.interactions} reported (16 ms or more), slowest ${p.worstInteractionMs} ms (waiting ${p.worstInputDelayMs} \xB7 handlers ${p.worstProcessingMs} \xB7 to paint ${p.worstPresentationMs})${m}${w}`});if(l.length){t.push("");t.push(`Input response (scripted steps, Event Timing). Inputs under 16 ms aren't reported. Under 200 ms is good.`);t.push(...l)}const d=e.results.filter(h=>h.cpu===a&&h.median&&h.median.topScripts.length).map(h=>`- **${h.caseName}**: ${h.median.topScripts.slice(0,3).map(p=>`${p.name} ${p.ms} ms`).join(", ")}`);if(d.length){t.push("");t.push(`Scripts in slow frames (Long Animation Frames; frames that ran past the end of a run are left out):`);t.push(...d)}}if(e.traces.length){t.push("");t.push(`Chrome traces (open in DevTools \u2192 Performance \u2192 Load profile): ${e.traces.join(", ")}`)}if(e.warnings.length){t.push("");t.push(...e.warnings.map(a=>`\u26A0\uFE0F ${a}`))}return t.join("\n")}var import_node_module,import_node_child_process13,import_node_path11,import_node_fs10,import_node_os8,import_node_url,r1,GPU_RENDERER_JS,COMMON_RATES,FRAME_STATES,PLAYWRIGHT_MISSING,FRAME_TRACE_CATEGORIES,FULL_TRACE_CATEGORIES,MAX_TRACE_CHARS,sleep2,LOCK_FILE,lockedHere,MIN_DROPPED_GAP_PP,MIN_FPS_GAP;var init_webBench=__esm({"src/webBench/webBench.ts"(){"use strict";import_node_module=require("module");import_node_child_process13=require("child_process");import_node_path11=require("path");import_node_fs10=require("fs");import_node_os8=require("os");import_node_url=require("url");init_inPageProbe();r1=e=>Math.round(e*10)/10;GPU_RENDERER_JS=`(() => {
|
|
384
|
-
try {
|
|
385
|
-
const gl = document.createElement("canvas").getContext("webgl2") || document.createElement("canvas").getContext("webgl");
|
|
386
|
-
if (!gl) return null;
|
|
387
|
-
const ext = gl.getExtension("WEBGL_debug_renderer_info");
|
|
388
|
-
return String(gl.getParameter(ext ? ext.UNMASKED_RENDERER_WEBGL : gl.RENDERER));
|
|
389
|
-
} catch { return null; }
|
|
390
|
-
})()`;COMMON_RATES=[30,60,75,90,120,144,165,240];FRAME_STATES=["STATE_PRESENTED_ALL","STATE_PRESENTED_PARTIAL","STATE_DROPPED"];PLAYWRIGHT_MISSING="Playwright isn't installed in this project. Install it, then run again:\n npm i -D playwright && npx playwright install chromium";FRAME_TRACE_CATEGORIES=["disabled-by-default-devtools.timeline.frame","blink.user_timing"];FULL_TRACE_CATEGORIES=["devtools.timeline","disabled-by-default-devtools.timeline","disabled-by-default-devtools.timeline.frame","blink.user_timing","loading","latencyInfo","v8.execute"];MAX_TRACE_CHARS=15e7;sleep2=e=>new Promise(n=>setTimeout(n,e));LOCK_FILE=(0,import_node_path11.join)((0,import_node_os8.tmpdir)(),"buoy-web-bench.lock");lockedHere=false;MIN_DROPPED_GAP_PP=1.5;MIN_FPS_GAP=2}});function nextLoad(e,n){const t=Math.max(e+1,e*n);const r=Math.pow(10,Math.max(0,Math.floor(Math.log10(t))-1));return Math.ceil(t/r)*r}function median(e){if(!e.length)return null;const n=[...e].sort((r,i)=>r-i);const t=Math.floor(n.length/2);return n.length%2?n[t]:Math.round((n[t-1]+n[t])/2)}function bracketResolved(e,n,t){if(n-e<=1)return true;if(e<=0)return false;return(n-e)/e<=t/100}async function rampOnce(e,n){const t=[];const r=(u,l,d,h)=>({status:u,stopReason:l,highestPass:d?{load:d.load,fps:d.fps??0}:null,lowestMiss:h?{load:h.load,fps:h.fps??0}:null,resolved:u==="below_one"||u==="bracketed"&&!!d&&!!h&&bracketResolved(d.load,h.load,n.precisionPct),steps:t});const i=(u,l,d)=>r("invalid",u.fps==null?"measurement_failed":"page_error",l,d);const s=async(u,l=false)=>{const d=await e(u);if(l)d.confirm=true;t.push(d);return d};let o=null;let a=null;let c=await s(n.start);if(!c.valid)return i(c,null,null);if(c.pass)o=c;else{a=c;let u=n.start;while(!o){if(u<=1)return r("below_one","performance",null,a);if(!n.timeLeft())return r("lower_bound","deadline",null,a);u=Math.max(1,Math.floor(u/2));c=await s(u);if(!c.valid)return i(c,null,a);if(c.pass)o=c;else a=c}}while(!a||a.load<=o.load){if(o.load>=n.max)return r("lower_bound","max",o,null);if(!n.timeLeft())return r("lower_bound","deadline",o,null);c=await s(Math.min(n.max,nextLoad(o.load,n.growth)));if(!c.valid)return i(c,o,null);if(c.pass){o=c;continue}if(!n.timeLeft())return r("bracketed","performance",o,c);const u=await s(c.load,true);if(!u.valid)return i(u,o,null);if(u.pass)o=u;else a=u}while(!bracketResolved(o.load,a.load,n.precisionPct)&&n.timeLeft()){const u=Math.round((o.load+a.load)/2);if(u<=o.load||u>=a.load)break;c=await s(u);if(!c.valid)break;if(c.pass)o=c;else a=c}return r("bracketed","performance",o,a)}async function runWebRamp(e,n=()=>{}){if(!e.cases?.length)throw new Error("Pass at least one case.");if(!e.param)throw new Error('Pass `param`, the query param that sets the load (e.g. "lights").');const t=(y,_)=>{if(y!=null&&!Number.isFinite(y))throw new Error(`${_} must be a finite number.`)};for(const[y,_]of Object.entries({start:e.start,growth:e.growth,max:e.max,targetFps:e.targetFps,precisionPct:e.precisionPct,rounds:e.rounds,settleMs:e.settleMs,measureMs:e.measureMs,cpuSlowdown:e.cpuSlowdown}))t(_,y);const r=Math.max(1,Math.floor(e.start??100));const i=Math.min(4,Math.max(1.05,e.growth??1.3));const s=Math.max(r,Math.floor(e.max??1e9));const o=e.targetFps??55;const a=Math.min(50,Math.max(.5,e.precisionPct??4));const c=Math.max(1,Math.min(5,Math.floor(e.rounds??1)));const u=Math.max(0,e.settleMs??1e3);const l=Math.max(500,e.measureMs??2e3);const d=Math.max(1,e.cpuSlowdown??1);const h={width:e.viewport?.width??1280,height:e.viewport?.height??800,deviceScaleFactor:e.viewport?.deviceScaleFactor??1};const p=[];const m=Date.now();const g=m+(e.maxBatchMs??40*6e4);const w=()=>g-Date.now();const f=m>>>0;const b=await waitForHostLock(Math.min(e.lockWaitMs??20*6e4,Math.max(0,w())),n);let v=false;try{const y=await loadChromium(e.projectRoot??process.cwd());const _=await y.launch({headless:!e.headed,args:["--enable-gpu","--disable-backgrounding-occluded-windows","--disable-renderer-backgrounding","--disable-background-timer-throttling"]});try{const $={viewport:{width:h.width,height:h.height},deviceScaleFactor:h.deviceScaleFactor};let k=null;let T=60;{const M=await _.newContext($);try{const S=await M.newPage();await S.goto("about:blank");k=await S.evaluate(GPU_RENDERER_JS)??null;const x=await withDeadline(S.evaluate(measureFramesJs(200,1e3)),1e4,async()=>({fps:60}));T=snapRefreshRate(x.fps)}finally{await closeWithin(M,5e3)}}n(`GPU ${k??"unknown"} \xB7 idle ${T} Hz`);if(k&&isSoftwareGpu(k))p.push(`Chrome is drawing with a software GPU (${k}), so ceilings are far lower than on a real screen.`);if(o>T*.95){p.push(`The target (${o} fps) is at or above this browser's idle frame rate (${T} Hz), so even an empty page can miss it. Use headed: true on a faster screen, or measure with a target your contract allows.`)}const A=e.cases.map(M=>({caseName:M.name,ceiling:null,atLeast:null,rounds:[],errors:[]}));const I=async(M,S,x,E)=>{const j=E.length;const P=caseUrl(e.url,{...S,params:{...S.params??{},[e.param]:String(x)}},e.path);const B=F=>Math.max(1e3,Math.min(F,w()+15e3));try{await M.goto(P,{waitUntil:"load",timeout:B(6e4)});if(e.readySelector)await M.waitForSelector(e.readySelector,{state:"attached",timeout:B(6e4)});const F=await withDeadline(M.evaluate(measureFramesJs(u,l)),u+l+6e4,async()=>{throw new Error("the page stopped drawing (no frames for 60 s)")});const C=E.length>j?E[E.length-1]:void 0;if(C)return{load:x,fps:F.fps,p95GapMs:F.p95,valid:false,pass:false,error:C};return{load:x,fps:F.fps,p95GapMs:F.p95,valid:true,pass:F.fps>=o}}catch(F){return{load:x,fps:null,p95GapMs:null,valid:false,pass:false,error:(F?.message??String(F)).split("\n")[0].slice(0,200)}}};let R=false;for(let M=0;M<c&&!R;M++){const S=shuffled(e.cases.map((x,E)=>({c:x,i:E})),f+M*7919>>>0);for(const{c:x,i:E}of S){const j=A[E];if(R||w()<=0){j.rounds.push({round:M+1,status:"skipped",stopReason:"not_run",highestPass:null,lowestMiss:null,resolved:false,steps:[]});continue}n(`round ${M+1}/${c} \xB7 ${x.name}`);let P;try{P=await _.newContext($);const B=await P.newPage();B.on("pageerror",C=>j.errors.push(String(C?.message??C).slice(0,200)));if(d>1){const C=await P.newCDPSession(B);await C.send("Emulation.setCPUThrottlingRate",{rate:d})}const F=await rampOnce(C=>I(B,x,C,j.errors),{start:r,growth:i,max:s,precisionPct:a,timeLeft:()=>w()>0});j.rounds.push({round:M+1,...F});n(` ${x.name}: ${F.status} ${F.highestPass?.load??"-"}`)}catch(B){j.errors.push((B?.message??String(B)).split("\n")[0].slice(0,200));j.rounds.push({round:M+1,status:"invalid",stopReason:"measurement_failed",highestPass:null,lowestMiss:null,resolved:false,steps:[]})}finally{if(P&&!await closeWithin(P,1e4)){v=true;R=true;p.push(`${x.name}'s browser context didn't close, so the batch stopped to keep later runs clean.`)}}}}for(const M of A){const S=M.rounds.filter(E=>E.status==="bracketed"||E.status==="below_one");M.ceiling=median(S.map(E=>E.highestPass?.load??0));const x=M.rounds.filter(E=>E.status==="lower_bound"&&E.highestPass).map(E=>E.highestPass.load);M.atLeast=x.length?Math.max(...x):null}if(w()<=0)p.push("The batch hit its time limit. Rounds marked skipped or lower_bound didn't finish.");return{url:e.url,browser:`Chromium ${_.version()}${e.headed?"":" (headless)"}`,gpu:k,refreshHz:T,targetFps:o,cpuSlowdown:d,viewport:h,seed:f,results:A,warnings:p}}finally{if(!await closeWithin(_,1e4))v=true}}finally{b(v)}}function formatWebRampMarkdown(e){const n=s=>s==null?"\u2014":s.toLocaleString("en-US");const t=s=>s?`${n(s.load)} @ ${s.fps.toFixed(1)}`:"\u2014";const r=[];r.push(`### Web ceiling \xB7 ${e.url}`);r.push(`${e.browser}${e.gpu?` \xB7 GPU: ${e.gpu}${isSoftwareGpu(e.gpu)?" \u26A0\uFE0F software":""}`:""} \xB7 ${e.viewport.width}\xD7${e.viewport.height} @${e.viewport.deviceScaleFactor}x \xB7 idle ${e.refreshHz} Hz \xB7 target ${e.targetFps} fps${e.cpuSlowdown>1?` \xB7 CPU slowed ${e.cpuSlowdown}x`:""}`);r.push("");r.push("**Ceiling** is the most load that held the target, timed from main-thread `requestAnimationFrame` callbacks (a stand-in for drawing speed; it can't see a canvas that stopped updating, so check the looks too). Each round ramps ~30% a step, confirms the first miss, then bisects. With several rounds the ceiling is their median. Ceilings within about 10% are a tie until more rounds agree.");r.push("");const i=Math.max(0,...e.results.map(s=>s.ceiling??0));r.push("| Case | Ceiling | Each round: highest pass @ fps \u2192 lowest miss @ fps | Notes |");r.push("|------|--------:|------------------------------------------------------|-------|");for(const s of e.results){const o=s.rounds.map(c=>{if(c.status==="skipped")return`r${c.round}: not run`;if(c.status==="invalid")return`r${c.round}: invalid (${c.stopReason}) after ${t(c.highestPass)}`;if(c.status==="lower_bound")return`r${c.round}: at least ${t(c.highestPass)} (${c.stopReason})`;if(c.status==="below_one")return`r${c.round}: even 1 missed (${t(c.lowestMiss)})`;return`r${c.round}: ${t(c.highestPass)} \u2192 ${t(c.lowestMiss)}${c.resolved?"":" (wide)"}`}).join("<br>");const a=[s.ceiling===i&&i>0?"best":"",s.atLeast!=null?`at least ${n(s.atLeast)}`:"",s.rounds.some(c=>c.status==="invalid")?"a round broke: check the page before trusting it":"",s.errors.length?`${s.errors.length} page error(s): ${s.errors[0]}`:""].filter(Boolean);r.push(`| ${s.caseName} | ${n(s.ceiling)} | ${o} | ${a.join("; ")} |`)}if(e.warnings.length){r.push("");for(const s of e.warnings)r.push(`- \u26A0\uFE0F ${s}`)}return r.join("\n")}var measureFramesJs;var init_webRamp=__esm({"src/webBench/webRamp.ts"(){"use strict";init_webBench();measureFramesJs=(e,n)=>`new Promise((resolve) => {
|
|
391
|
-
setTimeout(() => {
|
|
392
|
-
const deltas = [];
|
|
393
|
-
let start;
|
|
394
|
-
let last;
|
|
395
|
-
const loop = (now) => {
|
|
396
|
-
if (start === undefined) {
|
|
397
|
-
start = last = now;
|
|
398
|
-
requestAnimationFrame(loop);
|
|
399
|
-
return;
|
|
400
|
-
}
|
|
401
|
-
deltas.push(now - last);
|
|
402
|
-
last = now;
|
|
403
|
-
if (now - start < ${n}) requestAnimationFrame(loop);
|
|
404
|
-
else {
|
|
405
|
-
const total = deltas.reduce((a, b) => a + b, 0);
|
|
406
|
-
const sorted = [...deltas].sort((a, b) => a - b);
|
|
407
|
-
resolve({ fps: total > 0 ? (deltas.length * 1000) / total : 0, p95: sorted[Math.floor(sorted.length * 0.95)] || 0 });
|
|
408
|
-
}
|
|
409
|
-
};
|
|
410
|
-
requestAnimationFrame(loop);
|
|
411
|
-
}, ${e});
|
|
412
|
-
})`}});async function runWebShots(e,n=()=>{}){if(!e.cases?.length)throw new Error("Pass at least one case.");if(!e.outDir)throw new Error("Pass outDir, the folder to save screenshots in.");const t=[...new Set((e.atMs?.length?e.atMs:[500,2e3]).map(c=>Math.max(0,Math.round(c))))].sort((c,u)=>c-u);const r=(0,import_path.join)(e.outDir,new Date().toISOString().replace(/[:.]/g,"-"));(0,import_fs.mkdirSync)(r,{recursive:true});const i={width:e.viewport?.width??1280,height:e.viewport?.height??800,deviceScaleFactor:e.viewport?.deviceScaleFactor??1};const s={dir:"",files:[],pageErrors:[],diffs:[],outliers:[]};s.dir=r;const o=await waitForHostLock(e.lockWaitMs??20*6e4,n);let a=false;try{const c=await loadChromium(e.projectRoot??process.cwd());const u=await c.launch({headless:true,args:["--enable-gpu"]});try{for(const[l,d]of e.cases.entries()){let h;try{h=await u.newContext({viewport:{width:i.width,height:i.height},deviceScaleFactor:i.deviceScaleFactor});const p=await h.newPage();p.on("pageerror",g=>s.pageErrors.push({caseName:d.name,error:String(g?.message??g).slice(0,200)}));await p.goto(caseUrl(e.url,d,e.path),{waitUntil:"load",timeout:6e4});if(e.readySelector)await p.waitForSelector(e.readySelector,{state:"attached",timeout:6e4});const m=Date.now();for(const g of t){const w=m+g-Date.now();if(w>0)await p.waitForTimeout(w);const f=Date.now()-m;const b=(0,import_path.join)(r,`${String(l+1).padStart(2,"0")}-${safe(d.name)}-${g}ms.png`);try{if(e.clipSelector){const v=await p.$(e.clipSelector);if(!v)throw new Error(`clipSelector ${e.clipSelector} not found`);await v.screenshot({path:b})}else await p.screenshot({path:b});s.files.push({caseName:d.name,atMs:g,actualMs:f,file:b})}catch(v){s.files.push({caseName:d.name,atMs:g,actualMs:f,file:null,error:(v?.message??String(v)).split("\n")[0]})}}n(`${d.name}: ${t.length} shot(s)`)}catch(p){for(const m of t)s.files.push({caseName:d.name,atMs:m,file:null,error:(p?.message??String(p)).split("\n")[0]})}finally{if(h&&!await closeWithin(h,1e4))a=true}}if(e.cases.length>1){let l;try{l=await u.newContext({viewport:{width:400,height:300}});const d=await l.newPage();const h=e.cases[0].name;for(const f of t){const b=s.files.find(y=>y.caseName===h&&y.atMs===f&&y.file)?.file;if(!b)continue;const v=(0,import_fs.readFileSync)(b).toString("base64");for(const y of s.files.filter(_=>_.caseName!==h&&_.atMs===f&&_.file)){const _=await d.evaluate(diffJs(v,(0,import_fs.readFileSync)(y.file).toString("base64")));if(_)s.diffs.push({caseName:y.caseName,atMs:f,..._})}}const p=new Map;for(const f of s.diffs)p.set(f.caseName,[...p.get(f.caseName)??[],f.changedPct]);const m=[...p].map(([f,b])=>[f,b.reduce((v,y)=>v+y,0)/b.length]);const g=m.map(([,f])=>f).sort((f,b)=>f-b);const w=g.length?g[Math.floor(g.length/2)]:0;s.outliers=m.filter(([,f])=>f>Math.max(1,w*2)).map(([f])=>f)}catch{}finally{if(l)await closeWithin(l,1e4)}}}finally{if(!await closeWithin(u,1e4))a=true}}finally{o(a)}return s}var import_fs,import_path,safe,diffJs;var init_webShots=__esm({"src/webBench/webShots.ts"(){"use strict";import_fs=require("fs");import_path=require("path");init_webBench();safe=e=>e.replace(/[^\w.-]+/g,"_").slice(0,80);diffJs=(e,n)=>`(async () => {
|
|
413
|
-
const load = (s) => new Promise((res, rej) => { const i = new Image(); i.onload = () => res(i); i.onerror = rej; i.src = "data:image/png;base64," + s; });
|
|
414
|
-
const [ia, ib] = await Promise.all([load(${JSON.stringify(e)}), load(${JSON.stringify(n)})]);
|
|
415
|
-
const w = ia.naturalWidth, h = ia.naturalHeight;
|
|
416
|
-
const px = (img) => { const c = document.createElement("canvas"); c.width = w; c.height = h; const g = c.getContext("2d"); g.drawImage(img, 0, 0, w, h); return g.getImageData(0, 0, w, h).data; };
|
|
417
|
-
const da = px(ia), db = px(ib);
|
|
418
|
-
let sum = 0, changed = 0;
|
|
419
|
-
for (let i = 0; i < da.length; i += 4) {
|
|
420
|
-
const d = (Math.abs(da[i] - db[i]) + Math.abs(da[i + 1] - db[i + 1]) + Math.abs(da[i + 2] - db[i + 2])) / 3;
|
|
421
|
-
sum += d;
|
|
422
|
-
if (d > 32) changed++;
|
|
423
|
-
}
|
|
424
|
-
const n = da.length / 4;
|
|
425
|
-
return { meanDiff: Math.round((sum / n) * 100) / 100, changedPct: Math.round((changed / n) * 10000) / 100 };
|
|
426
|
-
})()`}});function setOptimizeDeadline(e){deadline=e}function optimizeNote(e=Date.now(),n=deadline){if(n==null)return null;const t=Math.round((n-e)/6e4);if(t>10){return`
|
|
427
|
-
|
|
428
|
-
\u23F1 **Buoy Optimize: ${t} min left** (deadline ${clock(n)}). You're not done. When this step ends, start the next round: forks of the best, a new idea family, or an untried idea from the bank. A good score or a written RESULTS.md is not a reason to stop.`}if(t>0){return`
|
|
429
|
-
|
|
430
|
-
\u23F1 **Buoy Optimize: ${t} min left** (deadline ${clock(n)}). Confirm the best checked version, install it and finish the report.`}return`
|
|
431
|
-
|
|
432
|
-
\u23F1 **Buoy Optimize: the deadline (${clock(n)}) has passed.** Leave the best checked version in place and report.`}var deadline,clock;var init_session=__esm({"src/optimize/session.ts"(){"use strict";deadline=null;clock=e=>new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"})}});function hasPro(e){if(readEntitlement().isPro)return true;return e.connectedDevices().some(n=>n.tier==="pro")}function registerWebBenchTools(e,n){e.registerTool("run_web_benchmark",{description:"Benchmark variants of a web page in a fresh headless Chromium (needs Playwright in the project). Each case is a path + query params on a running app; each run loads a fresh page, waits until ready, then records frame rate, frame gaps, long tasks, Long Animation Frames (with script names), layout shifts, DOM size, and Chrome's own main-thread, script, style and layout time. Cases run in rounds with the order shuffled each round. `cpuSlowdown` repeats everything with Chrome's CPU throttled (e.g. [1, 4, 6]) as a stand-in for slower phones; it doesn't slow the GPU. Blocks until done.",inputSchema:{url:import_zod23.z.string().describe("Origin of the running app, e.g. http://localhost:5173"),path:import_zod23.z.string().optional().describe("Default path for cases, e.g. /bench/lights"),cases:import_zod23.z.array(import_zod23.z.object({name:import_zod23.z.string(),path:import_zod23.z.string().optional(),params:import_zod23.z.record(import_zod23.z.string()).optional(),control:import_zod23.z.boolean().optional().describe("Does different work (e.g. an empty page). Shown, never the baseline or a candidate.")})).min(1).describe("Variants to compare. The first is the baseline."),runsPerCase:import_zod23.z.number().optional().describe("Measured runs per case (1\u201310). Default 3."),perCaseDurationMs:import_zod23.z.number().optional().describe("Recording length per run. Default 5000."),settleMs:import_zod23.z.number().optional().describe("Wait after the page is ready, before recording. Default 1000."),cpuSlowdown:import_zod23.z.array(import_zod23.z.number()).optional().describe("CPU throttling rates; 1 = none. Default [1]."),viewport:import_zod23.z.object({width:import_zod23.z.number(),height:import_zod23.z.number(),deviceScaleFactor:import_zod23.z.number().optional()}).optional().describe("Fixed viewport. Default 1280\xD7800 at 1x."),readySelector:import_zod23.z.string().optional().describe("CSS selector that must appear before a run counts as ready."),steps:import_zod23.z.array(import_zod23.z.union([import_zod23.z.object({click:import_zod23.z.string()}),import_zod23.z.object({press:import_zod23.z.string()}),import_zod23.z.object({type:import_zod23.z.object({selector:import_zod23.z.string(),text:import_zod23.z.string()})}),import_zod23.z.object({scroll:import_zod23.z.number()}),import_zod23.z.object({wait:import_zod23.z.number()}),import_zod23.z.object({expect:import_zod23.z.object({selector:import_zod23.z.string(),text:import_zod23.z.string().optional()})})])).optional().describe("Real input during each run, in order: {click: selector}, {press: key}, {type: {selector, text}}, {scroll: px}, {wait: ms}, {expect: {selector, text?}} (checked after the run; fails runs that skipped the work). Click targets are located before recording and must not move. Adds input delay, handler time and time to next paint per case."),traceDir:import_zod23.z.string().optional().describe("Save one Chrome trace per case here (extra, unranked runs)."),headed:import_zod23.z.boolean().optional().describe("Show the browser window. Default false."),allowPageErrors:import_zod23.z.boolean().optional().describe("Keep runs whose page threw an uncaught error. Default false: such runs fail."),projectRoot:import_zod23.z.string().optional().describe("Folder to load Playwright from. Default: the server's working directory."),outFile:import_zod23.z.string().optional().describe("Also save the full result and options as JSON here, to read again later."),extraRoundsWhenClose:import_zod23.z.number().optional().describe("If the two smoothest cases are too close to call, run up to this many extra rounds of just those two. Default 0."),maxBatchMs:import_zod23.z.number().optional().describe("Stop starting new runs after this long. Default 30 minutes."),budgets:import_zod23.z.object({droppedPct:import_zod23.z.number().optional(),inputMs:import_zod23.z.number().optional(),freezeMs:import_zod23.z.number().optional(),mainThreadPct:import_zod23.z.number().optional(),jsHeapMb:import_zod23.z.number().optional()}).optional().describe("Hard limits. The report says which cases meet all of them; an unmeasured limit counts as not met.")}},async t=>{if(!hasPro(n))return fail8(PRO_REQUIRED);try{const r=await runWebBench({url:t.url,path:t.path,cases:t.cases,runsPerCase:t.runsPerCase,durationMs:t.perCaseDurationMs,settleMs:t.settleMs,cpuSlowdown:t.cpuSlowdown,viewport:t.viewport,readySelector:t.readySelector,steps:t.steps,traceDir:t.traceDir,headed:t.headed,allowPageErrors:t.allowPageErrors,projectRoot:t.projectRoot,outFile:t.outFile,extraRoundsWhenClose:t.extraRoundsWhenClose,maxBatchMs:t.maxBatchMs,budgets:t.budgets},o=>process.stderr.write(`[buoy-mcp] web-bench: ${o}
|
|
433
|
-
`));const i={status:r.status,browser:r.browser,gpu:r.gpu??null,viewport:r.viewport,results:r.results.map(o=>({caseName:o.caseName,cpu:o.cpu,validRuns:o.validRuns,fpsMin:o.fpsMin,fpsMax:o.fpsMax,plannedRuns:o.plannedRuns,isBaseline:o.isBaseline,control:o.control===true,deltaDroppedPct:o.deltaDroppedPct,droppedRange:o.droppedMin==null?null:[o.droppedMin,o.droppedMax],flags:o.flags,budget:o.budget,median:o.median,failures:o.runs.filter(a=>a.failed).map(a=>a.failed)})),traces:r.traces,warnings:r.warnings,replay:r.replay};const s=`${formatWebBenchMarkdown(r)}
|
|
434
|
-
|
|
435
|
-
\`\`\`json
|
|
436
|
-
${JSON.stringify(i,null,2)}
|
|
437
|
-
\`\`\``;return r.status==="failed"?fail8(`Every case failed.
|
|
438
|
-
|
|
439
|
-
${s}`):text6(s)}catch(r){return fail8(r?.message??String(r))}});e.registerTool("find_web_ceiling",{description:"Find the most load each web variant can hold at a target frame rate, with no cap. For each case, a fresh headless Chromium (real GPU) opens the page with `param` set (e.g. ?lights=100), waits until ready, settles, then counts requestAnimationFrame callbacks. It raises the load ~30% a step until a valid sample misses `targetFps`, confirms the miss, then bisects to within a few percent; if the first load misses it searches down. A page error ends the round as invalid instead of counting as a miss. An app's own capped test is not the ceiling. Needs Playwright in the project. Blocks until done.",inputSchema:{url:import_zod23.z.string().describe("Origin of the running app, e.g. http://localhost:5173"),path:import_zod23.z.string().optional().describe("Default path for cases."),cases:import_zod23.z.array(import_zod23.z.object({name:import_zod23.z.string(),path:import_zod23.z.string().optional(),params:import_zod23.z.record(import_zod23.z.string()).optional()})).min(1).describe("Variants to ramp, e.g. [{name: 'baseline', params: {variant: 'baseline'}}, {name: 'atlas', params: {variant: 'atlas'}}]."),param:import_zod23.z.string().describe("Query param that sets the load, e.g. 'lights' or 'count'."),start:import_zod23.z.number().optional().describe("First load. Default 100."),growth:import_zod23.z.number().optional().describe("Growth per step. Default 1.3."),max:import_zod23.z.number().optional().describe("Highest load to try. Default 1,000,000,000."),targetFps:import_zod23.z.number().optional().describe("Frame rate each step must hold. Default 55."),precisionPct:import_zod23.z.number().optional().describe("Bisect until the pass/miss gap is within this percent. Default 4."),rounds:import_zod23.z.number().optional().describe("Ramps per case (1\u20135); the ceiling is the median of valid rounds. Default 1. Use 3 to settle close calls."),maxBatchMs:import_zod23.z.number().optional().describe("Stop the whole batch after this long. Default 40 minutes."),settleMs:import_zod23.z.number().optional().describe("Wait after ready before counting frames. Default 1000."),measureMs:import_zod23.z.number().optional().describe("How long to count frames per step. Default 2000."),cpuSlowdown:import_zod23.z.number().optional().describe("CPU throttling rate; 1 = none. Default 1."),viewport:import_zod23.z.object({width:import_zod23.z.number(),height:import_zod23.z.number(),deviceScaleFactor:import_zod23.z.number().optional()}).optional(),readySelector:import_zod23.z.string().optional().describe("CSS selector that must exist before counting frames."),headed:import_zod23.z.boolean().optional().describe("Show the browser window (uses the screen's refresh rate). Default false."),projectRoot:import_zod23.z.string().optional().describe("Folder to load Playwright from.")}},async t=>{if(!hasPro(n))return fail8(PRO_REQUIRED.replace("run_web_benchmark","find_web_ceiling"));try{const r=await runWebRamp(t,o=>process.stderr.write(`[buoy-mcp] web-ceiling: ${o}
|
|
440
|
-
`));const i=r.results.map(o=>({caseName:o.caseName,ceiling:o.ceiling,atLeast:o.atLeast,rounds:o.rounds.map(a=>({status:a.status,stopReason:a.stopReason,highestPass:a.highestPass,lowestMiss:a.lowestMiss,resolved:a.resolved})),errors:o.errors.slice(0,3)}));const s=`${formatWebRampMarkdown(r)}
|
|
441
|
-
|
|
442
|
-
\`\`\`json
|
|
443
|
-
${JSON.stringify({gpu:r.gpu,refreshHz:r.refreshHz,seed:r.seed,results:i},null,2)}
|
|
444
|
-
\`\`\``;return text6(s)}catch(r){return fail8(r?.message??String(r))}});e.registerTool("screenshot_web_variants",{description:"Screenshot every web variant at the same moments after it's ready, in a fresh headless Chromium (real GPU), and save PNGs in a new timestamped folder inside outDir. Use it to check each variant still looks right: open the files and compare them side by side with the baseline. Use the same params (e.g. the same count and pattern) for every case. Animated scenes differ by timing, so compare shapes, colors, glow and layout, and take several moments to catch frozen or broken motion.",inputSchema:{url:import_zod23.z.string().describe("Origin of the running app."),path:import_zod23.z.string().optional(),cases:import_zod23.z.array(import_zod23.z.object({name:import_zod23.z.string(),path:import_zod23.z.string().optional(),params:import_zod23.z.record(import_zod23.z.string()).optional()})).min(1),atMs:import_zod23.z.array(import_zod23.z.number()).optional().describe("Times after ready to capture, in ms. Default [500, 2000]."),outDir:import_zod23.z.string().describe("Folder to save the PNGs in."),viewport:import_zod23.z.object({width:import_zod23.z.number(),height:import_zod23.z.number(),deviceScaleFactor:import_zod23.z.number().optional()}).optional(),readySelector:import_zod23.z.string().optional(),clipSelector:import_zod23.z.string().optional().describe("Crop to this element, e.g. 'canvas'."),projectRoot:import_zod23.z.string().optional()}},async t=>{if(!hasPro(n))return fail8(PRO_REQUIRED.replace("run_web_benchmark","screenshot_web_variants"));try{const r=await runWebShots(t,c=>process.stderr.write(`[buoy-mcp] web-shots: ${c}
|
|
445
|
-
`));const i=r.files.map(c=>`- ${c.caseName} @ ${c.atMs} ms${c.actualMs!=null&&Math.abs(c.actualMs-c.atMs)>50?` (taken at ${c.actualMs} ms)`:""}: ${c.file??`failed (${c.error})`}`);const s=r.pageErrors.map(c=>`- ${c.caseName}: ${c.error}`);const o=t.cases[0]?.name;const a=r.diffs.length?`
|
|
446
|
-
|
|
447
|
-
**Difference from ${o}** (same moment; mean 0\u2013255, and % of pixels off by more than 32):
|
|
448
|
-
`+r.diffs.map(c=>`- ${c.caseName} @ ${c.atMs} ms: mean ${c.meanDiff}, ${c.changedPct}% changed${r.outliers.includes(c.caseName)?" \u26A0\uFE0F outlier":""}`).join("\n")+(r.outliers.length?`
|
|
146
|
+
_Compact view. Pass includeValues:true for the full state tree. Dispatch with redux_dispatch({type, payload})._${s}`)}catch(r){return fail2(errMsg2(r))}});e.registerTool("redux_dispatch",{description:"Dispatch a Redux action to the app's store (e.g. to trigger a state change while debugging). Provide the action type and optional payload \u2014 they're sent as { type, payload }.",inputSchema:{type:import_zod9.z.string().describe('The action type, e.g. "counter/increment" or "auth/logout".'),payload:import_zod9.z.unknown().optional().describe("Optional action payload (any JSON)."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i={type:t.type};if(t.payload!==void 0)i.payload=t.payload;const o=await n.callAction(REDUX_TOOL_ID,"dispatch",{action:i},r);if(!o||!o.dispatched)return fail2(noStoreMessage(o?.reason));return text(`Dispatched \`${t.type}\`${t.payload!==void 0?` with payload ${JSON.stringify(t.payload)}`:""}.`)}catch(r){return fail2(errMsg2(r))}})}var import_zod9,REDUX_TOOL_ID,TOP_LEVEL_ONLY_NOTE;var init_redux=__esm({"src/tools/packs/redux.ts"(){"use strict";import_zod9=require("zod");init_packKit();REDUX_TOOL_ID="redux";TOP_LEVEL_ONLY_NOTE="\n\n_Note: capture is top-level-only on this device (thunk-internal / RTK Query actions aren't recorded). Put `import '@buoy-gg/redux';` first in the app entry, or add `buoyReduxMiddleware`, for full capture._"}});function truncate2(e,n=200){if(e===null||e===void 0)return"(null)";const t=typeof e==="string"?e:JSON.stringify(e);return t.length>n?`${t.slice(0,n)}\u2026(+${t.length-n} chars)`:t}function registerStorageTools(e,n){e.registerTool("get_storage",{description:"Read the app's storage keys across ALL backends: AsyncStorage, MMKV (per instance), and Expo SecureStore. Data wrong or missing after an app restart \u2192 read the persisted values here FIRST \u2014 the bug is usually a stale, missing, or malformed stored value, and reading it beats hunting for it in code. Compact by DEFAULT \u2014 keys only \u2014 so it's token-cheap; pass includeValues:true for the values (truncated), or a `pattern` substring to narrow. Buoy's own internal keys are already filtered out.",inputSchema:{pattern:import_zod10.z.string().optional().describe("Only keys containing this substring (case-insensitive)."),includeValues:import_zod10.z.boolean().optional().describe("Include each key's value (truncated). Default false (keys only)."),limit:import_zod10.z.number().optional().describe("Max keys per backend section. Default 100."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=t.pattern?.toLowerCase();const o=typeof t.limit==="number"&&t.limit>0?t.limit:100;const s=p=>!i||p.toLowerCase().includes(i);const a=[];const c=await n.callAction(STORAGE_TOOL_ID,"async.getAllKeys",{},r);if(!Array.isArray(c)){return fail2("No storage result from the device. The storage tool may be inactive.")}const l=c.filter(s).slice(0,o);if(l.length>0){let p;if(t.includeValues){const g=await n.callAction(STORAGE_TOOL_ID,"async.multiGet",{keys:l},r);const m=new Map((g??[]).map(([f,b])=>[f,b]));p=l.map(f=>`- \`${f}\` = ${truncate2(m.get(f)??null)}`)}else{p=l.map(g=>`- \`${g}\``)}a.push(`**AsyncStorage (${l.length}/${c.length} keys):**
|
|
147
|
+
${p.join("\n")}`)}const u=await n.callAction(STORAGE_TOOL_ID,"mmkv.snapshot",{},r).catch(()=>null);for(const p of u??[]){const g=p.entries.filter(b=>s(b.key)).slice(0,o);if(g.length===0)continue;const m=g.map(b=>t.includeValues?`- \`${b.key}\` (${b.valueType}) = ${truncate2(b.value)}`:`- \`${b.key}\``);const f=[p.encrypted&&"encrypted",p.readOnly&&"read-only"].filter(Boolean).join(", ");a.push(`**MMKV \`${p.id}\`${f?` (${f})`:""} (${g.length}/${p.entries.length} keys):**
|
|
148
|
+
${m.join("\n")}`)}const d=await n.callAction(STORAGE_TOOL_ID,"secure.keys",{},r).catch(()=>null);const h=(d??[]).filter(p=>s(p.key)).slice(0,o);if(h.length>0){const p=await Promise.all(h.map(async g=>{if(g.requireAuthentication)return`- \`${g.key}\` \u{1F512} (biometric-protected \u2014 not read)`;if(!t.includeValues)return`- \`${g.key}\``;const m=await n.callAction(STORAGE_TOOL_ID,"secure.get",{key:g.key},r).catch(()=>null);return`- \`${g.key}\` = ${truncate2(m)}`}));a.push(`**SecureStore (${h.length} registered keys):**
|
|
149
|
+
${p.join("\n")}`)}if(a.length===0){return text(`No storage keys${i?` matching "${t.pattern}"`:""} in any backend.`)}const w=t.includeValues?"":"\n\n_Keys only. Pass includeValues:true for values, or a pattern to filter. Modify AsyncStorage with storage_action._";return text(`${a.join("\n\n")}${w}`)}catch(r){return fail2(errMsg2(r))}});e.registerTool("storage_action",{description:"Modify the app's AsyncStorage: set a key, remove a key, or clear supported app AsyncStorage keys (Buoy's own devtool keys are preserved). Values are stored as strings \u2014 JSON-encode objects yourself.",inputSchema:{action:import_zod10.z.enum(["set","remove","clear"]).describe("set/remove a key, or clear supported app AsyncStorage keys."),key:import_zod10.z.string().optional().describe("The key (required for set and remove)."),value:import_zod10.z.string().optional().describe("The string value to store (required for set; JSON-encode objects)."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);if(t.action==="clear"){await n.callAction(STORAGE_TOOL_ID,"clearAppStorage",{},r);return text("Requested clearing of supported app AsyncStorage keys. Read storage again to confirm.")}if(!t.key){return fail2(`'${t.action}' needs a key.`)}if(t.action==="remove"){await n.callAction(STORAGE_TOOL_ID,"async.removeItem",{key:t.key},r);return text(`Requested removal of storage key "${t.key}".`)}if(t.value===void 0){return fail2("'set' needs a value (a string).")}await n.callAction(STORAGE_TOOL_ID,"async.setItem",{key:t.key,value:t.value},r);return text(`Requested update of storage key "${t.key}".`)}catch(r){return fail2(errMsg2(r))}})}var import_zod10,STORAGE_TOOL_ID;var init_storage=__esm({"src/tools/packs/storage.ts"(){"use strict";import_zod10=require("zod");init_packKit();STORAGE_TOOL_ID="storage"}});function valueKey(e){if(typeof e==="number"){if(!Number.isFinite(e)||Number.isInteger(e)&&Math.abs(e)<10)return null;return`n:${e}`}if(typeof e!=="string")return null;const n=e.trim();if(n.length<3||n.length>80)return null;const t=/^[$€£]?-?[\d,]+(\.\d+)?$/.test(n)?Number(n.replace(/[$€£,]/g,"")):NaN;if(Number.isFinite(t)&&/[\d]/.test(n))return valueKey(t);return`s:${n}`}function walk(e,n,t,r){if(r.length>=MAX_LEAVES||t>MAX_DEPTH||e==null)return;if(typeof e==="object"){const o=Array.isArray(e)?e.slice(0,50).map((s,a)=>[String(a),s]):Object.entries(e);for(const[s,a]of o)walk(a,n?`${n}.${s}`:s,t+1,r);return}const i=valueKey(e);if(i)r.push([i,n])}function indexState(e,n,t){const r=[];walk(t,"",0,r);for(const[i,o]of r){const s=o?`${n}, ${o}`:n;const a=e.get(i)??[];if(a.length<3)a.push(s);e.set(i,a)}}async function liveStateIndex(e,n){const t=new Set(e.connectedDevices().find(s=>s.deviceId===n)?.tools.map(s=>s.toolId)??[]);const r={timeoutMs:1500,silent:true};const i=[];const o=new Map;if(t.has("zustand")){i.push(e.callAction("zustand","listStores",{includeValues:true},n,r).then(s=>{for(const a of s?.stores??[])indexState(o,`${a.name} store`,a.currentState)}))}if(t.has("redux")){i.push(e.callAction("redux","getState",{includeValues:true},n,r).then(s=>{const a=s;if(a?.available)indexState(o,"redux state",a.state)}))}if(t.has("jotai")){i.push(e.callAction("jotai","listAtoms",{includeValues:true},n,r).then(s=>{for(const a of s?.atoms??[])indexState(o,`atom ${a.label}`,a.currentValue)}))}if(!i.length)return null;await Promise.all(i.map(s=>s.catch(()=>void 0)));return o.size?o:null}function stateNote(e,n){if(!e||!n)return"";const t=valueKey(n);const r=t?e.get(t):void 0;return r?.length?` = live state: ${r.join("; ")}`:""}var MAX_LEAVES,MAX_DEPTH;var init_liveValues=__esm({"src/tools/packs/liveValues.ts"(){"use strict";MAX_LEAVES=4e3;MAX_DEPTH=6}});function pixelmatch(e,n,t,r,i,o={}){const{threshold:s=.1,alpha:a=.1,aaColor:c=[255,255,0],diffColor:l=[255,0,0],checkerboard:u=true,includeAA:d,diffColorAlt:h,diffMask:w}=o;if(!isPixelData(e)||!isPixelData(n)||t&&!isPixelData(t))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(e.length!==n.length||t&&t.length!==e.length)throw new Error(`Image sizes do not match. Image 1 size: ${e.length}, image 2 size: ${n.length}`);if(e.length!==r*i*4)throw new Error(`Image data size does not match width/height. Expecting ${r*i*4}. Got ${e.length}`);const p=r*i;const g=new Uint32Array(e.buffer,e.byteOffset,p);const m=new Uint32Array(n.buffer,n.byteOffset,p);let f=true;for(let k=0;k<p;k++){if(g[k]!==m[k]){f=false;break}}if(f){if(t&&!w){for(let k=0,M=0;k<p;k++,M+=4)drawGrayPixel(e,M,a,t)}return 0}const b=35215*s*s;const[v,y,$]=c;const[T,_,x]=l;const[I,D,E]=h||l;let S=0;for(let k=0,M=0;k<p;k++,M+=4){const A=g[k]===m[k]?0:colorDelta(e,n,M,M,u);if(Math.abs(A)>b){const P=k%r;const R=k/r|0;const j=!d&&(antialiased(e,P,R,r,i,g,m,u)||antialiased(n,P,R,r,i,m,g,u));if(j){if(t&&!w)drawPixel(t,M,v,y,$)}else{if(t){if(A<0){drawPixel(t,M,I,D,E)}else{drawPixel(t,M,T,_,x)}}S++}}else if(t&&!w){drawGrayPixel(e,M,a,t)}}return S}function isPixelData(e){return ArrayBuffer.isView(e)&&e.BYTES_PER_ELEMENT===1}function antialiased(e,n,t,r,i,o,s,a){const c=Math.max(n-1,0);const l=Math.max(t-1,0);const u=Math.min(n+1,r-1);const d=Math.min(t+1,i-1);const h=(t*r+n)*4;const w=e[h];const p=e[h+1];const g=e[h+2];const m=e[h+3];let f=n===c||n===u||t===l||t===d?1:0;let b=0;let v=0;let y=0;let $=0;let T=0;let _=0;for(let x=c;x<=u;x++){for(let I=l;I<=d;I++){if(x===n&&I===t)continue;const D=brightnessDelta(e,h,(I*r+x)*4,w,p,g,m,a);if(D===0){f++;if(f>2)return false}else if(D<b){b=D;y=x;$=I}else if(D>v){v=D;T=x;_=I}}}if(b===0||v===0)return false;return hasManySiblings(o,y,$,r,i)&&hasManySiblings(s,y,$,r,i)||hasManySiblings(o,T,_,r,i)&&hasManySiblings(s,T,_,r,i)}function hasManySiblings(e,n,t,r,i){const o=Math.max(n-1,0);const s=Math.max(t-1,0);const a=Math.min(n+1,r-1);const c=Math.min(t+1,i-1);const l=e[t*r+n];let u=n===o||n===a||t===s||t===c?1:0;for(let d=o;d<=a;d++){for(let h=s;h<=c;h++){if(d===n&&h===t)continue;u+=+(l===e[h*r+d]);if(u>2)return true}}return false}function colorDelta(e,n,t,r,i){const o=e[t];const s=e[t+1];const a=e[t+2];const c=e[t+3];const l=n[r];const u=n[r+1];const d=n[r+2];const h=n[r+3];let w=o-l;let p=s-u;let g=a-d;const m=c-h;if(c<255||h<255){let $=255,T=255,_=255;if(i){$=48+159*(t%2);T=48+159*((t/1.618033988749895|0)%2);_=48+159*((t/2.618033988749895|0)%2)}w=(o*c-l*h-$*m)/255;p=(s*c-u*h-T*m)/255;g=(a*c-d*h-_*m)/255}const f=w*.29889531+p*.58662247+g*.11448223;const b=w*.59597799-p*.2741761-g*.32180189;const v=w*.21147017-p*.52261711+g*.31114694;const y=.5053*f*f+.299*b*b+.1957*v*v;return f>0?-y:y}function brightnessDelta(e,n,t,r,i,o,s,a){const c=e[t];const l=e[t+1];const u=e[t+2];const d=e[t+3];let h=r-c;let w=i-l;let p=o-u;const g=s-d;if(!h&&!w&&!p&&!g)return 0;if(s<255||d<255){let m=255,f=255,b=255;if(a){m=48+159*(n%2);f=48+159*((n/1.618033988749895|0)%2);b=48+159*((n/2.618033988749895|0)%2)}h=(r*s-c*d-m*g)/255;w=(i*s-l*d-f*g)/255;p=(o*s-u*d-b*g)/255}return h*.29889531+w*.58662247+p*.11448223}function drawPixel(e,n,t,r,i){e[n]=t;e[n+1]=r;e[n+2]=i;e[n+3]=255}function drawGrayPixel(e,n,t,r){const i=255+(e[n]*.29889531+e[n+1]*.58662247+e[n+2]*.11448223-255)*t*e[n+3]/255;drawPixel(r,n,i,i,i)}var init_pixelmatch=__esm({"../../node_modules/pixelmatch/index.js"(){"use strict"}});function decodePng(e){return import_pngjs3.PNG.sync.read(e)}function diffScreens(e,n,t={}){const r=decodePng(e);const i=decodePng(n);if(r.width!==i.width||r.height!==i.height){throw new Error(`The screenshots are different sizes (${r.width}\xD7${r.height} vs ${i.width}\xD7${i.height}). Compare on the same device and orientation, or save a new baseline.`)}const{width:o,height:s}=r;const a=Math.round(s*(t.ignoreTop??0));for(const w of[r,i])w.data.fill(0,0,a*o*4);for(const w of t.masks??[]){const p=Math.max(0,Math.floor(w.x*o));const g=Math.min(o,Math.ceil((w.x+w.width)*o));const m=Math.max(0,Math.floor(w.y*s));const f=Math.min(s,Math.ceil((w.y+w.height)*s));for(const b of[r,i])for(let v=m;v<f;v++)b.data.fill(0,(v*o+p)*4,(v*o+g)*4)}const c=t.threshold??.1;const l=new import_pngjs3.PNG({width:o,height:s});const u=pixelmatch(r.data,i.data,l.data,o,s,{threshold:c,includeAA:false,diffMask:true});const d=new import_pngjs3.PNG({width:o,height:s});pixelmatch(r.data,i.data,d.data,o,s,{threshold:c,includeAA:false,alpha:.25,diffColor:[230,30,40]});const h=o*(s-a);return{width:o,height:s,changedPixels:u,percent:h?u/h*100:0,boxes:changedBoxes(l.data,o,s),diffPng:import_pngjs3.PNG.sync.write(d)}}function changedBoxes(e,n,t){const r=Math.max(8,Math.round(n/48));const i=Math.ceil(n/r);const o=Math.ceil(t/r);const s=new Uint32Array(i*o);for(let u=0;u<t;u++){for(let d=0;d<n;d++){if(e[(u*n+d)*4+3]>0)s[Math.floor(u/r)*i+Math.floor(d/r)]++}}const a=1;const c=new Uint8Array(i*o);const l=[];for(let u=0;u<s.length;u++){if(c[u]||s[u]<a)continue;const d={x0:Infinity,y0:Infinity,x1:-1,y1:-1,pixels:0};const h=[u];c[u]=1;while(h.length){const w=h.pop();const p=w%i;const g=Math.floor(w/i);d.x0=Math.min(d.x0,p);d.y0=Math.min(d.y0,g);d.x1=Math.max(d.x1,p);d.y1=Math.max(d.y1,g);d.pixels+=s[w];for(let m=-2;m<=2;m++){for(let f=-2;f<=2;f++){const b=p+f;const v=g+m;if(b<0||v<0||b>=i||v>=o)continue;const y=v*i+b;if(!c[y]&&s[y]>=a){c[y]=1;h.push(y)}}}}l.push(d)}return l.sort((u,d)=>d.pixels-u.pixels).slice(0,8).map(u=>({x:u.x0*r/n,y:u.y0*r/t,width:Math.min(n,(u.x1+1)*r-u.x0*r)/n,height:Math.min(t,(u.y1+1)*r-u.y0*r)/t,pixels:u.pixels}))}function boxColors(e,n,t,r=0){const i=decodePng(e);const o=decodePng(n);if(i.width!==o.width||i.height!==o.height)return null;const{width:s,height:a}=i;const c=Math.max(0,Math.floor(t.x*s));const l=Math.min(s,Math.ceil((t.x+t.width)*s));const u=Math.max(Math.round(a*r),Math.floor(t.y*a));const d=Math.min(a,Math.ceil((t.y+t.height)*a));const h=new Map;const w=new Map;for(let b=u;b<d;b++){for(let v=c;v<l;v++){const y=(b*s+v)*4;const $=i.data[y]<<16|i.data[y+1]<<8|i.data[y+2];const T=o.data[y]<<16|o.data[y+1]<<8|o.data[y+2];if($===T)continue;h.set($,(h.get($)??0)+1);w.set(T,(w.get(T)??0)+1)}}const p=b=>[...b].sort((v,y)=>y[1]-v[1])[0]?.[0];const g=p(h);const m=p(w);if(g===void 0||m===void 0)return null;const f=b=>`#${b.toString(16).padStart(6,"0").toUpperCase()}`;return{before:f(g),after:f(m)}}function describeSpot(e){const n=e.x+e.width/2;const t=e.y+e.height/2;const r=t<.33?"top":t<.66?"middle":"bottom";const i=n<.33?" left":n<.66?"":" right";return`${r}${i}`}function cropPng(e,n){const t=decodePng(e);const r=Math.max(0,Math.floor(n.x*t.width));const i=Math.max(0,Math.floor(n.y*t.height));const o=Math.max(1,Math.min(t.width-r,Math.round(n.width*t.width)));const s=Math.max(1,Math.min(t.height-i,Math.round(n.height*t.height)));const a=new import_pngjs3.PNG({width:o,height:s});import_pngjs3.PNG.bitblt(t,a,r,i,o,s,0,0);return import_pngjs3.PNG.sync.write(a)}var import_pngjs3;var init_imageDiff=__esm({"src/capture/imageDiff.ts"(){"use strict";import_pngjs3=__toESM(require_png());init_pixelmatch()}});function touchOwnerFromLog(e){let n=null;let t;const r=[];for(const i of e.split("\n")){const o=/digitizer attached \(sender ([0-9A-F]+)\)/i.exec(i);if(o){if(!r.includes(o[1]))r.push(o[1]);t=n;n=o[1];continue}if(/already have a main display digitizer/i.test(i)){if(t!==void 0)n=t??OTHER_UNSEEN;t=void 0;continue}t=void 0;const s=/digitizer detached \(sender ([0-9A-F]+)\)/i.exec(i);if(s){const a=r.indexOf(s[1]);if(a>=0)r.splice(a,1);if(n===s[1]||n===OTHER_UNSEEN&&a<0)n=r.find(c=>IDB_SENDER.test(c))??r[r.length-1]??null}}if(!n)return"unknown";return IDB_SENDER.test(n)?"idb":"other"}async function simTouchOwner(e){const n=cache.get(e);if(n&&Date.now()-n.at<6e4)return n.owner;let t="unknown";try{const{stdout:r}=await execFileAsync9("xcrun",["simctl","spawn",e,"log","show","--last","24h","--style","compact","--predicate",'process == "backboardd" AND category == "TouchEvents"'],{timeout:2e4,maxBuffer:16*1024*1024});t=touchOwnerFromLog(r.split("\n").filter(i=>/digitizer|already have a main/i.test(i)).join("\n"))}catch{t="unknown"}cache.set(e,{owner:t,at:Date.now()});return t}async function assertSimTouchable(e){if(await simTouchOwner(e)==="other")throw new Error(TOUCH_TAKEN)}var import_node_child_process10,import_node_util9,execFileAsync9,IDB_SENDER,OTHER_UNSEEN,TOUCH_TAKEN,cache;var init_simTouch=__esm({"src/capture/simTouch.ts"(){"use strict";import_node_child_process10=require("child_process");import_node_util9=require("util");execFileAsync9=(0,import_node_util9.promisify)(import_node_child_process10.execFile);IDB_SENDER=/^ACEFADE/i;OTHER_UNSEEN="unseen";TOUCH_TAKEN="Real touches can't reach this simulator right now. On Xcode 27, DeviceHub (the app that shows simulators) takes over each booted simulator's touch screen, so a touch sent from here is dropped. Use tap_element for React elements (it presses them inside the app), or run_flow. Don't quit DeviceHub to fix this: quitting it shuts down every simulator.";cache=new Map}});var HID_SWIFT,HID_INTERFACE,HID_HASH;var init_hidSource_generated=__esm({"src/capture/hidSource.generated.ts"(){"use strict";HID_SWIFT=`import Foundation
|
|
150
|
+
import Darwin
|
|
151
|
+
import CryptoKit
|
|
449
152
|
|
|
450
|
-
|
|
153
|
+
struct TouchLockError: Error, CustomStringConvertible {
|
|
154
|
+
let description: String
|
|
155
|
+
}
|
|
451
156
|
|
|
452
|
-
|
|
157
|
+
/** Keep one device's touches apart across helper processes. */
|
|
158
|
+
final class TouchCommandLock {
|
|
159
|
+
private var fd: Int32
|
|
160
|
+
|
|
161
|
+
init(deviceID: String) throws {
|
|
162
|
+
let dir = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".buoy/hid-locks")
|
|
163
|
+
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
|
|
164
|
+
let name = SHA256.hash(data: Data(deviceID.utf8)).map { String(format: "%02x", $0) }.joined()
|
|
165
|
+
fd = open(dir.appendingPathComponent(name).path, O_RDWR | O_CREAT, 0o600)
|
|
166
|
+
guard fd >= 0 else { throw TouchLockError(description: "Could not open the touch lock.") }
|
|
167
|
+
let end = DispatchTime.now().uptimeNanoseconds + 1_000_000_000
|
|
168
|
+
while flock(fd, LOCK_EX | LOCK_NB) != 0 {
|
|
169
|
+
let error = errno
|
|
170
|
+
if error != EWOULDBLOCK && error != EAGAIN {
|
|
171
|
+
close(fd); fd = -1
|
|
172
|
+
throw TouchLockError(description: "Could not lock this device for touch.")
|
|
173
|
+
}
|
|
174
|
+
if DispatchTime.now().uptimeNanoseconds >= end {
|
|
175
|
+
close(fd); fd = -1
|
|
176
|
+
throw TouchLockError(description: "This device is busy with another touch. Try again soon.")
|
|
177
|
+
}
|
|
178
|
+
usleep(20_000)
|
|
179
|
+
}
|
|
180
|
+
}
|
|
453
181
|
|
|
454
|
-
|
|
455
|
-
|
|
182
|
+
func release() {
|
|
183
|
+
if fd >= 0 { flock(fd, LOCK_UN); close(fd); fd = -1 }
|
|
184
|
+
}
|
|
185
|
+
deinit { release() }
|
|
186
|
+
}
|
|
456
187
|
|
|
457
|
-
|
|
188
|
+
import Foundation
|
|
458
189
|
import CoreDevice
|
|
459
190
|
import Darwin
|
|
460
191
|
|
|
@@ -524,8 +255,16 @@ struct Command {
|
|
|
524
255
|
let start: (Double, Double)
|
|
525
256
|
let finish: (Double, Double)
|
|
526
257
|
let milliseconds: Double
|
|
258
|
+
/// two: where the second finger starts and ends.
|
|
259
|
+
var startTwo: (Double, Double)?
|
|
260
|
+
var finishTwo: (Double, Double)?
|
|
261
|
+
/// The screen's shape (from --points), so two fingers turn on a true circle.
|
|
262
|
+
var aspect: (Double, Double) = (1, 1)
|
|
527
263
|
/// drag: how long to hold before moving (a press-and-hold drag).
|
|
528
264
|
var holdMilliseconds: Double = 0
|
|
265
|
+
/// scroll: how long to rest at the end before lifting, so the list stops
|
|
266
|
+
/// where the finger stopped instead of coasting on.
|
|
267
|
+
var restMilliseconds: Double = 0
|
|
529
268
|
var keys: [KeyStroke] = []
|
|
530
269
|
var button: HardwareButton?
|
|
531
270
|
|
|
@@ -535,17 +274,20 @@ struct Command {
|
|
|
535
274
|
hidtouch --device <CoreDevice-id> [--points <width> <height>] swipe <x1> <y1> <x2> <y2> <ms>
|
|
536
275
|
hidtouch --device <CoreDevice-id> [--points <width> <height>] long-press <x> <y> <ms>
|
|
537
276
|
hidtouch --device <CoreDevice-id> [--points <width> <height>] drag <x1> <y1> <x2> <y2> <hold-ms> <move-ms>
|
|
277
|
+
hidtouch --device <CoreDevice-id> [--points <width> <height>] scroll <x1> <y1> <x2> <y2> <move-ms> <rest-ms>
|
|
278
|
+
hidtouch --device <CoreDevice-id> [--points <width> <height>] two <ax1> <ay1> <bx1> <by1> <ax2> <ay2> <bx2> <by2> <ms>
|
|
538
279
|
hidtouch --device <CoreDevice-id> type <text> (or "-" to read the text from stdin)
|
|
539
280
|
hidtouch --device <CoreDevice-id> key backspace
|
|
540
281
|
hidtouch --device <CoreDevice-id> button home|lock|siri|volume-up|volume-down
|
|
541
282
|
|
|
542
283
|
Coordinates default to 0...1 fractions, with (0,0) at the top left.
|
|
284
|
+
two moves two fingers at once: finger a from (ax1, ay1) to (ax2, ay2) and finger b from (bx1, by1) to (bx2, by2). Pinch, spread, rotate and two-finger pans are all this.
|
|
543
285
|
--points converts screen points to fractions using the supplied width and height.
|
|
544
286
|
Durations must be 1...10000 ms. A simulator must be booted; a phone must be connected and unlocked. The id is the simulator UDID or the phone's CoreDevice identifier.
|
|
545
287
|
Quote text as one argument. Typing supports printable ASCII and newline on a US keyboard layout.
|
|
546
288
|
"""
|
|
547
289
|
|
|
548
|
-
init(_ arguments: [String]) throws {
|
|
290
|
+
init(_ arguments: [String], input: String? = nil) throws {
|
|
549
291
|
var args = ArraySlice(arguments)
|
|
550
292
|
var id: UUID?
|
|
551
293
|
var width = 1.0
|
|
@@ -573,8 +315,18 @@ struct Command {
|
|
|
573
315
|
}
|
|
574
316
|
guard let id else { throw UsageError("--device is required.") }
|
|
575
317
|
guard let action = args.popFirst() else { throw UsageError("A gesture is required.") }
|
|
576
|
-
if
|
|
577
|
-
|
|
318
|
+
if action == "ping" {
|
|
319
|
+
// Wake the device connection and touch support, touching nothing.
|
|
320
|
+
guard args.isEmpty else { throw UsageError("ping takes no arguments.") }
|
|
321
|
+
deviceID = id
|
|
322
|
+
self.action = action
|
|
323
|
+
start = (0, 0)
|
|
324
|
+
finish = (0, 0)
|
|
325
|
+
milliseconds = 0
|
|
326
|
+
return
|
|
327
|
+
}
|
|
328
|
+
if ["type", "key", "button"].contains(action) {
|
|
329
|
+
guard args.count == 1, let value = args.first else {
|
|
578
330
|
throw UsageError("\\(action) requires exactly one argument.")
|
|
579
331
|
}
|
|
580
332
|
deviceID = id
|
|
@@ -586,7 +338,7 @@ struct Command {
|
|
|
586
338
|
case "type":
|
|
587
339
|
// "-" reads the text from stdin, so a typed password never
|
|
588
340
|
// shows up in the process list.
|
|
589
|
-
let text = value == "-" ? String(decoding: FileHandle.standardInput.readDataToEndOfFile(), as: UTF8.self) : value
|
|
341
|
+
let text = value == "-" ? (input ?? String(decoding: FileHandle.standardInput.readDataToEndOfFile(), as: UTF8.self)) : value
|
|
590
342
|
keys = try KeyStroke.map(text)
|
|
591
343
|
case "key":
|
|
592
344
|
guard value == "backspace" else { throw UsageError("Unknown key: \\(value). Expected backspace.") }
|
|
@@ -599,7 +351,7 @@ struct Command {
|
|
|
599
351
|
}
|
|
600
352
|
return
|
|
601
353
|
}
|
|
602
|
-
let counts = ["tap": 2, "swipe": 5, "long-press": 3, "drag": 6]
|
|
354
|
+
let counts = ["tap": 2, "swipe": 5, "long-press": 3, "drag": 6, "scroll": 6, "two": 9]
|
|
603
355
|
guard counts[action] == args.count else { throw UsageError("Invalid gesture or argument count.") }
|
|
604
356
|
func point() throws -> (Double, Double) {
|
|
605
357
|
let x = try number(args.popFirst()) / width
|
|
@@ -609,13 +361,30 @@ struct Command {
|
|
|
609
361
|
}
|
|
610
362
|
return (x, y)
|
|
611
363
|
}
|
|
364
|
+
if action == "two" {
|
|
365
|
+
let a1 = try point(), b1 = try point(), a2 = try point(), b2 = try point()
|
|
366
|
+
let duration = try number(args.popFirst())
|
|
367
|
+
guard (1...10000).contains(duration) else { throw UsageError("Duration must be 1...10000 ms.") }
|
|
368
|
+
deviceID = id
|
|
369
|
+
self.action = action
|
|
370
|
+
start = a1
|
|
371
|
+
finish = a2
|
|
372
|
+
startTwo = b1
|
|
373
|
+
finishTwo = b2
|
|
374
|
+
milliseconds = duration
|
|
375
|
+
aspect = (width, height)
|
|
376
|
+
return
|
|
377
|
+
}
|
|
612
378
|
let start = try point()
|
|
613
|
-
let finish = action == "swipe" || action == "drag" ? try point() : start
|
|
379
|
+
let finish = action == "swipe" || action == "drag" || action == "scroll" ? try point() : start
|
|
614
380
|
let hold = action == "drag" ? try number(args.popFirst()) : 0
|
|
615
381
|
guard (0...10000).contains(hold) else { throw UsageError("Hold must be 0...10000 ms.") }
|
|
616
382
|
// A real iPhone ignores a 100 ms touch; 150 ms taps both phones and simulators.
|
|
617
383
|
let duration = action == "tap" ? 150.0 : try number(args.popFirst())
|
|
618
384
|
guard (1...10000).contains(duration) else { throw UsageError("Duration must be 1...10000 ms.") }
|
|
385
|
+
let rest = action == "scroll" ? try number(args.popFirst()) : 0
|
|
386
|
+
guard (0...10000).contains(rest) else { throw UsageError("Rest must be 0...10000 ms.") }
|
|
387
|
+
restMilliseconds = rest
|
|
619
388
|
holdMilliseconds = hold
|
|
620
389
|
deviceID = id
|
|
621
390
|
self.action = action
|
|
@@ -628,6 +397,7 @@ struct Command {
|
|
|
628
397
|
@main struct HIDTouch {
|
|
629
398
|
static func main() async {
|
|
630
399
|
let arguments = Array(CommandLine.arguments.dropFirst())
|
|
400
|
+
if arguments == ["--stream"] { await stream(); return }
|
|
631
401
|
if arguments.contains("--help") && Array(arguments.suffix(2)) != ["type", "--help"] {
|
|
632
402
|
print(Command.usage)
|
|
633
403
|
return
|
|
@@ -681,6 +451,55 @@ struct Command {
|
|
|
681
451
|
}
|
|
682
452
|
}
|
|
683
453
|
|
|
454
|
+
struct Request: Decodable { let args: [String]; let input: String }
|
|
455
|
+
|
|
456
|
+
static func stream() async {
|
|
457
|
+
let manager = DeviceManager(serviceConnection: CoreDeviceService.sharedConnection, allowedDeviceVisibilityClasses: [.default, .simulators])
|
|
458
|
+
// SIGALRM ends even a blocked CoreDevice call.
|
|
459
|
+
alarm(40)
|
|
460
|
+
await manager.awaitFullInitialization()
|
|
461
|
+
alarm(0)
|
|
462
|
+
while let line = readLine() {
|
|
463
|
+
alarm(40)
|
|
464
|
+
defer { alarm(0) }
|
|
465
|
+
do {
|
|
466
|
+
let request = try JSONDecoder().decode(Request.self, from: Data(line.utf8))
|
|
467
|
+
let command = try Command(request.args, input: request.input)
|
|
468
|
+
do {
|
|
469
|
+
let lock = try TouchCommandLock(deviceID: command.deviceID.uuidString)
|
|
470
|
+
defer { lock.release() }
|
|
471
|
+
guard let device = manager.devices[command.deviceID] else { throw UsageError("The device is not in CoreDevice.") }
|
|
472
|
+
switch command.action {
|
|
473
|
+
case "ping":
|
|
474
|
+
_ = try await device.getImplementation(for: CapabilityStaticMember<DigitizerHIDCapability>())
|
|
475
|
+
print("{\\"ok\\":true}")
|
|
476
|
+
fflush(stdout)
|
|
477
|
+
continue
|
|
478
|
+
case "type", "key":
|
|
479
|
+
let keyboard = try await device.getImplementation(for: CapabilityStaticMember<KeyboardHIDCapability>())
|
|
480
|
+
try sendKeys(command.keys, keyboard: keyboard)
|
|
481
|
+
case "button":
|
|
482
|
+
let buttons = try await device.getImplementation(for: CapabilityStaticMember<ButtonHIDCapability>())
|
|
483
|
+
if let button = command.button { try press(button, buttons: buttons) }
|
|
484
|
+
default:
|
|
485
|
+
let digitizer = try await device.getImplementation(for: CapabilityStaticMember<DigitizerHIDCapability>())
|
|
486
|
+
try await gesture(command, digitizer: digitizer)
|
|
487
|
+
}
|
|
488
|
+
// This process stays up, so the queued release is still
|
|
489
|
+
// delivered after we reply; the short wait only keeps the
|
|
490
|
+
// next touch (held off by the lock) from landing on it.
|
|
491
|
+
try await Task.sleep(nanoseconds: 80_000_000)
|
|
492
|
+
}
|
|
493
|
+
print("{\\"ok\\":true}")
|
|
494
|
+
} catch {
|
|
495
|
+
let data = try! JSONSerialization.data(withJSONObject: ["ok": false, "error": String(describing: error)])
|
|
496
|
+
print(String(decoding: data, as: UTF8.self))
|
|
497
|
+
}
|
|
498
|
+
fflush(stdout)
|
|
499
|
+
}
|
|
500
|
+
withExtendedLifetime(manager) {}
|
|
501
|
+
}
|
|
502
|
+
|
|
684
503
|
static func sendKeys(_ keys: [KeyStroke], keyboard: any HIDKeyboard) throws {
|
|
685
504
|
func send(_ code: UInt16, _ state: HIDButtonState) throws {
|
|
686
505
|
try keyboard.send(key: HIDKeyboardUsageCode(rawValue: code), state: state)
|
|
@@ -720,12 +539,37 @@ struct Command {
|
|
|
720
539
|
down = false
|
|
721
540
|
}
|
|
722
541
|
|
|
542
|
+
/// Two fingers part of the way through a gesture. Each turns around the
|
|
543
|
+
/// point between them and slides toward or away from it, so a rotation
|
|
544
|
+
/// follows a circle (straight lines would cut the corner and barely turn).
|
|
545
|
+
static func twoFingers(_ command: Command, _ b1: (Double, Double), _ b2: (Double, Double), _ t: Double) -> ((Double, Double), (Double, Double)) {
|
|
546
|
+
let (w, h) = command.aspect
|
|
547
|
+
let a1 = (command.start.0 * w, command.start.1 * h), a2 = (command.finish.0 * w, command.finish.1 * h)
|
|
548
|
+
let p1 = (b1.0 * w, b1.1 * h), p2 = (b2.0 * w, b2.1 * h)
|
|
549
|
+
let c1 = ((a1.0 + p1.0) / 2, (a1.1 + p1.1) / 2), c2 = ((a2.0 + p2.0) / 2, (a2.1 + p2.1) / 2)
|
|
550
|
+
let c = (c1.0 + (c2.0 - c1.0) * t, c1.1 + (c2.1 - c1.1) * t)
|
|
551
|
+
let r1 = hypot(a1.0 - c1.0, a1.1 - c1.1), r2 = hypot(a2.0 - c2.0, a2.1 - c2.1)
|
|
552
|
+
let t1 = atan2(a1.1 - c1.1, a1.0 - c1.0)
|
|
553
|
+
var turn = atan2(a2.1 - c2.1, a2.0 - c2.0) - t1
|
|
554
|
+
if turn > Double.pi { turn -= 2 * Double.pi }
|
|
555
|
+
if turn < -Double.pi { turn += 2 * Double.pi }
|
|
556
|
+
let r = r1 + (r2 - r1) * t, angle = t1 + turn * t
|
|
557
|
+
let clamp = { (v: Double) in min(1, max(0, v)) }
|
|
558
|
+
let a = (clamp((c.0 + r * cos(angle)) / w), clamp((c.1 + r * sin(angle)) / h))
|
|
559
|
+
let b = (clamp((c.0 - r * cos(angle)) / w), clamp((c.1 - r * sin(angle)) / h))
|
|
560
|
+
return (a, b)
|
|
561
|
+
}
|
|
562
|
+
|
|
723
563
|
static func gesture(_ command: Command, digitizer: any HIDDigitizer) async throws {
|
|
564
|
+
// ping only wakes the connection: never send a touch for it.
|
|
565
|
+
if command.action == "ping" { return }
|
|
724
566
|
var current = command.start
|
|
567
|
+
var currentTwo = command.startTwo
|
|
725
568
|
func send(_ type: DigitizerEventType) throws {
|
|
726
569
|
try digitizer.send(
|
|
727
570
|
pointOne: DigitizerPoint(x: current.0, y: current.1),
|
|
728
|
-
pointTwo:
|
|
571
|
+
pointTwo: currentTwo.map { DigitizerPoint(x: $0.0, y: $0.1) },
|
|
572
|
+
eventType: type, edge: .none, target: .mainScreen
|
|
729
573
|
)
|
|
730
574
|
digitizer.sendBarrier()
|
|
731
575
|
}
|
|
@@ -734,7 +578,7 @@ struct Command {
|
|
|
734
578
|
defer { if down { try? send(.end) } }
|
|
735
579
|
try send(.start)
|
|
736
580
|
down = true
|
|
737
|
-
if command.action == "swipe" || command.action == "drag" {
|
|
581
|
+
if command.action == "swipe" || command.action == "drag" || command.action == "scroll" || command.action == "two" {
|
|
738
582
|
// A drag holds still first, so the app sees a long press, then moves.
|
|
739
583
|
if command.holdMilliseconds > 0 {
|
|
740
584
|
try await Task.sleep(nanoseconds: UInt64(command.holdMilliseconds * 1_000_000))
|
|
@@ -745,12 +589,29 @@ struct Command {
|
|
|
745
589
|
for step in 1...steps {
|
|
746
590
|
let fraction = Double(step) / Double(steps)
|
|
747
591
|
try await clock.sleep(until: began + .nanoseconds(Int64(command.milliseconds * fraction * 1_000_000)))
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
592
|
+
if let b1 = command.startTwo, let b2 = command.finishTwo {
|
|
593
|
+
(current, currentTwo) = twoFingers(command, b1, b2, fraction)
|
|
594
|
+
} else {
|
|
595
|
+
// scroll: ease out, so the finger is slowing to a stop as it
|
|
596
|
+
// lifts and the list doesn't fling on.
|
|
597
|
+
let f = command.action == "scroll" ? 1 - pow(1 - fraction, 3) : fraction
|
|
598
|
+
current = (
|
|
599
|
+
command.start.0 + (command.finish.0 - command.start.0) * f,
|
|
600
|
+
command.start.1 + (command.finish.1 - command.start.1) * f
|
|
601
|
+
)
|
|
602
|
+
}
|
|
752
603
|
try send(.position)
|
|
753
604
|
}
|
|
605
|
+
// scroll: keep the finger still at the end, still reporting, so
|
|
606
|
+
// the lift has no speed and the list doesn't coast.
|
|
607
|
+
if command.restMilliseconds > 0 {
|
|
608
|
+
let restSteps = max(1, Int(ceil(command.restMilliseconds / (1000.0 / 60.0))))
|
|
609
|
+
let restBegan = clock.now
|
|
610
|
+
for step in 1...restSteps {
|
|
611
|
+
try await clock.sleep(until: restBegan + .nanoseconds(Int64(command.restMilliseconds * Double(step) / Double(restSteps) * 1_000_000)))
|
|
612
|
+
try send(.position)
|
|
613
|
+
}
|
|
614
|
+
}
|
|
754
615
|
} else {
|
|
755
616
|
try await Task.sleep(nanoseconds: UInt64(command.milliseconds * 1_000_000))
|
|
756
617
|
}
|
|
@@ -758,44 +619,373 @@ struct Command {
|
|
|
758
619
|
down = false
|
|
759
620
|
}
|
|
760
621
|
}
|
|
761
|
-
`;HID_INTERFACE="// swift-interface-format-version: 1.0\n// swift-compiler-version: Apple Swift version 6.4\n// swift-module-flags: -target arm64-apple-macosx15.0 -enable-library-evolution -module-name CoreDevice\n// Reconstructed API subset. No replacement framework code is linked.\n// Non-frozen types and protocol/class calls resolve through Apple metadata and thunks.\nimport Foundation\nimport CoreGraphics\npublic struct Capability {}\npublic protocol CoreDeviceServiceConnection {}\npublic struct CoreDeviceService {\n public static var sharedConnection: any CoreDeviceServiceConnection { get }\n}\npublic enum DeviceVisibilityClass: Swift.Hashable {\n case `default`, wirelessPairableDevices, devicesBeingProvisioned, simulators\n public static func == (lhs: DeviceVisibilityClass, rhs: DeviceVisibilityClass) -> Swift.Bool\n public func hash(into hasher: inout Swift.Hasher)\n public var hashValue: Swift.Int { get }\n}\npublic class DeviceManager {\n public static var shared: DeviceManager { get }\n public init(serviceConnection: any CoreDeviceServiceConnection, allowedDeviceVisibilityClasses: Swift.Set<DeviceVisibilityClass>)\n public func awaitFullInitialization() async\n public func waitForPostPluginLoadCheckIn() async\n public var devices: [Foundation.UUID: RemoteDevice] { get }\n public func deviceNamed(_ name: Swift.String) throws -> RemoteDevice\n}\npublic class RemoteDevice {\n public var deviceIdentifier: Foundation.UUID { get }\n public func getImplementation<C: DeviceCapability>(for capability: CapabilityStaticMember<C>) async throws -> C.ProtocolType\n}\npublic protocol DeviceCapability {\n associatedtype ProtocolType\n static var capability: Capability { get }\n}\npublic struct CapabilityStaticMember<C> {\n public init()\n}\npublic struct DigitizerHIDCapability: DeviceCapability {\n public typealias ProtocolType = any HIDDigitizer\n public static var capability: Capability { get }\n}\npublic protocol DeviceCapabilityProtocol {\n static var capability: Capability { get }\n static var identifier: Swift.String { get }\n static var identifierSuffix: Swift.String { get }\n static var priority: Swift.Int { get }\n}\npublic protocol HIDDigitizer: DeviceCapabilityProtocol {\n func send(pointOne: DigitizerPoint, pointTwo: DigitizerPoint?, eventType: DigitizerEventType, edge: DigitizerEdge, target: DigitizerTarget) throws\n func sendBarrier()\n}\npublic struct DigitizerPoint {\n public init(x: Swift.Double, y: Swift.Double)\n}\npublic enum DigitizerEventType { case start, position, end }\npublic enum DigitizerEdge { case none, top, left, bottom, right }\npublic enum DigitizerTarget { case mainScreen, display1, display2, display3, display4, display5, display6, display7, display8, display9, display10 }\npublic struct KeyboardHIDCapability: DeviceCapability {\n public typealias ProtocolType = any HIDKeyboard\n public static var capability: Capability { get }\n}\npublic protocol HIDKeyboard: DeviceCapabilityProtocol {\n func send(key: HIDKeyboardUsageCode, state: HIDButtonState) throws\n func sendBarrier()\n}\npublic struct HIDKeyboardUsageCode {\n public init(rawValue: Swift.UInt16)\n}\npublic enum HIDButtonState { case down, up }\npublic struct ButtonHIDCapability: DeviceCapability {\n public typealias ProtocolType = any HIDButton\n public static var capability: Capability { get }\n}\npublic protocol HIDButton: DeviceCapabilityProtocol {\n func sendCustomButton(usagePage: Swift.Int, usageCode: Swift.Int, state: HIDButtonState) throws\n func sendBarrier()\n}\n";HID_HASH="3f80e965020a"}});async function xcodeBuild(){try{const{stdout:e}=await execFileAsync13("xcode-select",["-p"],{timeout:1e4});const n=import_node_path12.default.join(e.trim(),"..","Info.plist");const{stdout:t}=await execFileAsync13("plutil",["-extract","DTXcodeBuild","raw",n],{timeout:1e4});return t.trim().replace(/[^\w.-]/g,"")||"unknown"}catch{return"unknown"}}async function build(){if(process.platform!=="darwin")return null;const e=import_node_path12.default.join(import_node_os9.default.homedir(),".buoy","hidtouch",`${await xcodeBuild()}-${HID_HASH}`);const n=import_node_path12.default.join(e,"hidtouch");try{await import_node_fs11.promises.access(n);return n}catch{}try{await import_node_fs11.promises.access(import_node_path12.default.join(PRIVATE_FRAMEWORKS,"CoreDevice.framework"))}catch{buildError="CoreDevice is not installed (it ships with Xcode 15 and later).";return null}const t=await import_node_fs11.promises.mkdtemp(import_node_path12.default.join(import_node_os9.default.tmpdir(),"buoy-hidtouch-"));try{await import_node_fs11.promises.mkdir(import_node_path12.default.join(t,"modules"));await import_node_fs11.promises.writeFile(import_node_path12.default.join(t,"hidtouch.swift"),HID_SWIFT);await import_node_fs11.promises.writeFile(import_node_path12.default.join(t,"modules","CoreDevice.swiftinterface"),HID_INTERFACE);const r=import_node_path12.default.join(t,"hidtouch");await execFileAsync13("xcrun",["swiftc","-O","-module-cache-path",import_node_path12.default.join(t,"cache"),"-I",import_node_path12.default.join(t,"modules"),"-F",PRIVATE_FRAMEWORKS,"-framework","CoreDevice","-parse-as-library",import_node_path12.default.join(t,"hidtouch.swift"),"-o",r],{timeout:18e4,maxBuffer:8*1024*1024,env:{...process.env,TMPDIR:t}});await import_node_fs11.promises.mkdir(e,{recursive:true});const i=`${n}.${process.pid}`;await import_node_fs11.promises.copyFile(r,i);await import_node_fs11.promises.chmod(i,493);await import_node_fs11.promises.rename(i,n);return n}catch(r){const i=r;buildError=(i.stderr||i.message||"").trim().split("\n").slice(-3).join(" ").slice(0,300);return null}finally{await import_node_fs11.promises.rm(t,{recursive:true,force:true}).catch(()=>void 0)}}function simHidTool(){built??=build();return built}async function deviceOrientation(e){try{const{stdout:n}=await execFileAsync13("xcrun",["devicectl","device","orientation","get","--device",e],{timeout:15e3});const t=/Orientation:\s*(\w+)/.exec(n)?.[1];return t==="portrait"||t==="portraitUpsideDown"||t==="landscapeLeft"||t==="landscapeRight"?t:null}catch{return null}}function toDigitizer(e,n,t,r){if(!t)return r==="portraitUpsideDown"?[1-e,1-n]:[e,n];if(r==="landscapeRight")return[n,1-e];return[1-n,e]}async function run3(e,n,t){try{const r=execFileAsync13(e,n,{timeout:45e3});r.child.stdin?.end(t??"");await r}catch(r){const i=r;throw new Error(`The simulator touch failed: ${(i.stderr||i.message||"").replace(/^hidtouch:\s*/,"").split("\n")[0].slice(0,300)}`)}}async function simHidTap(e,n,t,r,i,s){const o=t.width>t.height;const[a,c]=toDigitizer(r/t.width,i/t.height,o,await deviceOrientation(n));await run3(e,s?["--device",n,"long-press",frac(a),frac(c),String(Math.round(s))]:["--device",n,"tap",frac(a),frac(c)])}async function simHidSwipe(e,n,t,r,i,s,o=0){const a=t.width>t.height;const c=await deviceOrientation(n);const u=toDigitizer(r[0]/t.width,r[1]/t.height,a,c);const l=toDigitizer(i[0]/t.width,i[1]/t.height,a,c);const d=String(Math.round(Math.min(1e4,Math.max(1,s))));const h=[frac(u[0]),frac(u[1]),frac(l[0]),frac(l[1])];await run3(e,o>0?["--device",n,"drag",...h,String(Math.round(Math.min(1e4,o))),d]:["--device",n,"swipe",...h,d])}async function simHidType(e,n,t){if(!SIM_TYPEABLE.test(t))throw new Error("The simulator keyboard types plain ASCII letters, digits, punctuation and newlines only. For other text use tap_element with text.");if(!t)return;await run3(e,["--device",n,"type","-"],t)}var import_node_child_process15,import_node_util13,import_node_fs11,import_node_os9,import_node_path12,execFileAsync13,PRIVATE_FRAMEWORKS,built,buildError,clamp3,frac,SIM_TYPEABLE;var init_simHid=__esm({"src/capture/simHid.ts"(){"use strict";import_node_child_process15=require("child_process");import_node_util13=require("util");import_node_fs11=require("fs");import_node_os9=__toESM(require("os"));import_node_path12=__toESM(require("path"));init_hidSource_generated();execFileAsync13=(0,import_node_util13.promisify)(import_node_child_process15.execFile);PRIVATE_FRAMEWORKS="/Library/Developer/PrivateFrameworks";built=null;buildError="";clamp3=e=>Math.min(1,Math.max(0,e));frac=e=>clamp3(e).toFixed(5);SIM_TYPEABLE=/^[\x20-\x7e\n]*$/}});async function phoneScreenSize(e){const n=phoneScreens.get(e);if(n&&Date.now()-n.at<3e4)return n.size;const t=await phoneScreenshot(e);const r={width:t.readUInt32BE(16),height:t.readUInt32BE(20)};phoneScreens.set(e,{size:r,at:Date.now()});return r}async function xcodeShimDir(){const e=(await execFileAsync14("xcode-select",["-p"],{timeout:5e3}).catch(()=>({stdout:""}))).stdout.trim();if(!e.endsWith("/Contents/Developer"))return null;const n=import_node_path13.default.dirname(e);const t=import_node_path13.default.join(e,"Library","PrivateFrameworks","SimulatorKit.framework");const r=import_node_path13.default.join(n,"SharedFrameworks","SimulatorKit.framework");const i=u=>import_node_fs12.promises.access(u).then(()=>true,()=>false);if(await i(t)||!await i(r))return null;const s=(await execFileAsync14("plutil",["-extract","DTXcodeBuild","raw","-o","-",import_node_path13.default.join(n,"Info.plist")]).catch(()=>({stdout:"x"}))).stdout.trim();const o=import_node_path13.default.join(import_node_os10.default.homedir(),".buoy","xcode-shim",s.replace(/[^\w.-]/g,"_"),"Contents");const a=import_node_path13.default.join(o,"Developer");if(await i(import_node_path13.default.join(a,"Library","PrivateFrameworks","SimulatorKit.framework")))return a;await import_node_fs12.promises.mkdir(import_node_path13.default.join(a,"Library","PrivateFrameworks"),{recursive:true});const c=async(u,l,d)=>{for(const h of await import_node_fs12.promises.readdir(u)){if(h===d)continue;await import_node_fs12.promises.symlink(import_node_path13.default.join(u,h),import_node_path13.default.join(l,h)).catch(()=>void 0)}};await c(n,o,"Developer");await c(e,a,"Library");await c(import_node_path13.default.join(e,"Library"),import_node_path13.default.join(a,"Library"),"PrivateFrameworks");await c(import_node_path13.default.join(e,"Library","PrivateFrameworks"),import_node_path13.default.join(a,"Library","PrivateFrameworks"),"").catch(()=>void 0);await import_node_fs12.promises.symlink(r,import_node_path13.default.join(a,"Library","PrivateFrameworks","SimulatorKit.framework")).catch(()=>void 0);return a}async function restartCompanion(e){const n=`/tmp/idb/${e}.buoy-restart`;await import_node_fs12.promises.mkdir("/tmp/idb",{recursive:true}).catch(()=>void 0);const t=async()=>{try{await(await import_node_fs12.promises.open(n,"wx")).close();return true}catch{const r=await import_node_fs12.promises.stat(n).then(i=>Date.now()-i.mtimeMs,()=>0);if(r>15e3){const i=`${n}.stale-${process.pid}-${Date.now()}`;await import_node_fs12.promises.rename(n,i).then(()=>import_node_fs12.promises.unlink(i).catch(()=>void 0),()=>void 0);return t()}return false}};if(!await t()){for(let r=0;r<60;r++){await delay4(250);if(!await import_node_fs12.promises.stat(n).then(()=>true,()=>false))return}return}try{await execFileAsync14("pkill",["-f",`idb_companion --udid ${e}`],{timeout:5e3}).catch(()=>void 0);await delay4(300);const r=await xcodeShimDir().catch(()=>null);const i=(0,import_node_child_process16.spawn)("idb_companion",["--udid",e,"--grpc-domain-sock",`/tmp/idb/${e}_companion.sock`,"--only","simulator"],{detached:true,stdio:"ignore",env:r?{...process.env,DEVELOPER_DIR:r}:process.env});i.on("error",()=>void 0);i.unref();await delay4(1800)}finally{await import_node_fs12.promises.unlink(n).catch(()=>void 0)}}async function idb(e,n=15e3,t=false){try{const{stdout:r}=await execFileAsync14("idb",e,{timeout:n});return r}catch(r){const i=r;if(i.code==="ENOENT")throw new Error(IDB_MISSING);const s=(i.stderr||i.message||"").slice(0,300);const o=e.includes("--udid")?e[e.indexOf("--udid")+1]:void 0;if(!t&&o&&/not booted|connection refused|Failed to connect to companion/i.test(s)){await restartCompanion(o);return idb(e,n,true)}if(/SimulatorKit is required/i.test(s)){if(!t&&o&&await xcodeShimDir().catch(()=>null)){await restartCompanion(o);return idb(e,n,true)}throw new Error("idb can't send touches with this Xcode: it can't load SimulatorKit, and Buoy could not work around it. Use tap_element (it calls the element's handler) for now. Reading the screen (describe_screen, screenshot_component) still works.")}throw new Error(`idb ${e[0]} ${e[1]??""} failed: ${s}`)}}async function iosTree(e){const n=JSON.parse(await idb(["ui","describe-all","--udid",e,"--json","--nested"]));const t=[];const r=s=>{t.push(s);for(const o of s.children??[])r(o)};n.forEach(r);const i=t.find(s=>s.type==="Application"&&s.frame);return{all:t,screen:i?.frame?{width:i.frame.width,height:i.frame.height}:{width:0,height:0}}}async function findByLabel(e,n,t){const r=n.trim().toLowerCase();const i=Date.now()+8e3;const s=u=>{const l=(u.AXLabel??"").trim().toLowerCase();if(!l)return 0;if(l===r)return 3;if(l.startsWith(r))return 2;if(l.includes(r))return 1;return 0};let o=t.all.filter(u=>s(u)>0&&u.frame&&u.type!=="Application");if(!o.some(u=>s(u)===3)&&t.screen.width){const u=[];for(const l of[.95,.97,.09,.06])for(let d=20;d<t.screen.width;d+=40)u.push([d,Math.round(t.screen.height*l)]);for(const[l,d]of u){if(Date.now()>i)break;try{const h=JSON.parse(await idb(["ui","describe-point","--udid",e,String(l),String(d),"--json"],3e3));if(s(h)>0&&h.frame)o.push(h);if(s(h)===3)break}catch(h){if(IDB_SETUP.test(String(h)))throw h}}}const a=Math.max(0,...o.map(s));o=o.filter(u=>s(u)===a);let c=o.filter((u,l)=>o.findIndex(d=>JSON.stringify(d.frame)===JSON.stringify(u.frame))===l);if(c.length>1){const u=c.filter(l=>(l.AXLabel??"").trim()===n.trim());if(u.length)c=u}if(c.length>1){const u=c.filter(l=>l.type&&!/StaticText|Text$|Other|Image/.test(l.type));if(u.length)c=u}return c}function registerNativeTools(e,n){async function t(c,u){if(c.platform==="android")return adbScreenSize(c.serial);if(c.platform==="ios-device")return phoneScreenSize(c.udid);try{const l=(u??await iosTree(c.udid)).screen;if(!l.width)throw new Error("Could not read the simulator's screen size from idb.");return l}catch(l){if(u||!await simHidTool())throw l;const d=import_node_path13.default.join(import_node_os10.default.tmpdir(),`buoy-size-${process.pid}-${Date.now()}.png`);try{await execFileAsync14("xcrun",["simctl","io",c.udid,"screenshot","--type=png",d],{timeout:2e4});const h=await import_node_fs12.promises.readFile(d);return{width:h.readUInt32BE(16),height:h.readUInt32BE(20)}}finally{await import_node_fs12.promises.rm(d,{force:true}).catch(()=>void 0)}}}async function r(c,u,l){if(c.platform==="android")await adbTap(c.serial,u.x,u.y,l);else if(c.platform==="ios-device"){const d=await simHidTool();if(!d)throw new Error(PHONE_TOUCH);await simHidTap(d,await coreDeviceId(c.udid),await t(c),u.x,u.y,l)}else if(await simHidTool()){await simHidTap(await simHidTool(),c.udid,await t(c),u.x,u.y,l)}else{await assertSimTouchable(c.udid);await idb(["ui","tap","--udid",c.udid,...l?["--duration",(l/1e3).toFixed(2)]:[],String(Math.round(u.x)),String(Math.round(u.y))])}}async function i(c,u,l){const d=await n.callAction(UI_TOOL_ID,"describeScreen",{},c);const h=(l.query??"").toLowerCase();const p=(d.elements??[]).filter(b=>l.nativeTag!=null?b.nativeTag===l.nativeTag:l.testID?b.testID===l.testID:(b.text??b.label??"").toLowerCase()===h);const m=p.filter(b=>b.tap);if(m.length===0)return"No element on screen matches that. Call describe_screen, or use label for native controls.";if(m.length>1&&l.nativeTag==null)return`${m.length} elements match equally well, so nothing was tapped. Use nativeTag: ${m.map(b=>`#${b.nativeTag}`).join(", ")}.`;const g=m[0].tap;const w=`"${m[0].text??m[0].label??m[0].name}"`;if(u.platform==="android"){const b=await adbAppFrame(u.serial,u.packageName);const v=b??{x:0,y:0,...await adbScreenSize(u.serial)};return{x:v.x+g.x*v.width,y:v.y+g.y*v.height,what:w}}const f=await t(u);return{x:g.x*f.width,y:g.y*f.height,what:w}}async function s(c,u){if(c.platform==="android"){const p=findUiNodes(await adbUiNodes(c.serial),u);if(p.length===0)return`No native element labeled "${u}" was found on screen.`;if(p.length>1)return`${p.length} native elements match "${u}" equally well, so nothing was tapped: ${p.map(g=>`"${g.desc||g.text||g.id}" at (${g.bounds.x}, ${g.bounds.y})`).join(", ")}. Tap one by x/y.`;const m=p[0].bounds;return{x:m.x+m.width/2,y:m.y+m.height/2,what:`"${p[0].desc||p[0].text||p[0].id}" (${p[0].cls.split(".").pop()})`}}const l=await iosTree(c.udid);const d=await findByLabel(c.udid,u,l);if(d.length===0)return`No native element labeled "${u}" was found on screen.`;if(d.length>1)return`${d.length} native elements match "${u}" equally well, so nothing was tapped: ${d.map(p=>`"${p.AXLabel}" at (${Math.round(p.frame.x)}, ${Math.round(p.frame.y)})`).join(", ")}. Tap one by x/y.`;const h=d[0].frame;return{x:h.x+h.width/2,y:h.y+h.height/2,what:`"${d[0].AXLabel}" (${d[0].type})`}}const o=import_zod24.z.string().optional().describe("Android: the adb serial, when several devices are connected.");const a=c=>c.platform==="ios"?"pt":"px";e.registerTool("native_tap",{description:"Tap the screen for real (an OS touch: CoreDevice on the iOS Simulator, the way Xcode sends it, or idb on older Xcode; adb on Android), for native-only controls like a native tab bar or a system dialog, or when tap_element finds no handler. Pass holdMs for a long press. label and x/y work even when the app's JS is stuck.",inputSchema:{label:import_zod24.z.string().optional().describe('Native accessibility label, e.g. "Rewards" for a native tab.'),query:import_zod24.z.string().optional().describe("Text of an element from describe_screen."),testID:import_zod24.z.string().optional(),nativeTag:import_zod24.z.number().optional(),x:import_zod24.z.number().min(0).max(1).optional().describe("Horizontal position, 0 to 1."),y:import_zod24.z.number().min(0).max(1).optional().describe("Vertical position, 0 to 1."),holdMs:import_zod24.z.number().min(100).max(1e4).optional().describe("Hold the touch this long: a long press (context menus, Paste, reorder handles). 600 is a typical long press."),serial:o,deviceId:deviceIdInput}},async c=>{try{const u=c.nativeTag!=null||!!c.testID||!!c.query;const{id:l,host:d,online:h}=await hostTarget(n,c.deviceId,{serial:c.serial},{allowOffline:!u});if(d.platform==="ios-device"&&!await simHidTool())return fail2(PHONE_TOUCH);let p;if(c.x!=null&&c.y!=null){const g=await t(d);p={x:c.x*g.width,y:c.y*g.height,what:`(${c.x.toFixed(2)}, ${c.y.toFixed(2)})`}}else if(u){p=await i(l,d,c)}else if(c.label){if(d.platform==="ios-device")return fail2("label works on simulators and Android. On a physical iPhone, tap by query, testID or nativeTag (from describe_screen), or by x and y.");p=await s(d,c.label)}else{return fail2("Give label, query, testID, nativeTag, or x and y.")}if(typeof p==="string")return fail2(p);await r(d,p,c.holdMs);const m=h?await observeAfterAction(n,l):" (The app is not connected, so its screen was not read back.)";return text(`${c.holdMs?`Long-pressed (${c.holdMs}ms)`:"Tapped"} ${p.what} with a real touch at (${Math.round(p.x)}, ${Math.round(p.y)}) ${a(d)}.${m}`)}catch(u){return fail2(errMsg2(u))}});e.registerTool("native_type",{description:"Type text on the real keyboard into the focused field (CoreDevice or idb on the iOS Simulator, adb on Android). Tap the field first (tap_element or native_tap). Unlike tap_element's text, this goes through the keyboard like a person typing. It types plain ASCII only (letters, digits, punctuation, newlines).",inputSchema:{text:import_zod24.z.string().describe("The text to type. Write {{secret:NAME}} for a password: Buoy types BUOY_SECRET_NAME from its environment and hides it in what it returns. Prefer real password fields (shown as dots)."),serial:o,deviceId:deviceIdInput}},async c=>{try{const{id:u,host:l,online:d}=await hostTarget(n,c.deviceId,{serial:c.serial},{allowOffline:true});if(l.platform==="ios-device"&&!await simHidTool())return fail2(PHONE_TOUCH);const h=fillSecrets(c.text);if(l.platform==="android")await adbText(l.serial,h);else if(l.platform==="ios-device")await simHidType(await simHidTool(),await coreDeviceId(l.udid),h);else{const m=await simHidTool();if(m)await simHidType(m,l.udid,h);else{await assertSimTouchable(l.udid);await idb(["ui","text","--udid",l.udid,h])}}await delay4(300);const p=d?await observeAfterAction(n,u):"";return text(`Typed ${JSON.stringify(c.text)} on the keyboard.${p}`)}catch(u){return fail2(errMsg2(u))}});e.registerTool("native_swipe",{description:"Swipe the screen for real (CoreDevice or idb on the iOS Simulator, adb on Android): scroll a list, dismiss a sheet, change a page. Give a direction (the way your finger moves) or from/to points as fractions of the screen.",inputSchema:{direction:import_zod24.z.enum(["up","down","left","right"]).optional().describe('"up" scrolls content down the list (finger moves up).'),fromX:import_zod24.z.number().min(0).max(1).optional(),fromY:import_zod24.z.number().min(0).max(1).optional(),toX:import_zod24.z.number().min(0).max(1).optional(),toY:import_zod24.z.number().min(0).max(1).optional(),durationMs:import_zod24.z.number().min(50).max(5e3).optional().describe("Default 300 (1200 with drag)."),drag:import_zod24.z.boolean().optional().describe("Drag instead of flick: press, hold, then move (reorder handles, drag and drop, sliders). On the iOS Simulator with older Xcode (idb) it is a slow swipe only."),serial:o,deviceId:deviceIdInput}},async c=>{try{const{id:u,host:l,online:d}=await hostTarget(n,c.deviceId,{serial:c.serial},{allowOffline:true});if(l.platform==="ios-device"&&!await simHidTool())return fail2(PHONE_TOUCH);const h=await t(l);let p;let m;if(c.fromX!=null&&c.fromY!=null&&c.toX!=null&&c.toY!=null){p=[c.fromX,c.fromY];m=[c.toX,c.toY]}else{const $=c.direction??"up";const k=$==="left"?-.35:$==="right"?.35:0;const T=$==="up"?-.3:$==="down"?.3:0;p=[.5-k/2,.5-T/2];m=[.5+k/2,.5+T/2]}const g=[p[0]*h.width,p[1]*h.height];const w=[m[0]*h.width,m[1]*h.height];let f=0;if(c.drag&&l.platform==="android"){const $=Number((await adbShell(l.serial,"settings get secure long_press_timeout").catch(()=>"")).trim())||500;f=$*1.5+600}const b=Math.max(c.durationMs??(c.drag?1200:300),f);const v=[...g,...w].map($=>String(Math.round($)));const y=l.platform==="android"?null:await simHidTool();if(l.platform!=="android"&&!y)await assertSimTouchable(l.udid);if(l.platform==="android"){if(c.drag)await adbShell(l.serial,`input draganddrop ${v.join(" ")} ${Math.round(b)}`);else await adbSwipe(l.serial,g,w,b)}else if(y){const $=l.platform==="ios-device"?await coreDeviceId(l.udid):l.udid;await simHidSwipe(y,$,h,g,w,b,c.drag?700:0)}else if(c.drag){await idb(["ui","swipe","--udid",l.udid,...v,"--duration",(b/1e3).toFixed(2),"--delta","4"])}else await idb(["ui","swipe","--udid",l.udid,...v,"--duration",(b/1e3).toFixed(2)]);await delay4(400);const _=d?await observeAfterAction(n,u):"";return text(`${c.drag?"Dragged":"Swiped"} from (${g.map(Math.round).join(", ")}) to (${w.map(Math.round).join(", ")}) ${a(l)}.${_}`)}catch(u){return fail2(errMsg2(u))}})}var import_zod24,import_node_child_process16,import_node_util14,import_node_fs12,import_node_os10,import_node_path13,execFileAsync14,UI_TOOL_ID,delay4,IDB_MISSING,PHONE_TOUCH,phoneScreens,IDB_SETUP;var init_native=__esm({"src/tools/packs/native.ts"(){"use strict";import_zod24=require("zod");import_node_child_process16=require("child_process");import_node_util14=require("util");import_node_fs12=require("fs");import_node_os10=__toESM(require("os"));import_node_path13=__toESM(require("path"));init_packKit();init_interact();init_adb();init_hostKit();init_secrets();init_simTouch();init_simHid();init_iosDevice();execFileAsync14=(0,import_node_util14.promisify)(import_node_child_process16.execFile);UI_TOOL_ID="highlight-updates";delay4=e=>new Promise(n=>setTimeout(n,e));IDB_MISSING="Native touch on the iOS Simulator needs idb on this Mac (brew install facebook/fb/idb-companion && pipx install fb-idb).";PHONE_TOUCH="Real touches on a physical iPhone need Xcode's CoreDevice touch support, and Buoy couldn't set it up on this Mac. Use tap_element (it calls the element's handler) or run_flow; screenshots, recording and app control work on the iPhone.";phoneScreens=new Map;IDB_SETUP=/idb on this Mac|SimulatorKit|not booted|connection refused|Failed to connect to companion/i}});function projectDir(){return process.env.BUOY_PROJECT_ROOT||process.cwd()}function stamp(e=new Date){const n=t=>String(t).padStart(2,"0");return`${e.getFullYear()}${n(e.getMonth()+1)}${n(e.getDate())}-${n(e.getHours())}${n(e.getMinutes())}${n(e.getSeconds())}`}function noteAgentCall(e,n,t){if(READ_ONLY.test(n)||sessions.size===0)return;let r=typeof t?.deviceId==="string"?t.deviceId:void 0;if(!r){try{r=e.resolveDevice()}catch{return}}const i=r?sessions.get(r):void 0;if(!i?.rec)return;const s=Object.entries(t??{}).filter(([o,a])=>o!=="deviceId"&&a!==void 0&&typeof a!=="object").map(([o,a])=>`${o}: ${String(a).slice(0,60)}`).join(", ");i.agent.push({at:Date.now(),t:0,source:"agent",status:"neutral",title:n,detail:s?redact(s):void 0});clearTimeout(i.afterAction);i.afterAction=setTimeout(()=>void gather(e,i),700);i.afterAction.unref?.()}async function gather(e,n){const t=e.connectedDevices().some(i=>i.deviceId===n.id);if(!t){n.failedPolls++;addConsole(n,(e.lastSync(n.id,"console")?.payload??{}).entries??[]);return}try{const i=await e.callAction("events","exportEvents",{settings:{format:"json",includeEventData:false},limit:500},n.id,{timeoutMs:4e3,silent:true});const s=i?.output?JSON.parse(i.output):null;const o=Array.isArray(s)?s:s?.events??[];for(const a of o){const c=a.timestamp?Date.parse(a.timestamp):NaN;if(!Number.isFinite(c))continue;const u=a.status==="error"||a.status==="success"||a.status==="pending"?a.status:"neutral";const l={at:c,t:0,source:a.source??"event",status:u,title:scrubSecrets(redact(a.title??"")),detail:a.subtitle?scrubSecrets(redact(a.subtitle)):void 0};n.events.set(`${c}|${l.source}|${l.title}|${l.detail??""}|${u}`,l)}if((i?.returned??0)>=500)n.notes.add("Busy app: some events may be missing from busy stretches.")}catch{n.failedPolls++}let r=[];try{const{payload:i}=await e.getSnapshot("console",n.id,{timeoutMs:2500,silent:true});r=i?.entries??[]}catch{r=(e.lastSync(n.id,"console")?.payload??{}).entries??[]}addConsole(n,r)}function addConsole(e,n){for(const t of n){if(typeof t.timestamp!=="number")continue;const[r,...i]=scrubSecrets(redact(t.message??"")).split("\n");const s=t.level==="error"?"error":t.level==="warning"?"warning":"neutral";e.events.set(`console|${t.timestamp}|${t.id??r}`,{at:t.timestamp,t:0,source:"console",status:s,title:r.slice(0,200),detail:i.join("\n").trim().slice(0,600)||void 0})}}async function finish(e,n){const t=n.rec;if(n.poll)clearInterval(n.poll);clearTimeout(n.afterAction);n.stopped??={durationMs:await stopRecording(t)};const{durationMs:r}=n.stopped;await gather(e,n);if(n.failedPolls)n.notes.add(`The app's events could not be read ${n.failedPolls} time(s) during the recording (the app may have been reloading or stuck), so parts of the timeline may be missing.`);const i=t.startedAt;const s=i+r;const o=[...n.events.values(),...n.agent].filter(m=>m.at>=i-500&&m.at<=s+500).map(({at:m,...g})=>({...g,title:scrubSecrets(g.title),detail:g.detail?scrubSecrets(g.detail):void 0,t:Math.max(0,m-i)})).sort((m,g)=>m.t-g.t);if(!o.some(m=>m.source!=="agent"))n.notes.add("No app events were captured. Is the Events tool installed in the app?");const a=t.file.replace(/\.mp4$/,"");const c=hostLabel(t.host);const u=[...n.notes];await import_node_fs13.promises.writeFile(`${a}.timeline.json`,JSON.stringify({device:c,startedAt:new Date(i).toISOString(),durationMs:r,notes:u,items:o},null,1));await import_node_fs13.promises.writeFile(`${a}.html`,viewerHtml({title:n.name,video:import_node_path14.default.basename(t.file),durationMs:r,items:o,device:c,notes:u}));sessions.delete(n.id);const l=m=>import_node_path14.default.relative(projectDir(),m);const d=new Map;for(const m of o)d.set(m.source,(d.get(m.source)??0)+1);const h=m=>`${(m/1e3).toFixed(1)}s`;const p=o.filter(m=>m.status==="error"||m.source==="route"||m.source==="agent").slice(0,14);return[`Saved a ${h(r)} recording of ${c}.`,`- Video: ${l(t.file)}`,`- Viewer (video + timeline, click an event to jump there): ${l(`${a}.html`)}`,`- Timeline data: ${l(`${a}.timeline.json`)}`,"",o.length?`Events: ${[...d].map(([m,g])=>`${m} ${g}`).join(", ")}.`:"No events in this window.",...p.length?["What happened:",...p.map(m=>`- ${h(m.t)} [${m.source}]${m.status==="error"?" ERROR":""} ${m.title}${m.detail&&m.source!=="route"?` (${m.detail.split("\n")[0].slice(0,80)})`:""}`)]:[],...u.map(m=>`Note: ${m}`),"Recordings are kept out of git (.buoy/recordings/.gitignore). Secrets in logs are hidden, but the video shows the screen as it was: check it before sharing."].join("\n")}function registerRecordingTools(e,n){setRecordingProbe(()=>sessions.size>0);e.registerTool("screen_recording",{description:"Record the screen of the iOS Simulator or Android device (start, do the steps, stop). On stop, saves an MP4 plus a viewer page that plays it beside a timeline of what the app did (web calls, query fetches, route changes, store writes, console errors) and what you did (your taps and other actions), and returns a short written summary. In .buoy/recordings. Use it to show a bug or a fix, e.g. for a pull request. Max 3 minutes.",inputSchema:{action:import_zod25.z.enum(["start","stop"]),name:import_zod25.z.string().optional().describe('start: a short name for the files, e.g. "checkout-timeout".'),serial:import_zod25.z.string().optional().describe("Android: the adb serial, when several devices are connected."),deviceId:deviceIdInput}},async t=>{try{if(t.action==="start"){const{id:s,host:o}=await hostTarget(n,t.deviceId,{serial:t.serial});if(sessions.has(s))return fail2("A recording is already running on this device. Stop it first.");const a=(t.name??"recording").trim().replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"recording";const c={id:s,name:a,events:new Map,agent:[],notes:new Set,failedPolls:0};sessions.set(s,c);let u;c.starting=new Promise(d=>u=d);try{const d=import_node_path14.default.join(projectDir(),".buoy","recordings");await import_node_fs13.promises.mkdir(d,{recursive:true});await import_node_fs13.promises.writeFile(import_node_path14.default.join(d,".gitignore"),"*\n",{flag:"wx"}).catch(()=>void 0);await n.getSnapshot("events",s,{timeoutMs:2e3,silent:true}).catch(()=>void 0);const h=import_node_path14.default.join(d,`${a}-${stamp()}-${(0,import_node_crypto6.randomUUID)().slice(0,6)}.mp4`);c.rec=await startRecording(o,h)}catch(d){sessions.delete(s);throw d}finally{u()}c.poll=setInterval(()=>void gather(n,c),2e3);c.poll.unref?.();c.rec.stopTimer=setTimeout(()=>{c.finishing??=finish(n,c);c.finishing.then(d=>finished.set(s,`The recording hit the ${MAX_RECORDING_MS/6e4}-minute limit and was saved.
|
|
762
|
-
${d}`),d=>finished.set(s,`The recording hit the time limit and could not be saved: ${errMsg2(d)}`))},MAX_RECORDING_MS);c.rec.stopTimer.unref?.();const l=typedSecretValues().length?" Note: a secret was typed earlier this session; if it is still on screen, the video will show it. Typing secrets is blocked until the recording stops.":" Typing secrets ({{secret:NAME}}) is blocked until the recording stops, because a video can't hide them.";return text(`Recording ${hostLabel(o)}. Do the steps, then call screen_recording with action "stop". It stops by itself after ${MAX_RECORDING_MS/6e4} minutes.${l}`)}let r=t.deviceId;if(!r){try{r=n.requireProDevice()}catch{r=void 0}}if(!r||!sessions.has(r)){if(r&&finished.has(r)){const s=finished.get(r);finished.delete(r);return text(s)}if(sessions.size===1)r=[...sessions.keys()][0];else return fail2(sessions.size?"Several recordings are running. Pass deviceId.":'No recording is running. Start one with action "start".')}const i=sessions.get(r);await i.starting;if(!i.rec)return fail2("The recording did not start.");i.finishing??=finish(n,i);try{return text(await i.finishing)}catch(s){i.finishing=void 0;return fail2(`Could not save the recording: ${errMsg2(s)}. Call stop again to retry.`)}}catch(r){return fail2(errMsg2(r))}})}var import_zod25,import_node_fs13,import_node_path14,import_node_crypto6,sessions,finished,READ_ONLY;var init_recording=__esm({"src/tools/packs/recording.ts"(){"use strict";import_zod25=require("zod");import_node_fs13=require("fs");import_node_path14=__toESM(require("path"));import_node_crypto6=require("crypto");init_packKit();init_hostKit();init_secrets();init_recorder();sessions=new Map;finished=new Map;READ_ONLY=/^(get_|list_|describe_screen$|screenshot_component$|screen_recording$|wait_for_automation$|compare_reports$)/}});async function run4(e,n,t=2e4){try{const{stdout:r}=await execFileAsync15(e,n,{timeout:t});return r}catch(r){const i=r;throw new Error(`${e} ${n.slice(0,3).join(" ")} failed: ${(i.stderr||i.message||"").trim().split("\n").slice(-2).join(" ").slice(0,300)}`)}}async function rotate(e,n){if(e.platform==="android"){await adbShell(e.serial,"settings put system accelerometer_rotation 0");await adbShell(e.serial,`settings put system user_rotation ${ANDROID_ROTATION[n]}`);return`Rotated to ${n.replace("_"," ")} (auto-rotate is now off on this device; rotate to portrait to go back).`}await devicectl2(["device","orientation","set","--device",e.udid,IOS_ORIENTATION[n]]);return`Rotated the device to ${n.replace("_"," ")}. An app that only supports portrait keeps its screen upright.`}async function shake(e){if(e.platform==="ios"){await run4("xcrun",["simctl","spawn",e.udid,"notifyutil","-p","com.apple.UIKit.SimulatorShake"]);return"Sent a shake to the simulator (the same event as Device > Shake). Check the screen: an app only reacts if it listens for shakes."}if(e.platform==="android"){if(!/^emulator-\d+$/.test(e.serial))throw new Error("A physical Android phone can't be shaken from the computer. Use an emulator, or shake the phone.");for(const n of["0:25:0","0:-25:0","0:25:0","0:-25:0","0:9.81:0"]){await adb(e.serial,["emu","sensor","set","acceleration",n]);await new Promise(t=>setTimeout(t,80))}return"Shook the emulator (an accelerometer burst). Check the screen: an app only reacts if it listens for shakes."}throw new Error("A physical iPhone can't be shaken from the computer. Use a simulator, or shake the phone.")}async function setClipboard(e,n){if(e.platform==="ios"){await new Promise((t,r)=>{const i=(0,import_node_child_process17.spawn)("xcrun",["simctl","pbcopy",e.udid],{stdio:["pipe","ignore","pipe"]});let s="";i.stderr.on("data",o=>s+=o);i.on("error",r);i.on("exit",o=>o===0?t():r(new Error(`simctl pbcopy failed: ${s.trim()}`)));i.stdin.end(n)})}else if(e.platform==="ios-device"){const t=import_node_path15.default.join(import_node_os11.default.tmpdir(),`buoy-clip-${(0,import_node_crypto7.randomUUID)()}.txt`);await import_node_fs14.promises.writeFile(t,n,{mode:384});try{await devicectl2(["device","pasteboard","copy","--device",e.udid,"--type","public.utf8-plain-text","--file",t])}finally{await import_node_fs14.promises.unlink(t).catch(()=>void 0)}}else{throw new Error("Setting the clipboard from the computer isn't supported on Android. Use native_type to type the text instead.")}return e.platform==="ios-device"?"Put the text on the iPhone's clipboard. To paste it for real, long-press the field (native_tap with holdMs: 600) and tap Paste (native_tap with x and y; labels don't work on a phone).":'Put the text on the clipboard. To paste it for real, long-press the field (native_tap with holdMs: 600) and tap Paste (native_tap label: "Paste").'}async function biometrics(e,n,t){if(e.platform==="android"){if(!/^emulator-\d+$/.test(e.serial))throw new Error("Biometrics can be simulated on an Android emulator only.");const r=await adbShell(e.serial,"dumpsys fingerprint").catch(()=>"");if(n&&/"count"\s*:\s*0|enrolled[^\n]*\b0\b/i.test(r)){throw new Error("No fingerprint is enrolled on this emulator. Enroll one in Settings > Security, then try again.")}const i=t??(n?1:9731);await adb(e.serial,["emu","finger","touch",String(i)]);return n?`Touched fingerprint id ${i}. It matches only if that finger is enrolled in the emulator's Settings (enroll one there first if the app says no fingerprints).`:`Touched fingerprint id ${i}, meant to fail. It would match instead if id ${i} is enrolled; pass another fingerId if so.`}await devicectl2(["device","simulate","biometrics","--device",e.udid,n?"--success":"--failure"]);return n?"Simulated a matching Face ID / Touch ID.":"Simulated a Face ID / Touch ID that doesn't match."}var import_node_child_process17,import_node_util15,import_node_fs14,import_node_os11,import_node_path15,import_node_crypto7,execFileAsync15,devicectl2,IOS_ORIENTATION,ANDROID_ROTATION;var init_deviceGestures=__esm({"src/capture/deviceGestures.ts"(){"use strict";import_node_child_process17=require("child_process");import_node_util15=require("util");import_node_fs14=require("fs");import_node_os11=__toESM(require("os"));import_node_path15=__toESM(require("path"));import_node_crypto7=require("crypto");init_adb();execFileAsync15=(0,import_node_util15.promisify)(import_node_child_process17.execFile);devicectl2=e=>run4("xcrun",["devicectl",...e,"--quiet"]);IOS_ORIENTATION={portrait:"portrait",landscape_left:"landscapeLeft",landscape_right:"landscapeRight",upside_down:"portraitUpsideDown"};ANDROID_ROTATION={portrait:0,landscape_left:1,upside_down:2,landscape_right:3}}});function registerDeviceTools(e,n){e.registerTool("device_control",{description:"Do something to the device itself: rotate (orientation), shake (shake-to-undo, shake-to-report, dev menus), clipboard (text on the clipboard for a real paste), biometrics (Face ID / Touch ID / fingerprint match or fail). iOS Simulator, physical iPhone (rotate, clipboard) and Android (rotate, emulator shake and fingerprint). Returns the screen after when the app is connected (not for clipboard).",inputSchema:{action:import_zod26.z.enum(["rotate","shake","clipboard","biometrics"]),orientation:import_zod26.z.enum(["portrait","landscape_left","landscape_right","upside_down"]).optional().describe("rotate (required)."),text:import_zod26.z.string().optional().describe("clipboard (required). {{secret:NAME}} works here too."),match:import_zod26.z.boolean().optional().describe("biometrics: true for a match (default), false for a failed one."),fingerId:import_zod26.z.number().int().min(1).optional().describe("biometrics on an Android emulator: the finger id to touch: an enrolled one for a match (default 1), one that is not enrolled for a failure (default 9731)."),serial:import_zod26.z.string().optional().describe("Android: the adb serial, when several devices are connected."),deviceId:deviceIdInput}},async t=>{try{const{id:r,host:i,online:s}=await hostTarget(n,t.deviceId,{serial:t.serial},{allowOffline:t.action!=="clipboard"});let o;switch(t.action){case"rotate":if(!t.orientation)return fail2("rotate requires `orientation`.");o=await rotate(i,t.orientation);break;case"shake":o=await shake(i);break;case"clipboard":if(t.text===void 0)return fail2("clipboard requires `text`.");o=await setClipboard(i,fillSecrets(t.text));break;case"biometrics":o=await biometrics(i,t.match!==false,t.fingerId);break}await new Promise(c=>setTimeout(c,700));const a=s&&t.action!=="clipboard"?await observeAfterAction(n,r):"";return text(`${o} (${hostLabel(i)})${a}`)}catch(r){return fail2(errMsg2(r))}})}var import_zod26;var init_device=__esm({"src/tools/packs/device.ts"(){"use strict";import_zod26=require("zod");init_packKit();init_hostKit();init_secrets();init_interact();init_deviceGestures()}});function parseReact19Frames(e,n=10){const t=[];for(const r of e.split("\n")){if(t.length>=n)break;const i=parseReact19Stack(r);if(i)t.push(i)}return t}function parseReact19Stack(e){for(const n of e.split("\n")){if(/\b(?:react[-_]stack[-_](?:top|bottom)[-_]frame|jsxDEV(?:Impl)?|jsxWithValidation|createElement)\b/.test(n))continue;const t=n.trim();const r=/:(\d+):(\d+)\)?\s*$/.exec(t);if(!r)continue;const i=t.slice(0,r.index);const s=/\s\((?=https?:\/\/|file:\/\/|address at |\/|[A-Za-z]:[\\/])/.exec(i);let o;let a;if(s){o=i.slice(s.index+2);a=s.index}else{const d=/(?:^at\s+|@)((?:https?:\/\/|file:\/\/|\/|[A-Za-z]:[\\/]).*)$/.exec(i);if(!d)continue;o=d[1];a=d.index}const c=Object.assign([t,o,r[1],r[2]],{index:a});const u=Number(c[2]);const l=Number(c[3]);if(!Number.isSafeInteger(u)||u<1||!Number.isSafeInteger(l))continue;return{file:c[1].replace(/^address at\s+/,""),lineNumber:u,column:l,methodName:t.slice(0,c.index).replace(/^at\s+/,"").replace(/[(@\s]+$/,"")||"x"}}return null}function isBundleURL(e){return/^https?:\/\//i.test(e)}function relativeSourcePath(e,n=process.env.BUOY_PROJECT_ROOT||process.cwd()){let t=e;if(t.startsWith("file://")){try{t=(0,import_node_url2.fileURLToPath)(t)}catch{return e}}if(isBundleURL(t))return t;const r=/^[A-Za-z]:[\\/]/.test(t)&&/^[A-Za-z]:[\\/]/.test(n)?import_node_path16.default.win32:import_node_path16.default;if(!r.isAbsolute(t))return t;const i=r.relative(r.resolve(n),t);return i&&i!==".."&&!i.startsWith(`..${r.sep}`)&&!r.isAbsolute(i)?i.split(r.sep).join("/"):t}async function symbolicateFrame(e,n,t=fetch){const r=await t(`${n.replace(/\/$/,"")}/symbolicate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({stack:[e]}),signal:AbortSignal.timeout(5e3)});if(!r.ok)throw new Error(`Metro could not map this frame (HTTP ${r.status}).`);const i=await r.json();const s=i?.stack?.[0];if(typeof s?.file!=="string"||!s.file||isBundleURL(s.file)||typeof s.lineNumber!=="number"||!Number.isInteger(s.lineNumber)||s.lineNumber<1){throw new Error("Metro did not return a source file and line.")}return{fileName:s.file,lineNumber:s.lineNumber,...typeof s.column==="number"&&Number.isInteger(s.column)&&s.column>=0?{columnNumber:s.column}:{}}}async function symbolicateAppFrame(e,n,t=fetch){const r=await t(`${n.replace(/\/$/,"")}/symbolicate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({stack:e}),signal:AbortSignal.timeout(5e3)});if(!r.ok){const s=(await r.json().catch(()=>null))?.error;const o=typeof s==="string"&&s?` Metro said: ${s.slice(0,200)}`:"";const a=/serialized source map/i.test(o)?" Its cache looks stale; restarting Metro with --clear usually fixes this.":"";throw new Error(`Metro could not map these frames (HTTP ${r.status}).${o}${a}`)}const i=await r.json();for(const s of i?.stack??[]){if(typeof s?.file!=="string"||!s.file||isBundleURL(s.file)||LIBRARY.test(s.file))continue;if(typeof s.lineNumber!=="number"||!Number.isInteger(s.lineNumber)||s.lineNumber<1)continue;return{fileName:s.file,lineNumber:s.lineNumber,...typeof s.column==="number"&&s.column>=0?{columnNumber:s.column}:{}}}throw new Error("Every frame mapped into library code, none into the app.")}async function resolveEntry(e,n){if(!e.source&&e.rawStack&&n){const r=parseReact19Frames(e.rawStack).filter(i=>isBundleURL(i.file));if(r.length){try{return{...e,source:await symbolicateAppFrame(r,n)}}catch(i){const s=/library code/.test(errMsg2(i));return{...e,source:void 0,reason:s?"rendered by library code (no line in the app).":`Could not map the source frame: ${errMsg2(i)}`}}}}const t=e.source&&isBundleURL(e.source.fileName)?{file:e.source.fileName,lineNumber:e.source.lineNumber??0,column:e.source.columnNumber??0,methodName:"x"}:!e.source&&e.rawStack?parseReact19Stack(e.rawStack):null;if(e.source&&!isBundleURL(e.source.fileName))return e;if(!t)return{...e,source:void 0,reason:"React gave no source frame. Use a dev build."};if(!isBundleURL(t.file)){return{...e,source:{fileName:t.file,lineNumber:t.lineNumber,columnNumber:t.column}}}if(!n)return{...e,source:void 0,reason:"The dev server address is not known."};try{return{...e,source:await symbolicateFrame(t,n)}}catch(r){return{...e,source:void 0,reason:`Could not map the source frame: ${errMsg2(r)}`}}}function formatComponentSource(e,n){if(!e.found)return e.reason;let t="";const r=i=>{const s=i.source;let o;if(s){o=relativeSourcePath(s.fileName,n)+(s.lineNumber!=null?`:${s.lineNumber}`:"")+(s.lineNumber!=null&&s.columnNumber!=null?`:${s.columnNumber}`:"")}else if(i.reason?.startsWith("rendered by library")){o=i.reason}else{const a=i.reason??"React gave no source frame. Use a dev build.";o=a===t?"no source (same reason as above).":`no source. ${a}`;t=a}return`${i.name}: ${o} [memo: ${i.memo?"yes":"no"}; forwardRef: ${i.forwardRef?"yes":"no"}]`};return[r(e.component),...e.owners.slice(0,6).map(i=>` owner ${r(i)}`),"Lines after the name are where each component is used (its JSX call site in the parent's file)."].join("\n")}function registerSourceTools(e,n){e.registerTool("get_component_source",{description:"Find where a React view is used in code. Use its name, testID, text, or nativeTag from describe_screen. Get file paths, lines, and up to six owners. See memo and forwardRef flags too. These paths point to JSX calls. Needs a dev build and Buoy Pro.",inputSchema:{query:import_zod27.z.string().trim().min(1).optional().describe("A component name, testID, or text from describe_screen."),nativeTag:import_zod27.z.number().int().nonnegative().optional().describe("The nativeTag from describe_screen. Takes priority over query."),deviceId:deviceIdInput}},async({query:t,nativeTag:r,deviceId:i})=>{try{const s=n.requireProDevice(i);if(r==null&&!t?.trim())return fail2("Pass a query or nativeTag.");const o=await n.callAction("highlight-updates","getComponentSource",{query:t,nativeTag:r},s);if(!o)return fail2("The app gave no source result. Turn on highlight-updates or update Buoy.");if(!o.found)return text(o.reason);const a=n.devServerOrigin(s);const c=await Promise.all([o.component,...o.owners.slice(0,6)].map(d=>resolveEntry(d,a)));const u=o.component.definedIn?await resolveEntry({name:o.component.name,memo:false,forwardRef:false,source:o.component.definedIn.source,rawStack:o.component.definedIn.rawStack},a):null;const l=u?.source?`Its own JSX starts in: ${relativeSourcePath(u.source.fileName)}${u.source.lineNumber!=null?` (line ${u.source.lineNumber})`:""} (usually its definition; a helper that builds JSX can show here instead)
|
|
763
|
-
|
|
622
|
+
`;HID_INTERFACE="// swift-interface-format-version: 1.0\n// swift-compiler-version: Apple Swift version 6.4\n// swift-module-flags: -target arm64-apple-macosx15.0 -enable-library-evolution -module-name CoreDevice\n// Reconstructed API subset. No replacement framework code is linked.\n// Non-frozen types and protocol/class calls resolve through Apple metadata and thunks.\nimport Foundation\nimport CoreGraphics\npublic struct Capability {}\npublic protocol CoreDeviceServiceConnection {}\npublic struct CoreDeviceService {\n public static var sharedConnection: any CoreDeviceServiceConnection { get }\n}\npublic enum DeviceVisibilityClass: Swift.Hashable {\n case `default`, wirelessPairableDevices, devicesBeingProvisioned, simulators\n public static func == (lhs: DeviceVisibilityClass, rhs: DeviceVisibilityClass) -> Swift.Bool\n public func hash(into hasher: inout Swift.Hasher)\n public var hashValue: Swift.Int { get }\n}\npublic class DeviceManager {\n public static var shared: DeviceManager { get }\n public init(serviceConnection: any CoreDeviceServiceConnection, allowedDeviceVisibilityClasses: Swift.Set<DeviceVisibilityClass>)\n public func awaitFullInitialization() async\n public func waitForPostPluginLoadCheckIn() async\n public var devices: [Foundation.UUID: RemoteDevice] { get }\n public func deviceNamed(_ name: Swift.String) throws -> RemoteDevice\n}\npublic class RemoteDevice {\n public var deviceIdentifier: Foundation.UUID { get }\n public func getImplementation<C: DeviceCapability>(for capability: CapabilityStaticMember<C>) async throws -> C.ProtocolType\n}\npublic protocol DeviceCapability {\n associatedtype ProtocolType\n static var capability: Capability { get }\n}\npublic struct CapabilityStaticMember<C> {\n public init()\n}\npublic struct DigitizerHIDCapability: DeviceCapability {\n public typealias ProtocolType = any HIDDigitizer\n public static var capability: Capability { get }\n}\npublic protocol DeviceCapabilityProtocol {\n static var capability: Capability { get }\n static var identifier: Swift.String { get }\n static var identifierSuffix: Swift.String { get }\n static var priority: Swift.Int { get }\n}\npublic protocol HIDDigitizer: DeviceCapabilityProtocol {\n func send(pointOne: DigitizerPoint, pointTwo: DigitizerPoint?, eventType: DigitizerEventType, edge: DigitizerEdge, target: DigitizerTarget) throws\n func sendBarrier()\n}\npublic struct DigitizerPoint {\n public init(x: Swift.Double, y: Swift.Double)\n}\npublic enum DigitizerEventType { case start, position, end }\npublic enum DigitizerEdge { case none, top, left, bottom, right }\npublic enum DigitizerTarget { case mainScreen, display1, display2, display3, display4, display5, display6, display7, display8, display9, display10 }\npublic struct KeyboardHIDCapability: DeviceCapability {\n public typealias ProtocolType = any HIDKeyboard\n public static var capability: Capability { get }\n}\npublic protocol HIDKeyboard: DeviceCapabilityProtocol {\n func send(key: HIDKeyboardUsageCode, state: HIDButtonState) throws\n func sendBarrier()\n}\npublic struct HIDKeyboardUsageCode {\n public init(rawValue: Swift.UInt16)\n}\npublic enum HIDButtonState { case down, up }\npublic struct ButtonHIDCapability: DeviceCapability {\n public typealias ProtocolType = any HIDButton\n public static var capability: Capability { get }\n}\npublic protocol HIDButton: DeviceCapabilityProtocol {\n func sendCustomButton(usagePage: Swift.Int, usageCode: Swift.Int, state: HIDButtonState) throws\n func sendBarrier()\n}\n";HID_HASH="718c261deb06"}});async function xcodeBuild(){try{const{stdout:e}=await execFileAsync10("xcode-select",["-p"],{timeout:1e4});const n=import_node_path9.default.join(process.env.DEVELOPER_DIR||e.trim(),"..","Info.plist");const{stdout:t}=await execFileAsync10("plutil",["-extract","DTXcodeBuild","raw",n],{timeout:1e4});return t.trim().replace(/[^\w.-]/g,"")||"unknown"}catch{return"unknown"}}async function build(e){if(process.platform!=="darwin")return null;const n=import_node_path9.default.join(import_node_os7.default.homedir(),".buoy","hidtouch",`${e}-${HID_HASH}`);const t=import_node_path9.default.join(n,"hidtouch");try{await import_node_fs8.promises.access(t);return t}catch{}try{await import_node_fs8.promises.access(import_node_path9.default.join(PRIVATE_FRAMEWORKS,"CoreDevice.framework"))}catch{buildError="CoreDevice is not installed (it ships with Xcode 15 and later).";return null}const r=await import_node_fs8.promises.mkdtemp(import_node_path9.default.join(import_node_os7.default.tmpdir(),"buoy-hidtouch-"));try{await import_node_fs8.promises.mkdir(import_node_path9.default.join(r,"modules"));await import_node_fs8.promises.writeFile(import_node_path9.default.join(r,"hidtouch.swift"),HID_SWIFT);await import_node_fs8.promises.writeFile(import_node_path9.default.join(r,"modules","CoreDevice.swiftinterface"),HID_INTERFACE);const i=import_node_path9.default.join(r,"hidtouch");await execFileAsync10("xcrun",["swiftc","-O","-module-cache-path",import_node_path9.default.join(r,"cache"),"-I",import_node_path9.default.join(r,"modules"),"-F",PRIVATE_FRAMEWORKS,"-framework","CoreDevice","-parse-as-library",import_node_path9.default.join(r,"hidtouch.swift"),"-o",i],{timeout:18e4,maxBuffer:8*1024*1024,env:{...process.env,TMPDIR:r}});await import_node_fs8.promises.mkdir(n,{recursive:true});const o=`${t}.${process.pid}`;await import_node_fs8.promises.copyFile(i,o);await import_node_fs8.promises.chmod(o,493);await import_node_fs8.promises.rename(o,t);return t}catch(i){const o=i;buildError=(o.stderr||o.message||"").trim().split("\n").slice(-3).join(" ").slice(0,300);return null}finally{await import_node_fs8.promises.rm(r,{recursive:true,force:true}).catch(()=>void 0)}}function simHidTool(){const e=Date.now();const n=!built||e-lastUsed>=1e4||developerDir!==process.env.DEVELOPER_DIR;lastUsed=e;if(refreshing)return refreshing;if(!n)return built;developerDir=process.env.DEVELOPER_DIR;const t=developerDir;refreshing=xcodeBuild().then(r=>{const i=JSON.stringify([t,r]);if(!built||buildKey!==i){buildKey=i;buildError="";built=build(r)}return built}).finally(()=>{refreshing=null});return refreshing}async function deviceOrientation(e){try{const{stdout:n}=await execFileAsync10("xcrun",["devicectl","device","orientation","get","--device",e],{timeout:15e3});const t=/Orientation:\s*(\w+)/.exec(n)?.[1];return t==="portrait"||t==="portraitUpsideDown"||t==="landscapeLeft"||t==="landscapeRight"?t:null}catch{return null}}async function appUpsideDown(e,n){if(!n)return null;try{const{stdout:t}=await execFileAsync10("xcrun",["simctl","get_app_container",e,n,"app"],{timeout:1e4});const{stdout:r}=await execFileAsync10("plutil",["-convert","json","-o","-",import_node_path9.default.join(t.trim(),"Info.plist")],{timeout:1e4});const i=JSON.parse(r);const{stdout:o}=await execFileAsync10("xcrun",["simctl","getenv",e,"SIMULATOR_MODEL_IDENTIFIER"],{timeout:1e4});const s=o.trim().startsWith("iPad")?"ipad":"iphone";const a=i[`UISupportedInterfaceOrientations~${s}`]??i.UISupportedInterfaceOrientations;if(!Array.isArray(a)||!a.every(c=>typeof c==="string"))return null;return a.includes("UIInterfaceOrientationPortraitUpsideDown")}catch{return null}}function toDigitizer(e,n,t,r,i){if(r==="portraitUpsideDown"){if(i==null)throw new Error("Upside-down touch needs the app turn list. Turn the device upright and try again.");return i?[1-e,1-n]:[e,n]}if(!t)return[e,n];if(r==="landscapeRight")return[n,1-e];return[1-n,e]}async function run(e,n,t,r=false){try{const i=n[n.indexOf("--device")+1];await runHidStream(e,i,n,t)}catch(i){const o=i;const s=o.stderr||o.message||"";if(/HID Digitizer/i.test(s)&&/not supported/i.test(s)){console.error("[buoy:hid]",s);throw new Error(r?"Your iPhone isn't connected. Unlock it and plug it in, or put it on the same Wi-Fi. Then try again.":"Touch is not supported on this iOS Simulator.")}throw new Error(`The touch failed: ${s.replace(/^hidtouch:\s*/,"").split("\n")[0].slice(0,300)}`)}}async function simHidTap(e,n,t,r,i,o,s){const a=t.width>t.height;const c=s!==void 0?s:await deviceOrientation(n);const l=c==="portraitUpsideDown"?await appUpsideDown(n,t.bundleId):null;const[u,d]=toDigitizer(r/t.width,i/t.height,a,c,l);await run(e,o?["--device",n,"long-press",frac(u),frac(d),String(Math.round(o))]:["--device",n,"tap",frac(u),frac(d)],void 0,t.isPhone);return c}async function simHidSwipe(e,n,t,r,i,o,s=0,a=0,c){const l=t.width>t.height;const u=c!==void 0?c:await deviceOrientation(n);const d=u==="portraitUpsideDown"?await appUpsideDown(n,t.bundleId):null;const h=toDigitizer(r[0]/t.width,r[1]/t.height,l,u,d);const w=toDigitizer(i[0]/t.width,i[1]/t.height,l,u,d);const p=String(Math.round(Math.min(1e4,Math.max(1,o))));const g=[frac(h[0]),frac(h[1]),frac(w[0]),frac(w[1])];const m=s>0?["--device",n,"drag",...g,String(Math.round(Math.min(1e4,s))),p]:a>0?["--device",n,"scroll",...g,p,String(Math.round(Math.min(1e4,a)))]:["--device",n,"swipe",...g,p];await run(e,m,void 0,t.isPhone);return u}async function simHidTwo(e,n,t,r,i,o,s,a){const c=t.width>t.height;const l=await deviceOrientation(n);const u=l==="portraitUpsideDown"?await appUpsideDown(n,t.bundleId):null;const d=c?{w:t.height,h:t.width}:{w:t.width,h:t.height};const h=[r,i,o,s].flatMap(w=>{const[p,g]=toDigitizer(w[0]/t.width,w[1]/t.height,c,l,u);return[(clamp3(p)*d.w).toFixed(2),(clamp3(g)*d.h).toFixed(2)]});await run(e,["--device",n,"--points",String(d.w),String(d.h),"two",...h,String(Math.round(Math.min(1e4,Math.max(1,a))))],void 0,t.isPhone);return l}async function simHidType(e,n,t){if(!SIM_TYPEABLE.test(t))throw new Error("The simulator keyboard types plain ASCII letters, digits, punctuation and newlines only. For other text use tap_element with text.");if(!t)return;await run(e,["--device",n,"type","-"],t)}var import_node_child_process11,import_node_util10,import_node_fs8,import_node_os7,import_node_path9,execFileAsync10,PRIVATE_FRAMEWORKS,built,buildError,lastUsed,developerDir,buildKey,refreshing,clamp3,frac,SIM_TYPEABLE;var init_simHid=__esm({"src/capture/simHid.ts"(){"use strict";import_node_child_process11=require("child_process");import_node_util10=require("util");import_node_fs8=require("fs");import_node_os7=__toESM(require("os"));import_node_path9=__toESM(require("path"));init_hidSource_generated();init_hidStream();execFileAsync10=(0,import_node_util10.promisify)(import_node_child_process11.execFile);PRIVATE_FRAMEWORKS="/Library/Developer/PrivateFrameworks";built=null;buildError="";lastUsed=0;refreshing=null;clamp3=e=>Math.min(1,Math.max(0,e));frac=e=>clamp3(e).toFixed(5);SIM_TYPEABLE=/^[\x20-\x7e\n]*$/}});function pickDescribeScreenMatch(e,n,t){if(t!=null){const o=e.find(s=>s.nativeTag===t);if(o)return o}const r=(n??"").trim().toLowerCase();if(!r)return void 0;let i;for(const o of e){const s=[o.testID,o.label,o.text,o.name].filter(Boolean).map(l=>l.toLowerCase());let a=0;for(const l of s){if(l===r)a=Math.max(a,100);else if(l.startsWith(r))a=Math.max(a,50);else if(l.includes(r))a=Math.max(a,25)}const c=o.tap;if(c&&c.x>=0&&c.x<=1&&c.y>=0&&c.y<=1)a+=20;else if(c)a-=40;if(a<=0)continue;if(!i||a>i.score)i={el:o,score:a}}return i?.el}function frameToRect(e,n){return{x:e.x*n.width,y:e.y*n.height,width:e.width*n.width,height:e.height*n.height}}var init_screenshotLocate=__esm({"src/tools/packs/screenshotLocate.ts"(){"use strict"}});function reasonMessage(e,n){switch(e.reason){case"no-renders":return"No components matched via highlight tracking or the live fiber walk. Pass a testID / name from describe_screen, then retry.";case"no-match":return n?`Nothing matched "${n}".`:"No query or nativeTag given \u2014 pass one, or a testID/name to search for.";case"no-measurement":return"Found the component but couldn't measure it \u2014 it may have just unmounted. Re-navigate to it and retry.";default:return e.reason?`Locate failed: ${e.reason}`:"Couldn't locate that component."}}function candidatesText(e){if(!e||e.length===0)return"";const n=e.map(t=>{const r=t.testID||t.nativeID;return`- ${t.componentName||t.viewType}${r?` (${r})`:""} \u2014 nativeTag ${t.nativeTag}, rendered \xD7${t.renderCount}`});return`
|
|
623
|
+
|
|
624
|
+
Closest matches (retry with a more precise query, or pass nativeTag directly):
|
|
625
|
+
${n.join("\n")}`}function registerScreenshotTools(e,n){e.registerTool("screenshot_component",{_meta:coreTool(),description:"Take a screenshot of the app. Pass compareTo with a saved PNG path to view both screens. It first says what changed, measured: where, which element, and the exact colors before and now. Then the saved file, then the live screen. Leave query and nativeTag out for the whole screen. To crop a React Native view on an iOS Sim, pass query or nativeTag. The tool may scroll that view into sight. Use describe_screen to read text or find controls. Pictures use more tokens. Run the MCP on the device host.",inputSchema:{compareTo:import_zod11.z.string().min(1).optional().describe("A saved PNG file to view next to this screen. Use a full path or a path from the project root. The file stays as it is."),query:import_zod11.z.string().optional().describe('Fuzzy match against testID, nativeID, accessibilityLabel, component name, or view type \u2014 e.g. "submit-button".'),nativeTag:import_zod11.z.number().optional().describe("An exact nativeTag (from a previous call's candidates) to skip fuzzy matching."),scrollIntoView:import_zod11.z.boolean().optional().describe("Attempt to scroll an off-screen component into view before capture. Default true; inspect the result."),serial:import_zod11.z.string().optional().describe("Android: the adb serial, when several devices are connected."),baseline:import_zod11.z.string().optional().describe('Whole screen only: a name like "home". The first call saves the screen as that baseline (in .buoy/baselines); later calls compare against it and report what changed, with a diff picture.'),updateBaseline:import_zod11.z.boolean().optional().describe("With baseline: save the current screen as the new baseline instead of comparing."),steady:import_zod11.z.boolean().optional().describe("With baseline: freeze the app's clock at the baseline's moment while capturing, so countdowns and times match (needs @buoy-gg/clock). Default true when the app has the clock tool."),threshold:import_zod11.z.number().min(0).max(1).optional().describe("With baseline: per-pixel color tolerance, 0 to 1. Default 0.1."),ignore:import_zod11.z.array(import_zod11.z.string()).optional().describe('With baseline: leave these out of the comparison, by testID (e.g. ["live-map", "ad-banner"]), for parts that change on their own.'),ignoreAreas:import_zod11.z.array(import_zod11.z.object({x:import_zod11.z.number(),y:import_zod11.z.number(),width:import_zod11.z.number(),height:import_zod11.z.number()})).optional().describe("With baseline: areas to leave out, as fractions of the screen (0 to 1)."),deviceId:deviceIdInput}},async t=>{try{if(t.compareTo){if(t.query||t.nativeTag!=null)return fail3("compareTo uses the whole screen. Leave query and nativeTag out.");if(t.baseline||t.updateBaseline!=null||t.steady!=null||t.threshold!=null||t.ignore!=null||t.ignoreAreas!=null)return fail3("compareTo shows both pictures. Use baseline for diff options.");return await compareFileShot(n,t.compareTo,t.deviceId,t.serial)}if(t.baseline){if(t.query||t.nativeTag!=null)return fail3("baseline works on the whole screen: leave query and nativeTag out.");return await baselineShot(n,t.baseline,{deviceId:t.deviceId,serial:t.serial,update:t.updateBaseline,threshold:t.threshold,steady:t.steady,ignore:t.ignore,ignoreAreas:t.ignoreAreas})}if(!t.query&&t.nativeTag==null){const{id:y,host:$,online:T}=await hostTarget(n,t.deviceId,{serial:t.serial},{allowOffline:true});let _=Buffer.alloc(0);const x=await maskSecrets(n,y,T,async()=>_=await hostPng($));const I={length:x.covered};const D=await toSmallImage(x.png);const E=$.platform==="ios-device"&&isAllBlack(_)?` ${BLACK_PHONE_NOTE}`:"";return{content:[{type:"image",data:D.data,mimeType:D.mimeType},{type:"text",text:`Whole screen of ${hostLabel($)}, ${D.width}\xD7${D.height}px.${I.length?` ${I.length} element(s) showing a secret were blacked out.`:""}${E}`}]}}const r=n.requireProDevice(t.deviceId);await n.callAction(TOOL_ID,"setSilentTracking",{enabled:true},r).catch(()=>{});let i=t.nativeTag;const o=i==null&&t.query?await exactTag(n,r,t.query):null;if(o)i=o.tag;const s=await n.callAction(TOOL_ID,"locateComponent",{query:i==null?t.query:void 0,nativeTag:i,scrollIntoView:t.scrollIntoView??true,margin:MARGIN_PT},r);let a=s;if(!a.matched&&(a.reason==="no-renders"||a.reason==="no-match")){const y=await n.callAction(TOOL_ID,"describeScreen",{},r).catch(()=>null);const $=y?.elements?pickDescribeScreenMatch(y.elements,t.query,i):void 0;if($?.frame&&y?.screen){a={matched:true,live:true,rect:frameToRect($.frame,y.screen),screen:y.screen,nativeTag:$.nativeTag??void 0,componentName:$.name,testID:$.testID}}else if(a.reason==="no-renders"){a={matched:false,reason:"no-match",candidates:a.candidates}}}if(!a.matched||!a.rect||!a.screen){return fail3(reasonMessage(a,t.query)+candidatesText(a.candidates))}if(i==null&&t.query){const y=t.query.toLowerCase();const $=a.candidates?.find(D=>D.nativeTag===a.nativeTag);const T=await n.callAction(TOOL_ID,"describeScreen",{},r,{timeoutMs:4e3}).catch(()=>null);const _=T?.elements?.find(D=>D.nativeTag===a.nativeTag);const x=[a.testID,a.nativeID,a.componentName,$?.testID,$?.nativeID,$?.componentName,_?.testID,_?.nativeID,_?.text,_?.label].filter(Boolean).map(D=>String(D).toLowerCase());const I=x.some(D=>D.includes(y)||D.length>3&&y.includes(D));if(!I){return fail3(`"${t.query}" is not on the current screen (the closest component was ${a.componentName??"unknown"}${a.testID?` [${a.testID}]`:""}). Navigate to it first, or pass a testID from describe_screen.`+candidatesText(a.candidates))}}const{host:c}=await hostTarget(n,r);if(c.platform!=="ios")return fail3("Cropping one component works on the iOS Simulator. Leave query out for a whole-screen picture.");let l={ok:false};const u=await maskSecrets(n,r,true,async()=>{l=await captureIosFramebuffer(c.udid);return l.ok&&l.srcPath?import_node_fs9.promises.readFile(l.srcPath):Buffer.alloc(0)});if(u.covered&&l.ok&&l.srcPath)await import_node_fs9.promises.writeFile(l.srcPath,u.png);if(!l.ok||!l.srcPath||!l.width||!l.height){return fail3(l.error??"Screenshot capture failed.")}const d=l.width/a.screen.width;const h=a.rect;const w=CAPTURE_PADDING_PT;const p=await cropToBuffer(l.srcPath,{width:l.width,height:l.height},{x:(h.x-w)*d,y:(h.y-w)*d,width:(h.width+w*2)*d,height:(h.height+w*2)*d});if(!p.ok||!p.buffer){return fail3(p.error??"Crop failed.")}const g=a.componentName||o?.name||"component";const m=a.testID??o?.testID;const f=m?` (testID: "${m}")`:"";const b=a.inView===false?"\n\nNote: the component is partly off-screen even after scrolling, so the crop is clamped to the screen edge.":"";const v=`Captured "${g}"${f} \u2014 ${p.width}\xD7${p.height}px.${b}`;return{content:[{type:"image",data:p.buffer.toString("base64"),mimeType:"image/png"},{type:"text",text:v}]}}catch(r){return fail3(errMsg3(r))}})}async function maskSecrets(e,n,t,r){const i=typeof r==="function"?r:async()=>r;const o=secretValues();if(!o.length)return{png:await i(),covered:0};const s=t?await secretBoxes(e,n,o):null;const a=await i();const c=t?await secretBoxes(e,n,o):null;if(s===null||c===null){if(t||typedSecretValues().length){throw new Error("Buoy can't read the app's screen to hide secrets right now, so no picture was taken. Try again in a moment.")}return{png:a,covered:0}}const l=[...s,...c];if(!a.length)return{png:a,covered:0};return{png:l.length?blackOut(a,l):a,covered:Math.max(s.length,c.length)}}async function secretBoxes(e,n,t){const r=await e.callAction(TOOL_ID,"describeScreen",{includeHidden:false,includeBuoy:true,fullText:true},n,{timeoutMs:4e3}).catch(()=>null);if(!r?.screen)return null;const i=typedSecretValues().length>0;const o=[];for(const s of r.elements??[]){const a=s.value;const c=[s.text,s.label,a].filter(h=>h!=null&&h!=="").map(String);const l=c.some(h=>t.some(w=>showsSecret(h,w)));const u=i&&s.control==="text"&&a===void 0;if(!l&&!u)continue;const d=s.frame?.width&&s.frame.height?fractionFrame(s,r.screen):void 0;if(!d)return null;o.push({...d,pixels:0})}return o}function showsSecret(e,n){const t=e.replace(/\s+/g," ");const r=n.replace(/\s+/g," ").trim();if(t.includes(r))return true;const i=t.replace(/(…|\.\.\.)$/,"");for(let o=r.length-1;o>=MIN_SECRET_LENGTH;o--)if(i.endsWith(r.slice(0,o)))return true;return false}function blackOut(e,n){const t=import_pngjs4.PNG.sync.read(e);for(const r of n){const i=Math.max(0,Math.floor((r.x-.01)*t.width));const o=Math.min(t.width,Math.ceil((r.x+r.width+.01)*t.width));const s=Math.max(0,Math.floor((r.y-.005)*t.height));const a=Math.min(t.height,Math.ceil((r.y+r.height+.005)*t.height));for(let c=s;c<a;c++){for(let l=i;l<o;l++){const u=(c*t.width+l)*4;t.data[u]=t.data[u+1]=t.data[u+2]=0;t.data[u+3]=255}}}return import_pngjs4.PNG.sync.write(t)}async function exactTag(e,n,t){const r=await e.callAction(TOOL_ID,"describeScreen",{},n,{timeoutMs:4e3}).catch(()=>null);const i=r?.elements??[];const o=l=>({tag:l.nativeTag,name:l.name,testID:l.testID});const s=i.filter(l=>l.testID===t&&l.nativeTag!=null);if(s.length===1)return o(s[0]);const a=t.trim().toLowerCase();const c=i.filter(l=>(l.text??l.label??"").trim().toLowerCase()===a&&l.nativeTag!=null);return c.length===1?o(c[0]):null}async function readComparisonPng(e){const n=32*1024*1024;const t=i=>{if(!i.isFile()||i.size>n)throw new Error("Use a PNG file under 32 MB.")};t(await import_node_fs9.promises.stat(e));const r=await import_node_fs9.promises.open(e,import_node_fs9.constants.O_RDONLY|import_node_fs9.constants.O_NONBLOCK);try{t(await r.stat());const i=[];let o=0;while(o<=n){const l=Buffer.alloc(Math.min(64*1024,n+1-o));const{bytesRead:u}=await r.read(l,0,l.length,null);if(!u)break;o+=u;if(o>n)throw new Error("Use a PNG file under 32 MB.");i.push(l.subarray(0,u))}const s=Buffer.concat(i,o);if(s.length<24||s.subarray(0,8).toString("hex")!=="89504e470d0a1a0a")throw new Error("The saved file must be a PNG.");const a=s.readUInt32BE(16),c=s.readUInt32BE(20);if(!a||!c||a*c>32e6)throw new Error("Use a PNG with at most 32 million pixels.");return s}finally{await r.close()}}async function compareFileShot(e,n,t,r){const i=n==="~"?import_node_os8.default.homedir():n.startsWith("~/")?import_node_path10.default.join(import_node_os8.default.homedir(),n.slice(2)):n;const o=await readComparisonPng(import_node_path10.default.resolve(process.env.BUOY_PROJECT_ROOT||process.cwd(),i));const{id:s,host:a,online:c}=await hostTarget(e,t,{serial:r},{allowOffline:true});const l=await maskSecrets(e,s,c,()=>hostPng(a));const u=await toSmallImage(o);const d=await toSmallImage(l.png);const h=await measureChange(e,s,c,o,l.png);return{content:[...h?[{type:"text",text:h}]:[],{type:"text",text:`Saved file: ${n} (${u.width}x${u.height}).`},{type:"image",data:u.data,mimeType:u.mimeType},{type:"text",text:`Current screen (${d.width}x${d.height}). Compare it with the saved file above.${l.covered?" Fields with secrets are hidden in this screen.":""}`},{type:"image",data:d.data,mimeType:d.mimeType}]}}async function measureChange(e,n,t,r,i){const o=.06;let s;try{s=diffScreens(r,i,{ignoreTop:o})}catch{return null}if(!s.boxes.length)return"Measured: no change outside the status bar.";let a=[];if(t){try{const l=await e.callAction("highlight-updates","describeScreen",{},n,{timeoutMs:3e3,silent:true});const u=l?.screen??{width:1,height:1};a=(l?.elements??[]).map(d=>({name:d.name,words:d.text??d.label,testID:d.testID,frame:fractionFrame(d,u)}))}catch{}}const c=s.boxes.slice(0,3).map(l=>{const u=elementsIn(l,a)[0];const d=boxColors(r,i,l,o);return`- ${describeSpot(l)}${u?`, ${u}`:""}${d?`: main color ${d.before} before, ${d.after} now`:""}.`});return[`Measured: ${s.percent.toFixed(1)}% of the screen changed, in ${s.boxes.length} area${s.boxes.length===1?"":"s"}.`,...c].join("\n")}function baselinePath(e){const n=e.trim().replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"")||"screen";return import_node_path10.default.join(process.env.BUOY_PROJECT_ROOT||process.cwd(),".buoy","baselines",`${n}.png`)}function fractionFrame(e,n){if(e.frame&&e.frame.width&&e.frame.height){const t=e.frame.x+e.frame.width>1.5||e.frame.y+e.frame.height>1.5;return t?{x:e.frame.x/n.width,y:e.frame.y/n.height,width:e.frame.width/n.width,height:e.frame.height/n.height}:{...e.frame}}if(e.tap)return{x:e.tap.x-.01,y:e.tap.y-.01,width:.02,height:.02};return void 0}function elementsIn(e,n){const t=[];for(const r of n){const i=r.frame;if(!i)continue;const o=Math.max(0,Math.min(e.x+e.width,i.x+i.width)-Math.max(e.x,i.x));const s=Math.max(0,Math.min(e.y+e.height,i.y+i.height)-Math.max(e.y,i.y));const a=i.width*i.height;if(!a||o*s/a<.5)continue;t.push({label:labelOf(r),area:a,words:!!r.words})}return[...new Set(t.sort((r,i)=>Number(i.words)-Number(r.words)||r.area-i.area).map(r=>r.label))].slice(0,3)}function textChanges(e,n){const t=d=>d.testID?`id:${d.testID}`:`${d.name??""}@${d.frame?`${Math.round(d.frame.x*40)},${Math.round(d.frame.y*40)}`:"?"}`;const r=new Map(e.filter(d=>d.words).map(d=>[t(d),d]));const i=new Map(n.filter(d=>d.words).map(d=>[t(d),d]));const o=new Set([...r.values()].map(d=>d.words));const s=new Set([...i.values()].map(d=>d.words));const a=[];for(const[d,h]of i){const w=r.get(d);if(w){if(w.words!==h.words)a.push(`changed: ${labelOf({...h,words:void 0})} "${w.words}" \u2192 "${h.words}"`)}else if(!o.has(h.words))a.push(`appeared: ${labelOf(h)}`)}for(const[d,h]of r)if(!i.has(d)&&!s.has(h.words))a.push(`gone: ${labelOf(h)}`);const c=[...r.entries()].filter(([d,h])=>!i.has(d)&&!s.has(h.words)).map(([,d])=>d);const l=[...i.entries()].filter(([d,h])=>!r.has(d)&&!o.has(h.words)).map(([,d])=>d);const u=(d,h)=>!!d&&!!h&&d.x<h.x+h.width&&h.x<d.x+d.width&&d.y<h.y+h.height&&h.y<d.y+d.height;for(const d of l){const h=c.find(p=>p.name===d.name&&u(p.frame,d.frame));if(!h)continue;c.splice(c.indexOf(h),1);const w=new Set([`appeared: ${labelOf(d)}`,`gone: ${labelOf(h)}`]);for(let p=a.length-1;p>=0;p--)if(w.has(a[p]))a.splice(p,1);a.push(`changed: ${labelOf({...d,words:void 0})} "${h.words}" \u2192 "${d.words}"`)}return a.slice(0,12)}async function readScreen(e,n){try{const[t,r,i]=await Promise.all([e.callAction("highlight-updates","describeScreen",{includeBuoy:true},n,{timeoutMs:4e3}),e.callAction("highlight-updates","describeScreen",{},n,{timeoutMs:4e3}),e.callAction("route-events","getCurrentRoute",{},n,{timeoutMs:2e3}).catch(()=>null)]);const o=r?.screen??t?.screen;if(!o)return null;const s=new Set((r?.elements??[]).map(u=>u.nativeTag));const a=[];for(const u of t?.elements??[]){if(s.has(u.nativeTag))continue;const d=fractionFrame(u,o);if(d)a.push({x:d.x-.01,y:d.y-.01,width:d.width+.02,height:d.height+.02,pixels:0})}const c=(r?.elements??[]).map(u=>{const d=scrubSecrets((u.text??u.label??"").replace(/[\s\u200b\u00a0]+/g," ").trim());return{name:u.name,words:d||void 0,testID:u.testID?scrubSecrets(u.testID):void 0,frame:fractionFrame(u,o)}});const l=i?.path??i?.pathname;return{elements:c,masks:a,route:l?scrubSecrets(l):void 0}}catch{return null}}async function withFrozenClock(e,n,t,r){let i;let o;let s;try{await e.callAction("clock","freeze",{time:t},n);await new Promise(c=>setTimeout(c,1300));i=await r()}catch(c){o=c}finally{try{await e.callAction("clock","reset",{},n)}catch(c){s=c}}const a=s?` WARNING: putting the app's clock back failed (${errMsg3(s)}); run clock_action reset.`:"";if(o)throw new Error(`${errMsg3(o)}${a}`);return{result:i,note:` The app's clock was frozen at ${new Date(t).toISOString()} for the capture.${a}`}}async function baselineShot(...e){return(await runBaseline(...e)).result}async function runBaseline(e,n,t){const{id:r,host:i}=await hostTarget(e,t.deviceId,{serial:t.serial});const o=baselinePath(n);const s=o.replace(/\.png$/,".json");const a=import_node_path10.default.relative(process.env.BUOY_PROJECT_ROOT||process.cwd(),o);let c=null;try{c=await import_node_fs9.promises.readFile(o)}catch{}const l=!c||!!t.update;const u=l?{}:JSON.parse(await import_node_fs9.promises.readFile(s,"utf8").catch(()=>"{}"));const d=hostLabel(i);const h=e.connectedDevices().find(z=>z.deviceId===r)?.tools.some(z=>z.toolId==="clock")??false;const w=t.steady??h;let p="";const g=async()=>{const{result:z,steadied:B}=await withSteadyStatusBar(i,async()=>({png:(await maskSecrets(e,r,true,()=>hostPng(i))).png,screen:await readScreen(e,r)}));return{...z,steadied:B}};let m;if(w&&h){const z=await e.callAction("clock","getState",{},r).catch(()=>null);if(z?.mode==="real"){const B=l||!u.steadyTime?Math.floor(Date.now()/6e4)*6e4:u.steadyTime;u.steadyTime=B;const F=await withFrozenClock(e,r,B,g);m=F.result;p+=F.note}else{m=await g();p+=" The app's clock was already overridden, so it was left as it was."}}else{m=await g();if(w&&!h)p+=" (steady needs the Clock tool in the app; times on screen may differ.)"}const f={width:m.png.readUInt32BE(16),height:m.png.readUInt32BE(20)};if(l){await import_node_fs9.promises.mkdir(import_node_path10.default.dirname(o),{recursive:true});await import_node_fs9.promises.writeFile(o,m.png);const z={...u,device:d,size:f,route:m.screen?.route,elements:m.screen?.elements};await import_node_fs9.promises.writeFile(s,JSON.stringify(z,null,1));const B=await toSmallImage(m.png);const F=`${c?"Replaced":"Saved"} baseline "${n}"`;return{outcome:{saved:true,changed:false,percent:0,texts:0,summary:`${F} (first run)`},result:{content:[{type:"image",data:B.data,mimeType:B.mimeType},{type:"text",text:`${c?"Replaced":"Saved"} baseline "${n}" (${a}) from ${d}${m.screen?.route?` on ${m.screen.route}`:""}. Call again with the same baseline to compare.${p}`}]}}}const b=[];if(u.device&&u.device!==d)b.push(`The baseline was saved on ${u.device}; this is ${d}.`);if(u.route&&m.screen?.route&&u.route!==m.screen.route)b.push(`The baseline was on ${u.route}; the app is now on ${m.screen.route}.`);const v=[...t.ignoreAreas??[]];const y=new Set(t.ignore??[]);const $=new Set(y);for(const z of[...u.elements??[],...m.screen?.elements??[]]){if(!z.testID||!y.has(z.testID)||!z.frame)continue;$.delete(z.testID);v.push({x:z.frame.x-.005,y:z.frame.y-.005,width:z.frame.width+.01,height:z.frame.height+.01})}if($.size)b.push(`Not on screen, so not left out: ${[...$].join(", ")}.`);const T=i.platform==="android"?[]:[{x:.28,y:0,width:.44,height:.055}];const _=diffScreens(c,m.png,{threshold:t.threshold,masks:[...m.screen?.masks??[],...v,...T],ignoreTop:m.steadied?0:.065});const x=z=>!!z&&v.some(B=>z.x+z.width/2>=B.x&&z.x+z.width/2<=B.x+B.width&&z.y+z.height/2>=B.y&&z.y+z.height/2<=B.y+B.height);const I=z=>(!z.testID||!y.has(z.testID))&&!x(z.frame);const D=u.elements&&m.screen?textChanges(u.elements.filter(I),m.screen.elements.filter(I)):[];const E=[m.steadied?"":"status bar",m.screen?.masks.length?"Buoy's overlay":"",v.length?"the parts you asked to ignore":""].filter(Boolean);const S=E.join(" and ");const k=S?`; ${S} left out`:"";const M=b.length?`
|
|
626
|
+
|
|
627
|
+
\u26A0\uFE0F ${b.join(" ")}`:"";if(_.changedPixels===0&&D.length===0){return{outcome:{saved:false,changed:false,percent:0,texts:0,summary:`no change from baseline "${n}"`},result:text(`No change from baseline "${n}" (${a}${k}).${p}${M}`)}}const A=_.boxes.map((z,B)=>{const F=m.screen?elementsIn(z,m.screen.elements):[];const U=`${describeSpot(z)} (x ${z.x.toFixed(2)}, y ${z.y.toFixed(2)}, ${z.width.toFixed(2)}\xD7${z.height.toFixed(2)})`;return`${B+1}. ${U}${F.length?`: ${F.join(", ")}`:""}`});const P=await toSmallImage(_.diffPng);const R=_.percent<.01&&_.changedPixels>0?"<0.01":_.percent.toFixed(2);const j=A[0]?`; ${A[0].replace(/^1\. /,"")}`:"";const C=D[0]?`; ${D[0]}`:"";const O=_.changedPixels===0?`no pixel change from baseline "${n}", but text changed`:`${R}% changed from baseline "${n}"`;const N={saved:false,changed:true,percent:_.percent,texts:D.length,summary:`${O}${j}${C}`};return{outcome:N,result:{content:[{type:"image",data:P.data,mimeType:P.mimeType},{type:"text",text:`**Changed from baseline "${n}": ${_.percent<.01&&_.changedPixels>0?"<0.01":_.percent.toFixed(2)}% of the screen** (${_.changedPixels} px${k}). Changes are red in the picture.${p}`+(A.length?`
|
|
628
|
+
|
|
629
|
+
Where:
|
|
630
|
+
${A.join("\n")}`:"")+(D.length?`
|
|
631
|
+
|
|
632
|
+
Text:
|
|
633
|
+
${D.map(z=>`- ${z}`).join("\n")}`:"")+`${M}
|
|
634
|
+
|
|
635
|
+
If this change is expected, save it with updateBaseline: true.`}]}}}var import_zod11,import_node_os8,import_node_fs9,import_node_path10,import_pngjs4,TOOL_ID,MARGIN_PT,CAPTURE_PADDING_PT,fail3,errMsg3,labelOf;var init_screenshot=__esm({"src/tools/packs/screenshot.ts"(){"use strict";import_zod11=require("zod");init_packKit();init_simctl();init_screenshotLocate();init_hostDevice();init_imageDiff();import_node_os8=__toESM(require("os"));import_node_fs9=require("fs");import_node_path10=__toESM(require("path"));init_hostKit();init_secrets();init_iosDevice();import_pngjs4=__toESM(require_png());TOOL_ID="highlight-updates";MARGIN_PT=12;CAPTURE_PADDING_PT=6;fail3=e=>({isError:true,content:[{type:"text",text:e}]});errMsg3=e=>e instanceof Error?e.message:String(e);labelOf=e=>`${e.name??"View"}${e.words?` "${e.words.length>40?`${e.words.slice(0,40)}\u2026`:e.words}"`:""}${e.testID?` [${e.testID}]`:""}`}});async function listSavedFlows(){try{return(await import_node_fs10.promises.readdir(FLOW_DIR())).filter(e=>e.endsWith(".json")).map(e=>e.slice(0,-5))}catch{return[]}}function matches(e,n){if(e.testID&&e.testID===n)return true;const t=n.toLowerCase();return[e.testID,e.text,e.label,e.name].filter(Boolean).some(r=>String(r).toLowerCase().includes(t))}function normalizeStep(e){if(!e||typeof e!=="object"||Array.isArray(e))return e;const n={...e};const t=s=>{if(!s||typeof s!=="object"||Array.isArray(s))return s;const a=s;return[a.testID,a.text,a.query,a.label,a.name].find(c=>typeof c==="string")??s};for(const s of["tap","into","waitFor","waitGone","expect","expectGone"])n[s]=t(n[s]);for(const s of Object.keys(n))if(n[s]===void 0)delete n[s];if(typeof n.into==="string")return n;const r=typeof n.type==="string"&&STEP_KINDS.includes(n.type)?"type":typeof n.action==="string"&&STEP_KINDS.includes(n.action)?"action":null;if(!r)return n;const i=n[r];delete n[r];const o=[n.query,n.text,n.target,n.selector,n.element,n.testID].map(t).find(s=>typeof s==="string");for(const s of["query","text","target","selector","element","testID"])delete n[s];if(i==="reload")n.reload=true;else if(i==="swipe"){n.swipe=n.direction??o??"up";delete n.direction}else if(i==="wait")n.waitMs=n.waitMs??n.ms??n.durationMs??n.timeoutMs;else if(o!==void 0&&n[i]===void 0)n[i]=o;delete n.ms;delete n.durationMs;return n}function registerFlowTools(e,n){e.registerTool("run_flow",{_meta:coreTool(),description:"Run supported UI actions and element checks in sequence, with per-step results. Stops on the first failed step unless continueOnFailure is true. Depending on include, attempts to return the final element tree and newly observed captured network/console entries. Background activity can appear in that output; it does not establish causation. Taps use exposed app handlers by default; a tap with no handler match (a native tab bar) falls back to a real touch on that native label. Pass real: true to make every tap a real touch. A tap waits up to 2 s for its target to show, so steps rarely need waitMs between them. A swipe step is a real swipe; add untilEnd: true to scroll to the end of a list. Review failures and check the expected behavior. To wait for something slow, use waitFor or waitGone with a timeoutMs, not a long waitMs. Requires Buoy Pro and the app interaction integration.",inputSchema:flowInput},async t=>runFlow(t));runFlow=async t=>{const r=Date.now();try{let i=t.steps;if(t.flow){if(!FLOW_NAME.test(t.flow))return fail4(`Flow names use letters, numbers, - and _ (got "${t.flow}").`);try{i=JSON.parse(await import_node_fs10.promises.readFile(import_node_path11.default.join(FLOW_DIR(),`${t.flow}.json`),"utf8")).steps}catch{const S=await listSavedFlows();return fail4(`No saved flow "${t.flow}". ${S.length?`Saved flows: ${S.join(", ")}.`:'No flows are saved yet; run one with save:"name" first.'}`)}}if(!i||i.length===0)return fail4('Pass steps, or flow:"name" to replay a saved flow.');if(t.save&&!FLOW_NAME.test(t.save))return fail4(`Flow names use letters, numbers, - and _ (got "${t.save}").`);const o=n.requireProDevice(t.deviceId);const s=t.include??"all";const a=nativeKit(n);let c=null;const l=()=>c??=hostTarget(n,o).then(async S=>{await a.primeScreen(o,S.host,S.online);return S});let u;const d=async(S,k,M,A)=>{const P=k?await a.buoyCover(o,S,M):null;if(P)throw new Error(P);const R=A?600:void 0;const j=await a.touch(S,M,R,u);if(j!==void 0)u=j;await a.mark(o,S,R?"hold":"tap",[[M.x,M.y]],void 0,R??150,j);await delay3(120);return`${A?"long-pressed":"tapped"} ${M.what} (real touch)`};const h=async(S,k,M)=>{const{host:A,online:P}=await l();const R=Date.now();let j=false;for(;;){let C=await a.findSpot(o,A,S,P,"app");if("miss"in C&&!C.tie&&(j||!P||Date.now()-R>=600)){if(!j){j=true;C=await a.findSpot(o,A,S,P,"native")}if("miss"in C&&!C.tie)C=await a.findSpot(o,A,S,P,"loose")}if(!("miss"in C))return d(A,P,C,k);if(C.tie||Date.now()-R>=M)throw new Error(C.miss);await delay3(POLL_MS)}};const w=async(S,k,M)=>{let A;try{A=await l()}catch{return null}if(A.host.platform==="ios-device")return null;const P=await a.findSpot(o,A.host,S,A.online,M?"nativeExact":"native").catch(()=>null);if(!P||"miss"in P)return null;return d(A.host,A.online,P,k)};const p=async()=>{const S=await n.callAction(UI_TOOL_ID,"describeScreen",{},o);return S?.elements??[]};const g=async()=>{try{const S=await n.callAction(APP_TOOL_ID,"ping",{},o,{timeoutMs:REALM_PROBE_MS,silent:true});return typeof S?.startedAt==="number"?S.startedAt:null}catch{return null}};const m=async(S,k)=>{const M=Date.now();while(Date.now()-M<k){const A=await g();if(A!==null&&A!==S)return Date.now()-M;await delay3(POLL_MS)}return null};const f=new Set;const b=new Set;const v=new Set((n.connectedDevices().find(S=>S.deviceId===o)?.tools??[]).map(S=>S.toolId));if(s==="all"){if(v.has("console")){const{payload:S}=await n.getSnapshot("console",o).catch(()=>({payload:null}));const k=S?.entries??[];for(const M of k)f.add(M.id)}if(v.has("network")){const{payload:S}=await n.getSnapshot("network",o).catch(()=>({payload:null}));const k=Array.isArray(S)?S:S?.events??[];for(const M of k)b.add(M.id)}}const y=async(S,k)=>{const M=Date.now();let A=false;for(;;){if(Date.now()-M>=k||Date.now()-r>MAX_FLOW_MS){return{ok:false,ms:Date.now()-M,unread:!A}}let P;try{P=await p();A=true}catch{await delay3(POLL_MS);continue}if(S(P))return{ok:true,ms:Date.now()-M,unread:false};await delay3(POLL_MS)}};const $=S=>`could not read the screen within ${S}ms, so this step is unknown`;const T=[];let _=null;let x=0;for(let S=0;S<i.length;S++){const k=i[S];const M=`${S+1}`;const A=k.timeoutMs??DEFAULT_WAIT_MS;if(Date.now()-r>MAX_FLOW_MS){T.push(`${M} \u2717 flow exceeded ${MAX_FLOW_MS/1e3}s \u2014 stopped here`);_=S;break}const P=[];const R=[];const j=k.reload||k.tap||k.swipe||k.type!==void 0||k.waitMs||k.waitFor||k.waitGone||k.expect||k.expectGone||k.snapshot;if(!j){T.push(`${S+1} \u2717 step does nothing \u2014 give it a tap/type/wait/expect${k.set!==void 0?" (`set` needs `tap` naming the control)":""}`);_=_??S;if(!t.continueOnFailure)break;continue}try{if(k.reload){const C=await g();await n.callAction(APP_TOOL_ID,"reloadApp",{strategy:"auto"},o);await delay3(TEARDOWN_GRACE_MS);const O=await m(C,Math.max(A,2e4));if(O==null){P.push("app did not come back after reload")}else{R.push(`reloaded (${O}ms)`);await y(N=>N.length>0,1e4)}}if(k.type!==void 0){const C=k.into??k.tap;if(!C){P.push("`type` needs `into` (which input to type into)")}else{const O=await n.callAction(UI_TOOL_ID,"tapElement",{...selector(C),text:fillSecrets(k.type)},o);if(!O?.tapped){P.push(O?.reason??`could not type into "${C}"`)}else if(O.matched?.via&&O.matched.via!=="onChangeText"){P.push(`"${C}" is not a text input \u2014 it ran ${O.matched.via} instead, and the text was not entered`)}else{R.push(`typed ${JSON.stringify(k.type)} into "${C}"`)}}}else if(k.tap&&(k.real??t.real)&&k.set===void 0){R.push(await h(k.tap,k.longPress,k.timeoutMs??3e3))}else if(k.tap){const C={...selector(k.tap)};if(k.longPress)C.longPress=true;if(k.set!==void 0)C.value=k.set;let O=await n.callAction(UI_TOOL_ID,"tapElement",C,o);for(let F=0;!O?.tapped&&/No element matched/.test(O?.reason??"")&&F<TAP_SETTLE_MS;F+=POLL_MS){await delay3(POLL_MS);O=await n.callAction(UI_TOOL_ID,"tapElement",C,o)}const N=/isn't showing|No element matched|no JS press handler|can't be driven in JS/;const z=/equally well/.test(O?.reason??"");const B=!O?.tapped&&k.set===void 0&&(z||N.test(O?.reason??""))?await w(k.tap,k.longPress,z):null;if(B){R.push(B)}else if(!O?.tapped){P.push(O?.reason??`no element matched "${k.tap}"`)}else{const F=O.matched;const U=F?.text??F?.label??F?.name??k.tap;if(k.set!==void 0&&F?.via&&F.via!=="onValueChange"){P.push(`"${U}" is not a toggle/slider \u2014 it ran ${F.via} instead, so it was not set to ${JSON.stringify(k.set)}`)}else{R.push(k.set!==void 0?`set "${U}" \u2192 ${JSON.stringify(F?.value??k.set)}`:`${k.longPress?"long-pressed":"tapped"} "${U}"`)}}}if(!P.length&&k.swipe){const{host:C,online:O}=await l();const N=await a.screenOf(C);const z=k.swipe;const{from:B,to:F}=swipePoints(z,!!k.untilEnd);const U=[B[0]*N.width,B[1]*N.height];const L=[F[0]*N.width,F[1]*N.height];const H=O?await a.buoyCover(o,C,{x:U[0],y:U[1]}):null;if(H)throw new Error(H);if(k.untilEnd){const{swipes:W,atEnd:J,lastRow:V}=await a.scrollToEnd(o,C,U,L,250);if(J)R.push(`swiped ${z} to the end (${W} swipes)${V?`; the last row is "${V}"`:""}`);else P.push(`swiped ${z} ${W} times and the screen was still moving`)}else{const W=await a.swipe(C,U,L,300);await a.mark(o,C,"swipe",[U],[L],300,W);await delay3(400);R.push(`swiped ${z}`)}}if(!P.length&&k.waitMs){await delay3(k.waitMs);R.push(`waited ${k.waitMs}ms`)}if(!P.length&&k.waitFor){const C=await y(O=>O.some(N=>matches(N,k.waitFor)),A);if(C.ok)R.push(`"${k.waitFor}" appeared (${C.ms}ms)`);else P.push(C.unread?$(A):`"${k.waitFor}" never appeared within ${A}ms`)}if(!P.length&&k.waitGone){const C=await y(O=>!O.some(N=>matches(N,k.waitGone)),A);if(C.ok)R.push(`"${k.waitGone}" gone (${C.ms}ms)`);else P.push(C.unread?$(A):`"${k.waitGone}" was still there after ${A}ms`)}if(!P.length&&k.expect){const C=await y(O=>O.some(N=>matches(N,k.expect)),k.timeoutMs??ASSERT_SETTLE_MS);if(C.ok)R.push(`"${k.expect}" is on screen`);else P.push(C.unread?$(k.timeoutMs??ASSERT_SETTLE_MS):`expected "${k.expect}" on screen \u2014 not found`)}if(!P.length&&k.expectGone){const C=await y(O=>!O.some(N=>matches(N,k.expectGone)),k.timeoutMs??ASSERT_SETTLE_MS);if(C.ok)R.push(`"${k.expectGone}" is gone`);else P.push(C.unread?$(k.timeoutMs??ASSERT_SETTLE_MS):`expected "${k.expectGone}" to be gone \u2014 still on screen`)}if(!P.length&&k.snapshot){const{outcome:C}=await runBaseline(n,k.snapshot,{deviceId:o,update:t.updateSnapshots});const O=k.maxChange??.05;if(C.changed&&(C.texts>0||C.percent>O)){P.push(`${C.summary}${C.texts>0?"":` (more than ${O}%)`}. Run screenshot_component with baseline "${k.snapshot}" to see the diff, or updateSnapshots: true if it is expected.`)}else R.push(C.summary)}}catch(C){P.push(errMsg4(C))}if(P.length){T.push(`${M} \u2717 ${describeStep(k)} \u2014 ${P.join("; ")}`);_=_??S;if(!t.continueOnFailure)break}else{x++;T.push(`${M} \u2713 ${R.join(", ")||describeStep(k)}`)}}const I=((Date.now()-r)/1e3).toFixed(1);const D=_===null?`**Flow: ${x}/${i.length} steps OK (${I}s)**`:`**Flow FAILED at step ${_+1} \u2014 ${x}/${i.length} steps OK (${I}s)**`;const E=[D,T.join("\n")];if(s!=="none"){E.push(`**Screen now:**${await observeAfterAction(n,o,void 0,0)}`)}if(s==="all"){if(v.has("network")){const{payload:S}=await n.getSnapshot("network",o).catch(()=>({payload:null}));const k=Array.isArray(S)?S:S?.events??[];const M=k.filter(A=>!b.has(A.id)).slice(-15);if(M.length){E.push(`**Network during this flow (${M.length}):**
|
|
636
|
+
`+M.map(A=>`${A.error||(A.status??0)>=400?"\u274C":"\u2705"} ${A.method??"GET"} ${A.path??A.url??"?"} \u2192 ${A.error??A.status??"pending"}`).join("\n"))}}if(v.has("console")){const{payload:S}=await n.getSnapshot("console",o).catch(()=>({payload:null}));const k=S?.entries??[];const M=k.filter(A=>!f.has(A.id)&&(A.level==="error"||A.level==="warning")).slice(-10);if(M.length){E.push(`**Console during this flow (${M.length}):**
|
|
637
|
+
`+M.map(A=>`[${A.level==="error"?"ERR":"warn"}] ${cap(firstLines(scrubSecrets(A.message??"")),220)}`).join("\n"))}}}if(t.save&&_===null){await import_node_fs10.promises.mkdir(FLOW_DIR(),{recursive:true});const S=import_node_path11.default.join(FLOW_DIR(),`${t.save}.json`);await import_node_fs10.promises.writeFile(S,JSON.stringify({steps:i},null,2)+"\n");E.push(`Saved as flow "${t.save}" (${import_node_path11.default.relative(process.cwd(),S)}). Replay with run_flow({flow:"${t.save}"}).`)}else if(t.save){E.push(`Not saved: the flow failed. Fix it, then run it again with save:"${t.save}".`)}return _===null?text2(E.join("\n\n")):{...text2(E.join("\n\n")),isError:true}}catch(i){return fail4(errMsg4(i))}}}function selector(e){return/\s/.test(e)?{query:e}:{testID:e,query:e}}function describeStep(e){if(e.tap)return`tap "${e.tap}"`;if(e.type!==void 0)return`type into "${e.into??"?"}"`;if(e.reload)return"reload";if(e.swipe)return`swipe ${e.swipe}${e.untilEnd?" to the end":""}`;if(e.waitFor)return`waitFor "${e.waitFor}"`;if(e.waitGone)return`waitGone "${e.waitGone}"`;if(e.expect)return`expect "${e.expect}"`;if(e.expectGone)return`expectGone "${e.expectGone}"`;if(e.snapshot)return`snapshot "${e.snapshot}"`;return"step"}var import_zod12,import_node_fs10,import_node_path11,FLOW_DIR,FLOW_NAME,UI_TOOL_ID,APP_TOOL_ID,text2,fail4,errMsg4,delay3,POLL_MS,TAP_SETTLE_MS,DEFAULT_WAIT_MS,ASSERT_SETTLE_MS,TEARDOWN_GRACE_MS,REALM_PROBE_MS,MAX_FLOW_MS,STEP_KINDS,stepSchema,flowInput,runFlow,cap,firstLines;var init_flow=__esm({"src/tools/packs/flow.ts"(){"use strict";init_screenshot();init_secrets();import_zod12=require("zod");init_packKit();import_node_fs10=require("fs");import_node_path11=__toESM(require("path"));init_native();init_interact();init_hostKit();FLOW_DIR=()=>import_node_path11.default.join(process.cwd(),".buoy","flows");FLOW_NAME=/^[A-Za-z0-9_-]{1,64}$/;UI_TOOL_ID="highlight-updates";APP_TOOL_ID="app";text2=e=>({content:[{type:"text",text:e}]});fail4=e=>({isError:true,content:[{type:"text",text:e}]});errMsg4=e=>e instanceof Error?e.message:String(e);delay3=e=>new Promise(n=>setTimeout(n,e));POLL_MS=250;TAP_SETTLE_MS=2e3;DEFAULT_WAIT_MS=5e3;ASSERT_SETTLE_MS=2e3;TEARDOWN_GRACE_MS=1200;REALM_PROBE_MS=1500;MAX_FLOW_MS=12e4;STEP_KINDS=["tap","waitFor","waitGone","expect","expectGone","reload","wait","swipe"];stepSchema=import_zod12.z.preprocess(normalizeStep,import_zod12.z.object({tap:import_zod12.z.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),longPress:import_zod12.z.boolean().optional().describe("Make `tap` a long-press instead."),type:import_zod12.z.string().optional().describe("Text to type (needs `into`)."),into:import_zod12.z.string().optional().describe("Target text input for `type`: testID or fuzzy text."),set:import_zod12.z.union([import_zod12.z.number(),import_zod12.z.boolean()]).optional().describe("Set a toggle (true/false) or slider (number) \u2014 pair with `tap` as the target."),swipe:import_zod12.z.enum(["up","down","left","right"]).optional().describe('A real swipe, the way the finger moves: "up" scrolls down the list.'),untilEnd:import_zod12.z.boolean().optional().describe("With swipe: keep swiping until the screen stops moving (the end of the list)."),real:import_zod12.z.boolean().optional().describe("Make this step's tap a real touch. Default: the flow's `real`."),reload:import_zod12.z.boolean().optional().describe("Reload the JS bundle before this step's action."),waitMs:import_zod12.z.number().min(0).max(3e4).optional().describe("Fixed pause after the action, in ms (max 30000). To wait for a result (a slow request, a new screen), use waitFor with timeoutMs instead: it stops as soon as the element shows."),waitFor:import_zod12.z.string().optional().describe("Wait until an element matching this appears (default 5s)."),waitGone:import_zod12.z.string().optional().describe("Wait until no element matches this (default 5s)."),expect:import_zod12.z.string().optional().describe("Assert an element matching this IS on screen (waits up to 2s for it); fails the flow if not."),expectGone:import_zod12.z.string().optional().describe("Assert nothing matches this (waits up to 2s for it to go); fails the flow if something does."),snapshot:import_zod12.z.string().optional().describe("Compare the whole screen to the baseline with this name (saved on the first run, like screenshot_component baseline). Fails the step on a text change or a change bigger than maxChange."),maxChange:import_zod12.z.number().min(0).max(100).optional().describe("snapshot: allowed changed share of the screen, in percent. Default 0.05."),timeoutMs:import_zod12.z.number().min(0).max(6e4).optional().describe("Budget for this step's waitFor/waitGone/expect, max 60000. Default 5000 (2000 for expect).")}).describe("One flow step. Order within a step: reload \u2192 tap/type/set/swipe \u2192 waitMs \u2192 waitFor/waitGone \u2192 expect."));flowInput={steps:import_zod12.z.array(stepSchema).min(1).optional().describe("Steps to run, in order. Leave out when replaying a saved flow."),flow:import_zod12.z.string().optional().describe("Replay a saved flow by name (from .buoy/flows in the project) instead of passing steps."),save:import_zod12.z.string().optional().describe('Save these steps under this name when the flow passes, so it can be replayed with flow:"name".'),include:import_zod12.z.enum(["all","screen","none"]).optional().describe("What to report after the flow: 'all' (default) = available final element tree + newly observed captured network/console entries; 'screen' = available final element tree only; 'none' = step results only."),updateSnapshots:import_zod12.z.boolean().optional().describe("Save every snapshot step's screen as its new baseline instead of comparing."),continueOnFailure:import_zod12.z.boolean().optional().describe("Keep going after a failed step instead of stopping. Default false."),real:import_zod12.z.boolean().optional().describe("Make every tap a real OS touch (iOS Simulator, Android), found by testID, text or native label. Default false."),deviceId:deviceIdInput};runFlow=async()=>fail4("run_flow is not ready.");cap=(e,n=160)=>{const t=scrubSecrets(e);return t.length>n?`${t.slice(0,n)}\u2026`:t};firstLines=(e,n=3)=>e.split("\n").map(t=>t.trim()).filter(Boolean).slice(0,n).join(" \u23CE ")}});function projectDir(){return process.env.BUOY_PROJECT_ROOT||process.cwd()}function stamp(e=new Date){const n=t=>String(t).padStart(2,"0");return`${e.getFullYear()}${n(e.getMonth()+1)}${n(e.getDate())}-${n(e.getHours())}${n(e.getMinutes())}${n(e.getSeconds())}`}function noteAgentCall(e,n,t){if(READ_ONLY.test(n)||sessions.size===0)return;let r=typeof t?.deviceId==="string"?t.deviceId:void 0;if(!r){try{r=e.resolveDevice()}catch{return}}const i=r?sessions.get(r):void 0;if(!i?.rec)return;const o=Object.entries(t??{}).filter(([s,a])=>s!=="deviceId"&&a!==void 0&&typeof a!=="object").map(([s,a])=>`${s}: ${String(a).slice(0,60)}`).join(", ");i.agent.push({at:Date.now(),t:0,source:"agent",status:"neutral",title:n,detail:o?redact(o):void 0});clearTimeout(i.afterAction);i.afterAction=setTimeout(()=>void gather(e,i),700);i.afterAction.unref?.()}function isRecording(e){return!!sessions.get(e)?.rec}function noteTouch(e,n){const t=sessions.get(e);if(t?.rec&&t.marks.length<500)t.marks.push(n)}async function gather(e,n){const t=e.connectedDevices().some(i=>i.deviceId===n.id);if(!t){n.failedPolls++;addConsole(n,(e.lastSync(n.id,"console")?.payload??{}).entries??[]);return}try{const i=await e.callAction("events","exportEvents",{settings:{format:"json",includeEventData:false},limit:500},n.id,{timeoutMs:4e3,silent:true});const o=i?.output?JSON.parse(i.output):null;const s=Array.isArray(o)?o:o?.events??[];for(const a of s){const c=a.timestamp?Date.parse(a.timestamp):NaN;if(!Number.isFinite(c))continue;const l=a.status==="error"||a.status==="success"||a.status==="pending"?a.status:"neutral";const u={at:c,t:0,source:a.source??"event",status:l,title:scrubSecrets(redact(a.title??"")),detail:a.subtitle?scrubSecrets(redact(a.subtitle)):void 0};n.events.set(`${c}|${u.source}|${u.title}|${u.detail??""}|${l}`,u)}if((i?.returned??0)>=500)n.notes.add("Busy app: some events may be missing from busy stretches.")}catch{n.failedPolls++}let r=[];try{const{payload:i}=await e.getSnapshot("console",n.id,{timeoutMs:2500,silent:true});r=i?.entries??[]}catch{r=(e.lastSync(n.id,"console")?.payload??{}).entries??[]}addConsole(n,r)}function addConsole(e,n){for(const t of n){if(typeof t.timestamp!=="number")continue;const[r,...i]=scrubSecrets(redact(t.message??"")).split("\n");const o=t.level==="error"?"error":t.level==="warning"?"warning":"neutral";e.events.set(`console|${t.timestamp}|${t.id??r}`,{at:t.timestamp,t:0,source:"console",status:o,title:r.slice(0,200),detail:i.join("\n").trim().slice(0,600)||void 0})}}async function finish(e,n){const t=n.rec;if(n.poll)clearInterval(n.poll);clearTimeout(n.afterAction);n.stopped??={durationMs:await stopRecording(t)};const{durationMs:r}=n.stopped;await gather(e,n);if(n.failedPolls)n.notes.add(`The app's events could not be read ${n.failedPolls} time(s) during the recording (the app may have been reloading or stuck), so parts of the timeline may be missing.`);const i=t.startedAt;const o=i+r;const s=[...n.events.values(),...n.agent].filter(m=>m.at>=i-500&&m.at<=o+500).map(({at:m,...f})=>({...f,title:scrubSecrets(f.title),detail:f.detail?scrubSecrets(f.detail):void 0,t:Math.max(0,m-i)})).sort((m,f)=>m.t-f.t);if(!s.some(m=>m.source!=="agent"))n.notes.add("No app events were captured. Is the Events tool installed in the app?");const a=t.file.replace(/\.mp4$/,"");const c=hostLabel(t.host);const l=n.marks.filter(m=>m.at>=i-500&&m.at<=o).map(({at:m,...f})=>({...f,t:Math.max(0,m-i)})).sort((m,f)=>m.t-f.t);let u=null;if(l.length){try{u=await burnTouchMarks(t.file,l,`${a}-taps.mp4`);if(u){const m=touchDotNote(l);if(m)n.notes.add(m)}if(!u)n.notes.add("Install ffmpeg to also get a copy of the video with the taps drawn in. The viewer shows them either way.")}catch(m){n.notes.add(`Could not draw the taps into a copy of the video: ${errMsg2(m).slice(0,160)}. The viewer shows them either way.`)}}const d=[...n.notes];await import_node_fs11.promises.writeFile(`${a}.timeline.json`,JSON.stringify({device:c,startedAt:new Date(i).toISOString(),durationMs:r,notes:d,items:s,touches:l},null,1));await import_node_fs11.promises.writeFile(`${a}.html`,viewerHtml({title:n.name,video:import_node_path12.default.basename(t.file),durationMs:r,items:s,device:c,notes:d,marks:l}));sessions.delete(n.id);const h=m=>import_node_path12.default.relative(projectDir(),m);const w=new Map;for(const m of s)w.set(m.source,(w.get(m.source)??0)+1);const p=m=>`${(m/1e3).toFixed(1)}s`;const g=s.filter(m=>m.status==="error"||m.source==="route"||m.source==="agent").slice(0,14);return[`Saved a ${p(r)} recording of ${c}.`,`- Video: ${h(t.file)}`,`- Viewer (video + timeline, click an event to jump there): ${h(`${a}.html`)}`,`- Timeline data: ${h(`${a}.timeline.json`)}`,...u?[`- Video with touch dots: ${h(u)}`]:l.length?[`- The viewer draws the ${l.length} real touch(es) on the video.`]:[],"",s.length?`Events: ${[...w].map(([m,f])=>`${m} ${f}`).join(", ")}.`:"No events in this window.",...g.length?["What happened:",...g.map(m=>`- ${p(m.t)} [${m.source}]${m.status==="error"?" ERROR":""} ${m.title}${m.detail&&m.source!=="route"?` (${m.detail.split("\n")[0].slice(0,80)})`:""}`)]:[],...d.map(m=>`Note: ${m}`),"Recordings are kept out of git (.buoy/recordings/.gitignore). Secrets in logs are hidden, but the video shows the screen as it was: check it before sharing."].join("\n")}function registerRecordingTools(e,n){setRecordingProbe(()=>sessions.size>0);e.registerTool("screen_recording",{_meta:coreTool(),description:"Record the screen of the iOS Simulator or Android device (start, do the steps, stop). On stop, saves an MP4 plus a viewer page that plays it beside a timeline of what the app did (web calls, query fetches, route changes, store writes, console errors) and what you did (your taps and other actions), and returns a short written summary. Real touches (native_tap, native_swipe, native_pinch) show as marks on the video, and with ffmpeg installed a copy of the MP4 has them drawn in. In .buoy/recordings. Use it to show a bug or a fix, e.g. for a pull request. Max 3 minutes. To record a set of taps or swipes, pass them as steps with start: Buoy records, runs them with real touches, stops and saves, all in one call.",inputSchema:{action:import_zod13.z.enum(["start","stop"]),name:import_zod13.z.string().optional().describe('start: a short name for the files, e.g. "checkout-timeout".'),steps:import_zod13.z.array(stepSchema).min(1).optional().describe('start: run_flow steps to record, e.g. [{tap:"One"},{tap:"Two"}]. Taps and swipes are real touches, so they show on the video. Each tap waits for its target, so no waitMs is needed between taps. The video stops and saves when they finish; no stop call needed.'),serial:import_zod13.z.string().optional().describe("Android: the adb serial, when several devices are connected."),deviceId:deviceIdInput}},async t=>{try{if(t.action==="start"){const{id:o,host:s}=await hostTarget(n,t.deviceId,{serial:t.serial});if(sessions.has(o))return fail2("A recording is already running on this device. Stop it first.");const a=(t.name??"recording").trim().replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"recording";const c={id:o,name:a,events:new Map,agent:[],notes:new Set,failedPolls:0,marks:[]};sessions.set(o,c);let l;c.starting=new Promise(d=>l=d);try{const d=import_node_path12.default.join(projectDir(),".buoy","recordings");await import_node_fs11.promises.mkdir(d,{recursive:true});await import_node_fs11.promises.writeFile(import_node_path12.default.join(d,".gitignore"),"*\n",{flag:"wx"}).catch(()=>void 0);await n.getSnapshot("events",o,{timeoutMs:2e3,silent:true}).catch(()=>void 0);const h=import_node_path12.default.join(d,`${a}-${stamp()}-${(0,import_node_crypto6.randomUUID)().slice(0,6)}.mp4`);c.rec=await startRecording(s,h)}catch(d){sessions.delete(o);throw d}finally{l()}c.poll=setInterval(()=>void gather(n,c),2e3);c.poll.unref?.();c.rec.stopTimer=setTimeout(()=>{c.finishing??=finish(n,c);c.finishing.then(d=>finished.set(o,`The recording hit the ${MAX_RECORDING_MS/6e4}-minute limit and was saved.
|
|
638
|
+
${d}`),d=>finished.set(o,`The recording hit the time limit and could not be saved: ${errMsg2(d)}`))},MAX_RECORDING_MS);c.rec.stopTimer.unref?.();if(t.steps){const d=Date.now();const h=await runFlow({steps:t.steps,real:true,include:"none",deviceId:o});const w=Math.max(STEPS_HOLD_MS,STEPS_MIN_MS-(Date.now()-d));const[p]=await Promise.all([observeAfterAction(n,o,void 0,0).catch(()=>""),delay4(w)]);c.finishing??=finish(n,c);let g;try{g=await c.finishing}catch(f){c.finishing=void 0;return fail2(`${h.content[0]?.text??""}
|
|
639
|
+
|
|
640
|
+
Could not save the recording: ${errMsg2(f)}. Call screen_recording with action "stop" to retry.`)}const m=text(`${h.content.map(f=>f.text).join("\n")}
|
|
641
|
+
|
|
642
|
+
${g}${p}`);return h.isError?{...m,isError:true}:m}const u=typedSecretValues().length?" Note: a secret was typed earlier this session; if it is still on screen, the video will show it. Typing secrets is blocked until the recording stops.":" Typing secrets ({{secret:NAME}}) is blocked until the recording stops, because a video can't hide them.";return text(`Recording ${hostLabel(s)}. Do the steps, then call screen_recording with action "stop". It stops by itself after ${MAX_RECORDING_MS/6e4} minutes.${u}`)}let r=t.deviceId;if(!r){try{r=n.requireProDevice()}catch{r=void 0}}if(!r||!sessions.has(r)){if(r&&finished.has(r)){const o=finished.get(r);finished.delete(r);return text(o)}if(sessions.size===1)r=[...sessions.keys()][0];else return fail2(sessions.size?"Several recordings are running. Pass deviceId.":'No recording is running. Start one with action "start".')}const i=sessions.get(r);await i.starting;if(!i.rec)return fail2("The recording did not start.");i.finishing??=finish(n,i);try{return text(await i.finishing)}catch(o){i.finishing=void 0;return fail2(`Could not save the recording: ${errMsg2(o)}. Call stop again to retry.`)}}catch(r){return fail2(errMsg2(r))}})}var import_zod13,import_node_fs11,import_node_path12,import_node_crypto6,sessions,finished,delay4,READ_ONLY,STEPS_HOLD_MS,STEPS_MIN_MS;var init_recording=__esm({"src/tools/packs/recording.ts"(){"use strict";import_zod13=require("zod");import_node_fs11=require("fs");import_node_path12=__toESM(require("path"));import_node_crypto6=require("crypto");init_packKit();init_hostKit();init_secrets();init_flow();init_interact();init_recorder();sessions=new Map;finished=new Map;delay4=e=>new Promise(n=>setTimeout(n,e));READ_ONLY=/^(get_|list_|describe_screen$|screenshot_component$|screen_recording$|wait_for_automation$|compare_reports$)/;STEPS_HOLD_MS=1200;STEPS_MIN_MS=3e3}});async function phoneScreenSize(e){const n=phoneScreens.get(e);if(n&&Date.now()-n.at<SCREEN_TTL_MS)return n.size;const t=await phoneScreenshot(e);const r={width:t.readUInt32BE(16),height:t.readUInt32BE(20)};phoneScreens.set(e,{size:r,at:Date.now()});return r}function swipePoints(e,n){if(n){if(e==="up")return{from:[.5,.88],to:[.5,.06]};if(e==="down")return{from:[.5,.3],to:[.5,.94]};if(e==="left")return{from:[.9,.5],to:[.1,.5]};return{from:[.1,.5],to:[.9,.5]}}const t=e==="left"?-.35:e==="right"?.35:0;const r=e==="up"?-.3:e==="down"?.3:0;return{from:[.5-t/2,.5-r/2],to:[.5+t/2,.5+r/2]}}function forgetScreenSize(e){barCache.delete(e);simScreens.delete(e);phoneScreens.delete(e)}function freshScreen(e){if(e.platform==="android")return;simScreens.delete(e.udid);phoneScreens.delete(e.udid)}async function xcodeShimDir(){const e=(await execFileAsync11("xcode-select",["-p"],{timeout:5e3}).catch(()=>({stdout:""}))).stdout.trim();if(!e.endsWith("/Contents/Developer"))return null;const n=import_node_path13.default.dirname(e);const t=import_node_path13.default.join(e,"Library","PrivateFrameworks","SimulatorKit.framework");const r=import_node_path13.default.join(n,"SharedFrameworks","SimulatorKit.framework");const i=l=>import_node_fs12.promises.access(l).then(()=>true,()=>false);if(await i(t)||!await i(r))return null;const o=(await execFileAsync11("plutil",["-extract","DTXcodeBuild","raw","-o","-",import_node_path13.default.join(n,"Info.plist")]).catch(()=>({stdout:"x"}))).stdout.trim();const s=import_node_path13.default.join(import_node_os9.default.homedir(),".buoy","xcode-shim",o.replace(/[^\w.-]/g,"_"),"Contents");const a=import_node_path13.default.join(s,"Developer");if(await i(import_node_path13.default.join(a,"Library","PrivateFrameworks","SimulatorKit.framework")))return a;await import_node_fs12.promises.mkdir(import_node_path13.default.join(a,"Library","PrivateFrameworks"),{recursive:true});const c=async(l,u,d)=>{for(const h of await import_node_fs12.promises.readdir(l)){if(h===d)continue;await import_node_fs12.promises.symlink(import_node_path13.default.join(l,h),import_node_path13.default.join(u,h)).catch(()=>void 0)}};await c(n,s,"Developer");await c(e,a,"Library");await c(import_node_path13.default.join(e,"Library"),import_node_path13.default.join(a,"Library"),"PrivateFrameworks");await c(import_node_path13.default.join(e,"Library","PrivateFrameworks"),import_node_path13.default.join(a,"Library","PrivateFrameworks"),"").catch(()=>void 0);await import_node_fs12.promises.symlink(r,import_node_path13.default.join(a,"Library","PrivateFrameworks","SimulatorKit.framework")).catch(()=>void 0);return a}async function restartCompanion(e){const n=`/tmp/idb/${e}.buoy-restart`;await import_node_fs12.promises.mkdir("/tmp/idb",{recursive:true}).catch(()=>void 0);const t=async()=>{try{await(await import_node_fs12.promises.open(n,"wx")).close();return true}catch{const r=await import_node_fs12.promises.stat(n).then(i=>Date.now()-i.mtimeMs,()=>0);if(r>15e3){const i=`${n}.stale-${process.pid}-${Date.now()}`;await import_node_fs12.promises.rename(n,i).then(()=>import_node_fs12.promises.unlink(i).catch(()=>void 0),()=>void 0);return t()}return false}};if(!await t()){for(let r=0;r<60;r++){await delay5(250);if(!await import_node_fs12.promises.stat(n).then(()=>true,()=>false))return}return}try{await execFileAsync11("pkill",["-f",`idb_companion --udid ${e}`],{timeout:5e3}).catch(()=>void 0);await delay5(300);const r=await xcodeShimDir().catch(()=>null);const i=(0,import_node_child_process12.spawn)("idb_companion",["--udid",e,"--grpc-domain-sock",`/tmp/idb/${e}_companion.sock`,"--only","simulator"],{detached:true,stdio:"ignore",env:r?{...process.env,DEVELOPER_DIR:r}:process.env});i.on("error",()=>void 0);i.unref();await delay5(1800)}finally{await import_node_fs12.promises.unlink(n).catch(()=>void 0)}}async function idb(e,n=15e3,t=false){try{const{stdout:r}=await execFileAsync11("idb",e,{timeout:n});return r}catch(r){const i=r;if(i.code==="ENOENT")throw new Error(IDB_MISSING);const o=(i.stderr||i.message||"").slice(0,300);const s=e.includes("--udid")?e[e.indexOf("--udid")+1]:void 0;if(!t&&s&&/not booted|connection refused|Failed to connect to companion/i.test(o)){await restartCompanion(s);return idb(e,n,true)}if(/SimulatorKit is required/i.test(o)){if(!t&&s&&await xcodeShimDir().catch(()=>null)){await restartCompanion(s);return idb(e,n,true)}throw new Error("idb can't send touches with this Xcode: it can't load SimulatorKit, and Buoy could not work around it. Use tap_element (it calls the element's handler) for now. Reading the screen (describe_screen, screenshot_component) still works.")}throw new Error(`idb ${e[0]} ${e[1]??""} failed: ${o}`)}}async function iosTree(e){const n=JSON.parse(await idb(["ui","describe-all","--udid",e,"--json","--nested"]));const t=[];const r=o=>{t.push(o);for(const s of o.children??[])r(s)};n.forEach(r);const i=t.find(o=>o.type==="Application"&&o.frame);return{all:t,screen:i?.frame?{width:i.frame.width,height:i.frame.height}:{width:0,height:0}}}async function loadBars(){if(barFileRead||process.env.VITEST)return;barFileRead=true;try{const e=JSON.parse(await import_node_fs12.promises.readFile(BAR_FILE,"utf8"));for(const[n,t]of Object.entries(e))if(!barCache.has(n)&&t?.screen&&Array.isArray(t.els))barCache.set(n,t)}catch{}}function saveBars(){if(process.env.VITEST)return;const e=Object.fromEntries([...barCache].map(([t,r])=>[t,{screen:r.screen,els:r.els.map(i=>({AXLabel:i.AXLabel,type:i.type,frame:i.frame}))}]));const n=`${BAR_FILE}.${process.pid}`;void import_node_fs12.promises.mkdir(import_node_path13.default.dirname(BAR_FILE),{recursive:true}).then(()=>import_node_fs12.promises.writeFile(n,JSON.stringify(e))).then(()=>import_node_fs12.promises.rename(n,BAR_FILE)).catch(()=>void 0)}async function cachedBarControl(e,n){await loadBars();const t=barCache.get(e);const r=n.trim().toLowerCase();const i=t?.els.find(o=>(o.AXLabel??"").trim().toLowerCase()===r&&o.frame);if(!t||!i?.frame)return null;try{const o=Math.round(i.frame.x+i.frame.width/2);const s=Math.round(i.frame.y+i.frame.height/2);const a=JSON.parse(await idb(["ui","describe-point","--udid",e,String(o),String(s),"--json"],3e3));if((a.AXLabel??"").trim().toLowerCase()===r&&a.frame)return{el:a,screen:t.screen}}catch{}barCache.delete(e);saveBars();return null}async function findByLabel(e,n,t,r=false,i=[.95,.97,.09,.06]){const o=n.trim().toLowerCase();const s=Date.now()+8e3;const a=p=>{const g=(p.AXLabel??"").trim().toLowerCase();if(!g)return 0;if(g===o)return 3;if(g.startsWith(o))return 2;if(g.includes(o))return 1;return 0};const{width:c,height:l}=t.screen;const u=p=>{if(!c||!p.frame)return true;const g=p.frame.x+p.frame.width/2;const m=p.frame.y+p.frame.height/2;return g>=0&&g<=c&&m>=0&&m<=l};let d=t.all.filter(p=>a(p)>0&&p.frame&&p.type!=="Application"&&u(p));if(!d.some(p=>a(p)===3)&&t.screen.width){const p=i.map(g=>{const m=[];for(let f=20;f<t.screen.width;f+=40)m.push([f,Math.round(t.screen.height*g)]);return m});for(const g of p){if(Date.now()>=s)break;const m=await Promise.allSettled(g.map(async([b,v])=>JSON.parse(await idb(["ui","describe-point","--udid",e,String(b),String(v),"--json"],3e3))));const f=[];for(const b of m){if(b.status==="rejected"){if(IDB_SETUP.test(String(b.reason)))throw b.reason;continue}const v=b.value;if(v?.frame&&v.AXLabel&&v.type&&v.type!=="Application")f.push(v);if(a(v)>0&&v.frame)d.push(v)}if(f.length){const b=barCache.get(e);const v=b&&b.screen.width===t.screen.width&&b.screen.height===t.screen.height;const y=[...v?b.els:[],...f].filter(($,T,_)=>_.findIndex(x=>x.AXLabel===$.AXLabel&&JSON.stringify(x.frame)===JSON.stringify($.frame))===T);barCache.set(e,{screen:t.screen,els:y});saveBars()}if(d.some(b=>a(b)===3))break}}const h=Math.max(0,...d.map(a));if(r&&h<3)return[];d=d.filter(p=>a(p)===h);let w=d.filter((p,g)=>d.findIndex(m=>JSON.stringify(m.frame)===JSON.stringify(p.frame))===g);if(w.length>1){const p=w.filter(g=>(g.AXLabel??"").trim()===n.trim());if(p.length)w=p}if(w.length>1){const p=w.filter(g=>g.type&&!/StaticText|Text$|Other|Image/.test(g.type));if(p.length)w=p}return w}async function iosNativeElements(e){const n=await iosTree(e);const t=n.all.filter(a=>a.frame&&a.frame.width>0&&a.type!=="Application");const r=a=>`${a.AXLabel??""}|${JSON.stringify(a.frame)}`;const i=new Set(t.map(r));const{width:o,height:s}=n.screen;if(o){const a=t.filter(d=>!!d.type&&!/StaticText|Text$|Other|Image|Group|Heading/.test(d.type));const c=(d,h)=>a.some(w=>d>=w.frame.x&&d<=w.frame.x+w.frame.width&&h>=w.frame.y&&h<=w.frame.y+w.frame.height);const l=[];for(const d of[.95,.97,.09,.06])for(let h=20;h<o;h+=40){const w=Math.round(s*d);if(!c(h,w))l.push([h,w])}const u=Date.now()+6e3;for(let d=0;d<l.length&&Date.now()<u;d+=8){const h=await Promise.all(l.slice(d,d+8).map(([w,p])=>idb(["ui","describe-point","--udid",e,String(w),String(p),"--json"],3e3).then(g=>JSON.parse(g),g=>{if(IDB_SETUP.test(String(g)))throw g;return null})));for(const w of h){if(!w?.type||!w.frame?.width||w.type==="Application"||i.has(r(w)))continue;i.add(r(w));t.push(w)}}}t.sort((a,c)=>a.frame.y-c.frame.y||a.frame.x-c.frame.x);return{elements:t,screen:n.screen}}function axLine(e){const n=e.frame;const t=[e.type??"Element",e.AXLabel?JSON.stringify(e.AXLabel.slice(0,80)):"",e.AXUniqueId?`id=${e.AXUniqueId}`:"",e.AXValue?`value=${JSON.stringify(String(e.AXValue).slice(0,40))}`:"",e.enabled===false?"(disabled)":""].filter(Boolean);return`${t.join(" ")} at (${Math.round(n.x)}, ${Math.round(n.y)}) ${Math.round(n.width)}x${Math.round(n.height)}`}function nativeKit(e){async function n(b,v,y){if(v.platform!=="ios"||!y)return;try{const $=await e.callAction(UI_TOOL_ID2,"describeScreen",{},b,{timeoutMs:2e3,silent:true});const T=$?.screen?.width??0;const _=$?.screen?.height??0;const x=Math.max(T,_)/Math.max(1,Math.min(T,_));if(T>0&&_>0&&x>1.7)simScreens.set(v.udid,{size:{width:T,height:_},at:Date.now()})}catch{}}async function t(b,v){if(b.platform==="android")return adbScreenSize(b.serial);if(b.platform==="ios-device")return{...await phoneScreenSize(b.udid),isPhone:true};const y=simScreens.get(b.udid);if(!v&&y&&Date.now()-y.at<SCREEN_TTL_MS)return y.size;try{const $=(v??await iosTree(b.udid)).screen;if(!$.width)throw new Error("Could not read the simulator's screen size from idb.");simScreens.set(b.udid,{size:$,at:Date.now()});return $}catch($){if(v||!await simHidTool())throw $;const T=import_node_path13.default.join(import_node_os9.default.tmpdir(),`buoy-size-${process.pid}-${Date.now()}.png`);try{await execFileAsync11("xcrun",["simctl","io",b.udid,"screenshot","--type=png",T],{timeout:2e4});const _=await import_node_fs12.promises.readFile(T);return{width:_.readUInt32BE(16),height:_.readUInt32BE(20)}}finally{await import_node_fs12.promises.rm(T,{force:true}).catch(()=>void 0)}}}async function r(b,v,y,$){if(b.platform==="android")await adbTap(b.serial,v.x,v.y,y);else if(b.platform==="ios-device"){const T=await simHidTool();if(!T)throw new Error(PHONE_TOUCH);return simHidTap(T,await coreDeviceId(b.udid),await t(b),v.x,v.y,y,$)}else if(await simHidTool()){return simHidTap(await simHidTool(),b.udid,{...await t(b),bundleId:b.bundleId},v.x,v.y,y,$)}else{await assertSimTouchable(b.udid);await idb(["ui","tap","--udid",b.udid,...y?["--duration",(y/1e3).toFixed(2)]:[],String(Math.round(v.x)),String(Math.round(v.y))])}}async function i(b,v){if(b.platform==="android"){const $=await adbAppFrame(b.serial,b.packageName);const T=$??{x:0,y:0,...await adbScreenSize(b.serial)};return[(v.x-T.x)/T.width,(v.y-T.y)/T.height]}const y=await t(b);return[v.x/y.width,v.y/y.height]}async function o(b,v,y){try{const[$,T]=await i(v,y);if(!($>=0&&$<=1&&T>=0&&T<=1))return null;return await e.callAction(UI_TOOL_ID2,"hitTest",{x:$,y:T},b,{timeoutMs:2500,silent:true})}catch{return null}}async function s(b,v,y){const $=await o(b,v,y);if(!$?.found||!$.buoy)return null;const T=$.path?.length?` (${$.path.slice(0,3).join(" in ")})`:"";return`Buoy's own overlay${T} is on top at that spot, so a real touch would land on Buoy, not the app. Nothing was touched. Close or minimize the Buoy panel first, or pass allowBuoy: true to touch Buoy on purpose.`}async function a(b,v,y,$,T,_,x){if(!isRecording(b))return;try{const I=await t(v);const D=k=>[k[0]/I.width,k[1]/I.height];const E=Date.now()-_-(v.platform==="android"?50:80);const S=x!==void 0?x:v.platform==="android"?null:await deviceOrientation(v.udid);noteTouch(b,{at:E,kind:y,ms:_,from:$.map(D),to:T?.map(D),screen:I,orientation:S})}catch{}}async function c(b,v,y){const $=await e.callAction(UI_TOOL_ID2,"describeScreen",{},b);const T=(y.query??"").toLowerCase();const _=($.elements??[]).filter(S=>y.nativeTag!=null?S.nativeTag===y.nativeTag:y.testID?S.testID===y.testID:(S.text??S.label??"").toLowerCase()===T);const x=_.filter(S=>S.tap);if(x.length===0)return"No element on screen matches that. Call describe_screen, or use label for native controls.";if(x.length>1&&y.nativeTag==null)return`${x.length} elements match equally well, so nothing was tapped. Use nativeTag: ${x.map(S=>`#${S.nativeTag}`).join(", ")}.`;const I=x[0].tap;const D=`"${x[0].text??x[0].label??x[0].name}"`;if(v.platform==="android"){const S=await adbAppFrame(v.serial,v.packageName);const k=S??{x:0,y:0,...await adbScreenSize(v.serial)};return{x:k.x+I.x*k.width,y:k.y+I.y*k.height,what:D}}const E=await t(v);return{x:I.x*E.width,y:I.y*E.height,what:D}}async function l(b,v,y=false){if(b.platform==="android"){const I=findUiNodes(await adbUiNodes(b.serial),v).filter(E=>!y||[E.desc,E.text].some(S=>(S??"").trim().toLowerCase()===v.trim().toLowerCase()));if(I.length===0)return`No native element labeled "${v}" was found on screen.`;if(I.length>1)return`${I.length} native elements match "${v}" equally well, so nothing was tapped: ${I.map(E=>`"${E.desc||E.text||E.id}" at (${E.bounds.x}, ${E.bounds.y})`).join(", ")}. Tap one by x/y.`;const D=I[0].bounds;return{x:D.x+D.width/2,y:D.y+D.height/2,what:`"${I[0].desc||I[0].text||I[0].id}" (${I[0].cls.split(".").pop()})`}}const $=await cachedBarControl(b.udid,v);if($){simScreens.set(b.udid,{size:$.screen,at:Date.now()});const I=$.el.frame;return{x:I.x+I.width/2,y:I.y+I.height/2,what:`"${$.el.AXLabel}" (${$.el.type})`}}const T=await iosTree(b.udid);await t(b,T);const _=await findByLabel(b.udid,v,T,y);if(_.length===0)return`No native element labeled "${v}" was found on screen.`;if(_.length>1)return`${_.length} native elements match "${v}" equally well, so nothing was tapped: ${_.map(I=>`"${I.AXLabel}" at (${Math.round(I.frame.x)}, ${Math.round(I.frame.y)})`).join(", ")}. Tap one by x/y.`;const x=_[0].frame;return{x:x.x+x.width/2,y:x.y+x.height/2,what:`"${_[0].AXLabel}" (${_[0].type})`}}async function u(b,v,y,$,T=false,_=0,x){const I=[...v,...y].map(E=>String(Math.round(E)));const D=b.platform==="android"?null:await simHidTool();if(b.platform!=="android"&&!D)await assertSimTouchable(b.udid);if(b.platform==="android"){if(T)await adbShell(b.serial,`input draganddrop ${I.join(" ")} ${Math.round($)}`);else await adbSwipe(b.serial,v,y,$);return void 0}if(D){const E=b.platform==="ios-device"?await coreDeviceId(b.udid):b.udid;const S=x?.screen??await t(b);return simHidSwipe(D,E,{...S,bundleId:b.platform==="ios"?b.bundleId:null},v,y,$,T?700:0,T?0:_,x?.orientation)}if(T)await idb(["ui","swipe","--udid",b.udid,...I,"--duration",($/1e3).toFixed(2),"--delta","4"]);else await idb(["ui","swipe","--udid",b.udid,...I,"--duration",($/1e3).toFixed(2)]);return void 0}async function d(b){try{const v=await e.callAction(UI_TOOL_ID2,"describeScreen",{},b,{timeoutMs:3e3,silent:true});const y=new Map;for(const $ of v?.elements??[]){if(!$.tap)continue;const T=`${$.name??""}|${$.text??$.label??""}|${$.nativeTag??""}`;if(y.has(T))y.set(T,{x:NaN,y:NaN});else y.set(T,$.tap)}return y}catch{return null}}function h(b,v,y,$,T=true){let _=0;let x=0;for(const[I,D]of v){const E=b.get(I);if(!E)x++;else if(Number.isFinite(E[y])&&Number.isFinite(D[y])&&Math.abs(D[y]-E[y])>$)_++}return _+(T&&x>=2?x:0)}function w(b,v,y){const $=[];for(const[T,_]of v){const x=b.get(T);if(x&&Number.isFinite(x[y])&&Number.isFinite(_[y])&&Math.abs(_[y]-x[y])>.002)$.push(_[y]-x[y])}if($.length<2)return 0;$.sort((T,_)=>T-_);return $[Math.floor($.length/2)]}async function p(b,v){await delay5(120);let y=await d(b);const $=Date.now()+2500;while(y&&Date.now()<$){await delay5(100);const T=await d(b);if(!T)break;const _=h(y,T,v,.002,false)===0;y=T;if(_)break}return y}async function g(b,v,y,$,T,_=15){const x=Math.abs($[1]-y[1])>=Math.abs($[0]-y[0])?"y":"x";let I=await d(b);if(I===null)throw new Error("Scrolling to the end needs the app connected, to see when the list stops moving.");let D=0;let E=false;const S={screen:await t(v)};const k=x==="y"?1:0;const M=x==="y"?S.screen.height:S.screen.width;const A=Math.sign($[k]-y[k]);const P=Math.abs($[k]-y[k])/M;const R=new Set;const j=(B,F)=>{for(const[U,L]of F){const H=B.get(U);if(H&&Number.isFinite(H[x])&&Number.isFinite(L[x])&&Math.abs(L[x]-H[x])>.01)R.add(U)}};let C=I;while(D<_){const B=await u(v,y,$,T,false,SCROLL_REST_MS,S);if(B!==void 0)S.orientation=B;D++;await a(b,v,"swipe",[y],[$],T,B);await delay5(90);const F=await d(b);await delay5(70);const U=await d(b);if(!F||!U)throw new Error("The app stopped answering while scrolling.");const L=w(F,U,x)*A;j(I,U);C=U;if(L>.004||L>=-.004&&h(F,U,x,.002,false)===0&&h(I,U,x,.01)>0){I=U;continue}const H=await p(b,x);if(!H)throw new Error("The app stopped answering while scrolling.");j(I,H);C=H;if(h(I,H,x,.01)===0){E=true;break}const W=w(I,H,x)*A;if(W>.01&&W<P*.85){E=true;break}I=H}const O=[...C].filter(([B,F])=>R.has(B)&&F[x]>=0&&F[x]<=1&&B.split("|")[1]);const N=B=>B.sort((F,U)=>(U[1][x]-F[1][x])*-A)[0];const z=N(O.filter(([B])=>!B.startsWith("Text|")))??N(O);return{swipes:D,atEnd:E,lastRow:z?z[0].split("|")[1]:void 0}}async function m(b,v){if(b.platform==="android"){const $=await adbAppFrame(b.serial,b.packageName);const T=$??{x:0,y:0,...await adbScreenSize(b.serial)};return{x:T.x+v.x*T.width,y:T.y+v.y*T.height}}const y=await t(b);return{x:v.x*y.width,y:v.y*y.height}}async function f(b,v,y,$,T){if($&&(T==="app"||T==="loose")){const _=await e.callAction(UI_TOOL_ID2,"describeScreen",{},b,{timeoutMs:4e3,silent:true}).catch(()=>null);const x=(_?.elements??[]).filter(S=>S.tap&&S.tap.x>=0&&S.tap.x<=1&&S.tap.y>=0&&S.tap.y<=1);const I=y.trim().toLowerCase();const D=S=>(S.text??S.label??"").trim().toLowerCase();const E=T==="app"?[x.filter(S=>S.testID===y),x.filter(S=>D(S)===I)]:[x.filter(S=>!!I&&D(S).includes(I))];for(const S of E){if(!S.length)continue;const k=S.filter(R=>R.interactive);const M=k.length?k:S;const A=M.filter((R,j)=>M.findIndex(C=>Math.abs(C.tap.x-R.tap.x)<.02&&Math.abs(C.tap.y-R.tap.y)<.02)===j);if(A.length>1){return{tie:true,miss:`${A.length} elements match "${y}", so nothing was touched: ${A.slice(0,5).map(R=>R.testID?`testID ${R.testID}`:JSON.stringify(R.text??R.label??R.name)).join(", ")}. Use an exact testID.`}}const P=A[0];return{...await m(v,P.tap),what:`"${P.text??P.label??P.name}"${P.testID?` [testID=${P.testID}]`:""}`}}}if((T==="native"||T==="nativeExact")&&v.platform!=="ios-device"){const _=await l(v,y,T==="nativeExact");if(typeof _!=="string")return _;if(/equally well/.test(_))return{miss:_,tie:true}}return{miss:`Nothing on screen matches "${y}".`}}return{primeScreen:n,screenOf:t,touch:r,hitAt:o,buoyCover:s,mark:a,reactSpot:c,labelSpot:l,swipe:u,scrollToEnd:g,findSpot:f}}async function nativeLabelTap(e,n,t,r,i=false){const o=nativeKit(e);const{id:s,host:a,online:c}=await hostTarget(e,n);if(a.platform==="ios-device")return null;freshScreen(a);await o.primeScreen(s,a,c);const l=await o.findSpot(s,a,t,c,i?"nativeExact":"native");if("miss"in l)return null;if(c&&await o.buoyCover(s,a,l))return null;const u=r?600:void 0;const d=await o.touch(a,l,u);await o.mark(s,a,u?"hold":"tap",[[l.x,l.y]],void 0,u??150,d);return`${u?"Long-pressed":"Tapped"} ${l.what} with a real touch at (${Math.round(l.x)}, ${Math.round(l.y)}).`}function warmNativeTouch(e){if(process.platform!=="darwin"||process.env.BUOY_WARM_TOUCH==="0")return;const n=Date.now();const t=async()=>{try{const r=e.peekProjectDevice();const i=r?e.listDevices().find(o=>o.deviceId===r)?.platform:void 0;if(r&&i==="ios"){const{host:o}=await hostTarget(e,r);if(o.platform!=="ios")return;const s=await simHidTool();if(s)await runHidStream(s,o.udid,["--device",o.udid,"ping"]);await deviceOrientation(o.udid);await loadBars();if(!barCache.has(o.udid)){const a=await iosTree(o.udid).catch(()=>null);if(a?.screen.width)await findByLabel(o.udid,"\0no such label",a,false,[.95]).catch(()=>void 0)}return}if(r&&i)return}catch{}if(Date.now()-n<3e4)setTimeout(()=>void t(),500).unref()};setTimeout(()=>void t(),300).unref()}function registerNativeTools(e,n){warmNativeTouch(n);const{primeScreen:t,screenOf:r,touch:i,hitAt:o,buoyCover:s,mark:a,reactSpot:c,labelSpot:l,swipe:u,scrollToEnd:d}=nativeKit(n);const h=import_zod14.z.string().optional().describe("Android: the adb serial, when several devices are connected.");const w=p=>p.platform==="ios"?"pt":"px";e.registerTool("native_tap",{_meta:coreTool(),description:"Tap the screen for real (an OS touch: CoreDevice on the iOS Simulator, the way Xcode sends it, or idb on older Xcode; adb on Android), for native-only controls like a native tab bar or a system dialog, or when tap_element finds no handler. Pass holdMs for a long press. label and x/y work even when the app's JS is stuck.",inputSchema:{label:import_zod14.z.string().optional().describe('Native accessibility label, e.g. "Rewards" for a native tab.'),query:import_zod14.z.string().optional().describe("Text of an element from describe_screen."),testID:import_zod14.z.string().optional(),nativeTag:import_zod14.z.number().optional(),x:import_zod14.z.number().min(0).max(1).optional().describe("Horizontal position, 0 to 1."),y:import_zod14.z.number().min(0).max(1).optional().describe("Vertical position, 0 to 1."),holdMs:import_zod14.z.number().min(100).max(1e4).optional().describe("Hold the touch this long: a long press (context menus, Paste, reorder handles). 600 is a typical long press."),allowBuoy:import_zod14.z.boolean().optional().describe("Touch even if Buoy's own panel covers the spot. By default the tap stops there, because it would hit Buoy instead of the app."),serial:h,deviceId:deviceIdInput}},async p=>{try{const g=p.nativeTag!=null||!!p.testID||!!p.query;const{id:m,host:f,online:b}=await hostTarget(n,p.deviceId,{serial:p.serial},{allowOffline:!g});freshScreen(f);await t(m,f,b);if(f.platform==="ios-device"&&!await simHidTool())return fail2(PHONE_TOUCH);let v;if(p.x!=null&&p.y!=null){const T=await r(f);v={x:p.x*T.width,y:p.y*T.height,what:`(${p.x.toFixed(2)}, ${p.y.toFixed(2)})`}}else if(g){v=await c(m,f,p)}else if(p.label){if(f.platform==="ios-device")return fail2("label works on simulators and Android. On a physical iPhone, tap by query, testID or nativeTag (from describe_screen), or by x and y.");v=await l(f,p.label)}else{return fail2("Give label, query, testID, nativeTag, or x and y.")}if(typeof v==="string")return fail2(v);if(b&&!p.allowBuoy){const T=await s(m,f,v);if(T)return fail2(T)}const y=await i(f,v,p.holdMs);await a(m,f,p.holdMs?"hold":"tap",[[v.x,v.y]],void 0,p.holdMs??150,y);const $=b?await observeAfterAction(n,m):" (The app is not connected, so its screen was not read back.)";return text(`${p.holdMs?`Long-pressed (${p.holdMs}ms)`:"Tapped"} ${v.what} with a real touch at (${Math.round(v.x)}, ${Math.round(v.y)}) ${w(f)}.${$}`)}catch(g){return fail2(errMsg2(g))}});e.registerTool("native_type",{description:"Type text on the real keyboard into the focused field (CoreDevice or idb on the iOS Simulator, adb on Android). Tap the field first (tap_element or native_tap). Unlike tap_element's text, this goes through the keyboard like a person typing. It types plain ASCII only (letters, digits, punctuation, newlines).",inputSchema:{text:import_zod14.z.string().describe("The text to type. Write {{secret:NAME}} for a password: Buoy types BUOY_SECRET_NAME from its environment and hides it in what it returns. Prefer real password fields (shown as dots)."),serial:h,deviceId:deviceIdInput}},async p=>{try{const{id:g,host:m,online:f}=await hostTarget(n,p.deviceId,{serial:p.serial},{allowOffline:true});if(m.platform==="ios-device"&&!await simHidTool())return fail2(PHONE_TOUCH);const b=fillSecrets(p.text);let v=false;if(m.platform==="android")await adbText(m.serial,b);else if(m.platform==="ios-device")await simHidType(await simHidTool(),await coreDeviceId(m.udid),b);else{const $=await simHidTool();if($){await simHidType($,m.udid,b);v=true}else{await assertSimTouchable(m.udid);await idb(["ui","text","--udid",m.udid,b])}}if(!v)await delay5(300);const y=f?await observeAfterAction(n,g):"";return text(`Typed ${JSON.stringify(p.text)} on the keyboard.${y}`)}catch(g){return fail2(errMsg2(g))}});e.registerTool("native_swipe",{_meta:coreTool(),description:"Swipe the screen for real (CoreDevice or idb on the iOS Simulator, adb on Android): scroll a list, dismiss a sheet, change a page. Give a direction (the way your finger moves) or from/to points as fractions of the screen. To reach the bottom of a list, pass untilEnd: true. It swipes again until the screen stops moving, in one call.",inputSchema:{direction:import_zod14.z.enum(["up","down","left","right"]).optional().describe('"up" scrolls content down the list (finger moves up).'),fromX:import_zod14.z.number().min(0).max(1).optional(),fromY:import_zod14.z.number().min(0).max(1).optional(),toX:import_zod14.z.number().min(0).max(1).optional(),toY:import_zod14.z.number().min(0).max(1).optional(),durationMs:import_zod14.z.number().min(50).max(5e3).optional().describe("Default 300 (1200 with drag)."),drag:import_zod14.z.boolean().optional().describe("Drag instead of flick: press, hold, then move (reorder handles, drag and drop, sliders). On the iOS Simulator with older Xcode (idb) it is a slow swipe only."),untilEnd:import_zod14.z.boolean().optional().describe("Keep swiping until the screen stops moving (the end of the list), up to 15 swipes. Returns the last screen."),allowBuoy:import_zod14.z.boolean().optional().describe("Swipe even if Buoy's own panel covers the starting point."),serial:h,deviceId:deviceIdInput}},async p=>{try{const{id:g,host:m,online:f}=await hostTarget(n,p.deviceId,{serial:p.serial},{allowOffline:true});freshScreen(m);await t(g,m,f);if(m.platform==="ios-device"&&!await simHidTool())return fail2(PHONE_TOUCH);const b=await r(m);let v;let y;if(p.fromX!=null&&p.fromY!=null&&p.toX!=null&&p.toY!=null){v=[p.fromX,p.fromY];y=[p.toX,p.toY]}else{({from:v,to:y}=swipePoints(p.direction??"up",!!p.untilEnd))}const $=[v[0]*b.width,v[1]*b.height];const T=[y[0]*b.width,y[1]*b.height];let _=0;if(p.drag&&m.platform==="android"){const S=Number((await adbShell(m.serial,"settings get secure long_press_timeout").catch(()=>"")).trim())||500;_=S*1.5+600}const x=Math.max(p.durationMs??(p.drag?1200:300),_);if(f&&!p.allowBuoy){const S=await s(g,m,{x:$[0],y:$[1]});if(S)return fail2(S)}if(p.untilEnd){if(p.drag)return fail2("untilEnd scrolls with flicks. Leave out drag.");if(!f)return fail2("untilEnd needs the app connected, to see when the list stops moving.");const S=await d(g,m,$,T,p.durationMs??250);const{swipes:k,atEnd:M}=S;const A=await observeAfterAction(n,g,void 0,0);const{lastRow:P}=S;return text(`${M?`Reached the end of the list after ${k} swipe(s)${P?`. The last row is "${P}"`:""}`:`Swiped ${k} times and the screen was still moving`}.${A}`)}const I=m.platform==="android"?null:await simHidTool();const D=await u(m,$,T,x,p.drag);await a(g,m,p.drag?"drag":"swipe",[$],[T],x+(p.drag&&I?700:0),D);await delay5(400);const E=f?await observeAfterAction(n,g):"";return text(`${p.drag?"Dragged":"Swiped"} from (${$.map(Math.round).join(", ")}) to (${T.map(Math.round).join(", ")}) ${w(m)}.${E}`)}catch(g){return fail2(errMsg2(g))}});e.registerTool("native_inspect",{description:"Read native controls on the screen. Pass pointX and pointY for points on iOS Sims, pixels elsewhere. Use x and y for screen fractions (0 to 1). Leave all points out to list controls, with types, labels, IDs, and frames. This includes tabs, alerts, and sheets. A point read also checks the app view and Buoy's cover. iOS Sims use idb; Android uses uiautomator. Real iPhones show just the app view.",inputSchema:{pointX:import_zod14.z.number().finite().min(0).optional().describe("From the left. iOS Sims use points. Other hosts use pixels."),pointY:import_zod14.z.number().finite().min(0).optional().describe("From the top. iOS Sims use points. Other hosts use pixels."),x:import_zod14.z.number().min(0).max(1).optional().describe("Horizontal position, 0 to 1."),y:import_zod14.z.number().min(0).max(1).optional().describe("Vertical position, 0 to 1."),serial:h,deviceId:deviceIdInput}},async p=>{try{const g=p.pointX!=null||p.pointY!=null;if(g&&(p.pointX==null||p.pointY==null))return fail2("Use pointX and pointY together.");if(g&&(p.x!=null||p.y!=null))return fail2("Use pointX/pointY or x/y, not both.");if(!g&&p.x==null!==(p.y==null))return fail2("Use x and y together.");const{id:m,host:f,online:b}=await hostTarget(n,p.deviceId,{serial:p.serial},{allowOffline:true});freshScreen(f);await t(m,f,b);const v=w(f);if(!g&&(p.x==null||p.y==null)){if(f.platform==="ios-device")return fail2("A physical iPhone doesn't share its native element tree with this Mac. Use describe_screen for the app's elements, or native_inspect with x and y to see what is at a point.");let _;let x=0;if(f.platform==="android"){const D=await adbUiNodes(f.serial);_=D.filter(E=>E.text||E.desc||E.id||E.clickable).map(E=>{const S=E.bounds;const k=[E.cls.split(".").pop(),E.text?JSON.stringify(E.text.slice(0,80)):"",E.desc?`desc=${JSON.stringify(E.desc.slice(0,60))}`:"",E.id?`id=${E.id.split("/").pop()}`:"",E.clickable?"(clickable)":""];return`${k.filter(Boolean).join(" ")} at (${S.x}, ${S.y}) ${S.width}x${S.height}`})}else{const{elements:D,screen:E}=await iosNativeElements(f.udid);const S=D.filter(k=>!E.width||k.frame.y<E.height&&k.frame.y+k.frame.height>0&&k.frame.x<E.width&&k.frame.x+k.frame.width>0);x=D.length-S.length;_=S.map(axLine)}const I=_.slice(0,150);return text([`${_.length} native element(s) on screen, top to bottom (${v}; frames are x, y, width x height)${x?`. ${x} more are scrolled out of view`:""}:`,...I.map(D=>`- ${D}`),..._.length>I.length?[`(${_.length-I.length} more not shown.)`]:[],"Tap one with native_tap label or x/y. For the app's React elements (testID, handlers), use describe_screen."].join("\n"))}let y;if(g){const _=await r(f);y={x:p.pointX,y:p.pointY};if(y.x>=_.width||y.y>=_.height){return fail2(`That point is outside the screen (${_.width} x ${_.height} ${v}).`)}}else{const _=await r(f);y={x:p.x*_.width,y:p.y*_.height}}const $=[g?`At (${Math.round(y.x)}, ${Math.round(y.y)}) ${v}:`:`At (${p.x.toFixed(2)}, ${p.y.toFixed(2)}) = (${Math.round(y.x)}, ${Math.round(y.y)}) ${v}:`];const T=b?o(m,f,y):Promise.resolve(null);if(f.platform==="android"){const _=(await adbUiNodes(f.serial)).filter(I=>{const D=I.bounds;return y.x>=D.x&&y.x<=D.x+D.width&&y.y>=D.y&&y.y<=D.y+D.height});const x=_.sort((I,D)=>I.bounds.width*I.bounds.height-D.bounds.width*D.bounds.height)[0];$.push(x?`- Native: ${x.cls.split(".").pop()}${x.text?` ${JSON.stringify(x.text.slice(0,80))}`:""}${x.desc?` desc=${JSON.stringify(x.desc.slice(0,60))}`:""}${x.id?` id=${x.id.split("/").pop()}`:""} at (${x.bounds.x}, ${x.bounds.y}) ${x.bounds.width}x${x.bounds.height}`:"- Native: nothing with a label or id here.")}else if(f.platform==="ios"){const _=JSON.parse(await idb(["ui","describe-point","--udid",f.udid,String(Math.round(y.x)),String(Math.round(y.y)),"--json"],5e3));$.push(_?.type&&_.frame?.width?`- Native: ${axLine(_)}`:"- Native: no accessible element here (plain views and canvases often have none).")}else{$.push("- Native: not available on a physical iPhone.")}if(!b)$.push("- App: not connected, so its views can't be read.");else{const _=await T;if(!_)$.push("- App: no answer (an older Buoy without hitTest, or the JS thread is busy).");else if(!_.found)$.push(`- App: ${_.reason??"no React view here (native UI, or outside the app's views)."}`);else{const x=_.view;const I=[x.name,x.testID?`testID=${x.testID}`:"",x.label?`label=${JSON.stringify(x.label)}`:"",x.text?JSON.stringify(x.text.slice(0,60)):""].filter(Boolean).join(" ");$.push(`- App: ${I}${_.path?.length?` in ${_.path.join(" < ")}`:""}.`);if(_.buoy)$.push("- This spot is Buoy's own overlay. A real touch here hits Buoy, not the app; close or minimize the panel first.");else if(_.target){const D=_.target;$.push(`- A tap here presses ${D.testID?`testID ${D.testID}`:JSON.stringify(D.text??D.label??D.name)} (${D.name}${D.nativeTag!=null?`, nativeTag ${D.nativeTag}`:""}).`)}else $.push("- Nothing tappable in the app here.")}}return text($.join("\n"))}catch(g){return fail2(errMsg2(g))}});e.registerTool("native_pinch",{description:"Pinch, spread or turn with two real fingers (CoreDevice on the iOS Simulator and a physical iPhone): zoom a map or photo, or rotate, in one call. scale above 1 zooms in (fingers spread), below 1 zooms out. The reply says how far a map turned and zoomed, read from the map itself. For other views it says how much of the area changed and shows it. No screenshot is needed. Not on Android or older Xcode, which can't send two fingers.",_meta:coreTool(),inputSchema:{x:import_zod14.z.number().min(0).max(1).optional().describe("Center between the fingers, 0 to 1. Default 0.5."),y:import_zod14.z.number().min(0).max(1).optional().describe("Center between the fingers, 0 to 1. Default 0.5."),scale:import_zod14.z.number().min(.1).max(10).optional().describe("How far the fingers spread: 2 doubles the gap (zoom in), 0.5 halves it (zoom out). Default 2."),rotate:import_zod14.z.number().min(-180).max(180).optional().describe("Turn the fingers this many degrees while pinching, clockwise. Default 0."),durationMs:import_zod14.z.number().min(100).max(5e3).optional().describe("Default 500."),allowBuoy:import_zod14.z.boolean().optional().describe("Pinch even if a finger starts on Buoy."),deviceId:deviceIdInput}},async p=>{try{const{id:g,host:m,online:f}=await hostTarget(n,p.deviceId,{},{allowOffline:true});freshScreen(m);await t(g,m,f);if(m.platform==="android")return fail2("Android's input command sends one finger only, so Buoy can't pinch there yet. Use the app's zoom buttons, or native_swipe for one-finger moves.");const b=await simHidTool();if(!b)return fail2(m.platform==="ios-device"?PHONE_TOUCH:"Pinching needs Xcode's CoreDevice touch support (Xcode 26 or later); idb sends one finger only.");const v=await r(m);const y=[(p.x??.5)*v.width,(p.y??.5)*v.height];const $=p.scale??2;const T=Math.min(v.width,v.height);const _=T*.4;const x=$>=1?Math.max(T*.04,_/$):_;const I=$>=1?_:Math.max(T*.04,_*$);const D=(p.rotate??0)*Math.PI/180;const E=G=>[Math.min(v.width-1,Math.max(1,G[0])),Math.min(v.height-1,Math.max(1,G[1]))];const S=(G,K)=>[E([y[0]-G*Math.cos(K),y[1]-G*Math.sin(K)]),E([y[0]+G*Math.cos(K),y[1]+G*Math.sin(K)])];const[k,M]=S(x,0);const[A,P]=S(I,D);if(f&&!p.allowBuoy){for(const[G,K]of[k,M]){const ie=await s(g,m,{x:G,y:K});if(ie)return fail2(ie)}}const R=p.durationMs??500;const j={x:Math.max(0,(y[0]-_)/v.width),y:Math.max(0,(y[1]-_)/v.height),width:Math.min(1,2*_/v.width),height:Math.min(1,2*_/v.height)};const C=f?await readMaps(n,g):[];const O=G=>G.find(K=>!K.frame||(p.x??.5)>=K.frame.x&&(p.x??.5)<=K.frame.x+K.frame.width&&(p.y??.5)>=K.frame.y&&(p.y??.5)<=K.frame.y+K.frame.height);const N=O(C);const z=N?null:await hostPng(m).catch(()=>null);const B=m.platform==="ios-device"?await coreDeviceId(m.udid):m.udid;const F=await simHidTwo(b,B,{...v,bundleId:m.platform==="ios"?m.bundleId:null},k,M,A,P,R);await a(g,m,"pinch",[k,M],[A,P],R,F);await delay5(400);const[U,L,H]=await Promise.all([f?observeAfterAction(n,g,void 0,0):Promise.resolve(""),z?hostPng(m).catch(()=>null):Promise.resolve(null),N?readMaps(n,g):Promise.resolve([])]);const W=I/x;const J=W>1.01?`Spread (zoom in, x${W.toFixed(2)})`:W<.99?`Pinched (zoom out, x${W.toFixed(2)})`:"Turned";const V=`${J}${p.rotate?`, turning ${p.rotate} degrees,`:""} around (${Math.round(y[0])}, ${Math.round(y[1])}) ${w(m)} with two real fingers.`;const se=N?H.find(G=>G.name===N.name&&G.testID===N.testID):void 0;const re=N&&se?mapChange(N,se):null;if(re)return text(`${V}
|
|
643
|
+
${re}${U}`);const ee=z&&L?await pinchProof(z,L,j):null;if(!ee)return text(`${V}${U}`);return{content:[{type:"text",text:`${V}
|
|
644
|
+
${ee.line}${U}`},{type:"image",data:ee.image.data,mimeType:ee.image.mimeType}]}}catch(g){return fail2(errMsg2(g))}})}async function pinchProof(e,n,t){try{const r=cropPng(e,t);const i=cropPng(n,t);const{percent:o}=diffScreens(r,i);const s=o<2?`Checked: the area under the fingers looks the same as before (${o.toFixed(1)}% changed). The pinch did not move anything there.`:`Checked: ${o.toFixed(0)}% of the area under the fingers changed, so it moved. It looks like this now:`;return{line:s,image:await toSmallImage(i,480)}}catch{return null}}async function readMaps(e,n){try{const t=await e.callAction(UI_TOOL_ID2,"readMaps",{},n,{timeoutMs:2e3,silent:true});return t?.maps??[]}catch{return[]}}function mapChange(e,n){const t=`The map${e.testID?` [${e.testID}]`:""}`;const r=[];const i=e.camera.heading,o=n.camera.heading;if(typeof i==="number"&&typeof o==="number"){const d=p=>(p%360+360)%360;const h=p=>Math.round(Math.min(d(p),360-d(p)));const w=Math.round(Math.abs((d(o)-d(i)+540)%360-180));r.push(`heading ${Math.round(d(i))}\xB0 before, ${Math.round(d(o))}\xB0 now (turned ${w}\xB0, now ${h(o)}\xB0 from north)`)}const s=e.camera.altitude,a=n.camera.altitude;const c=e.camera.zoom,l=n.camera.zoom;const u=typeof s==="number"&&typeof a==="number"&&s>0&&a>0?s/a:typeof c==="number"&&typeof l==="number"?Math.pow(2,l-c):null;if(u!=null&&Number.isFinite(u)){const d=u*u;const h=u>1.01?`zoomed in x${u.toFixed(2)}, so it shows about 1/${d.toFixed(1)} of the area it did`:u<.99?`zoomed out x${(1/u).toFixed(2)}, so it shows about ${d>0?(1/d).toFixed(1):"?"} times the area`:"same zoom";const w=typeof s==="number"&&typeof a==="number"?` (altitude ${Math.round(s).toLocaleString("en-US")} m to ${Math.round(a).toLocaleString("en-US")} m)`:typeof c==="number"&&typeof l==="number"?` (zoom ${c.toFixed(1)} to ${l.toFixed(1)})`:"";r.push(`${h}${w}`)}return r.length?`Checked in the app: ${t} ${r.join("; ")}.`:null}var import_zod14,import_node_child_process12,import_node_util11,import_node_fs12,import_node_os9,import_node_path13,execFileAsync11,UI_TOOL_ID2,delay5,IDB_MISSING,PHONE_TOUCH,phoneScreens,simScreens,SCROLL_REST_MS,SCREEN_TTL_MS,IDB_SETUP,barCache,BAR_FILE,barFileRead;var init_native=__esm({"src/tools/packs/native.ts"(){"use strict";import_zod14=require("zod");import_node_child_process12=require("child_process");import_node_util11=require("util");import_node_fs12=require("fs");import_node_os9=__toESM(require("os"));import_node_path13=__toESM(require("path"));init_packKit();init_interact();init_adb();init_hostDevice();init_imageDiff();init_hostKit();init_secrets();init_simTouch();init_simHid();init_recording();init_iosDevice();init_hidStream();execFileAsync11=(0,import_node_util11.promisify)(import_node_child_process12.execFile);UI_TOOL_ID2="highlight-updates";delay5=e=>new Promise(n=>setTimeout(n,e));IDB_MISSING="Native touch on the iOS Simulator needs idb on this Mac (brew install facebook/fb/idb-companion && pipx install fb-idb).";PHONE_TOUCH="Real touches on a physical iPhone need Xcode's CoreDevice touch support, and Buoy couldn't set it up on this Mac. Use tap_element (it calls the element's handler) or run_flow; screenshots, recording and app control work on the iPhone.";phoneScreens=new Map;simScreens=new Map;SCROLL_REST_MS=60;SCREEN_TTL_MS=3e3;IDB_SETUP=/idb on this Mac|SimulatorKit|not booted|connection refused|Failed to connect to companion/i;barCache=new Map;BAR_FILE=import_node_path13.default.join(import_node_os9.default.homedir(),".buoy","cache","native-bars.json");barFileRead=false}});async function observeAfterAction(e,n,t,r=300){let i="";for(let s=0;s<(t?6:1);s++){await delay6(s===0?r:250);try{const a=await e.callAction("route-events","getCurrentRoute",{},n,{timeoutMs:3e3,silent:true});i=String(a?.pathname??a?.path??"")}catch{break}if(!t||i.replace(/\(.*?\)\//g,"").replace(/\/$/,"")===t.replace(/\/$/,"")||i.endsWith(t))break}let o="";try{const s=await e.callAction(TOOL_ID2,"describeScreen",{},n,{timeoutMs:5e3,silent:true});const a=s?.elements??[];const c=new Set(a.filter(g=>g.name!=="Text").map(g=>g.text??g.label).filter(Boolean));const l=a.filter(g=>g.name!=="Text"&&g.tap&&(g.text??g.label));const u=(g,m)=>!!g.tap&&l.some(f=>Math.abs(f.tap.y-g.tap.y)<.06&&(f.text??f.label).includes(m));const d=a.filter(g=>{const m=g.text??g.label;if(g.name==="Text"&&(!m||/^[\s\uE000-\uF8FF]*$/.test(m)))return false;if(g.name==="Text"&&c.has(m))return false;if(g.name==="Text"&&m&&u(g,m))return false;return true});const h=g=>!g.tap||g.tap.x>=0&&g.tap.x<=1&&g.tap.y>=0&&g.tap.y<=1;const w=[...d.filter(h),...d.filter(g=>!h(g))];const p=w.slice(0,OBSERVE_MAX);o=p.map(formatElement).join("\n");if(w.length>p.length)o+=`
|
|
645
|
+
\u2026 ${w.length-p.length} more (describe_screen lists everything)`}catch{o="(could not read the screen)"}return`
|
|
646
|
+
|
|
647
|
+
Now on ${i?`\`${i}\``:"an unknown route"}. Screen (\u2022 = tappable):
|
|
648
|
+
${o}`}function formatElement(e){let n=e.interactive?"\u2022 ":" ";n+=e.name;const t=e.text??e.label;if(t)n+=` "${t}"`;if(e.role)n+=` <${e.role}>`;if(e.control)n+=` {${e.control}${e.value!==void 0?`=${JSON.stringify(e.value)}`:""}}`;if(e.longPressable)n+=" {long-press}";if(e.testID)n+=` [testID=${e.testID}]`;if(e.tap)n+=` (tap: ${e.tap.x},${e.tap.y})`;if(e.nativeTag!=null)n+=` #${e.nativeTag}`;return n}function registerInteractTools(e,n){e.registerTool("describe_screen",{_meta:coreTool(),description:"List elements exposed by the app React-fiber inspection integration, with available names, text, roles, testIDs, positions and native tags. This is not a complete native accessibility tree or a visual screenshot. Use the returned controls to select a target for tap_element; refresh after navigation or state changes. Empty results can reflect unavailable inspection. Requires Buoy Pro and the highlight-updates interaction integration.",inputSchema:{interactiveOnly:import_zod15.z.boolean().optional().describe("Only return tappable (onPress) elements. Default false (include labels/text for context)."),includeBuoy:import_zod15.z.boolean().optional().describe("Also list Buoy's own overlay \u2014 the dial, tool sheets, Ask Buoy's chat. Default false: the screen described is the app's. Exact testIDs inside Buoy (buoy-\u2026) can still be tapped without this."),includeHidden:import_zod15.z.boolean().optional().describe("Also list screens that are mounted but not showing (other tabs, screens under the current one). Default false: only what is on screen."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=liveStateIndex(n,r).catch(()=>null);const o=await n.callAction(TOOL_ID2,"describeScreen",{includeBuoy:t.includeBuoy,includeHidden:t.includeHidden},r);const s=o?.elements??[];const a=t.interactiveOnly?s.filter(g=>g.interactive):s;if(a.length===0){return text3("No elements found on screen. If the app just navigated, wait a moment and retry; make sure highlight-updates is enabled in the app.")}const c=o.hiddenBuoy?` Buoy's own overlay (${o.hiddenBuoy} element${o.hiddenBuoy===1?"":"s"}) is left out \u2014 pass includeBuoy:true to see it.`:"";const l=o.hiddenScreens?` ${o.hiddenScreens} screen${o.hiddenScreens===1?" that isn't":"s that aren't"} showing (other tabs, screens underneath) left out \u2014 pass includeHidden:true to see them.`:"";const u=`Screen ${o.screen.width}\xD7${o.screen.height} \u2014 ${a.length} element${a.length===1?"":"s"} (\u2022 = tappable). Tap with tap_element({ testID | query | nativeTag }).${c}${l}`;let d="";if(!t.includeHidden&&s.some(g=>g.name==="BottomTabsScreen")){try{const g=await n.callAction(TOOL_ID2,"describeScreen",{includeHidden:true},r,{timeoutMs:3e3,silent:true});const m=[...new Set((g?.elements??[]).filter(f=>f.name==="BottomTabsScreen").map(f=>f.text??f.label).filter(f=>!!f))];if(m.length>1)d=`
|
|
649
|
+
Tab bar (native, tap with tap_element query): ${m.join(", ")}.`}catch{}}const h=describeTipShown?"":`
|
|
650
|
+
Tip: run_flow does taps, typing and swipes in one call, e.g. steps [{tap:"Menu"},{tap:"Burgers"},{swipe:"up",untilEnd:true}] taps two things and scrolls to the end of the list.`;describeTipShown=true;const w=await i;const p=a.map(g=>formatElement(g)+stateNote(w,g.text));return text3(`${u}${d}${h}
|
|
651
|
+
|
|
652
|
+
${p.join("\n")}`)}catch(r){return fail5(errMsg5(r))}});e.registerTool("tap_element",{_meta:coreTool(),description:"Invoke a supported element handler in JavaScript: onPress/onLongPress, onValueChange or onChangeText. This does not reproduce native hit testing, keyboard entry or a physical gesture. Select an exposed element by nativeTag, testID or fuzzy query; inspect the matched target and resulting behavior. value sets a supported toggle or slider, text invokes a text-input handler, and longPress selects onLongPress. Can attempt to scroll an off-screen target into view. If a plain query finds no JS handler, Buoy tries a real touch on a native control with that label (a native tab bar). Use describe_screen for current controls and run_flow for sequences. Requires Buoy Pro and the app interaction integration.",inputSchema:{nativeTag:import_zod15.z.number().optional().describe("Exact nativeTag from describe_screen (most precise)."),testID:import_zod15.z.string().optional().describe("Exact testID of the element."),query:import_zod15.z.string().optional().describe('Fuzzy match against testID / label / visible text / component name \u2014 e.g. "Sign in".'),value:import_zod15.z.union([import_zod15.z.number(),import_zod15.z.boolean()]).optional().describe("For a toggle: true/false (omit to flip). For a slider: the numeric value (omit to jump to the far end)."),text:import_zod15.z.string().optional().describe("For a text input: the string to set via onChangeText."),longPress:import_zod15.z.boolean().optional().describe("Invoke the element's onLongPress instead of onPress. Fails with a clear reason if the element has no onLongPress handler."),scrollIntoView:import_zod15.z.boolean().optional().describe("Attempt to scroll an off-screen target into view. Default true; inspect the action result."),includeBuoy:import_zod15.z.boolean().optional().describe("Let a fuzzy `query` match Buoy's own overlay. Default false \u2014 an exact nativeTag/testID always may."),includeHidden:import_zod15.z.boolean().optional().describe("Also match elements on screens that are mounted but not showing. Default false."),observe:observeInput,deviceId:deviceIdInput}},async t=>{try{if(t.nativeTag==null&&!t.testID&&!t.query){return fail5("Provide one of: nativeTag, testID, or query (from describe_screen).")}const r=n.requireProDevice(t.deviceId);const i=await n.callAction(TOOL_ID2,"tapElement",{nativeTag:t.nativeTag,testID:t.testID,query:t.query,value:t.value,text:t.text===void 0?void 0:fillSecrets(t.text),longPress:t.longPress,scrollIntoView:t.scrollIntoView,includeBuoy:t.includeBuoy,includeHidden:t.includeHidden},r);tapCount+=1;const o=tapCount>=FLOW_TIP_EVERY&&tapCount%FLOW_TIP_EVERY===0?FLOW_TIP:"";if(i?.tapped&&i.matched){const l=i.matched;const u=l.text??l.label??l.name;const d=l.testID?` [testID=${l.testID}]`:l.nativeTag!=null?` #${l.nativeTag}`:"";const h=i.scrolled?" (scrolled into view)":"";const w=l.via==="onValueChange"?`Set "${u}"${d} \u2192 ${JSON.stringify(l.value)}`:l.via==="onChangeText"?`Typed ${JSON.stringify(l.value)} into "${u}"${d}`:l.via==="onLongPress"?`Long-pressed "${u}"${d}`:`Tapped "${u}"${d}`;const p=i.effect;const g=!p?"":p.commits>0?` ${p.commits} re-render${p.commits===1?"":"s"} followed.`:` No re-render followed within ${p.observedMs}ms \u2014 the handler ran but the app did not react. The element may sit on a screen beneath the current one, or be inert; do not treat this as done.`;const m=i.alsoMatched?.length?`
|
|
653
|
+
Also matched equally well (the choice was a coin toss \u2014 re-tap by #nativeTag if this was wrong):
|
|
654
|
+
`+i.alsoMatched.map(b=>`- ${b.name}${b.text?` "${b.text}"`:""}${b.testID?` [testID=${b.testID}]`:""}${b.nativeTag!=null?` #${b.nativeTag}`:""}`).join("\n"):"";const f=t.observe==="none"?"":await observeAfterAction(n,r);return text3(`${w}${h}.${g}${m}${f}${o}`)}const s=!!t.query&&!t.testID&&t.nativeTag==null&&t.value===void 0&&t.text===void 0&&!t.includeHidden;const a=/equally well/.test(i?.reason??"");if(!i?.tapped&&s&&(a||NO_HANDLER.test(i?.reason??""))){const l=await nativeLabelTap(n,r,t.query,t.longPress,a).catch(()=>null);if(l){const u=t.observe==="none"?"":await observeAfterAction(n,r);return text3(`${l} It is a native control with no JS handler, so Buoy sent a real touch.${u}`)}}let c=i?.reason??"Tap failed.";if(i?.candidates?.length){c+="\n\nTappable candidates:\n"+i.candidates.map(l=>`- ${l.name}${l.text?` "${l.text}"`:""}${l.testID?` [testID=${l.testID}]`:""}${l.nativeTag!=null?` #${l.nativeTag}`:""}`).join("\n")}return fail5(c)}catch(r){return fail5(errMsg5(r))}})}var import_zod15,TOOL_ID2,text3,fail5,errMsg5,delay6,OBSERVE_MAX,observeInput,tapCount,describeTipShown,NO_HANDLER,FLOW_TIP_EVERY,FLOW_TIP;var init_interact=__esm({"src/tools/packs/interact.ts"(){"use strict";init_secrets();import_zod15=require("zod");init_packKit();init_liveValues();init_native();TOOL_ID2="highlight-updates";text3=e=>({content:[{type:"text",text:e}]});fail5=e=>({isError:true,content:[{type:"text",text:e}]});errMsg5=e=>e instanceof Error?e.message:String(e);delay6=e=>new Promise(n=>setTimeout(n,e));OBSERVE_MAX=40;observeInput=import_zod15.z.enum(["screen","none"]).optional().describe('What to return after the action. Default "screen": the current route and what is on screen, so no follow-up describe_screen is needed. "none" skips it.');tapCount=0;describeTipShown=false;NO_HANDLER=/isn't showing|No element matched|no JS press handler/;FLOW_TIP_EVERY=3;FLOW_TIP="\n\nTip: driving several steps? `run_flow` does a whole tap/type/wait/assert sequence in ONE call and reports the final screen plus the network and console output it produced."}});function flattenRoutes(e,n=[]){for(const t of e??[]){if(t.path)n.push(t.path);if(t.children?.length)flattenRoutes(t.children,n)}return n}function registerRoutesTools(e,n){e.registerTool("get_routes",{description:'Read reported current navigation state and stack. includeSitemap:true includes available configured route paths; it does not establish complete application route coverage. Use get_events with sources:["route"] for retained navigation history.',inputSchema:{includeSitemap:import_zod16.z.boolean().optional().describe("Also list available configured route paths (can be long). Default false."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:i,stale:o}=await n.getSnapshot(ROUTES_TOOL_ID,r);const s=Array.isArray(i)?{events:i}:i??{};const a=Array.isArray(s.stack)?s.stack:[];const c=a.find(h=>h.isFocused)??a[a.length-1];const l=c?.pathname??"(unknown)";const u=[`**Current route:** \`${l}\``];if(a.length){const h=a.map((w,p)=>`${p+1}. \`${w.pathname??w.name??"?"}\`${w.isFocused?" \u2190 focused":""}`);u.push(`
|
|
655
|
+
**Navigation stack** (top last):
|
|
656
|
+
${h.join("\n")}`)}const d=flattenRoutes(s.sitemap?.routes);if(t.includeSitemap){const h=d.slice(0,200);u.push(`
|
|
657
|
+
**Sitemap (${d.length} routes${h.length<d.length?`, showing ${h.length}`:""}):**
|
|
658
|
+
${h.map(w=>`- \`${w}\``).join("\n")}`)}else{u.push(`
|
|
659
|
+
**Sitemap:** ${d.length} routes _(pass includeSitemap:true to list them)_`)}u.push("\n_Navigate with navigate({ path })._");return text(staleHeader(o)+u.join("\n"))}catch(r){return fail2(errMsg2(r))}});e.registerTool("navigate",{description:"Navigate the app to a route path (e.g. '/pokemon/25' or '/settings'). Use a concrete path \u2014 resolve any dynamic segments (like [id]) to real values first. See get_routes with includeSitemap:true for valid paths. Pushes by default (back still works); pass replace:true to leave the current screen instead of stacking on top of it (e.g. resetting to '/').",inputSchema:{path:import_zod16.z.string().describe("The concrete path to navigate to, e.g. '/pokemon/25'."),replace:import_zod16.z.boolean().optional().describe("Replace the current screen instead of pushing (use when resetting, e.g. to '/')."),observe:import_zod16.z.enum(["screen","none"]).optional().describe('What to return after navigating. Default "screen": the route it landed on and what is on screen. "none" skips it.'),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);await n.callAction(ROUTES_TOOL_ID,"navigate",{path:t.path,replace:t.replace===true},r);const i=t.observe==="none"?"":await observeAfterAction(n,r,t.path);return text(`Navigated to \`${t.path}\`${t.replace?" (replaced current screen)":""}.${i}`)}catch(r){return fail2(errMsg2(r))}})}var import_zod16,ROUTES_TOOL_ID;var init_routes=__esm({"src/tools/packs/routes.ts"(){"use strict";import_zod16=require("zod");init_packKit();init_interact();ROUTES_TOOL_ID="route-events"}});function hhmmss(e){const n=new Date(e);const t=(r,i=2)=>String(r).padStart(i,"0");return`${t(n.getHours())}:${t(n.getMinutes())}:${t(n.getSeconds())}.${t(n.getMilliseconds(),3)}`}function registerConsoleTools(e,n){e.registerTool("get_console",{description:"Read retained captured console output as a compact tail of timestamps, levels and messages. Filter by minimum level or a case-insensitive message substring. Fatal JavaScript errors may be included when supported hooks captured them; post-crash availability is not guaranteed. Missing entries do not establish that no error occurred. Use get_snapshot for available full entry details. Requires configured console capture and Buoy Pro.",inputSchema:{level:import_zod17.z.enum(["verbose","info","warning","error"]).optional().describe("Minimum level to include (severity threshold). e.g. 'warning' = warnings + errors. Default all."),limit:import_zod17.z.number().optional().describe("Most-recent N entries. Default 50."),pattern:import_zod17.z.string().optional().describe("Only entries whose message contains this substring (case-insensitive)."),deviceId:deviceIdInput}},async t=>{let r;let i;try{const o=n.requireProDevice(t.deviceId);({payload:r,stale:i}=await n.getSnapshot(CONSOLE_TOOL_ID,o))}catch(o){const s=lastSyncAfterDrop(n,o,CONSOLE_TOOL_ID);if(!s)return fail2(errMsg2(o));({payload:r,stale:i}=s)}{const o=staleHeader(i);const s=Array.isArray(r)?{entries:r}:r??{};const a=Array.isArray(s.entries)?s.entries:[];const c=t.level?SEVERITY[t.level]:0;const l=t.pattern?.toLowerCase();const u=a.filter(f=>SEVERITY[f.level]>=c&&(!l||(f.message??"").toLowerCase().includes(l)));const d=[...u].sort((f,b)=>f.id-b.id);const h=clampLimit(t.limit,50);const w=d.slice(-h);if(w.length===0){return text(`${o}No console entries${t.level?` at level \u2265 ${t.level}`:""}${l?` matching "${t.pattern}"`:""} (${a.length} total captured).`)}const p=w.map(f=>`${hhmmss(f.timestamp)} [${TAG[f.level]??f.level}] ${f.message}`);const g=t.level?`, level \u2265 ${t.level}`:"";const m=`**Console \u2014 ${a.length} entries (showing ${w.length}${g}):**`;return text(`${o}${m}
|
|
660
|
+
|
|
661
|
+
\`\`\`
|
|
662
|
+
${p.join("\n")}
|
|
663
|
+
\`\`\`
|
|
664
|
+
|
|
665
|
+
_Tail of recent logs. Use get_snapshot for available console entry details._`)}})}var import_zod17,CONSOLE_TOOL_ID,SEVERITY,TAG;var init_console=__esm({"src/tools/packs/console.ts"(){"use strict";import_zod17=require("zod");init_packKit();CONSOLE_TOOL_ID="console";SEVERITY={verbose:0,info:1,warning:2,error:3};TAG={verbose:"\xB7",info:"info",warning:"warn",error:"ERR"}}});function hhmmss2(e){const n=new Date(e);const t=r=>String(r).padStart(2,"0");return`${t(n.getHours())}:${t(n.getMinutes())}:${t(n.getSeconds())}`}function bytes(e){if(e<1024)return`${e}B`;if(e<1024*1024)return`${(e/1024).toFixed(1)}KB`;return`${(e/(1024*1024)).toFixed(2)}MB`}function units(e,n){if(n==="bytes")return bytes(e);if(e>=1e6)return`${(e/1e6).toFixed(1)}M`;if(e>=1e3)return`${(e/1e3).toFixed(1)}k`;return String(e)}function statusNote(e){switch(e){case"attached":return"";case"sdk-not-found":return"\n\n\u26A0\uFE0F The tool never found @sentry/react-native \u2014 nothing is being captured. The app must pass `getClient` to SentryRoot, or the SDK isn't installed.";case"no-client":return"\n\n\u26A0\uFE0F The SDK is present but no client appeared \u2014 is Sentry.init() being called?";default:return"\n\n\u23F3 Still looking for the app's Sentry client."}}function registerSentryTools(e,n){e.registerTool("get_sentry_envelopes",{description:"Inspect retained captured Sentry envelopes and available item types, sizes, spans and payload details. Coverage depends on supported hooks. Local capture does not prove successful delivery, ingestion or billing impact. Filter by item type to investigate the available evidence.",inputSchema:{type:import_zod18.z.string().optional().describe("Only envelopes containing this item type, e.g. 'event' for errors or 'transaction' for traces."),limit:import_zod18.z.number().optional().describe("Most-recent N envelopes. Default 25."),deviceId:import_zod18.z.string().optional().describe("The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out.")}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:i,stale:o}=await n.getSnapshot(SENTRY_TOOL_ID,r);const s=o?`${o}
|
|
666
|
+
|
|
667
|
+
`:"";const a=i??{};const c=Array.isArray(a.envelopes)?a.envelopes:[];const l=t.type?c.filter(p=>p.items.some(g=>g.type===t.type)):c;const u=typeof t.limit==="number"&&t.limit>0?t.limit:25;const d=l.slice(-u);if(d.length===0){return text4(`${s}No Sentry envelopes${t.type?` containing a '${t.type}' item`:""} (${c.length} captured this session).${statusNote(a.status)}`)}const h=d.map(p=>{const g=p.items.map(v=>v.type).join("+");const m=p.items.reduce((v,y)=>v+(y.spanCount??0),0);const f=m>0?` \xB7 ${m} span${m===1?"":"s"}`:"";const b=`${p.id}. ${hhmmss2(p.timestamp)} [${g}] ${bytes(p.totalBytes)}${f}`;return`${b}
|
|
668
|
+
\u2514\u2500 ${p.items[0]?.summary??"envelope"}`});const w=`**Sentry \u2014 ${c.length} envelope${c.length===1?"":"s"} sent (showing ${d.length}${t.type?`, type '${t.type}'`:""}):**`;return text4(`${s}${w}${statusNote(a.status)}
|
|
669
|
+
|
|
670
|
+
${h.join("\n")}
|
|
671
|
+
|
|
672
|
+
_Full payloads (exception, breadcrumbs, contexts) via get_snapshot('sentry'). Billing units via get_sentry_cost._`)}catch(r){return fail6(errMsg6(r))}});e.registerTool("get_sentry_cost",{description:"Inspect captured session usage and the tool's configured monthly extrapolation and quota assumptions. These estimates do not establish Sentry ingestion, current plan limits or an actual bill. Check the account's current terms and usage before making cost decisions.",inputSchema:{deviceId:import_zod18.z.string().optional().describe("The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out.")}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:i,stale:o}=await n.getSnapshot(SENTRY_TOOL_ID,r);const s=o?`${o}
|
|
673
|
+
|
|
674
|
+
`:"";const a=i??{};const c=a.usage;if(!c?.session){return text4(`${s}No usage is available in this capture.${statusNote(a.status)}`)}const l=c.session;const u=c.projectedMonthly;const d=Object.keys(l);const h=d.map(m=>{const f=CATEGORY_FORMAT[m];const b=units(l[m],f);if(!u)return`- ${m}: ${b} this session`;const v=u[m];const y=FREE_QUOTA[m];const $=y>0?Math.round(v/y*100):null;const T=$===null?" (no configured reference quota)":` \u2014 ${$}% of the configured reference quota of ${units(y,f)}`;return`- ${m}: ${b} this session \u2192 ~${units(v,f)}/mo${T}`});const w=c.windowMs?` over ${Math.round(c.windowMs/1e3)}s`:"";const p=c.topContributors?.length?`
|
|
675
|
+
|
|
676
|
+
**What produced it:**
|
|
677
|
+
${c.topContributors.map(m=>`- ${m.label} \u2014 ${m.units} ${m.category}`).join("\n")}`:"";const g=u?"\n\n_The monthly figure extrapolates one session on one device \u2014 it catches a config that is orders of magnitude off, it is not a forecast._":"\n\n_Session too short to project a month from._";return text4(`${s}**Sentry usage estimate \u2014 ${a.envelopes?.length??0} envelopes${w}:**
|
|
678
|
+
|
|
679
|
+
${h.join("\n")}${p}${g}`)}catch(r){return fail6(errMsg6(r))}});e.registerTool("get_sentry_drops",{description:"Why events never reached Sentry. Answers 'I called captureException but the event isn't in Sentry' \u2014 the single most common Sentry problem \u2014 by naming the layer that discarded it: a beforeSend callback returning null, a sample-rate roll, dedupe or another event processor, React Native tracing discarding an empty transaction, or a native rate limit.",inputSchema:{limit:import_zod18.z.number().optional().describe("Most-recent N drop records. Default 30."),deviceId:import_zod18.z.string().optional().describe("The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out.")}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:i,stale:o}=await n.getSnapshot(SENTRY_TOOL_ID,r);const s=o?`${o}
|
|
680
|
+
|
|
681
|
+
`:"";const a=i??{};const c=a.drops?.summary??[];const l=a.drops?.recent??[];if(c.length===0){return text4(`${s}No drops are reported in the available capture.${statusNote(a.status)}
|
|
682
|
+
|
|
683
|
+
_If an event is missing from sentry.io, check capture coverage, transport errors, the DSN/project, inbound filters and quota. Local capture does not confirm delivery._`)}const u=typeof t.limit==="number"&&t.limit>0?t.limit:30;const d=l.slice(-u);const h=c.map(p=>`- ${p.reason}: ${p.units} unit${p.units===1?"":"s"} across ${p.records} record${p.records===1?"":"s"}`);const w=d.map(p=>`${hhmmss2(p.timestamp)} [${p.reason}] ${p.category}${p.quantity>1?` \xD7${p.quantity}`:""} \u2014 ${p.detail} (${p.source})`);return text4(`${s}**Sentry drops \u2014 by reason:**
|
|
684
|
+
|
|
685
|
+
${h.join("\n")}
|
|
686
|
+
|
|
687
|
+
**Recent (${d.length}):**
|
|
688
|
+
|
|
689
|
+
\`\`\`
|
|
690
|
+
${w.join("\n")}
|
|
691
|
+
\`\`\`
|
|
692
|
+
|
|
693
|
+
_"observed" means the tool watched it happen; "reported" means the SDK counted it afterwards. Native drops only appear when the SDK runs with debug enabled._`)}catch(r){return fail6(errMsg6(r))}});e.registerTool("sentry_action",{description:"Act on the Sentry inspector. 'clear' drops every captured envelope and drop record \u2014 use it to get a clean window before driving a flow you want to measure.",inputSchema:{action:import_zod18.z.enum(["clear"]).describe("The action to perform."),deviceId:import_zod18.z.string().optional().describe("The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out.")}},async t=>{try{const r=n.requireProDevice(t.deviceId);await n.callAction(SENTRY_TOOL_ID,"clearEnvelopes",{},r);return text4("Cleared the Sentry inspector \u2014 envelopes and drop records. Drive your flow, then read get_sentry_envelopes or get_sentry_cost.")}catch(r){return fail6(errMsg6(r))}})}var import_zod18,SENTRY_TOOL_ID,text4,fail6,errMsg6,FREE_QUOTA,CATEGORY_FORMAT;var init_sentry=__esm({"src/tools/packs/sentry.ts"(){"use strict";import_zod18=require("zod");SENTRY_TOOL_ID="sentry";text4=e=>({content:[{type:"text",text:e}]});fail6=e=>({isError:true,content:[{type:"text",text:e}]});errMsg6=e=>e instanceof Error?e.message:String(e);FREE_QUOTA={errors:5e3,spans:5e6,replays:50,logBytes:5*1024**3,attachmentBytes:1*1024**3};CATEGORY_FORMAT={errors:"count",spans:"count",replays:"count",logBytes:"bytes",attachmentBytes:"bytes"}}});function kb(e){return e<1024?`${e} B`:`${(e/1024).toFixed(1)} KB`}function formatOutcome(e){const n=Object.entries(e.results).map(([r,i])=>{const o=i.skipped.slice(0,3).map(a=>`
|
|
694
|
+
\xB7 ${a.id}: ${a.reason}`).join("");const s=i.warnings.slice(0,3).map(a=>`
|
|
695
|
+
\u26A0 ${a}`).join("");return` ${i.ok?"\u2713":"\u2715"} ${r} \u2014 applied ${i.applied}${i.skipped.length?`, skipped ${i.skipped.length}`:""}${o}${s}`});const t=e.route;if(t){n.push(t.status==="navigated"?` \u2713 route \u2014 navigated to ${t.href}`:t.status==="deferred"?` \u21BB route \u2014 ${t.href} will be opened after the reload`:` \u2715 route \u2014 ${t.error??t.status}`)}return`Restored "${e.snapshotName}" (${e.mode}${e.willReload?", app reloading":""}):
|
|
696
|
+
${n.join("\n")}`}function registerTimeMachineTools(e,n){e.registerTool("get_time_machine",{description:"List the app's Time Machine state snapshots (restore points) and which state sources (storage/redux/zustand/jotai/react-query) can currently be captured/restored. Each snapshot also records the route it was captured on (shown as `route`), which a restore can navigate back to. Use time_machine_action to capture a snapshot before driving a flow, then restore supported sources to repeat the flow. Uncaptured and backend state can still differ.",inputSchema:{deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:i,stale:o}=await n.getSnapshot(TIME_MACHINE_TOOL_ID,r);const s=i??{};const a=s.snapshots??[];const c=s.providers??[];const l=c.map(h=>{const w=h.canCapture?h.canRestore?"capture+restore":"capture only":"unavailable";return`- ${h.label} (${h.id}): ${w}${h.detail?` \u2014 ${h.detail}`:""}`});if(s.route){l.push(s.route.available?`- Route (route): capture+restore \u2014 recorded with every snapshot; pass restoreRoute:true to return to it${s.route.current?` (now ${s.route.current})`:""}`:"- Route (route): unavailable \u2014 no Expo Router on this device, snapshots record no route")}const u=a.map(h=>{const w=Object.values(h.sources).reduce((m,f)=>m+f.warnings.length,0);const p=h.baseline?"baseline: clear supported providers and request reload":`${kb(h.sizeBytes)} \xB7 ${Object.keys(h.sources).join(", ")}`;const g=h.route?` \xB7 route ${h.route.href}`:"";return`- \`${h.id}\` **${h.name}** \u2014 ${new Date(h.createdAt).toISOString()} \xB7 ${p}${g}${w?` \xB7 \u26A0 ${w}`:""}`});const d=[`**Time Machine \u2014 ${a.length} snapshot(s):**`,u.length?u.join("\n"):"_none yet \u2014 capture one with time_machine_action_",`**Sources:**
|
|
697
|
+
${l.join("\n")||"_no providers registered_"}`];if(s.lastOutcome)d.push(`**Last restore:**
|
|
698
|
+
${formatOutcome(s.lastOutcome)}`);return text(staleHeader(o)+d.join("\n\n"))}catch(r){return fail2(errMsg2(r))}});e.registerTool("time_machine_action",{description:"Manage snapshots of supported registered state sources: capture, preview, restore, capture_baseline, delete or rename. Preview affected items before restoring. Live mode replaces supported state in place; reload mode restores supported persisted storage and requests a JS reload. Baselines clear providers that support clearing and request a reload; they do not reset backend state or reproduce a complete reinstall. restoreRoute:true requests the captured route when available. Inspect per-source applied/skipped results and reload outcomes.",inputSchema:{action:import_zod19.z.enum(["capture","capture_baseline","preview","restore","delete","rename"]).describe("What to do."),id:import_zod19.z.string().optional().describe("Snapshot id (required for restore/delete/rename; from get_time_machine)."),name:import_zod19.z.string().optional().describe("Snapshot name (for capture and rename)."),mode:import_zod19.z.enum(["live","reload"]).optional().describe("Restore mode. Default 'live'."),excludeKeys:import_zod19.z.array(import_zod19.z.string()).optional().describe('Restore only: item keys to LEAVE UNTOUCHED, as "sourceId::itemKey" (itemKey = the key shown by the preview action, e.g. "query::[\\"pokemon\\"]" or "storage::async:@cart").'),restoreRoute:import_zod19.z.boolean().optional().describe("Restore only: also navigate back to the route the snapshot was captured on (shown as `route` by get_time_machine). With mode 'reload' the navigation happens automatically on the next boot. Default false \u2014 state is restored but the app stays on the current screen."),sourceIds:import_zod19.z.array(import_zod19.z.string()).optional().describe("Capture/restore only these source ids (default all)."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=(o,s)=>n.callAction(TIME_MACHINE_TOOL_ID,o,s,r);switch(t.action){case"capture":{const o=await i("capture",{name:t.name??"",sourceIds:t.sourceIds});const s=o.snapshot;const a=Object.entries(s.sources).flatMap(([c,l])=>l.warnings.map(u=>`
|
|
699
|
+
\u26A0 ${c}: ${u}`)).join("");return text(`Captured \`${s.id}\` "${s.name}" \u2014 ${kb(s.sizeBytes)} \xB7 ${Object.keys(s.sources).join(", ")}${a}`)}case"capture_baseline":{const o=await i("captureBaseline",{});return text(`Captured baseline \`${o.snapshot.id}\` \u2014 restoring it wipes app storage and reloads.`)}case"preview":{if(!t.id)return fail2("preview requires `id` (from get_time_machine).");const o=await i("preview",{id:t.id});const s=[];let a=0;for(const l of o.sources){const u={};for(const w of l.items){u[w.verdict]=(u[w.verdict]??0)+1}const d=(u.added??0)+(u.removed??0)+(u.changed??0)+(u["too-large"]??0);a+=d;const h=Object.entries(u).filter(([w])=>w!=="unchanged").map(([w,p])=>`${p} ${w}`);s.push(`- **${l.label}**: ${h.length?h.join(", "):"no changes"}${l.error?` \u2014 \u26A0 ${l.error}`:""}`);for(const w of l.items.filter(p=>p.verdict!=="unchanged").slice(0,8)){s.push(` ${w.verdict==="added"?"+":w.verdict==="removed"?"\u2212":w.verdict==="wont-apply"?"\u2298":"\u2248"} ${w.label}${w.reason?` (${w.reason})`:""}`)}for(const w of l.notes)s.push(` \xB7 ${w}`)}const c=a===0?"**Restore would change NOTHING** (states identical or nothing applicable).":`**Restore would apply ${a} change(s):**`;return text(`${c}
|
|
700
|
+
${s.join("\n")}`)}case"restore":{if(!t.id)return fail2("restore requires `id` (from get_time_machine).");const o=await i("restore",{id:t.id,mode:t.mode??"live",excludeKeys:t.excludeKeys,restoreRoute:t.restoreRoute});return text(formatOutcome(o))}case"delete":{if(!t.id)return fail2("delete requires `id`.");await i("delete",{id:t.id});return text(`Deleted snapshot \`${t.id}\`.`)}case"rename":{if(!t.id||!t.name)return fail2("rename requires `id` and `name`.");await i("rename",{id:t.id,name:t.name});return text(`Renamed \`${t.id}\` to "${t.name}".`)}}}catch(r){return fail2(errMsg2(r))}})}var import_zod19,TIME_MACHINE_TOOL_ID;var init_timeMachine=__esm({"src/tools/packs/timeMachine.ts"(){"use strict";import_zod19=require("zod");init_packKit();TIME_MACHINE_TOOL_ID="time-machine"}});function duration(e){const n=e<0?"-":"+";let t=Math.abs(Math.round(e/1e3));if(t===0)return"0s";const r=[];for(const[i,o]of[["d",86400],["h",3600],["m",60],["s",1]]){if(t>=o){r.push(`${Math.floor(t/o)}${i}`);t%=o}if(r.length===2)break}return n+r.join(" ")}function describe(e){const n=[e.active?`**App clock: ${e.virtualIso}** (${e.mode}${e.rate!==1?`, ${e.rate}\xD7`:""}), ${duration(e.offsetMs)} from real time ${new Date(e.realNow).toISOString()}`:`**App clock: real time** (${e.virtualIso})`,`Time zone: ${e.timeZone} (the override never changes it)`,`Pending app timers: ${e.timers.timeouts} timeouts, ${e.timers.intervals} intervals`];if(e.lastJump){n.push(`Last change: ${duration(e.lastJump.byMs)}${e.lastJump.firedTimers?`, ran ${e.lastJump.firedTimers} due timer(s)`:""}`)}n.push(...describeTokens(e));n.push(`Settings: persist=${e.settings.persist} showChip=${e.settings.showChip} fireTimersOnJump=${e.settings.fireTimersOnJump}`);return n.join("\n")}function describeTokens(e){const n=e.tokens;if(!n)return[];if(!n.available)return["Sign-in tokens: unavailable (the app has no @buoy-gg/network)."];if(n.tokens.length===0)return["Sign-in tokens: none seen yet (they appear once the app sends a signed-in request)."];const t=["Sign-in tokens (read from captured requests; raw tokens are never shown):"];for(const i of n.tokens){const o=i.expiresAt!==void 0?i.expiresAt-e.virtualNow:void 0;const s=i.serverExpiresAt!==void 0?i.serverExpiresAt-e.realNow:void 0;const a=i.neverExpires?"never expires":o===void 0?"expiry unknown":o>0?`expires in ${duration(o).slice(1)} on the app's clock`:`expired ${duration(-o).slice(1)} ago on the app's clock`;const c=s!==void 0&&o!==void 0&&Math.abs(s-o)>2e3?s>0?`; the server accepts it for ${duration(s).slice(1)} more`:"; the server no longer accepts it":"";const l=[i.hint??i.formatLabel,i.expirySource?`expiry from ${i.expirySource}`:null,i.issuedBy?`issued by ${i.issuedBy}`:null,i.claims.sub?`sub ${i.claims.sub}`:null,`${i.uses} request(s)`,i.refreshes?`${i.refreshes} refresh(es)`:null,i.expiredSends?`SENT ${i.expiredSends}\xD7 AFTER EXPIRY`:null,i.rejected?`rejected ${i.rejected}\xD7`:null,i.looping?`REFRESH LOOP (${i.recentRefreshes} new tokens in 20s)`:null].filter(Boolean);t.push(`- [${i.id}] ${i.label} \u2192 ${i.host}: ${a}${c} (${l.join(", ")})`)}const r=n.check;if(r){const i=r.status==="refreshed"?`refreshed${r.kind==="401"&&r.forcedAt?" after the forced 401":""}${r.newIssuedBy?` via ${r.newIssuedBy}`:""}${r.newLifetimeMs?`; new token lasts ${duration(r.newLifetimeMs).slice(1)}`:""}`:r.status==="loop"?`REFRESH LOOP: ${r.newTokens} new tokens since the check started`:r.kind==="401"&&r.forcedAt===void 0?"waiting: the next request to that API will get a 401 (the app must send one)":`waiting for a new token (${duration(e.realNow-r.startedAt).slice(1)} so far)`;const o=r.staleAfterFailure?`; the app re-sent the old token ${r.staleAfterFailure}\xD7 after the 401`:"";t.push(`Refresh check (${r.kind==="401"?"forced 401":"jump to expiry"}): ${i}${o}`)}return t}function registerClockTools(e,n){e.registerTool("get_clock",{description:"Read the app's clock as the Clock tool (@buoy-gg/clock) sees it: the time the app reads now, whether it is overridden (running, frozen or sped up), how far it is from real time, and the pending app timers a jump ahead could run. Also lists the app's sign-in tokens seen in its traffic (JWT, PASETO, opaque tokens with an expiry from the login response, session cookies): time left on the app's clock and the server's, who issued them, refreshes, sends after expiry, refresh loops, and the result of a running refresh check. Check this before calling a date, countdown, expiry or sign-out a bug.",inputSchema:{deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(CLOCK_TOOL_ID,"getState",{},r);return text(describe(i))}catch(r){return fail2(errMsg2(r))}});e.registerTool("clock_action",{description:"Override the app's clock. set_time moves it to `time` (ISO 8601, 'YYYY-MM-DD HH:MM' in the device's zone, epoch ms, or relative like '+30d'), optionally frozen. shift jumps by `by` ('+1d', '-2h30m', '90s'); a forward shift also runs app setTimeout/setInterval callbacks that come due inside the jump, once each. freeze/resume stop and restart it, set_rate runs it faster (60 = a minute per second), reset returns to real time. To test token refresh: jump_to_token_expiry moves the app's clock to `leadMs` (default 10000) before a token expires, for apps that refresh before expiry; fail_next_request answers the next request to that token's API with a 401 once, for apps that refresh after a 401. Both start a refresh check; read get_clock after the app sends a request to see whether a new token arrived. stop_token_check ends it and withdraws an unfired 401. Moves Date.now(), new Date() and no-argument Intl formatting; performance.now(), animations, native timers, the time zone and the backend's clock stay real. Screens that already computed a time keep it until they re-read the clock or the app reloads; the override survives reload_app.",inputSchema:{action:import_zod20.z.enum(["set_time","shift","freeze","resume","set_rate","reset","settings","jump_to_token_expiry","fail_next_request","stop_token_check"]).describe("What to do."),time:import_zod20.z.union([import_zod20.z.string(),import_zod20.z.number()]).optional().describe("set_time (required) / freeze (optional): target time."),by:import_zod20.z.union([import_zod20.z.string(),import_zod20.z.number()]).optional().describe("shift (required): signed duration like '+1d', '-2h30m', '90s', or ms."),freeze:import_zod20.z.boolean().optional().describe("set_time: stop the clock at `time`. Default false."),fireTimers:import_zod20.z.boolean().optional().describe("shift: run app timers that come due inside a forward jump. Default on."),rate:import_zod20.z.number().optional().describe("set_rate (required): speed multiplier, 0.1-86400; 1 is normal."),persist:import_zod20.z.boolean().optional().describe("settings: keep the override across reloads."),showChip:import_zod20.z.boolean().optional().describe("settings: show the floating clock chip while overridden."),fireTimersOnJump:import_zod20.z.boolean().optional().describe("settings: default for shift's fireTimers."),token:import_zod20.z.string().optional().describe("jump_to_token_expiry / fail_next_request: token id from get_clock. Default: the most recently used token."),leadMs:import_zod20.z.number().optional().describe("jump_to_token_expiry: land this many ms before expiry. Default 10000."),status:import_zod20.z.number().optional().describe("fail_next_request: 401 (default) or 403."),times:import_zod20.z.number().optional().describe("fail_next_request: how many requests to fail, 1-10. Default 1."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=(s,a={})=>n.callAction(CLOCK_TOOL_ID,s,a,r);let o;switch(t.action){case"set_time":if(t.time===void 0)return fail2("set_time requires `time`.");o=await i("setTime",{time:t.time,freeze:t.freeze??false});break;case"shift":if(t.by===void 0)return fail2("shift requires `by`, e.g. '+1d'.");o=await i("shift",{by:t.by,...t.fireTimers!==void 0?{fireTimers:t.fireTimers}:{}});break;case"freeze":o=await i("freeze",t.time!==void 0?{time:t.time}:{});break;case"resume":o=await i("resume");break;case"set_rate":if(t.rate===void 0)return fail2("set_rate requires `rate`.");o=await i("setRate",{rate:t.rate});break;case"reset":o=await i("reset");break;case"settings":o=await i("updateSettings",{...t.persist!==void 0?{persist:t.persist}:{},...t.showChip!==void 0?{showChip:t.showChip}:{},...t.fireTimersOnJump!==void 0?{fireTimersOnJump:t.fireTimersOnJump}:{}});break;case"jump_to_token_expiry":o=await i("jumpToTokenExpiry",{...t.token?{token:t.token}:{},...t.leadMs!==void 0?{leadMs:t.leadMs}:{}});break;case"fail_next_request":o=await i("failNextRequest",{...t.token?{token:t.token}:{},...t.status!==void 0?{status:t.status}:{},...t.times!==void 0?{times:t.times}:{}});break;case"stop_token_check":o=await i("stopTokenCheck");break}return text(describe(o))}catch(r){return fail2(errMsg2(r))}})}var import_zod20,CLOCK_TOOL_ID;var init_clock=__esm({"src/tools/packs/clock.ts"(){"use strict";import_zod20=require("zod");init_packKit();CLOCK_TOOL_ID="clock"}});function describe2(e,n=12){const t=[];t.push(e.overriddenCount>0?`**${e.overriddenCount} permission(s) overridden** on ${e.platform}. The app sees the override; the OS state is unchanged.`:`**No overrides** on ${e.platform}: the app sees the real OS state.`);t.push(`Libraries found: ${e.libraries.length?e.libraries.join(", "):"none yet"}`);if(e.permissions.length===0){t.push("No permission APIs found yet. Rows appear for Expo modules in the app and for anything the app asks for.")}for(const i of e.permissions){const o=[i.override?`override **${i.override}**`:"not overridden",`system ${i.real??"unknown"}`,i.calls?`asked ${i.calls}\xD7`:"not asked yet",i.sources.length?`via ${i.sources.join(", ")}`:null,`can be: ${i.states.join(", ")}`].filter(Boolean);t.push(`- ${i.id} (${i.label}): ${o.join("; ")}`);if(i.warning)t.push(` \u26A0 ${i.warning}`)}const r=e.settings;t.push(`Settings: requestAnswer=${r.requestAnswer} notifyApp=${r.notifyApp} interceptSettings=${r.interceptSettings} enforce=${r.enforce} persist=${r.persist} showChip=${r.showChip}`);if(e.log.length){t.push("Recent calls (newest first):");for(const i of e.log.slice(0,n)){const o=new Date(i.at).toISOString().slice(11,19);const s=i.error??i.returned??"no answer";t.push(`- ${o} ${i.source}.${i.method} \u2192 ${s}${i.overridden?" (override)":""}${i.real&&i.real!==i.returned?`, system ${i.real}`:""}${i.answer?`, answered ${i.answer}`:""}`)}}if(e.host.bundleId){t.push(`Host: ${e.host.isSimulator?"simulator/emulator":e.host.isSimulator===false?"physical device":"unknown device"} "${e.host.deviceName??"?"}", app ${e.host.bundleId}`)}return t.join("\n")}async function run2(e,n){const{stdout:t}=await execFileAsync12(e,n,{timeout:2e4});return t}async function findSimulator(e,n){if(n)return n;const t=JSON.parse(await run2("xcrun",["simctl","list","devices","booted","-j"]));const r=Object.values(t.devices).flat();const i=r.filter(o=>o.name===e.host.deviceName);if(i.length===1)return i[0].udid;if(!e.host.deviceName&&r.length===1)return r[0].udid;throw new Error(i.length===0?`No booted simulator is named "${e.host.deviceName??"?"}". Pass \`udid\`.`:`${i.length} booted simulators are named "${e.host.deviceName}". Pass \`udid\`.`)}async function findAdbSerial(e){if(e)return e;const n=await run2("adb",["devices"]);const t=n.split("\n").slice(1).map(r=>r.trim().split(/\s+/)).filter(r=>r[1]==="device").map(r=>r[0]);if(t.length===1)return t[0];throw new Error(t.length===0?"No Android device is connected to adb.":"Several Android devices are connected. Pass `serial`.")}async function systemPermission(e,n,t,r){const i=e.host.bundleId;if(!i)throw new Error("The app did not report its bundle id (needs expo-application).");if(e.platform==="ios"){if(e.host.isSimulator===false)throw new Error("A physical iPhone can't be changed from the host. Use the app's Settings page.");const c=t==="all"?"all":SIMCTL_SERVICE[t];if(!c){throw new Error(`simctl has no privacy service for ${t}. Override it in the app instead (permission_action set).`)}const l=await findSimulator(e,r.udid);await run2("xcrun",["simctl","privacy",l,n,c,i]);return`simctl privacy ${n} ${c} for ${i} on ${l}.${n==="grant"?"":" iOS ends the app's process when a permission is revoked or reset; relaunch it."}`}const o=await findAdbSerial(r.serial);const s=t==="all"?Object.values(ANDROID_PERMISSIONS).flat():ANDROID_PERMISSIONS[t];if(!s)throw new Error(`No Android permission is known for ${t}.`);const a=[];for(const c of s){const l=`android.permission.${c}`;try{if(n==="grant")await run2("adb",["-s",o,"shell","pm","grant",i,l]);else{await run2("adb",["-s",o,"shell","pm","revoke",i,l]);if(n==="reset"){await run2("adb",["-s",o,"shell","pm","clear-permission-flags",i,l,"user-set","user-fixed"])}}a.push(c)}catch{}}if(a.length===0)throw new Error(`None of ${s.join(", ")} could be changed. Is it declared in the app's manifest?`);return`adb ${n} ${a.join(", ")} for ${i} on ${o}.${n==="grant"?"":" Android restarts the app's process when a permission is revoked."}`}function registerPermissionsTools(e,n){e.registerTool("get_permissions",{description:"Read the app's permissions as the Permissions tool (@buoy-gg/permissions) sees them: each permission the app can reach (location, camera, notifications, photos\u2026), what the OS says, any override, which libraries asked (Expo modules, PermissionsAndroid, react-native-permissions), the states this platform allows, and the recent permission calls with what each one returned. Check this before calling a permission screen, prompt or Settings flow a bug.",inputSchema:{logLimit:import_zod21.z.number().optional().describe("How many recent calls to list. Default 12."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(PERMISSIONS_TOOL_ID,"getState",{},r);return text(describe2(i,t.logLimit??12))}catch(r){return fail2(errMsg2(r))}});e.registerTool("permission_action",{description:"Override what the app sees when it asks for a permission, without changing the OS. set makes `permission` read as `state` (undetermined = not asked, granted, limited = approximate location / selected photos or contacts / provisional notifications, denied, blocked = Android 'don't ask again', restricted = iOS parental controls); iOS has no blocked (a refusal is final, so denied reads as blocked) and Android has no restricted. clear returns one permission to the OS answer, reset clears all. While overridden, the real system prompt never shows: a request from undetermined (or Android denied) is answered by `answer` (ask = Buoy shows a prompt on the device and waits for a tap; allow, limited or deny answer at once) and moves the state the way the OS would. Linking.openSettings and app-settings: open Buoy's stand-in for Settings. By default a change sends the app background \u2192 active, like a return from Settings, so screens that re-check on foreground update; permission hooks that read only on mount update on their next read. With enforce on (default), calls that need access (current position, launch camera, media library reads) fail with the native module's error while refused. request_real shows the real system prompt once so the OS grants what the override pretends. The override survives reload_app.",inputSchema:{action:import_zod21.z.enum(["set","clear","reset","answer","settings","request_real","return_from_settings","clear_log"]).describe("What to do."),permission:import_zod21.z.string().optional().describe(`set / clear / request_real (required): ${PERMISSION_IDS.join(", ")}, or android:<android.permission.NAME>.`),state:import_zod21.z.enum(["undetermined","granted","limited","denied","blocked","restricted"]).optional().describe("set (required): the state the app sees."),answer:import_zod21.z.enum(["ask","allow","limited","deny"]).optional().describe("answer (required): how a request from 'not asked' is answered while overridden."),notifyApp:import_zod21.z.boolean().optional().describe("settings: send background \u2192 active after each change. Default on."),interceptSettings:import_zod21.z.boolean().optional().describe("settings: stand in for Settings while overridden. Default on."),enforce:import_zod21.z.boolean().optional().describe("settings: fail calls that need a refused permission. Default on."),persist:import_zod21.z.boolean().optional().describe("settings: keep overrides across reloads. Default on."),showChip:import_zod21.z.boolean().optional().describe("settings: show the floating chip while overridden. Default on."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=(s,a={})=>n.callAction(PERMISSIONS_TOOL_ID,s,a,r);let o;switch(t.action){case"set":if(!t.permission||!t.state)return fail2("set requires `permission` and `state`.");o=await i("setOverride",{permission:t.permission,state:t.state});break;case"clear":if(!t.permission)return fail2("clear requires `permission`.");o=await i("clearOverride",{permission:t.permission});break;case"reset":o=await i("resetAll");break;case"answer":if(!t.answer)return fail2("answer requires `answer`: ask, allow, limited or deny.");o=await i("updateSettings",{requestAnswer:t.answer});break;case"settings":o=await i("updateSettings",{...t.notifyApp!==void 0?{notifyApp:t.notifyApp}:{},...t.interceptSettings!==void 0?{interceptSettings:t.interceptSettings}:{},...t.enforce!==void 0?{enforce:t.enforce}:{},...t.persist!==void 0?{persist:t.persist}:{},...t.showChip!==void 0?{showChip:t.showChip}:{}});break;case"request_real":if(!t.permission)return fail2("request_real requires `permission`.");o=await i("requestReal",{permission:t.permission});break;case"return_from_settings":o=await i("simulateReturnFromSettings");break;case"clear_log":o=await i("clearLog");break}return text(describe2(o))}catch(r){return fail2(errMsg2(r))}});e.registerTool("system_permission",{description:"Change the REAL OS permission for the connected app from this machine, for what an in-app override can't fake (native code that checks the OS itself, like reading a position or opening the camera). iOS Simulator uses `xcrun simctl privacy` (grant, revoke, reset; reset returns to 'not asked' so the real prompt shows again). There is no simctl service for notifications or tracking. Android uses `adb shell pm grant/revoke`; reset also clears 'don't ask again'. Revoking or resetting ends the app's process on both platforms, so relaunch it afterwards. Physical iPhones can't be changed this way.",inputSchema:{action:import_zod21.z.enum(["grant","revoke","reset"]).describe("grant, revoke, or reset to not asked."),permission:import_zod21.z.string().describe(`${PERMISSION_IDS.join(", ")}, or all.`),udid:import_zod21.z.string().optional().describe("iOS: the simulator udid, when its name is ambiguous."),serial:import_zod21.z.string().optional().describe("Android: the adb serial, when several devices are connected."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(PERMISSIONS_TOOL_ID,"getState",{},r);const o=await systemPermission(i,t.action,t.permission,{udid:t.udid,serial:t.serial});return text(o)}catch(r){return fail2(errMsg2(r))}})}var import_node_child_process13,import_node_util12,import_zod21,PERMISSIONS_TOOL_ID,execFileAsync12,PERMISSION_IDS,SIMCTL_SERVICE,ANDROID_PERMISSIONS;var init_permissions=__esm({"src/tools/packs/permissions.ts"(){"use strict";import_node_child_process13=require("child_process");import_node_util12=require("util");import_zod21=require("zod");init_packKit();PERMISSIONS_TOOL_ID="permissions";execFileAsync12=(0,import_node_util12.promisify)(import_node_child_process13.execFile);PERMISSION_IDS=["location","locationBackground","camera","microphone","notifications","photos","contacts","calendar","reminders","tracking","motion","bluetooth"];SIMCTL_SERVICE={location:"location",locationBackground:"location-always",camera:"camera",microphone:"microphone",photos:"photos",contacts:"contacts",calendar:"calendar",reminders:"reminders",motion:"motion"};ANDROID_PERMISSIONS={location:["ACCESS_FINE_LOCATION","ACCESS_COARSE_LOCATION"],locationBackground:["ACCESS_BACKGROUND_LOCATION"],camera:["CAMERA"],microphone:["RECORD_AUDIO"],notifications:["POST_NOTIFICATIONS"],photos:["READ_MEDIA_IMAGES","READ_MEDIA_VIDEO"],contacts:["READ_CONTACTS","WRITE_CONTACTS"],calendar:["READ_CALENDAR","WRITE_CALENDAR"],motion:["ACTIVITY_RECOGNITION"],bluetooth:["BLUETOOTH_SCAN","BLUETOOTH_CONNECT"]}}});function listeners(e){if(e==null)return"can't count";return e===0?"none":String(e)}function describe3(e){const n=[];if(e.away){const r=Math.round((Date.now()-e.away.startedAt)/1e3);n.push(`**Simulated: ${e.away.kind==="background"?"in the background":"interrupted (inactive)"}** for ${r}s`+(e.away.returnAt?`, returns in ${Math.max(0,Math.round((e.away.returnAt-Date.now())/1e3))}s`:", until return")+`. Real OS state: ${e.realAppState}.`)}else{n.push(`App state: active (real OS state: ${e.realAppState}).`)}if(e.power){n.push(`Simulated battery: ${Math.round(e.power.level*100)}%, ${e.power.state}${e.power.lowPowerMode?", low power mode":""} (reached ${e.power.reached.join(", ")})`+(e.power.realGetters.length?`; still real: ${e.power.realGetters.join(", ")}`:""))}if(e.scheme)n.push(`Simulated color scheme: ${e.scheme.scheme} (${e.scheme.mode}).`);n.push(`App listeners: app state ${listeners(e.listeners.appState)}, memory warning ${listeners(e.listeners.memoryWarning)}, deep link ${listeners(e.listeners.deepLink)}`+(e.platform==="android"?`, window focus ${listeners(e.listeners.focus)}`:"")+(e.batteryLibraries.length?`, battery ${listeners(e.listeners.battery)} (${e.batteryLibraries.join(", ")})`:", battery: no battery library installed")+".");if(e.report){const r=e.report;n.push(`
|
|
701
|
+
**Report: ${r.label}**${r.collectingUntil!=null?" (still collecting)":""}`);if(r.unavailable)n.push(r.unavailable);if(r.finding)n.push(`Finding: ${r.finding}`);if(r.note)n.push(`Note: ${r.note}`);const i=Object.entries(r.counts).map(([o,s])=>`${s} ${o}`).join(", ");if(!r.unavailable)n.push(`Counts: ${i||"nothing happened"}`);for(const o of r.events.slice(0,25)){n.push(`- +${(o.at/1e3).toFixed(1)}s ${o.whileAway?"[away] ":""}${o.source}: ${o.title}${o.subtitle?` (${o.subtitle})`:""}${o.status==="error"?" ERROR":""}`)}}if(e.relaunch){const r=e.relaunch;n.push(r.restored==null&&r.after==null?`
|
|
702
|
+
Relaunch: checking where the app landed (was on ${r.before??"unknown"}).`:`
|
|
703
|
+
Relaunch: ${r.restored?`restored ${r.after}`:`landed on ${r.after??"unknown"}, was on ${r.before??"unknown"}`}${r.tookMs!=null?` (${(r.tookMs/1e3).toFixed(1)}s)`:""}.`)}if(typeof e.handled==="boolean")n.push(`Back press handled by the app: ${e.handled}.`);if(e.log.length)n.push(`
|
|
704
|
+
Recent: ${e.log.slice(0,5).map(r=>r.text).join(" \xB7 ")}`);const t=e.recipes.filter(r=>!r.unavailable).map(r=>r.id);n.push(`Recipes: ${t.join(", ")}`);return n.join("\n")}async function simctl2(e){const{stdout:n}=await execFileAsync13("xcrun",["simctl",...e],{timeout:2e4});return n}async function hostColorScheme(e,n){if(e.platform==="ios"){await simctl2(["ui",e.udid,"appearance",n]);return`Simulator appearance set to ${n} (affects every app on this simulator).`}if(e.platform==="ios-device")throw new Error("A physical iPhone's appearance can't be changed from the computer. Leave `real` off to simulate it.");await adb(e.serial,["shell","cmd","uimode","night",n==="dark"?"yes":"no"]);return`Android night mode set to ${n==="dark"?"on":"off"} (affects every app on this device).`}function registerLifecycleTools(e,n){e.registerTool("get_lifecycle",{description:"Read the Lifecycle tool (@buoy-gg/lifecycle): the app's simulated and real app state, how many of the APP's own listeners each lifecycle signal has (app state, memory warning, deep link, battery), the report of what the app did during and after the last simulation (requests, query refetches, route changes, store writes, with a finding such as requests made while in the background), and the relaunch check (did the app reopen where it was). Read it after lifecycle_action; reports keep collecting for a few seconds after the app returns.",inputSchema:{deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(LIFECYCLE_TOOL_ID,"getState",{},r);return text(describe3(i))}catch(r){return fail2(errMsg2(r))}});e.registerTool("lifecycle_action",{description:"Put the app through lifecycle events and interruptions. background sends it to the background (iOS: inactive then background; Android: blur then background), interrupt makes it inactive like the app switcher or a call, return brings it back; `duration` ('5s', '31m') returns by itself, and skipWait with a duration moves the app clock instead of waiting (needs @buoy-gg/clock), which tests session timeouts in one call. memory_warning, open_url (`url`), press_back (Android; never exits the app, reports whether a screen handled it), color_scheme (`scheme`), battery (`level` 0-1, `lowPowerMode`, `state`; needs expo-battery, react-native-device-info or @capacitor/device), reset_battery, relaunch (restarts the app's JS, then checks where it landed), recipe (`id`, see get_lifecycle), clear_report, reset (end every simulation). Simulations reach the app's JS listeners only: nothing is suspended and the next real OS event wins. With `real: true` (iOS Simulator or Android), background/return/relaunch/color_scheme/open_url cause the real OS event instead (relaunch then kills the process, a real cold start). App control, iOS Simulator or Android, no lifecycle package needed: quit closes the app, launch opens it (works while it is closed), reinstall (`appPath`: a simulator .app or an .apk) wipes its data like a new user and keeps Buoy's sign-in on iOS, boot_simulator (`simulator`) starts an iOS Simulator. Read get_lifecycle afterwards for the report.",inputSchema:{action:import_zod22.z.enum(["background","interrupt","return","memory_warning","open_url","press_back","color_scheme","battery","reset_battery","relaunch","recipe","clear_report","reset","settings","quit","launch","reinstall","boot_simulator"]).describe("What to do."),duration:import_zod22.z.union([import_zod22.z.string(),import_zod22.z.number()]).optional().describe("background / interrupt: return by itself after this long ('5s', '5m', ms). Omit to stay until return."),skipWait:import_zod22.z.boolean().optional().describe("background / interrupt: move the app clock forward by `duration` and return at once. Needs @buoy-gg/clock."),url:import_zod22.z.string().optional().describe("open_url (required): the link, with its scheme."),scheme:import_zod22.z.enum(["light","dark","system"]).optional().describe("color_scheme (required). 'system' ends the simulated scheme."),mode:import_zod22.z.enum(["js","native"]).optional().describe("color_scheme: 'js' emits the change to JS listeners (default); 'native' overrides the app's native appearance too."),level:import_zod22.z.number().optional().describe("battery: 0 to 1 (or a percentage above 1)."),lowPowerMode:import_zod22.z.boolean().optional().describe("battery: low power mode on or off."),state:import_zod22.z.enum(["unplugged","charging","full","unknown"]).optional().describe("battery: charging state."),id:import_zod22.z.string().optional().describe("recipe (required): a recipe id from get_lifecycle, e.g. 'away-31m'."),showChip:import_zod22.z.boolean().optional().describe("settings: show the floating status chip while simulating."),reportWindow:import_zod22.z.union([import_zod22.z.string(),import_zod22.z.number()]).optional().describe("settings: how long reports keep collecting after the app returns ('5s')."),real:import_zod22.z.boolean().optional().describe("Cause the real OS event on the iOS Simulator or Android device (background, return, relaunch, color_scheme, open_url)."),appPath:import_zod22.z.string().optional().describe("reinstall (required): the built app, a simulator .app folder or an Android .apk."),keepBuoySignIn:import_zod22.z.boolean().optional().describe("reinstall, iOS: keep Buoy's sign-in and device id. Default true."),simulator:import_zod22.z.string().optional().describe('boot_simulator (required): simulator name or udid, e.g. "iPhone 17 Pro".'),udid:import_zod22.z.string().optional().describe("The simulator udid, when it can't be found by itself."),serial:import_zod22.z.string().optional().describe("Android: the adb serial, when several devices are connected."),deviceId:deviceIdInput}},async t=>{try{if(t.action==="boot_simulator"){if(!t.simulator&&!t.udid)return fail2('boot_simulator requires `simulator` (a name like "iPhone 17 Pro" or a udid).');if(!n.listDevices().some(a=>a.isPro))return fail2("boot_simulator needs a Buoy Pro app seen in this session. Open the app once first.");return text(await bootSimulator(t.simulator??t.udid))}const r=["quit","launch","reinstall"];if(t.real||r.includes(t.action)){const a=t.action==="launch"||t.action==="quit";const c=["quit","relaunch","reinstall"].includes(t.action);const{id:l,host:u,online:d}=await hostTarget(n,t.deviceId,{udid:t.udid,serial:t.serial},{allowOffline:a,changesApp:c});const h=(v,y={})=>n.callAction(LIFECYCLE_TOOL_ID,v,y,l);const w=d?await h("getState").catch(()=>null):null;const p=w?.host?.bundleId;if(p&&u.platform==="ios"&&!u.bundleId)u.bundleId=p;let g;switch(t.action){case"quit":g=`${await hostQuit(u)} Buoy disconnects until it is launched again (lifecycle_action launch).`;break;case"launch":g=`${await hostLaunch(u)} A dev build loads its bundle first; give it a few seconds to connect.`;break;case"reinstall":if(!t.appPath)return fail2("reinstall requires `appPath`: the built simulator .app folder or Android .apk.");g=await hostReinstall(u,t.appPath,t.keepBuoySignIn??true);break;case"background":g=`${await hostBackground(u)} Use return with real: true.`;break;case"return":await hostLaunch(u);g="Brought back to the foreground for real.";break;case"relaunch":if(d)await h("prepareRelaunch").catch(()=>void 0);await hostQuit(u);await hostLaunch(u);g="Killed the process and launched it again (a real cold start). Read get_lifecycle in a few seconds for where it landed; a dev build reloads its bundle first.";break;case"color_scheme":if(!t.scheme)return fail2("color_scheme requires `scheme`.");if(t.scheme==="system")return fail2("With real: true, pass light or dark; the device has no system value to go back to.");g=await hostColorScheme(u,t.scheme);break;case"open_url":if(!t.url)return fail2("open_url requires `url`.");g=await hostOpenUrl(u,t.url);break;default:return fail2(`${t.action} has no real (host-side) version. iOS has no command-line memory warning; leave \`real\` off to simulate it.`)}await sleep(1200);const m=` (${hostLabel(u)})`;const f=["return","color_scheme","open_url"].includes(t.action);const b=f&&w?await n.callAction(LIFECYCLE_TOOL_ID,"getState",{},l,{timeoutMs:5e3}).catch(()=>null):null;return text(`${g}${m}${b?`
|
|
705
|
+
|
|
706
|
+
${describe3(b)}`:""}`)}const i=n.requireProDevice(t.deviceId);const o=(a,c={})=>n.callAction(LIFECYCLE_TOOL_ID,a,c,i);let s;switch(t.action){case"background":s=await o("background",{duration:t.duration,skipWait:t.skipWait});break;case"interrupt":s=await o("interrupt",{duration:t.duration,skipWait:t.skipWait});break;case"return":s=await o("returnToApp");break;case"memory_warning":s=await o("memoryWarning");break;case"open_url":if(!t.url)return fail2("open_url requires `url`.");s=await o("openUrl",{url:t.url});break;case"press_back":s=await o("pressBack");break;case"color_scheme":if(!t.scheme)return fail2("color_scheme requires `scheme`.");s=await o("setColorScheme",{scheme:t.scheme,mode:t.mode??"js"});break;case"battery":s=await o("setPower",{...t.level!==void 0?{level:t.level}:{},...t.lowPowerMode!==void 0?{lowPowerMode:t.lowPowerMode}:{},...t.state?{state:t.state}:{}});break;case"reset_battery":s=await o("resetPower");break;case"relaunch":s=await o("relaunch");return text(`Relaunching: the app's JS restarts now. Read get_lifecycle in a few seconds for where it landed.
|
|
707
|
+
|
|
708
|
+
${describe3(s)}`);case"recipe":if(!t.id)return fail2("recipe requires `id`; get_lifecycle lists them.");s=await o("runRecipe",{id:t.id});break;case"clear_report":s=await o("clearReport");break;case"reset":s=await o("reset");break;case"settings":s=await o("updateSettings",{...t.showChip!==void 0?{showChip:t.showChip}:{},...t.reportWindow!==void 0?{reportWindow:t.reportWindow}:{}});break;default:return fail2(`Unknown action ${t.action}.`)}return text(describe3(s))}catch(r){return fail2(errMsg2(r))}})}var import_node_child_process14,import_node_util13,import_zod22,LIFECYCLE_TOOL_ID,execFileAsync13,sleep;var init_lifecycle=__esm({"src/tools/packs/lifecycle.ts"(){"use strict";import_node_child_process14=require("child_process");import_node_util13=require("util");import_zod22=require("zod");init_packKit();init_hostDevice();init_adb();init_hostKit();LIFECYCLE_TOOL_ID="lifecycle";execFileAsync13=(0,import_node_util13.promisify)(import_node_child_process14.execFile);sleep=e=>new Promise(n=>setTimeout(n,e))}});function meters(e){if(e==null||!Number.isFinite(e))return"?";return e<1e3?`${Math.round(e)} m`:`${(e/1e3).toFixed(e<1e4?1:0)} km`}function coord(e){return`${e.latitude.toFixed(5)}, ${e.longitude.toFixed(5)}`}function describe4(e){const n=e.override;const t=[];if(!e.active){t.push("**Location: real** (no override; the app gets the device's own location)")}else{const o=e.current.fix;const s=o?coord(o):`no fix (${e.current.reason})`;if(n.mode==="route"&&n.route&&e.progress){t.push(`**Location: route "${n.route.name??n.route.id??"custom"}"** ${n.playing?"moving":e.progress.finished?"arrived":"paused"} at ${(n.route.speed*3.6).toFixed(1)} km/h, ${meters(e.progress.along)} of ${meters(e.progress.length)}${n.route.loop?" (loops)":""} \u2192 ${s}`)}else if(n.mode==="fixed"){t.push(`**Location: pinned** ${n.place.label?`"${n.place.label}" `:""}\u2192 ${s}`)}else{t.push(`**Location: real position**, with overrides below`)}if(o){t.push(`Reported: \xB1${meters(o.accuracy)}${o.heading!=null?`, heading ${Math.round(o.heading)}\xB0`:""}${o.speed!=null?`, ${o.speed.toFixed(1)} m/s`:""}${n.jitter?`, drifting up to ${meters(n.jitter)}`:""}`)}if(!n.signal)t.push("GPS signal: OFF (updates stop, requests fail)");if(!n.services)t.push("Location services: OFF (the app is told they are disabled)")}if(e.permission){const o=e.permission;t.push(o.status==="granted"?`Permission: granted (${o.background?"always":"while in use"}, ${o.precision==="reduced"?"approximate":"precise"})`:`Permission: ${o.status.toUpperCase()} (the app's location requests fail)`)}if(e.current.precision==="reduced")t.push("Precise location is OFF in the permission: positions snap to ~3 km.");t.push(`Libraries overridden: ${e.libraries.length?e.libraries.join(", "):"none found in this app"}`);const r=e.watches.filter(o=>o.kind==="position");t.push(`Live watches: ${r.length?r.map(o=>`${o.library}#${o.id} (${o.updates} updates)`).join(", "):"none"}`);for(const o of e.tasks){if(o.kind==="geofencing"){t.push(`Geofencing task "${o.name}" (${o.intercepted?"simulated":"native"}, ${o.runs} runs):`);for(const s of o.regions){t.push(`- ${s.identifier}${s.label?` (${s.label})`:""}: ${s.state}, radius ${meters(s.radius)}${s.distance!=null?`, ${meters(s.distance)} from center`:""} (${coord(s)})`)}}else{t.push(`Background location task "${o.name}" (${o.intercepted?"simulated":"native"}, ${o.runs} runs)`)}}const i=e.log.slice(-10);if(i.length){t.push("Recent:");for(const o of i)t.push(`- [${o.kind}] ${o.text}${o.detail?` (${o.detail})`:""}`)}if(e.places.length)t.push(`App places: ${e.places.map(o=>o.label??coord(o)).join(", ")}`);if(e.routes.length)t.push(`App routes: ${e.routes.map(o=>o.id??o.name).join(", ")}`);t.push(`Presets: ${e.presets.map(o=>o.id).join(", ")}`);return t.join("\n")}async function bootedSimulators(){const{stdout:e}=await execFileAsync14("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const n=JSON.parse(e);return Object.values(n.devices).flat().filter(t=>t.state==="Booted").map(({udid:t,name:r})=>({udid:t,name:r}))}async function resolveSimulator(e){if(process.platform!=="darwin")throw new Error("sim_location needs macOS with Xcode's iOS Simulator.");const n=await bootedSimulators();if(e){if(!n.some(t=>t.udid===e))throw new Error(`Simulator ${e} is not booted.`);return e}if(n.length===1)return n[0].udid;if(n.length===0)throw new Error("No iOS Simulator is booted.");throw new Error(`${n.length} simulators are booted; pass \`udid\`: ${n.map(t=>`${t.name} (${t.udid})`).join(", ")}`)}function registerLocationTools(e,n){e.registerTool("get_location",{description:"Read where the app thinks it is, as the Location tool (@buoy-gg/location) sees it: real or overridden (pinned place, route with progress and speed), the position the app gets right now, GPS signal and location-services switches, which location libraries are overridden, the app's live location watches, its geofencing regions with inside/outside state and distance, background location tasks, and recent location events (requests, geofence enters and exits, errors). Check this before calling a distance, nearby list, geofence or location permission flow a bug.",inputSchema:{deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=await n.callAction(LOCATION_TOOL_ID,"getState",{},r);return text(describe4(i))}catch(r){return fail2(errMsg2(r))}});e.registerTool("location_action",{description:"Override where the app thinks it is. set_location pins it to `latitude`+`longitude`, a `query` ('lat, lon' or a Google/Apple Maps link) or a `place` name from get_location. start_route moves it along `points` ([{latitude, longitude}, ...]), a `route` (a preset: walk, run, drive, highway, tunnel, loop; or an app route id), or in a straight line `to` a place, at `speed` m/s; heading and speed follow the route. pause_route / resume_route / seek_route (`meters` or `fraction`) / set_speed control it, and stop_route ends it and stays where it got to. enter_region / exit_region move just inside or outside a monitored geofence `identifier`, which runs the app's geofencing task. conditions sets the signal quality in one step: `conditions` good (\xB15 m), weak (\xB165 m, drifting up to 50 m), no-signal or off. signal (on=false) stops updates and fails requests; services (on=false) reports location services disabled. tune sets `accuracy` and `jitter` (drift) in meters. use_real returns to the real position but keeps signal/services switches; reset ends every override. Works for expo-location (including background tasks and geofencing), @react-native-community/geolocation and react-native-geolocation-service. Permission comes from the device or the Permissions tool: a denied permission still fails. Native maps' own blue dot follows the device's real location; use sim_location for that. The override survives reload_app.",inputSchema:{action:import_zod23.z.enum(["set_location","start_route","pause_route","resume_route","stop_route","seek_route","set_speed","enter_region","exit_region","conditions","signal","services","tune","use_real","reset","settings","clear_log"]).describe("What to do."),latitude:import_zod23.z.number().optional().describe("set_location: latitude, -90 to 90."),longitude:import_zod23.z.number().optional().describe("set_location: longitude, -180 to 180."),label:import_zod23.z.string().optional().describe("set_location: a name to show for the place."),query:import_zod23.z.string().optional().describe("set_location: 'lat, lon' text or a Google/Apple Maps link."),place:import_zod23.z.string().optional().describe("set_location: a place name from get_location (app places and built-ins)."),points:import_zod23.z.array(import_zod23.z.object({latitude:import_zod23.z.number(),longitude:import_zod23.z.number()})).optional().describe("start_route: two or more points to travel through."),route:import_zod23.z.string().optional().describe("start_route: a preset id (walk, run, drive, highway, tunnel, loop) or an app route id."),to:import_zod23.z.string().optional().describe("start_route: travel in a straight line to this place name or 'lat, lon'."),speed:import_zod23.z.number().optional().describe("start_route / set_speed: meters per second (1.4 walk, 13.4 city, 30 highway)."),heading:import_zod23.z.number().optional().describe("start_route with a preset: direction to head, degrees from north. tune: heading reported while pinned."),loop:import_zod23.z.boolean().optional().describe("start_route with points: start over after the last point."),meters:import_zod23.z.number().optional().describe("seek_route: meters from the route's start."),fraction:import_zod23.z.number().optional().describe("seek_route: 0 to 1 along the route."),identifier:import_zod23.z.string().optional().describe("enter_region / exit_region (required): the region's identifier from get_location."),task:import_zod23.z.string().optional().describe("enter_region / exit_region: the geofencing task name, when two tasks share an identifier."),conditions:import_zod23.z.enum(["good","weak","no-signal","off"]).optional().describe("conditions (required): good, weak, no-signal or off."),on:import_zod23.z.boolean().optional().describe("signal / services (required): true = working, false = off."),accuracy:import_zod23.z.number().optional().describe("tune: reported accuracy radius in meters."),jitter:import_zod23.z.number().optional().describe("tune: GPS drift in meters (0 = none)."),interval:import_zod23.z.number().optional().describe("tune: ms between updates to live watches (default 1000)."),persist:import_zod23.z.boolean().optional().describe("settings: keep the override across reloads."),showChip:import_zod23.z.boolean().optional().describe("settings: show the floating location chip while overridden."),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=(a,c={})=>n.callAction(LOCATION_TOOL_ID,a,c,r);const o=(...a)=>{const c={};for(const l of a)if(t[l]!==void 0)c[l]=t[l];return c};let s;switch(t.action){case"set_location":s=await i("setLocation",o("latitude","longitude","label","query","place"));break;case"start_route":s=await i("startRoute",o("points","route","to","speed","heading","loop"));break;case"pause_route":s=await i("pauseRoute");break;case"resume_route":s=await i("resumeRoute");break;case"stop_route":s=await i("stopRoute");break;case"seek_route":s=await i("seekRoute",o("meters","fraction"));break;case"set_speed":if(t.speed===void 0)return fail2("set_speed requires `speed` in m/s.");s=await i("setSpeed",{speed:t.speed});break;case"enter_region":case"exit_region":if(!t.identifier)return fail2(`${t.action} requires \`identifier\`; get_location lists the regions.`);s=await i(t.action==="enter_region"?"enterRegion":"exitRegion",o("identifier","task"));break;case"conditions":if(!t.conditions)return fail2("conditions requires `conditions`: good, weak, no-signal or off.");s=await i("setConditions",{conditions:t.conditions});break;case"signal":if(t.on===void 0)return fail2("signal requires `on`.");s=await i("setSignal",{on:t.on});break;case"services":if(t.on===void 0)return fail2("services requires `on`.");s=await i("setServices",{on:t.on});break;case"tune":s=await i("tune",o("accuracy","jitter","heading","interval"));break;case"use_real":s=await i("useRealLocation");break;case"reset":s=await i("reset");break;case"settings":s=await i("updateSettings",o("persist","showChip"));break;case"clear_log":s=await i("clearLog");break}return text(describe4(s))}catch(r){return fail2(errMsg2(r))}});e.registerTool("sim_location",{description:"Set the iOS Simulator's own location with `xcrun simctl location` (runs on this Mac, not in the app). Unlike location_action, this reaches native code: map views' blue dot (react-native-maps, expo-maps, Mapbox), native geofence monitoring, other SDKs. set pins `latitude`+`longitude`; route moves through `points` at `speed` m/s (updates every `interval` s); clear stops it. Needs no Buoy in the app. The in-app Location tool, when on, still decides what the app's JS location calls return. Pass `udid` when more than one simulator is booted.",inputSchema:{action:import_zod23.z.enum(["set","route","clear"]).describe("What to do."),latitude:import_zod23.z.number().optional().describe("set: latitude."),longitude:import_zod23.z.number().optional().describe("set: longitude."),points:import_zod23.z.array(import_zod23.z.object({latitude:import_zod23.z.number(),longitude:import_zod23.z.number()})).optional().describe("route: two or more waypoints."),speed:import_zod23.z.number().optional().describe("route: meters per second. Default 20."),interval:import_zod23.z.number().optional().describe("route: seconds between updates. Default 1."),udid:import_zod23.z.string().optional().describe("The simulator's UDID. Required when several are booted.")}},async t=>{try{const r=await resolveSimulator(t.udid);const i=(...o)=>execFileAsync14("xcrun",["simctl","location",r,...o],{timeout:15e3});switch(t.action){case"set":if(t.latitude===void 0||t.longitude===void 0)return fail2("set requires `latitude` and `longitude`.");await i("set",`${t.latitude},${t.longitude}`);return text(`Simulator ${r} location set to ${t.latitude}, ${t.longitude}.`);case"route":{const o=t.points??[];if(o.length<2)return fail2("route requires two or more `points`.");const s=[`--speed=${t.speed??20}`,`--interval=${t.interval??1}`];await i("start",...s,...o.map(a=>`${a.latitude},${a.longitude}`));return text(`Simulator ${r} is moving through ${o.length} points at ${t.speed??20} m/s.`)}case"clear":await i("clear");return text(`Simulator ${r} location cleared.`)}}catch(r){return fail2(errMsg2(r))}})}var import_node_child_process15,import_node_util14,import_zod23,execFileAsync14,LOCATION_TOOL_ID;var init_location=__esm({"src/tools/packs/location.ts"(){"use strict";import_node_child_process15=require("child_process");import_node_util14=require("util");import_zod23=require("zod");init_packKit();execFileAsync14=(0,import_node_util14.promisify)(import_node_child_process15.execFile);LOCATION_TOOL_ID="location"}});function varSpec(e){const n=e.options?.length?` one of ${e.options.join("|")}`:"";const t=e.default!==void 0?` (default ${String(e.default)})`:"";return`${e.key}: ${e.type}${n}${t}`}function summarize(e){const n=e.vars?.length?`
|
|
709
|
+
variables: ${e.vars.map(varSpec).join("; ")}`:"";const t=e.stepLines?.length?`
|
|
710
|
+
${e.stepLines.map(o=>` \xB7 ${o.label} [${o.durability}]`).join("\n")}`:"";const r=[`v${e.version}`,e.author,e.usage?.runs?`${e.usage.runs} run(s)`:null,e.authoredAgainst?`authored against ${e.authoredAgainst}`:null,e.unsavedToRepo?"unsaved to repo":null].filter(Boolean).join(" \xB7 ");const i=e.expectedOutcome?`
|
|
711
|
+
expected: ${e.expectedOutcome}`:"";return`- \`${e.id}\` **${e.name}** \u2014 ${r}${n}${i}${t}`}function renderSection(e,n,t){if(!n.length)return`**${e} (0):**
|
|
712
|
+
_none_`;if(!t.length){return`**${e} (${n.length}):**
|
|
713
|
+
${n.map(summarize).join("\n")}`}const r=[`**${e} (${n.length}):**`];for(const o of t){const s=n.filter(a=>(a.folder??"").toLowerCase()===o.toLowerCase());if(!s.length)continue;r.push(`_${o} (${s.length})_
|
|
714
|
+
${s.map(summarize).join("\n")}`)}const i=n.filter(o=>!o.folder);if(i.length){r.push(`_Ungrouped (${i.length})_
|
|
715
|
+
${i.map(summarize).join("\n")}`)}return r.join("\n")}function formatActive(e){const n=Object.entries(e.varValues).map(([t,r])=>`${t}=${String(r)}`).join(", ");return[`**${e.name}** (\`${e.scenarioId}\` v${e.version}) \u2014 active since ${new Date(e.runAt).toISOString()}`,n?`variables: ${n}`:null,`effects:
|
|
716
|
+
${e.effects.map(t=>` \xB7 ${t.label} [${t.kind}]`).join("\n")}`].filter(Boolean).join("\n")}function registerScenariosTools(e,n){e.registerTool("get_scenarios",{description:"List saved scenarios, configured steps, available durability labels and the reported active scenario. Inspect these settings when app behavior may be simulated. A scenario covers its supported steps, not every source of app or backend state.",inputSchema:{deviceId:import_zod24.z.string().optional().describe("Target device id (auto-selected if one is connected).")}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:i,stale:o}=await n.getSnapshot(SCENARIOS_TOOL_ID,r);const s=i??{};const a=s.code??[];const c=s.device??[];const l=s.drafts??[];const u=s.folders??[];const d=[];d.push(s.active?`\u26A0\uFE0F **SIMULATED \u2014 a scenario is active.** The app is showing bent state right now.
|
|
717
|
+
${formatActive(s.active)}`:"**No scenario active** \u2014 the app is showing real data.");if(u.length){d.push(`**Folders:** ${u.join(" \xB7 ")} \u2014 the flows this team organizes by. Scenarios below are grouped under them; file new ones into an existing folder with \`scenario_action setFolder\` rather than inventing a name.`)}d.push(renderSection("Shipped with this app",a,u));d.push(renderSection("Saved on this device",c,u));if(l.length){d.push(`**Drafts awaiting review on the device (${l.length}):** these are INERT and cannot run until a human accepts them on the device.
|
|
718
|
+
${l.map(summarize).join("\n")}`)}return text5(staleHeader(o)+d.join("\n\n"))}catch(r){return fail7(errMsg7(r))}});e.registerTool("scenario_action",{description:"Preview, run, deactivate, save, organize or delete a scenario. Preview unfamiliar scenarios before running; inspect applied steps, failures and unrestored effects afterward. Storage changes need suitable undo steps. Saved scenarios are drafts requiring acceptance on the device before running. Reuse existing folders when appropriate. A completed scenario does not guarantee a deterministic app or backend state; overrides and cache edits have different coverage and lifetimes.",inputSchema:{action:import_zod24.z.enum(["preview","run","deactivate","save","setFolder","delete"]).describe("What to do."),folder:import_zod24.z.string().optional().describe("Folder name for action 'setFolder' \u2014 omit to un-file the scenario. Matching an existing folder case-insensitively files it there rather than creating a second one."),id:import_zod24.z.string().optional().describe("Scenario id (required for preview/run/delete; from get_scenarios)."),params:import_zod24.z.record(import_zod24.z.union([import_zod24.z.string(),import_zod24.z.number(),import_zod24.z.boolean()])).optional().describe("Variable values for preview/run, e.g. {storeId:'220'}. Declared defaults fill in the rest."),scenario:import_zod24.z.object({id:import_zod24.z.string().describe("Stable kebab-case id."),name:import_zod24.z.string().describe("Human name; may contain {{variable}} placeholders."),description:import_zod24.z.string().optional(),expectedOutcome:import_zod24.z.string().optional().describe("What SHOULD happen once applied \u2014 this is how a tester tells a bug from expected behavior without asking a developer. Write it."),author:import_zod24.z.string().optional(),authoredAgainst:import_zod24.z.string().optional().describe("App version this was written against."),folder:import_zod24.z.string().optional().describe('The flow this belongs to \u2014 "Checkout", "Login". Reuse a folder from get_scenarios; a scenario nobody can find is a scenario nobody runs.'),tags:import_zod24.z.array(import_zod24.z.string()).optional(),vars:import_zod24.z.array(import_zod24.z.object({key:import_zod24.z.string(),label:import_zod24.z.string().optional(),type:import_zod24.z.enum(["string","number","boolean","enum"]),options:import_zod24.z.array(import_zod24.z.union([import_zod24.z.string(),import_zod24.z.number(),import_zod24.z.boolean()])).optional(),default:import_zod24.z.union([import_zod24.z.string(),import_zod24.z.number(),import_zod24.z.boolean()]).optional()})).optional().describe("Declare a variable for every value a tester might want to change (a store id, a user, a status code) instead of freezing it into the steps."),steps:import_zod24.z.array(import_zod24.z.object({id:import_zod24.z.string().optional(),tool:import_zod24.z.string().describe("Tool id: network | storage | impersonate | route-events | query | time-machine"),action:import_zod24.z.string().describe("Action name on that tool, e.g. upsertOverrideRule, async.setItem, startImpersonation, navigate."),params:import_zod24.z.unknown().optional(),label:import_zod24.z.string().optional()})).describe("Steps, in order."),undoSteps:import_zod24.z.array(import_zod24.z.object({id:import_zod24.z.string().optional(),tool:import_zod24.z.string(),action:import_zod24.z.string(),params:import_zod24.z.unknown().optional(),label:import_zod24.z.string().optional()})).optional().describe("How to reverse effects that have no automatic inverse. Supply these whenever a step writes or removes storage, or deactivation will honestly report the key as unrestored.")}).optional().describe("The scenario to save (action 'save')."),deviceId:import_zod24.z.string().optional().describe("Target device id (auto-selected if one is connected).")}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=(o,s)=>n.callAction(SCENARIOS_TOOL_ID,o,s,r);switch(t.action){case"preview":{if(!t.id)return fail7("preview requires `id` (from get_scenarios).");const o=await i("preview",{id:t.id,params:t.params??{}});const s=[`**Dry run \u2014 \`${t.id}\`** (nothing has been changed)`,`variables: ${Object.entries(o.values).map(([a,c])=>`${a}=${String(c)}`).join(", ")||"none"}`,`**Would do:**
|
|
719
|
+
${o.willDo.map(a=>` \xB7 ${a.label} [${a.durability}]`).join("\n")}`];if(o.expectedOutcome)s.push(`**Expected outcome:** ${o.expectedOutcome}`);if(o.conflict){s.push(`\u26A0\uFE0F **Conflict:** "${o.conflict.activeName}" is active and touches the same target(s): ${o.conflict.overlaps.join(", ")}. Running will SWAP \u2014 it deactivates first.`)}if(o.warnings?.length)s.push(`**Warnings:**
|
|
720
|
+
${o.warnings.map(a=>` \xB7 ${a}`).join("\n")}`);s.push(o.ok?"Pre-flight checks passed. Review the intended effects before running.":`\u274C **Cannot run:**
|
|
721
|
+
${o.errors.map(a=>` \xB7 ${a}`).join("\n")}`);return text5(s.join("\n\n"))}case"run":{if(!t.id)return fail7("run requires `id` (from get_scenarios).");const o=await i("run",{id:t.id,params:t.params??{}});if(o.preflightErrors?.length){return fail7(`Pre-flight refused to run \`${t.id}\` \u2014 nothing was changed:
|
|
722
|
+
${o.preflightErrors.map(a=>` \xB7 ${a}`).join("\n")}`)}const s=(o.steps??[]).map(a=>{const c=a.skipped?"\u2013":a.ok?"\u2713":"\u2717";const l=a.error?`
|
|
723
|
+
${a.error}`:"";return` ${c} ${a.label} (${a.ms}ms)${l}`}).join("\n");if(!o.ok){return fail7(`Run FAILED \u2014 it stopped at the failing step and nothing after it ran. The steps before it DID apply:
|
|
724
|
+
${s}
|
|
725
|
+
|
|
726
|
+
The device is now in a partial state. Deactivate to reverse what landed, or fix the step and run again.`)}return text5([`\u2705 **Scenario active \u2014 ${o.name??t.id}**`,s,`**Reported effects:**
|
|
727
|
+
${(o.effects??[]).map(a=>` \xB7 ${a.label} [${a.kind}]`).join("\n")}`,"The device shows a SIMULATED banner while this is active. Deactivate when done, and account for these effects when interpreting observations."].join("\n\n"))}case"deactivate":{const o=await i("deactivate",{});const s=o.report;const a=[`Removed ${s.removedRules} override rule(s)`,s.stoppedImpersonation?"Ended impersonation":null,s.undoStepsRan?`Ran ${s.undoStepsRan} undo step(s)`:null].filter(Boolean);const c=s.unrestoredState??[];const l=(s.unrestoredStorageKeys.length?`
|
|
728
|
+
|
|
729
|
+
\u26A0\uFE0F **NOT restored:** ${s.unrestoredStorageKeys.join(", ")} \u2014 a storage write has no automatic inverse. The app still holds these values.`:"")+(c.length?`
|
|
730
|
+
|
|
731
|
+
\u26A0\uFE0F **Stores NOT restored:** ${c.join(", ")} \u2014 a state write has no automatic inverse. These stores still hold what the scenario wrote.`:"");const u=s.errors.length?`
|
|
732
|
+
|
|
733
|
+
Errors: ${s.errors.join("; ")}`:"";return text5(`**Deactivated.**
|
|
734
|
+
${a.map(d=>` \xB7 ${d}`).join("\n")}${l}${u}`)}case"save":{if(!t.scenario)return fail7("save requires `scenario`.");const o=await i("save",{scenario:t.scenario});if(!o.ok){return fail7(`Save rejected:
|
|
735
|
+
${(o.errors??[o.error??"unknown error"]).map(s=>` \xB7 ${s}`).join("\n")}`)}return text5(`Saved \`${o.id}\` **as a draft**.
|
|
736
|
+
|
|
737
|
+
It is INERT and cannot run yet. Ask the user to open Scenarios on the device, review what it will do, and tap **Accept to library** \u2014 a scenario never becomes runnable on someone's device without them seeing it first.`)}case"setFolder":{if(!t.id)return fail7("setFolder requires `id` (from get_scenarios).");const o=await i("setFolder",{id:t.id,folder:t.folder});return text5(o.folder?`Filed \`${o.id}\` under **${o.folder}**.`:`Removed \`${o.id}\` from its folder \u2014 it now shows under Ungrouped.`)}case"delete":{if(!t.id)return fail7("delete requires `id`.");await i("delete",{id:t.id});return text5(`Deleted \`${t.id}\` from the device library.`)}}}catch(r){return fail7(errMsg7(r))}})}var import_zod24,SCENARIOS_TOOL_ID,text5,fail7,errMsg7;var init_scenarios=__esm({"src/tools/packs/scenarios.ts"(){"use strict";import_zod24=require("zod");init_packKit();SCENARIOS_TOOL_ID="scenarios";text5=e=>({content:[{type:"text",text:e}]});fail7=e=>({isError:true,content:[{type:"text",text:e}]});errMsg7=e=>e instanceof Error?e.message:String(e)}});var camera_exports={};__export(camera_exports,{cliPath:()=>cliPath,describeDevices:()=>describeDevices,describeDiagnosis:()=>describeDiagnosis,describeInputs:()=>describeInputs,proRequired:()=>proRequired,readEntitlement:()=>readEntitlement,run:()=>run3});function candidates(){const e=process.env.BUOY_SIMCAM_DIR;const n=[...e?[import_node_path14.default.join(e,"buoycam")]:[],"/Applications/Buoy.app/Contents/Resources/simcam/buoycam",import_node_path14.default.join(import_node_os10.default.homedir(),"Applications/Buoy.app/Contents/Resources/simcam/buoycam")];let t=__dirname;for(let r=0;r<8;r++){n.push(import_node_path14.default.join(t,"apps/desktop/resources/simcam/buoycam"));const i=import_node_path14.default.dirname(t);if(i===t)break;t=i}return n}function cliPath(){if(resolved)return resolved;resolved=candidates().find(e=>(0,import_node_fs13.existsSync)(e))??null;return resolved}async function run3(e){const n=cliPath();if(!n){return{ok:false,error:"The simulator camera components were not found. They ship with the Buoy desktop app \u2014 install it, or set BUOY_SIMCAM_DIR to the directory holding `buoycam`."}}try{const{stdout:t}=await execFileAsync15(n,[...e,"--json"],{timeout:3e4});return{ok:true,data:JSON.parse(t)}}catch(t){const r=t.stdout??"";try{return{ok:false,data:JSON.parse(r)}}catch{return{ok:false,error:t.message||"the simulator camera CLI failed"}}}}function describeDiagnosis(e){const n=e.filter(o=>o.level==="fail");const t=e.filter(o=>o.level==="warn");if(n.length===0&&t.length===0){return"The simulator camera is healthy \u2014 every check passed."}const r=[];for(const o of[...n,...t]){r.push(`- **${o.name}** (${o.level}): ${o.detail}`);if(o.fix)r.push(` ${o.fix}`)}const i=n.length>0?`${n.length} problem${n.length===1?"":"s"} found.`:`No hard failures, but ${t.length} thing${t.length===1?"":"s"} worth knowing.`;return[i,"",...r].join("\n")}function describeDevices(e,n){if(e.length===0){return"No booted simulators.\n\n_Boot one first \u2014 `xcrun simctl boot <udid>`, or open Simulator.app. The camera attaches to a simulator, so nothing else here works until one is running._"}const t=[e.length===1?"1 booted simulator:":`${e.length} booted simulators:`,...e.map(r=>`- **${r.name}** (${r.runtime}) \u2014 \`${r.udid}\``)];if(e.length>1&&n===null){t.push("","_More than one is booted, so pass `udid` to list a specific one's apps \u2014 and to every other camera tool that takes one._");return t.join("\n")}if(n===null){t.push("","_Could not read the installed apps._");return t.join("\n")}if(n.length===0){t.push("","No apps installed on it.");return t.join("\n")}t.push("",`${n.length} installed app${n.length===1?"":"s"}:`,...n.map(r=>`- ${r.name} \u2014 \`${r.bundleId}\``),"","_Pass one of these bundle ids to `camera_launch` to relaunch it with the camera attached._");return t.join("\n")}function describeInputs(e,n){const t=[];t.push(e.length?'**Mac cameras** (for `kind: "camera"`):':"**Mac cameras**: none found.");if(e.length){t.push(...e.map(r=>`- ${r.name} \u2014 \`${r.uniqueId}\``))}else{t.push("_If this Mac has a webcam, Buoy has not been granted Camera permission (System Settings \u2192 Privacy & Security \u2192 Camera)._")}t.push("");t.push(n.length?'**Capturable windows** (for `kind: "screen"`, `value: "window:<id>"`):':"**Capturable windows**: none found.");if(n.length){t.push(...n.map(r=>`- ${r.app}${r.title?` \u2014 ${r.title}`:""} \u2014 \`window:${r.id}\``))}else{t.push("_Screen Recording permission is almost certainly missing (System Settings \u2192 Privacy & Security \u2192 Screen & System Audio Recording)._")}return t.join("\n")}function entitlementPaths(){const e=process.env.BUOY_ENTITLEMENT_FILE;if(e)return[e];return[import_node_path14.default.join(import_node_os10.default.homedir(),"Library/Application Support/Buoy/entitlement.json"),import_node_path14.default.join(import_node_os10.default.homedir(),"Library/Application Support/buoy-desktop/entitlement.json")]}function readEntitlement(){for(const e of entitlementPaths()){try{if(!(0,import_node_fs13.existsSync)(e))continue;const n=JSON.parse((0,import_node_fs13.readFileSync)(e,"utf8"));return{tier:n.tier==="pro"||n.tier==="free"?n.tier:"locked",isPro:n.isPro===true&&n.hasDesktopAccess===true&&typeof n.validUntil==="number"&&Number.isFinite(n.validUntil)&&Date.now()<n.validUntil&&typeof n.proValidUntil==="number"&&Number.isFinite(n.proValidUntil)&&Date.now()<n.proValidUntil}}catch{}}return{tier:"locked",isPro:false}}function proRequired(e){return`\`${e}\` is a Buoy Pro feature.
|
|
738
|
+
|
|
739
|
+
The simulator camera itself is free \u2014 the Mac camera, image, video, test-pattern and QR sources all work in the Buoy desktop panel with a Free account. Pro adds the screen region, the non-QR symbologies (PDF417, Aztec, DataMatrix, Code 128), and driving any of it from an agent.
|
|
740
|
+
|
|
741
|
+
_Tell the user to enter a licence in Buoy Desktop, or see https://buoy.gg/pricing. Don't try to work around it \u2014 use the desktop panel by hand instead._`}var import_node_child_process16,import_node_util15,import_node_fs13,import_node_os10,import_node_path14,execFileAsync15,resolved;var init_camera=__esm({"src/capture/camera.ts"(){"use strict";import_node_child_process16=require("child_process");import_node_util15=require("util");import_node_fs13=require("fs");import_node_os10=__toESM(require("os"));import_node_path14=__toESM(require("path"));execFileAsync15=(0,import_node_util15.promisify)(import_node_child_process16.execFile);resolved=null}});function registerCameraTools(e){e.registerTool("camera_source",{description:"Give the iOS Simulator a camera, and choose what it shows. Use this before testing anything that opens a camera \u2014 a QR or barcode scanner, document capture, an avatar picker. `barcode` generates the code from text, so testing a scanner needs no printed code and no second device; pdf417 is the barcode on a driver's licence. `screen` points the phone's camera at this Mac's screen. Needs no Buoy integration in the app under test.",inputSchema:{kind:import_zod25.z.enum(["barcode","image","video","camera","screen","pattern"]).describe("What the camera should show."),value:import_zod25.z.string().optional().describe("Text for `barcode`, a file path for `image`/`video`, a camera uniqueId for `camera` (see `camera_inputs`), or one of `behind` / `display` / `window:<id>` / `region:<id>[:<gutter>]` for `screen`."),format:import_zod25.z.enum(["qr","pdf417","aztec","code128"]).optional().describe("Barcode symbology; defaults to qr.")}},async n=>{const t=gate("camera_source");if(t)return t;const r=["source",n.kind];if(n.value)r.push(n.value);if(n.format)r.push("--format",n.format);const i=await run3(r);if(!i.ok){return fail8(i.error??i.data?.error??"could not set the camera source")}const o=n.kind==="barcode"?`a ${n.format??"qr"} code reading "${n.value}"`:n.kind==="screen"?`this Mac's screen (${n.value??"behind the simulator window"})`:n.value??n.kind;return text6(`The simulator camera is now showing ${o}, at ${i.data?.fps??0} fps.
|
|
742
|
+
|
|
743
|
+
_Apps already running do not pick up a camera they started without \u2014 use \`camera_launch\` to relaunch one, or \`camera_zero_setup\` so that anything the simulator launches gets it._`)});e.registerTool("camera_status",{description:"Check what the simulator camera is doing and what it is currently decoding. Use this to confirm a scanner test is actually seeing a code before concluding the app is broken.",inputSchema:{}},async()=>{const n=gate("camera_status");if(n)return n;const t=await run3(["status"]);if(!t.ok||!t.data){return fail8(t.error??"could not read the simulator camera status")}const{publishing:r,fps:i,codes:o}=t.data;if(!r){return text6("The simulator camera is not publishing anything.\n\n_Set a source with `camera_source` first._")}return text6([`Publishing at ${i} fps.`,o.length?`Currently decoding: ${o.map(s=>`\`${s}\``).join(", ")}`:"No barcode in the current frame.","","_A code shown here is what the app receives. If the app is not reacting to it, the problem is in the app, not the camera \u2014 `camera_diagnose` will say whether the app is even reading the feed._"].join("\n"))});e.registerTool("camera_launch",{description:"Relaunch a simulator app with the camera attached. A camera can only be attached when a process starts, so an app that is already running cannot be given one \u2014 this terminates and relaunches it.",inputSchema:{bundleId:import_zod25.z.string().describe("The app's bundle identifier."),udid:import_zod25.z.string().optional().describe("Simulator udid, if more than one is booted.")}},async n=>{const t=gate("camera_launch");if(t)return t;const r=["launch",n.bundleId];if(n.udid)r.push("--udid",n.udid);const i=await run3(r);if(!i.ok){return fail8(i.error??i.data?.error??"could not launch the app")}return text6(`Relaunched \`${n.bundleId}\` with the camera attached${i.data?.pid?` (pid ${i.data.pid})`:""}.`)});e.registerTool("camera_diagnose",{description:"Work out why the simulator camera is not working. Checks that the pieces are present, a simulator is booted, something is publishing, SOMETHING IS READING IT, the library is loaded in the target app, no other tool owns the injection, and no camera library in the project disables simulator cameras at compile time.",inputSchema:{bundleId:import_zod25.z.string().optional().describe("Check a specific app \u2014 whether the library is actually loaded in it.")}},async n=>{const t=["diagnose"];if(n.bundleId)t.push(n.bundleId);const r=await run3(t);if(!r.data?.checks){return fail8(r.error??"could not run the simulator camera diagnosis")}const i=readEntitlement();const o=i.isPro?"":"\n\n_This install is on the **free** tier, so the other `camera_*` tools are blocked. The camera still works by hand in the Buoy desktop panel._";return text6(describeDiagnosis(r.data.checks)+o)});e.registerTool("camera_stop",{description:"Turn the simulator camera off and stop publishing frames. The camera stays on until stopped \u2014 across app relaunches and after a test finishes \u2014 so call this when done, or the next thing that opens a camera will still see the last source.",inputSchema:{}},async()=>{const n=gate("camera_stop");if(n)return n;const t=await run3(["stop"]);if(!t.ok){return fail8(t.error??t.data?.error??"could not stop the camera")}return text6("The simulator camera is off.")});e.registerTool("camera_devices",{description:"List booted simulators and the apps installed on one. Use this to find the bundle id `camera_launch` needs, or the udid to pass when more than one simulator is booted. Lists every app on the simulator, not just Buoy-integrated ones \u2014 the camera works on any of them.",inputSchema:{udid:import_zod25.z.string().optional().describe("Which simulator's apps to list. Only needed when several are booted.")}},async n=>{const t=gate("camera_devices");if(t)return t;const r=await run3(["devices"]);if(!r.ok||!r.data){return fail8(r.error??"could not list booted simulators")}const i=r.data.devices??[];let o=null;if(i.length===1||n.udid){const s=await run3(["apps",...n.udid?["--udid",n.udid]:[]]);o=s.ok?s.data?.apps??[]:null}return text6(describeDevices(i,o))});e.registerTool("camera_inputs",{description:"List what this Mac can point the simulator camera at: its webcams (the uniqueId for `camera_source` with kind `camera`) and the windows the screen source can film (the id for `window:<id>`). Call this before choosing a `camera` or windowed `screen` source \u2014 those ids cannot be guessed.",inputSchema:{}},async()=>{const n=gate("camera_inputs");if(n)return n;const[t,r]=await Promise.all([run3(["cameras"]),run3(["windows"])]);if(!t.ok&&!r.ok){return fail8(t.error??r.error??"could not list the Mac's cameras or windows")}return text6(describeInputs(t.data?.cameras??[],r.data?.windows??[]))});e.registerTool("camera_zero_setup",{description:"Make every app the simulator launches get a camera, however it was launched \u2014 `expo start`, `react-native run-ios`, Xcode, a test runner. Use this when you are not the one starting the app, so `camera_launch` is not an option. It loads Buoy's library into every process in that simulator, SpringBoard included, so turn it off when finished.",inputSchema:{action:import_zod25.z.enum(["on","off","status"]).describe("Turn it on, off, or report the current state."),udid:import_zod25.z.string().optional().describe("Which simulator. Only needed when several are booted.")}},async n=>{const t=gate("camera_zero_setup");if(t)return t;const r=await run3(["zero-setup",n.action,...n.udid?["--udid",n.udid]:[]]);if(!r.ok){return fail8(r.error??r.data?.error??"could not change zero-setup mode")}const i=r.data??{};if(n.action==="status"){if(!i.enabled)return text6("Zero-setup mode is **off**.");return text6(i.foreign?`Zero-setup is on, but **another tool owns it** (\`${i.path}\`). Quit that tool before turning Buoy's on.`:"Zero-setup mode is **on** \u2014 anything this simulator launches gets the camera.")}if(n.action==="on"){return text6("Zero-setup mode is **on**. Anything this simulator launches from now on gets the camera \u2014 start your app however you normally would.\n\n_This loads the library into every process in the simulator. Turn it off with `camera_zero_setup` action `off` when you are done._")}return text6("Zero-setup mode is **off**.")})}var import_zod25,text6,gate,fail8;var init_camera2=__esm({"src/tools/packs/camera.ts"(){"use strict";import_zod25=require("zod");init_camera();text6=e=>({content:[{type:"text",text:e}]});gate=e=>readEntitlement().isPro?null:fail8(proRequired(e));fail8=e=>({isError:true,content:[{type:"text",text:e}]})}});var START_PROBE_JS,END_PROBE_JS,COLLECT_PROBE_JS,MEASURE_REFRESH_JS;var init_inPageProbe=__esm({"src/webBench/inPageProbe.ts"(){"use strict";START_PROBE_JS=`(() => {
|
|
744
|
+
const supported = (t) => {
|
|
745
|
+
try { return (PerformanceObserver.supportedEntryTypes || []).includes(t); } catch { return false; }
|
|
746
|
+
};
|
|
747
|
+
const frames = [], longTasks = [], loaf = [], shifts = [], events = [], observers = [];
|
|
748
|
+
const watch = (type, cb, extra) => {
|
|
749
|
+
if (!supported(type)) return false;
|
|
750
|
+
const o = new PerformanceObserver((l) => l.getEntries().forEach(cb));
|
|
751
|
+
o.observe(Object.assign({ type, buffered: false }, extra || {}));
|
|
752
|
+
observers.push([o, cb]);
|
|
753
|
+
return true;
|
|
754
|
+
};
|
|
755
|
+
const hasLong = watch("longtask", (e) => longTasks.push({ start: e.startTime, end: e.startTime + e.duration }));
|
|
756
|
+
const hasLoaf = watch("long-animation-frame", (e) => loaf.push({
|
|
757
|
+
startTime: e.startTime,
|
|
758
|
+
duration: e.duration,
|
|
759
|
+
blockingDuration: e.blockingDuration || 0,
|
|
760
|
+
styleAndLayoutStart: e.styleAndLayoutStart || 0,
|
|
761
|
+
scripts: (e.scripts || []).map((s) => {
|
|
762
|
+
const file = s.sourceURL ? s.sourceURL.split("?")[0].split("/").pop() : "";
|
|
763
|
+
const where = s.sourceFunctionName ? s.sourceFunctionName + (file ? " @ " + file : "") : file;
|
|
764
|
+
// Invokers like "FrameRequestCallback" say how a script ran, not which
|
|
765
|
+
// one; add the function and file when the browser gives them.
|
|
766
|
+
const name = s.invoker ? (where ? s.invoker + " \u2192 " + where : s.invoker) : where || "(anonymous)";
|
|
767
|
+
return { duration: s.duration, name, forced: s.forcedStyleAndLayoutDuration || 0 };
|
|
768
|
+
}),
|
|
769
|
+
}));
|
|
770
|
+
// 16 ms is Event Timing's smallest threshold; the default (104) hides most taps.
|
|
771
|
+
const hasEvents = watch("event", (e) => {
|
|
772
|
+
if (e.interactionId) events.push({
|
|
773
|
+
name: e.name, startTime: e.startTime, duration: e.duration,
|
|
774
|
+
processingStart: e.processingStart, processingEnd: e.processingEnd, interactionId: e.interactionId,
|
|
775
|
+
});
|
|
776
|
+
}, { durationThreshold: 16 });
|
|
777
|
+
// Click proof: which step selectors each real click landed inside, read
|
|
778
|
+
// at the moment of the click (capture phase, before the page's handlers).
|
|
779
|
+
const clickTargets = Array.isArray(window.__buoyBenchClickTargets) ? window.__buoyBenchClickTargets : [];
|
|
780
|
+
const clicks = [], keys = [];
|
|
781
|
+
// Only real (trusted) input counts as proof; a click the page fakes in
|
|
782
|
+
// script doesn't. Input after the run's end doesn't count either.
|
|
783
|
+
const onClick = (e) => {
|
|
784
|
+
if (!e.isTrusted || ended) return;
|
|
785
|
+
const t = e.target;
|
|
786
|
+
const hit = clickTargets.filter((sel) => { try { return t && t.closest && t.closest(sel); } catch { return false; } });
|
|
787
|
+
clicks.push({ t: performance.now(), hit });
|
|
788
|
+
};
|
|
789
|
+
const onKey = (e) => {
|
|
790
|
+
if (!e.isTrusted || ended) return;
|
|
791
|
+
keys.push({ t: performance.now(), key: e.key, ctrl: e.ctrlKey, shift: e.shiftKey, alt: e.altKey, meta: e.metaKey });
|
|
792
|
+
};
|
|
793
|
+
// Expect steps, judged inside end() so no page work can slip in between
|
|
794
|
+
// the end of the run and the check.
|
|
795
|
+
const expects = Array.isArray(window.__buoyBenchExpects) ? window.__buoyBenchExpects : [];
|
|
796
|
+
let expectResults = null;
|
|
797
|
+
document.addEventListener("click", onClick, true);
|
|
798
|
+
document.addEventListener("keydown", onKey, true);
|
|
799
|
+
const hasShift = watch("layout-shift", (e) => shifts.push({ startTime: e.startTime, value: e.value, hadRecentInput: e.hadRecentInput }));
|
|
800
|
+
let hidden = document.visibilityState === "hidden";
|
|
801
|
+
const onVis = () => { if (document.visibilityState === "hidden") hidden = true; };
|
|
802
|
+
document.addEventListener("visibilitychange", onVis);
|
|
803
|
+
// Latched: a resize or zoom that's undone before stop still changed the work.
|
|
804
|
+
let resized = false;
|
|
805
|
+
const onResize = () => { resized = true; };
|
|
806
|
+
window.addEventListener("resize", onResize);
|
|
807
|
+
// A pixel-ratio change (moving to another screen) may not fire resize.
|
|
808
|
+
let dprQuery = null;
|
|
809
|
+
try {
|
|
810
|
+
dprQuery = matchMedia("(resolution: " + window.devicePixelRatio + "dppx)");
|
|
811
|
+
dprQuery.addEventListener("change", onResize);
|
|
812
|
+
} catch {}
|
|
813
|
+
let raf = 0;
|
|
814
|
+
const tick = (t) => { frames.push(t); raf = requestAnimationFrame(tick); };
|
|
815
|
+
raf = requestAnimationFrame(tick);
|
|
816
|
+
const start = performance.now();
|
|
817
|
+
// Trace markers: the driver counts Chrome's frames between these two.
|
|
818
|
+
try { performance.mark("__buoy_bench_start"); } catch {}
|
|
819
|
+
const domStart = document.getElementsByTagName("*").length;
|
|
820
|
+
let ended = 0;
|
|
821
|
+
window.__buoyBench = {
|
|
822
|
+
// Two steps so the driver can read Chrome's counters between them:
|
|
823
|
+
// end() freezes the end time at once; collect() then waits up to two
|
|
824
|
+
// frames (capped at 300 ms) so an input's entry, which only arrives after
|
|
825
|
+
// its paint, isn't lost. Entries after the end are filtered out later.
|
|
826
|
+
end: () => {
|
|
827
|
+
if (ended) return ended;
|
|
828
|
+
ended = performance.now();
|
|
829
|
+
try { performance.mark("__buoy_bench_end"); } catch {}
|
|
830
|
+
cancelAnimationFrame(raf);
|
|
831
|
+
expectResults = expects.map((x) => {
|
|
832
|
+
const n = document.querySelector(x.selector);
|
|
833
|
+
const full = n ? (n.textContent || "") : null;
|
|
834
|
+
// Match against the full text here; only a short snippet goes back.
|
|
835
|
+
return { selector: x.selector, text: x.text == null ? null : x.text, found: !!n, matched: full != null && (x.text == null || full.includes(x.text)), content: full == null ? null : full.slice(0, 200) };
|
|
836
|
+
});
|
|
837
|
+
return ended;
|
|
838
|
+
},
|
|
839
|
+
collect: () => new Promise((resolve) => {
|
|
840
|
+
const end = window.__buoyBench.end();
|
|
841
|
+
let done = false;
|
|
842
|
+
const finish = () => {
|
|
843
|
+
if (done) return;
|
|
844
|
+
done = true;
|
|
845
|
+
document.removeEventListener("visibilitychange", onVis);
|
|
846
|
+
window.removeEventListener("resize", onResize);
|
|
847
|
+
document.removeEventListener("click", onClick, true);
|
|
848
|
+
document.removeEventListener("keydown", onKey, true);
|
|
849
|
+
try { dprQuery && dprQuery.removeEventListener("change", onResize); } catch {}
|
|
850
|
+
for (const [o, cb] of observers) { o.takeRecords().forEach(cb); o.disconnect(); }
|
|
851
|
+
resolve({
|
|
852
|
+
start, end, frames,
|
|
853
|
+
longTasks: hasLong ? longTasks : null,
|
|
854
|
+
loaf: hasLoaf ? loaf : null,
|
|
855
|
+
shifts: hasShift ? shifts : null,
|
|
856
|
+
events: hasEvents ? events : null,
|
|
857
|
+
clicks,
|
|
858
|
+
keys,
|
|
859
|
+
expectResults,
|
|
860
|
+
domStart,
|
|
861
|
+
domEnd: document.getElementsByTagName("*").length,
|
|
862
|
+
hidden,
|
|
863
|
+
resized,
|
|
864
|
+
});
|
|
865
|
+
};
|
|
866
|
+
requestAnimationFrame(() => requestAnimationFrame(finish));
|
|
867
|
+
setTimeout(finish, 300);
|
|
868
|
+
}),
|
|
869
|
+
};
|
|
870
|
+
return true;
|
|
871
|
+
})()`;END_PROBE_JS=`(() => (window.__buoyBench ? window.__buoyBench.end() : null))()`;COLLECT_PROBE_JS=`(() => (window.__buoyBench ? window.__buoyBench.collect() : null))()`;MEASURE_REFRESH_JS=`new Promise((resolve) => {
|
|
872
|
+
let n = 0, t0 = 0;
|
|
873
|
+
const tick = (t) => {
|
|
874
|
+
if (!t0) t0 = t;
|
|
875
|
+
n++;
|
|
876
|
+
if (t - t0 >= 1000) resolve(((n - 1) / (t - t0)) * 1000);
|
|
877
|
+
else requestAnimationFrame(tick);
|
|
878
|
+
};
|
|
879
|
+
requestAnimationFrame(tick);
|
|
880
|
+
})`}});var webBench_exports={};__export(webBench_exports,{GPU_RENDERER_JS:()=>GPU_RENDERER_JS,PLAYWRIGHT_MISSING:()=>PLAYWRIGHT_MISSING,aggregateCase:()=>aggregateCase,caseUrl:()=>caseUrl,cdpDeltas:()=>cdpDeltas,checkBudgets:()=>checkBudgets,closeCall:()=>closeCall,closeWithin:()=>closeWithin,expectFailureFrom:()=>expectFailureFrom,formatWebBenchMarkdown:()=>formatWebBenchMarkdown,isSoftwareGpu:()=>isSoftwareGpu,keyMatches:()=>keyMatches,loadChromium:()=>loadChromium,locateStepTargets:()=>locateStepTargets,mergeInteractions:()=>mergeInteractions,missedInput:()=>missedInput,oneLine:()=>oneLine,percentile:()=>percentile,runWebBench:()=>runWebBench,shuffled:()=>shuffled,snapRefreshRate:()=>snapRefreshRate,summarizeFrameTrace:()=>summarizeFrameTrace,summarizeProbe:()=>summarizeProbe,takeHostLock:()=>takeHostLock,tiedPairs:()=>tiedPairs,validateWebBenchOptions:()=>validateWebBenchOptions,waitForHostLock:()=>waitForHostLock,webBenchFlags:()=>webBenchFlags,withDeadline:()=>withDeadline});function checkBudgets(e,n,t=[]){const r=e.median;const i=[];const o=[];const s=(d,h,w)=>{if(h==null)return;if(w==null)o.push(d);else if(w>h)i.push(`${d} ${w} > ${h}`)};s("droppedPct",n.droppedPct,e.droppedMin!=null?r?.droppedPct:null);const a=e.runs.filter(d=>!d.failed&&d.fps!=null);const c=t.some(d=>"click"in d||"press"in d||"type"in d);const l=a.map(d=>d.interactions==null||!d.inputCaptureComplete?null:d.worstInteractionMs??16);s("inputMs",n.inputMs,c&&l.length&&l.every(d=>d!=null)?Math.max(...l):null);const u=a.map(d=>Math.max(d.frameGapMaxMs??0,d.edgeSilenceMs??0));s("freezeMs",n.freezeMs,u.length?Math.max(...u):null);s("mainThreadPct",n.mainThreadPct,r?.mainThreadPct);s("jsHeapMb",n.jsHeapMb,r?.heapMb);return{meets:Boolean(r)&&i.length===0&&o.length===0,over:i,unknown:o}}function isSoftwareGpu(e){return/swiftshader|llvmpipe|softpipe|software|microsoft basic render/i.test(e)}function percentile(e,n){if(e.length===0)return null;const t=[...e].sort((i,o)=>i-o);const r=Math.ceil(n/100*t.length)-1;return t[Math.min(t.length-1,Math.max(0,r))]}function snapRefreshRate(e){for(const n of COMMON_RATES)if(Math.abs(e-n)/n<=.08)return n;return Math.max(1,Math.round(e))}function shuffled(e,n){let t=n>>>0;const r=()=>{t=t+1831565813>>>0;let o=t;o=Math.imul(o^o>>>15,o|1);o^=o+Math.imul(o^o>>>7,o|61);return((o^o>>>14)>>>0)/4294967296};const i=[...e];for(let o=i.length-1;o>0;o--){const s=Math.floor(r()*(o+1));[i[o],i[s]]=[i[s],i[o]]}return i}function caseUrl(e,n,t){const r=new URL(e);const i=n.path??t;if(i)r.pathname=i.startsWith("/")?i:`${r.pathname.replace(/\/$/,"")}/${i}`;for(const[o,s]of Object.entries(n.params??{}))r.searchParams.set(o,s);return r.toString()}function summarizeFrameTrace(e){const n=w=>e.find(p=>p.name===w&&p.ts!=null);const t=n("__buoy_bench_start");const r=n("__buoy_bench_end");if(!t||!r||r.ts<=t.ts)return null;if(t.pid!==r.pid)return null;const i=t.pid;const o={STATE_PRESENTED_ALL:0,STATE_PRESENTED_PARTIAL:1,STATE_DROPPED:2};const s=new Map;for(const w of e){if(w.name!=="PipelineReporter"||w.ph!=="b")continue;if(i!=null&&w.pid!==i)continue;if(w.ts==null||w.ts<t.ts||w.ts>r.ts)continue;const p=w.args?.frame_reporter;if(!p||p.frame_sequence==null)continue;const g=p.state;if(!FRAME_STATES.includes(g))continue;const m=`${p.layer_tree_host_id??""}:${p.frame_source??""}:${p.frame_sequence}`;const f=Boolean(p.affects_smoothness)&&g!=="STATE_PRESENTED_ALL";const b=s.get(m);if(!b)s.set(m,{state:g,fault:f});else{if(o[g]>o[b.state])b.state=g;b.fault=b.fault||f}}let a=0;let c=0;let l=0;let u=0;for(const w of s.values()){if(w.state==="STATE_PRESENTED_ALL")a++;else if(w.state==="STATE_PRESENTED_PARTIAL")c++;else l++;if(w.fault)u++}const d=a+c+l;if(d===0)return null;const h=(r.ts-t.ts)/1e6;return{full:a,partial:c,dropped:l,faults:u,shownFps:r1((a+c)/h),droppedPct:r1(u/d*100)}}function keyMatches(e,n){const t=e.split("+");const r=t[t.length-1];const i=new Set(t.slice(0,-1).map(a=>a.toLowerCase()));if(n.key!==r)return false;const o=r.toLowerCase();const s={ctrl:i.has("control")||o==="control",alt:i.has("alt")||o==="alt",meta:i.has("meta")||i.has("command")||o==="meta",shift:i.has("shift")||o==="shift"};if(Boolean(n.ctrl)!==s.ctrl||Boolean(n.alt)!==s.alt||Boolean(n.meta)!==s.meta)return false;if(!s.shift&&n.shift&&r.length!==1)return false;if(s.shift&&!n.shift)return false;return true}function mergeInteractions(e){const n=[];for(const t of e){const r=t.startTime+t.duration;const i=n.find(s=>s.interactionId===t.interactionId&&Math.abs(s.startTime+s.duration-r)<=8);if(!i){n.push({...t});continue}const o=i.startTime+i.duration;i.startTime=Math.min(i.startTime,t.startTime);i.processingStart=Math.min(i.processingStart,t.processingStart);i.processingEnd=Math.max(i.processingEnd,t.processingEnd);i.duration=Math.max(o,r)-i.startTime;if(t.processingEnd-t.processingStart>0)i.name=t.name}return n}function summarizeProbe(e,n){const{start:t,end:r}=e;const i=Math.max(1,r-t);const o=[];for(let _=1;_<e.frames.length;_++)o.push(e.frames[_]-e.frames[_-1]);const s=1e3/n;const a=percentile(o,95);let c=null;if(e.longTasks){let _=0;for(const x of e.longTasks){const I=Math.min(x.end,r)-Math.max(x.start,t);if(I>0)_+=I}c=r1(Math.min(100,_/i*100))}let l=null;let u=null;let d=null;let h=[];let w=0;if(e.loaf){let _=0;let x=0;let I=0;const D=new Map;for(const E of e.loaf){if(E.startTime>=t&&E.startTime<=r&&E.startTime+E.duration>r)w++;if(E.startTime<t||E.startTime+E.duration>r)continue;_+=E.blockingDuration;if(E.styleAndLayoutStart>E.startTime)x+=Math.max(0,E.startTime+E.duration-E.styleAndLayoutStart);for(const S of E.scripts){I+=S.forced;const k=D.get(S.name)??{ms:0,count:0};k.ms+=S.duration;k.count++;D.set(S.name,k)}}l=r1(_);u=r1(x);d=r1(I);h=[...D.entries()].map(([E,S])=>({name:E,ms:r1(S.ms),count:S.count})).sort((E,S)=>S.ms-E.ms).slice(0,5)}let p=null;if(e.shifts){let _=0;for(const x of e.shifts)if(!x.hadRecentInput&&x.startTime>=t&&x.startTime<=r)_+=x.value;p=Math.round(_*1e3)/1e3}let g=null;let m=null;if(e.events){const _=mergeInteractions(e.events.filter(x=>x.startTime>=t&&x.startTime<=r));g=new Set(_.map(x=>x.interactionId)).size;for(const x of _)if(!m||x.duration>m.duration)m=x}const f=m;const b=e.frames;const v=[...(e.clicks??[]).map(_=>_.t),...(e.keys??[]).map(_=>_.t)];const y=v.length?Math.max(...v):null;const $=y==null||b.filter(_=>_>y).length>=2;const T=b.length===0?i:Math.max(0,b[0]-t,r-b[b.length-1]);return{edgeSilenceMs:r1(T),frameGapCount:o.length,inputCaptureComplete:$,resized:Boolean(e.resized),interactions:g,worstInteractionMs:f?r1(f.duration):null,worstInputDelayMs:f?r1(Math.max(0,f.processingStart-f.startTime)):null,worstProcessingMs:f?r1(Math.max(0,f.processingEnd-f.processingStart)):null,worstPresentationMs:f?r1(Math.max(0,f.startTime+f.duration-f.processingEnd)):null,fps:r1(e.frames.length/i*1e3),frameGapP95Ms:a==null?null:r1(a),frameGapMaxMs:o.length?r1(Math.max(...o)):null,longFrames:o.filter(_=>_>s*1.5).length,longTaskPct:c,loafBlockingMs:l,styleLayoutMs:u,forcedLayoutMs:d,topScripts:h,loafCutOff:w,layoutShift:p,domNodesStart:e.domStart,domNodesEnd:e.domEnd}}function cdpDeltas(e,n,t){const r=a=>a in e&&a in n?n[a]-e[a]:null;const i=a=>{const c=r(a);return c==null?null:r1(c*1e3)};const o=i("TaskDuration");const s=i("Timestamp")??t;return{mainThreadPct:o==null?null:r1(o/Math.max(1,s)*100),scriptMs:i("ScriptDuration"),styleMs:i("RecalcStyleDuration"),layoutMs:i("LayoutDuration"),layoutCount:r("LayoutCount"),styleCount:r("RecalcStyleCount"),heapMb:"JSHeapUsedSize"in n?r1(n.JSHeapUsedSize/(1024*1024)):null}}function webBenchFlags(e,n){const t=[];if(e.droppedPct!=null&&e.droppedPct>=5)t.push(`${e.droppedPct}% of frames dropped or partial`);if(e.fps!=null&&e.fps<n*.95)t.push("Low main-thread frame rate");if(e.frameGapCount&&e.longFrames/e.frameGapCount>=.02)t.push("Frequent long frames");const r=Math.max(e.frameGapMaxMs??0,e.edgeSilenceMs??0);if(r>=100)t.push(`Freeze of ${Math.round(r)} ms`);if(e.mainThreadPct!=null&&e.mainThreadPct>=80)t.push("Main thread near full");if(e.longTaskPct!=null&&e.longTaskPct>=20)t.push("Long tasks block the main thread");if(e.forcedLayoutMs!=null&&e.forcedLayoutMs>=50)t.push(`Forced layout in scripts (${Math.round(e.forcedLayoutMs)} ms)`);if(e.layoutShift!=null&&e.layoutShift>=.1)t.push(`Layout shifts (${e.layoutShift})`);if(e.worstInteractionMs!=null&&e.worstInteractionMs>=200){t.push(`Slow response to input (${Math.round(e.worstInteractionMs)} ms)`)}return t}function aggregateCase(e,n){const t=e.filter(c=>!c.failed&&c.fps!=null);const r=[...t].sort((c,l)=>(c.fps??0)-(l.fps??0));const i=t.filter(c=>c.droppedPct!=null).length;const o=t.length>0&&i===t.length;const s=o?[...t].sort((c,l)=>c.droppedPct-l.droppedPct):r;const a=s.length?s[Math.floor((s.length-1)/2)]:null;return{caseName:e[0]?.caseName??"",cpu:e[0]?.cpu??1,validRuns:t.length,plannedRuns:e.length,isBaseline:false,deltaDroppedPct:null,tracedRuns:i,...(()=>{const c=o?t.map(u=>u.droppedPct):[];const l=t.map(u=>u.worstInteractionMs).filter(u=>u!=null);return{droppedMin:c.length?Math.min(...c):null,droppedMax:c.length?Math.max(...c):null,inputMin:l.length?Math.min(...l):null,inputMax:l.length?Math.max(...l):null}})(),runs:e,median:a,fpsMin:r.length?r[0].fps:null,fpsMax:r.length?r[r.length-1].fps:null,flags:a?webBenchFlags(o?a:{...a,droppedPct:null},n):[]}}async function loadChromium(e){const n=(0,import_node_module.createRequire)((0,import_node_path15.join)(e,"noop.js"));for(const t of["playwright","playwright-core"]){let r;try{r=n.resolve(t)}catch{continue}const i=await import((0,import_node_url.pathToFileURL)(r).href);const o=i.chromium??i.default?.chromium;if(o)return o}throw new Error(`${PLAYWRIGHT_MISSING}
|
|
881
|
+
(Searched from ${e}. Pass projectRoot to look elsewhere.)`)}async function withDeadline(e,n,t){let r;const i=new Promise(o=>{r=setTimeout(()=>o("timeout"),n)});try{const o=await Promise.race([e,i]);if(o==="timeout"){e.catch(()=>{});return await t()}return o}finally{clearTimeout(r)}}function gitCommit(e){try{return(0,import_node_child_process17.execFileSync)("git",["rev-parse","HEAD"],{cwd:e,stdio:["ignore","pipe","ignore"],timeout:3e3}).toString().trim()}catch{return null}}function gitDirty(e){try{const n=(0,import_node_child_process17.execFileSync)("git",["status","--porcelain"],{cwd:e,stdio:["ignore","pipe","ignore"],timeout:5e3});return n.toString().trim().length>0}catch{return null}}async function closeWithin(e,n){if(!e)return true;return withDeadline(e.close().then(()=>true,()=>false),n,async()=>false)}function validateWebBenchOptions(e){if(!e.cases?.length)throw new Error("Give at least one case.");const n=new Set;for(const s of e.cases){if(!s.name?.trim())throw new Error("Every case needs a name.");if(n.has(s.name))throw new Error(`Two cases are named "${s.name}". Give each case its own name.`);n.add(s.name)}const t=(s,a,c,l)=>{if(s==null)return;if(!Number.isInteger(s)||s<c||s>l)throw new Error(`${a} must be a whole number from ${c} to ${l}.`)};const r=(s,a,c)=>{if(s==null)return;if(!Number.isFinite(s)||s<c)throw new Error(`${a} must be a number of at least ${c}.`)};const i=(s,a,c,l)=>{if(s==null)return;if(!Number.isFinite(s)||s<c||s>l)throw new Error(`${a} must be from ${c} to ${l}.`)};t(e.runsPerCase,"runsPerCase",1,10);i(e.durationMs,"durationMs",500,12e4);i(e.settleMs,"settleMs",0,6e4);i(e.refreshHz,"refreshHz",1,500);const o=e.cpuSlowdown??[];for(const s of o)i(s,"each cpuSlowdown rate",1,20);if(new Set(o).size!==o.length)throw new Error("cpuSlowdown has the same rate twice.");if(e.viewport){t(e.viewport.width,"viewport.width",200,8e3);t(e.viewport.height,"viewport.height",200,8e3);i(e.viewport.deviceScaleFactor,"viewport.deviceScaleFactor",.5,4)}t(e.extraRoundsWhenClose,"extraRoundsWhenClose",0,10);i(e.maxBatchMs,"maxBatchMs",1e4,6*60*6e4);for(const[s,a]of Object.entries(e.budgets??{}))i(a,`budgets.${s}`,0,1e9);for(const s of e.steps??[]){if("wait"in s)i(s.wait,"a wait step",0,6e4);if("scroll"in s)i(s.scroll,"a scroll step",-1e5,1e5)}new URL(e.url)}function oneLine(e){return e.replace(/\u001b\[[0-9;]*m/g,"").split("\n")[0].trim().slice(0,160)}async function locateStepTargets(e,n){const t=new Map;for(const r of n){if("expect"in r)continue;const i="click"in r?r.click:"type"in r?r.type.selector:null;if(!i||t.has(i))continue;const o=await e.$(i);const s=o?await o.boundingBox():null;if(!s)throw new Error(`step target ${i} isn't on the page (or isn't visible)`);t.set(i,{x:s.x+s.width/2,y:s.y+s.height/2})}return t}async function runSteps(e,n,t){for(const r of n){if("click"in r){const i=t.get(r.click);await e.mouse.click(i.x,i.y)}else if("press"in r)await e.keyboard.press(r.press);else if("type"in r){const i=t.get(r.type.selector);await e.mouse.click(i.x,i.y);await e.keyboard.type(r.type.text)}else if("scroll"in r)await e.mouse.wheel(0,r.scroll);else if("wait"in r)await sleep2(r.wait)}}function missedInput(e,n,t=[]){const r=[...n].sort((u,d)=>u.t-d.t);const i=[...t].sort((u,d)=>u.t-d.t);let o=0;let s=0;let a=-Infinity;const c=u=>{while(o<r.length){const d=r[o++];if(d.t>=a&&d.hit.includes(u)){a=d.t;return true}}return false};const l=u=>{while(s<i.length){const d=i[s++];if(d.t>=a&&keyMatches(u,d)){a=d.t;return true}}return false};for(const[u,d]of e.entries()){if("click"in d&&!c(d.click)){return`step ${u+1} (click ${d.click}) has no real click on its target, in order (moved, covered, or ignored)`}if("type"in d){if(!c(d.type.selector))return`step ${u+1} (type into ${d.type.selector}) has no real click on its target`;for(const h of d.type.text){if(!l(h))return`step ${u+1} (type "${d.type.text}") didn't deliver the key "${h}"`}}if("press"in d&&!l(d.press))return`step ${u+1} (press ${d.press}) didn't deliver that key`}return null}async function expectsAlreadyTrue(e,n){for(const t of n){if(!("expect"in t))continue;const{selector:r,text:i}=t.expect;const o=await e.evaluate(`(() => { const n = document.querySelector(${JSON.stringify(r)}); if (!n) return false; ${i==null?"return true;":`return (n.textContent || "").includes(${JSON.stringify(i)});`} })()`);if(o)return i==null?r:`${r} contains "${i}"`}return null}async function checkTargetsStill(e,n){for(const[t,r]of n){const i=await e.$(t);const o=i?await i.boundingBox():null;if(!o)return`step target ${t} was gone after the run`;const s=o.x+o.width/2;const a=o.y+o.height/2;if(Math.abs(s-r.x)>4||Math.abs(a-r.y)>4){return`step target ${t} moved during the run, so a click may have missed it`}}return null}function expectFailureFrom(e){for(const n of e){if(!n.found)return`expected ${n.selector} at the end of the run, but it isn't there`;const t=n.matched??(n.text==null||(n.content??"").includes(n.text));if(!t){return`expected ${n.selector} to contain "${n.text}" at the end of the run, got "${(n.content??"").slice(0,60)}"`}}return null}async function readMetrics(e){const{metrics:n}=await e.send("Performance.getMetrics");return Object.fromEntries(n.map(t=>[t.name,t.value]))}async function runWebBench(e,n=()=>{}){validateWebBenchOptions(e);const t=await waitForHostLock(e.lockWaitMs??20*6e4,n);const r={browserLeftRunning:false};try{return await runWebBenchLocked(e,n,r)}finally{t(r.browserLeftRunning)}}async function waitForHostLock(e,n=()=>{},t=2e3){const r=Date.now()+Math.max(0,e);let i=false;for(;;){try{return takeHostLock()}catch(o){const s=o?.message??String(o);const a=/Another web benchmark|already running/.test(s);if(!a||Date.now()+t>r)throw o;if(!i){n("another web benchmark is running; waiting for it to finish");i=true}await new Promise(c=>setTimeout(c,t))}}}function takeHostLock(){if(lockedHere){throw new Error("A web benchmark is already running in this process (or left a stuck browser). Wait, or restart the MCP server.")}const e=`${process.pid}:${Date.now()}:${Math.random().toString(36).slice(2)}`;const n=JSON.stringify({pid:process.pid,token:e,startedAt:new Date().toISOString()});const t=()=>{const o=`${LOCK_FILE}.${e.replace(/[^\w]/g,"")}.tmp`;try{(0,import_node_fs14.writeFileSync)(o,n);(0,import_node_fs14.linkSync)(o,LOCK_FILE);return true}catch{return false}finally{try{(0,import_node_fs14.unlinkSync)(o)}catch{}}};const r=()=>{try{return JSON.parse((0,import_node_fs14.readFileSync)(LOCK_FILE,"utf8"))}catch{return null}};const i=o=>{if(!o)return false;try{process.kill(o,0);return true}catch{return false}};if(!t()){const o=r();if(!o)throw new Error("Another web benchmark is starting. Wait for it to finish.");if(i(o.pid)){throw new Error(`Another web benchmark is running (pid ${o.pid}, since ${o.startedAt}). Two at once would skew both; wait for it to finish.`)}const s=`${LOCK_FILE}.cleanup`;let a=null;try{if(Date.now()-(0,import_node_fs14.statSync)(s).mtimeMs>3e4){const c=`${s}.${e.replace(/[^\w]/g,"")}.old`;(0,import_node_fs14.renameSync)(s,c);if(Date.now()-(0,import_node_fs14.statSync)(c).mtimeMs>3e4)(0,import_node_fs14.unlinkSync)(c);else{try{(0,import_node_fs14.linkSync)(c,s)}catch{}(0,import_node_fs14.unlinkSync)(c)}}}catch{}try{a=(0,import_node_fs14.openSync)(s,"wx")}catch{throw new Error("Another web benchmark is clearing an old lock. Try again in a moment.")}try{const c=r();if(c?.token===o.token)(0,import_node_fs14.unlinkSync)(LOCK_FILE);if(!t())throw new Error("Another web benchmark just started. Wait for it to finish.")}finally{(0,import_node_fs14.closeSync)(a);try{(0,import_node_fs14.unlinkSync)(s)}catch{}}}lockedHere=true;return(o=false)=>{if(o)return;lockedHere=false;if(r()?.token===e){try{(0,import_node_fs14.unlinkSync)(LOCK_FILE)}catch{}}}}async function runWebBenchLocked(e,n,t){const r=e.runsPerCase??3;const i=Math.max(500,e.durationMs??5e3);const o=Math.max(0,e.settleMs??1e3);const s=e.frameTrace!==false;const a=(e.cpuSlowdown?.length?e.cpuSlowdown:[1]).map(k=>Math.max(1,k));let c=e.refreshHz??60;const l={width:e.viewport?.width??1280,height:e.viewport?.height??800,deviceScaleFactor:e.viewport?.deviceScaleFactor??1};const u=[];const d=[];let h=null;if(r<2)u.push("runsPerCase=1 gives no spread; use 3 or more before choosing.");const w=await loadChromium(e.projectRoot??process.cwd());const p=await w.launch({headless:!e.headed,args:["--enable-gpu"]});const g=[];const m=[];const f=Date.now();const b=new Date(f).toISOString();const v=e.maxBatchMs??30*6e4;let y=false;let $=false;const T={commit:gitCommit(e.projectRoot??process.cwd()),dirty:gitDirty(e.projectRoot??process.cwd())};try{const k={viewport:{width:l.width,height:l.height},deviceScaleFactor:l.deviceScaleFactor};const M=await withDeadline(p.newContext(k),3e4,async()=>{t.browserLeftRunning=true;throw new Error("Chromium didn't open a page in 30 s. Restart the MCP server and try again.")});const A=3e4+15e3+o+i+6e4;const P=async(O,N,z,B)=>{const F={};return withDeadline(j(F,O,N,z,B),A,async()=>{F.cancelled=true;if(!F.ctx)y=true;else if(!await closeWithin(F.ctx,1e4))y=true;return{...R(O.name,N,z),failed:`run took over ${Math.round(A/1e3)} s (the page may be stuck in a loop)`}})};const R=(O,N,z)=>({caseName:O,cpu:N,round:z,fps:null,frameGapP95Ms:null,frameGapMaxMs:null,longFrames:0,longTaskPct:null,loafBlockingMs:null,styleLayoutMs:null,forcedLayoutMs:null,topScripts:[],layoutShift:null,domNodesStart:null,domNodesEnd:null,mainThreadPct:null,scriptMs:null,styleMs:null,layoutMs:null,layoutCount:null,styleCount:null,heapMb:null,pageErrors:[]});const j=async(O,N,z,B,F)=>{const U=await p.newContext(k);O.ctx=U;if(O.cancelled){await closeWithin(U,1e4);throw new Error("run was cancelled during setup")}const L=await U.newPage();const H=[];L.on("pageerror",J=>H.push(String(J?.message??J)));const W={...R(N.name,z,B),pageErrors:H};try{const J=await U.newCDPSession(L);await J.send("Performance.enable",{timeDomain:"timeTicks"});if(z>1)await J.send("Emulation.setCPUThrottlingRate",{rate:z});const V=await L.goto(caseUrl(e.url,N,e.path),{waitUntil:"load",timeout:3e4});if(V&&V.status()>=400)return{...W,failed:`HTTP ${V.status()}`};if(e.readySelector)await L.waitForSelector(e.readySelector,{state:"attached",timeout:15e3});await sleep2(o);const se=F||s;if(se){await J.send("Tracing.start",{transferMode:"ReturnAsStream",categories:(F?FULL_TRACE_CATEGORIES:FRAME_TRACE_CATEGORIES).join(",")})}const re=e.steps?.length?await locateStepTargets(L,e.steps):new Map;if(e.steps?.length){const te=await expectsAlreadyTrue(L,e.steps);if(te)return{...W,failed:`expect ${te} already held before the steps, so it can't prove they worked`};const ne=[...re.keys()];const Z=e.steps.flatMap(oe=>"expect"in oe?[oe.expect]:[]);await L.evaluate(`window.__buoyBenchClickTargets = ${JSON.stringify(ne)}; window.__buoyBenchExpects = ${JSON.stringify(Z)}; true`)}const ee=await readMetrics(J);await L.evaluate(START_PROBE_JS);const G=Date.now();if(e.steps?.length)await runSteps(L,e.steps,re);const K=i-(Date.now()-G);if(K>0)await sleep2(K);await L.evaluate(END_PROBE_JS);const ie=await readMetrics(J);const le=Date.now()-G;const Q=await L.evaluate(COLLECT_PROBE_JS);let Y=null;if(se){const te=new Promise(X=>J.on("Tracing.tracingComplete",ae=>X(ae.stream)));await J.send("Tracing.end");const ne=await te;const Z=F?(0,import_node_fs14.openSync)(F,"w"):null;const oe=[];let ce=0;try{for(;;){const X=await J.send("IO.read",{handle:ne});const ae=X.base64Encoded?Buffer.from(X.data,"base64").toString("utf8"):X.data;ce+=ae.length;if(Z!=null)(0,import_node_fs14.writeSync)(Z,ae);if(ce<=MAX_TRACE_CHARS)oe.push(ae);else oe.length=0;if(X.eof)break}}finally{await J.send("IO.close",{handle:ne}).catch(()=>{});if(Z!=null)(0,import_node_fs14.closeSync)(Z)}if(F)d.push(F);if(ce>MAX_TRACE_CHARS){u.push(`Trace for ${N.name} was over ${Math.round(MAX_TRACE_CHARS/1e6)} MB, so its frames weren't counted. A page that busy shows its problem in the table already.`)}else{try{const X=JSON.parse(oe.join(""));Y=summarizeFrameTrace(Array.isArray(X)?X:X.traceEvents??[])}catch{Y=null}}}if(!Q)return{...W,failed:"probe returned nothing (page navigated away?)"};if(Q.hidden)return{...W,failed:"page was hidden during the run"};if(Q.resized)return{...W,failed:"the window size or zoom changed during the run"};if(H.length&&!e.allowPageErrors){return{...W,failed:`page error: ${oneLine(H[0])}`}}if(e.steps?.length){const te=missedInput(e.steps,Q.clicks??[],Q.keys??[]);if(te)return{...W,failed:te};const ne=expectFailureFrom(Q.expectResults??[]);if(ne)return{...W,failed:ne};const Z=await checkTargetsStill(L,re);if(Z)return{...W,failed:Z}}const ue="Timestamp"in ee&&"Timestamp"in ie?r1((ie.Timestamp-ee.Timestamp)*1e3):null;return{...W,...summarizeProbe(Q,c),...cdpDeltas(ee,ie,le),probeSpanMs:r1(Q.end-Q.start),cdpSpanMs:ue,shownFps:Y?.shownFps??null,droppedFrames:Y?.faults??null,frameCounts:Y?{full:Y.full,partial:Y.partial,dropped:Y.dropped,faults:Y.faults}:null,droppedPct:Y?.droppedPct??null}}catch(J){return{...W,failed:oneLine(J?.message??String(J))}}finally{await closeWithin(L,5e3);if(!await closeWithin(U,1e4))y=true}};{const O=await withDeadline(M.newPage(),15e3,async()=>{throw new Error("Chromium didn't open the GPU check page in 15 s.")});try{h=await withDeadline(O.evaluate(GPU_RENDERER_JS),5e3,async()=>null)??null}catch{h=null}finally{await closeWithin(O,5e3)}if(h)n(`GPU ${h}`);if(h&&isSoftwareGpu(h)){u.push(`Chrome is drawing with a software GPU (${h}). Canvas, WebGL and Skia pages run several times slower than on a real screen, so their numbers mean little. Try headed: true, or a machine with a GPU.`)}}if(e.refreshHz==null){const O=await withDeadline(M.newPage(),15e3,async()=>{throw new Error("Chromium didn't open the calibration page in 15 s.")});try{await withDeadline(O.goto("about:blank"),15e3,async()=>null);const N=await withDeadline(O.evaluate(MEASURE_REFRESH_JS),5e3,async()=>{throw new Error("idle rate check timed out")});c=snapRefreshRate(N);n(`idle frame rate ${N.toFixed(1)} \u2192 ${c} Hz`)}catch{u.push("Couldn't measure the idle frame rate; frame budgets assume 60 Hz.")}finally{await closeWithin(O,5e3)}}n("warmup load");await P(e.cases[0],1,-1);const C=async(O,N,z,B)=>{if(y){g.push({...R(O.name,N,z),failed:"an earlier run left the browser stuck; batch stopped"});return}if(Date.now()-f>v){g.push({...R(O.name,N,z),failed:"batch time limit reached; run skipped"});return}n(B);m.push({cpu:N,round:z,caseName:O.name});g.push(await P(O,N,z))};for(const O of a){for(let N=0;N<r;N++){const z=shuffled(e.cases,2654435769^N*7919+O);for(const B of z)await C(B,O,N,`cpu ${O}x \xB7 round ${N+1}/${r} \xB7 ${B.name}`)}for(let N=0;N<(e.extraRoundsWhenClose??0);N++){const z=e.cases.map(L=>aggregateCase(g.filter(H=>H.cpu===O&&H.caseName===L.name),c));for(const L of z)L.control=e.cases.find(H=>H.name===L.caseName)?.control===true;const B=new Set([...tiedPairs(z).flat(),...z.filter(L=>!L.control&&L.validRuns<2&&L.plannedRuns>0).map(L=>L.caseName)]);if(B.size===0)break;const F=r+N;const U=shuffled(e.cases.filter(L=>B.has(L.name)),20973^F*7919+O);for(const L of U)await C(L,O,F,`cpu ${O}x \xB7 extra round ${N+1} (close call) \xB7 ${L.name}`)}}if(e.traceDir){(0,import_node_fs14.mkdirSync)(e.traceDir,{recursive:true});for(const[O,N]of e.cases.entries()){const z=(0,import_node_path15.join)(e.traceDir,`${String(O+1).padStart(2,"0")}-${N.name.replace(/[^\w.-]+/g,"_")}.json`);if(y||Date.now()-f>v){u.push(`Trace run for ${N.name} skipped (batch time limit or a stuck browser).`);continue}n(`trace \xB7 ${N.name}`);const B=await P(N,a[0],-1,z);if(B.failed)u.push(`Trace run for ${N.name} failed: ${B.failed}`)}}await closeWithin(M,1e4)}finally{const k=await closeWithin(p,15e3);t.browserLeftRunning=!k;if(!k){$=true;u.push("Chromium didn't close in 15 s and may still be running. The benchmark lock stays held; restart the MCP server before the next batch.")}}const _=[];for(const k of a){for(const M of e.cases){_.push(aggregateCase(g.filter(A=>A.cpu===k&&A.caseName===M.name),c))}}for(const k of _)k.control=e.cases.find(M=>M.name===k.caseName)?.control===true;for(const k of a){const M=_.filter(j=>j.cpu===k);const A=M.find(j=>!j.control);if(!A)continue;A.isBaseline=true;const P=j=>j.droppedMin!=null?j.median?.droppedPct??null:null;const R=P(A);for(const j of M.filter(C=>C!==A&&!C.control)){const C=P(j);j.deltaDroppedPct=R!=null&&C!=null?r1(C-R):null}}if(e.allowPageErrors&&g.some(k=>k.pageErrors.length)){u.push("Some runs threw page errors (kept because allowPageErrors is on).")}if(y)u.push("A browser context wouldn't close, so the batch stopped early. Restart and run again.");if(e.budgets)for(const k of _)k.budget=checkBudgets(k,e.budgets,e.steps??[]);const x=_.filter(k=>k.median).length;const I=_.every(k=>k.validRuns===k.plannedRuns);const D=x===0?"failed":x<_.length||!I?"partial":"ok";const E=_.filter(k=>k.median&&k.validRuns>0&&k.validRuns<k.plannedRuns);for(const k of E){const M=Array.from(new Set(k.runs.filter(A=>A.failed).map(A=>A.failed)));u.push(`${k.caseName} (CPU ${k.cpu}x): ${k.plannedRuns-k.validRuns} of ${k.plannedRuns} runs failed: ${M.join("; ")}`)}for(const k of _){const M=k.median;if(M?.probeSpanMs&&M.cdpSpanMs&&Math.abs(M.cdpSpanMs-M.probeSpanMs)/M.probeSpanMs>.15){u.push(`${k.caseName} (CPU ${k.cpu}x): Chrome's counters cover ${Math.round(M.cdpSpanMs)} ms but frames cover ${Math.round(M.probeSpanMs)} ms, so its cost columns include extra time.`)}if(M?.probeSpanMs!=null&&M.probeSpanMs<i*.8){u.push(`${k.caseName} (CPU ${k.cpu}x) recorded ${Math.round(M.probeSpanMs)} ms, not the ${i} ms asked for.`)}}const S={status:D,hasSteps:Boolean(e.steps?.length),browserLeftRunning:$,replay:{startedAt:b,...T,runOrder:m},url:e.url,browser:`Chromium ${p.version()}${e.headed?"":" (headless)"}`,gpu:h,viewport:l,refreshHz:c,durationMs:i,runsPerCase:r,results:_,traces:d,warnings:u};if(e.outFile){try{(0,import_node_fs14.writeFileSync)(e.outFile,JSON.stringify({options:e,result:S},null,2))}catch(k){S.warnings.push(`Couldn't write outFile ${e.outFile}: ${oneLine(k?.message??String(k))}`)}}return S}function tiedPairs(e){const n=e.filter(o=>!o.control&&o.median&&o.validRuns>1);const t=n.filter(o=>o.droppedMin!=null);const r=[];if(t.length>=2&&t.length===n.length){const o=[...t].sort((s,a)=>s.median.droppedPct-a.median.droppedPct);for(let s=1;s<o.length;s++){const[a,c]=[o[s-1],o[s]];const l=c.median.droppedPct-a.median.droppedPct<=MIN_DROPPED_GAP_PP;if(c.droppedMin<=a.droppedMax||l)r.push([a.caseName,c.caseName])}return r}if(t.length>0)return r;const i=n.filter(o=>o.median.fps!=null).sort((o,s)=>s.median.fps-o.median.fps);for(let o=1;o<i.length;o++){const[s,a]=[i[o-1],i[o]];const c=s.median.fps-a.median.fps<=MIN_FPS_GAP;if((a.fpsMax??0)>=(s.fpsMin??0)||c)r.push([s.caseName,a.caseName])}return r}function closeCall(e){const n=e.filter(a=>!a.control&&a.median);const t=[];const r=n.filter(a=>a.validRuns<2);if(r.length)t.push(`**Too few runs to rank:** ${r.map(a=>a.caseName).join(", ")} (need 2 or more valid runs).`);const i=n.filter(a=>a.validRuns>1);const o=i.filter(a=>a.droppedMin!=null);if(o.length>0&&o.length<i.length){t.push(`**Not enough traced runs to compare smoothness:** ${i.filter(a=>!o.includes(a)).map(a=>`${a.caseName} (${a.tracedRuns}/${a.validRuns} traced)`).join(", ")}.`);return t.join("\n")}const s=new Map(i.map(a=>[a.caseName,a]));for(const[a,c]of tiedPairs(e)){const l=s.get(a);const u=s.get(c);t.push(o.length?`**Too close to call:** ${a} (${l.droppedMin}\u2013${l.droppedMax}% dropped) and ${c} (${u.droppedMin}\u2013${u.droppedMax}%) overlap or sit within ${MIN_DROPPED_GAP_PP} pp. No clear winner between them; more runs may separate them.`:`**Too close to call:** ${a} and ${c} overlap or sit within ${MIN_FPS_GAP} FPS. No clear winner between them; more runs may separate them.`)}return t.length?t.join("\n"):null}function formatWebBenchMarkdown(e){const n=(a,c=1)=>a==null?"\u2014":a.toFixed(c);const t=[];t.push(`### Web benchmark \xB7 ${e.url}`);t.push(`${e.browser}${e.gpu?` \xB7 GPU: ${e.gpu}${isSoftwareGpu(e.gpu)?" \u26A0\uFE0F software":""}`:""} \xB7 ${e.viewport.width}\xD7${e.viewport.height} @${e.viewport.deviceScaleFactor}x \xB7 ${e.runsPerCase} runs${e.results.some(a=>a.plannedRuns>e.runsPerCase)?" (more for close calls)":""} \xD7 ${e.durationMs/1e3}s per case, fresh browser context each run, case order shuffled each round.`);const r=e.results.map(a=>a.median?.probeSpanMs).filter(a=>a!=null);const i=e.results.map(a=>a.median?.cdpSpanMs).filter(a=>a!=null);const o=a=>`${(Math.min(...a)/1e3).toFixed(2)}\u2013${(Math.max(...a)/1e3).toFixed(2)} s`;if(r.length){t.push(`Recorded: frames over ${o(r)}${i.length?`; cost columns (Chrome's counters) over ${o(i)}`:""}, not the requested time.`)}if(e.replay?.dirty)t.push(`Note: the project had uncommitted changes, so commit ${e.replay.commit?.slice(0,10)??"?"} alone doesn't describe the code that ran.`);t.push("");t.push(`**How to read this.** Dropped % is the smoothness number: frames Chrome dropped or only partly produced that it says hurt smoothness, as a share of the frames it wanted, from its own verdicts in a trace. Rank on it first, and only across variants doing the same work. Shown FPS counts frames Chrome produced (headless Chrome displays nothing), so an animation that changes less often needs fewer; don't compare it across variants that update at different rates. Main-thread FPS and frame gaps come from requestAnimationFrame. Main thread % is Chrome's task time for the run. Desktop numbers, even with CPU slowdown, don't stand in for a real phone's GPU, memory or heat.`);const s=Array.from(new Set(e.results.map(a=>a.cpu)));for(const a of s){t.push("");t.push(a===1?`#### No CPU slowdown`:`#### CPU slowed ${a}x`);t.push("");t.push(`| Case | Runs | Shown FPS | Dropped % | Main-thread FPS (range) | p95 gap ms | Worst gap ms | Main thread % | Script ms | Style ms | Layout ms | Layouts | DOM nodes | JS heap MB | Flags |`);t.push(`|------|-----:|----------:|----------:|------------------------:|-----------:|-------------:|--------------:|----------:|---------:|----------:|--------:|----------:|--------:|-------|`);for(const h of e.results.filter(w=>w.cpu===a)){const w=h.median;if(!w){const m=h.runs.find(f=>f.failed)?.failed??"no valid runs";t.push(`| ${h.caseName} | 0/${h.plannedRuns} | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u274C FAILED (${m}) |`);continue}const p=h.fpsMin!=null&&h.fpsMax!=null&&h.validRuns>1?` (${n(h.fpsMin)}\u2013${n(h.fpsMax)})`:"";const g=h.flags.length?`\u26A0\uFE0F ${h.flags.join("; ")}`:"no flags";t.push(`| ${h.isBaseline?`${h.caseName} (baseline)`:h.control?`${h.caseName} (control)`:h.caseName} | ${h.validRuns}/${h.plannedRuns} | ${n(w.shownFps)} | ${h.droppedMin==null&&h.tracedRuns>0?`\u2014 (${h.tracedRuns}/${h.validRuns} traced)`:n(h.droppedMin==null?null:w.droppedPct)}${h.droppedMin!=null&&h.validRuns>1?` [${h.droppedMin}\u2013${h.droppedMax}]`:""}${h.deltaDroppedPct!=null?` (${h.deltaDroppedPct>0?"+":""}${h.deltaDroppedPct} pp)`:""} | ${n(w.fps)}${p} | ${n(w.frameGapP95Ms)} | ${n(w.frameGapMaxMs)} | ${n(w.mainThreadPct)} | ${n(w.scriptMs,0)} | ${n(w.styleMs,0)} | ${n(w.layoutMs,0)} | ${n(w.layoutCount,0)} | ${n(w.domNodesEnd,0)} | ${n(w.heapMb)} | ${g} |`)}const c=closeCall(e.results.filter(h=>h.cpu===a));if(c){t.push("");t.push(c)}const l=e.results.filter(h=>h.cpu===a&&h.budget);if(l.length){t.push("");t.push(`Budget:`);for(const h of l){const w=h.budget;const p=[...w.over,...w.unknown.map(m=>`${m} not measured`)].join("; ");const g=h.control?`${h.caseName} (control)`:h.caseName;t.push(`- **${g}**: ${w.meets?"meets every limit":`misses (${p||"no result"})`}`)}}const u=e.results.filter(h=>h.cpu===a&&h.median?.interactions!=null&&(e.hasSteps||h.median.interactions>0)).map(h=>{const w=h.median;const p=h.inputMin!=null&&h.inputMax!=null?` \xB7 slowest across all runs ${h.inputMax} ms (range ${h.inputMin}\u2013${h.inputMax})`:"";const g=h.runs.filter(f=>!f.failed&&f.fps!=null&&f.inputCaptureComplete===false).length;const m=g?` \xB7 \u26A0\uFE0F timing incomplete in ${g} run(s): the last input's paint came after the run ended, so its time is unknown (leave more time after the last step)`:"";if(!w.interactions)return`- **${h.caseName}**: middle run had no input entry (inputs under 16 ms aren't reported)${p}${m}`;return`- **${h.caseName}**: middle run: ${w.interactions} reported (16 ms or more), slowest ${w.worstInteractionMs} ms (waiting ${w.worstInputDelayMs} \xB7 handlers ${w.worstProcessingMs} \xB7 to paint ${w.worstPresentationMs})${p}${m}`});if(u.length){t.push("");t.push(`Input response (scripted steps, Event Timing). Inputs under 16 ms aren't reported. Under 200 ms is good.`);t.push(...u)}const d=e.results.filter(h=>h.cpu===a&&h.median&&h.median.topScripts.length).map(h=>`- **${h.caseName}**: ${h.median.topScripts.slice(0,3).map(w=>`${w.name} ${w.ms} ms`).join(", ")}`);if(d.length){t.push("");t.push(`Scripts in slow frames (Long Animation Frames; frames that ran past the end of a run are left out):`);t.push(...d)}}if(e.traces.length){t.push("");t.push(`Chrome traces (open in DevTools \u2192 Performance \u2192 Load profile): ${e.traces.join(", ")}`)}if(e.warnings.length){t.push("");t.push(...e.warnings.map(a=>`\u26A0\uFE0F ${a}`))}return t.join("\n")}var import_node_module,import_node_child_process17,import_node_path15,import_node_fs14,import_node_os11,import_node_url,r1,GPU_RENDERER_JS,COMMON_RATES,FRAME_STATES,PLAYWRIGHT_MISSING,FRAME_TRACE_CATEGORIES,FULL_TRACE_CATEGORIES,MAX_TRACE_CHARS,sleep2,LOCK_FILE,lockedHere,MIN_DROPPED_GAP_PP,MIN_FPS_GAP;var init_webBench=__esm({"src/webBench/webBench.ts"(){"use strict";import_node_module=require("module");import_node_child_process17=require("child_process");import_node_path15=require("path");import_node_fs14=require("fs");import_node_os11=require("os");import_node_url=require("url");init_inPageProbe();r1=e=>Math.round(e*10)/10;GPU_RENDERER_JS=`(() => {
|
|
882
|
+
try {
|
|
883
|
+
const gl = document.createElement("canvas").getContext("webgl2") || document.createElement("canvas").getContext("webgl");
|
|
884
|
+
if (!gl) return null;
|
|
885
|
+
const ext = gl.getExtension("WEBGL_debug_renderer_info");
|
|
886
|
+
return String(gl.getParameter(ext ? ext.UNMASKED_RENDERER_WEBGL : gl.RENDERER));
|
|
887
|
+
} catch { return null; }
|
|
888
|
+
})()`;COMMON_RATES=[30,60,75,90,120,144,165,240];FRAME_STATES=["STATE_PRESENTED_ALL","STATE_PRESENTED_PARTIAL","STATE_DROPPED"];PLAYWRIGHT_MISSING="Playwright isn't installed in this project. Install it, then run again:\n npm i -D playwright && npx playwright install chromium";FRAME_TRACE_CATEGORIES=["disabled-by-default-devtools.timeline.frame","blink.user_timing"];FULL_TRACE_CATEGORIES=["devtools.timeline","disabled-by-default-devtools.timeline","disabled-by-default-devtools.timeline.frame","blink.user_timing","loading","latencyInfo","v8.execute"];MAX_TRACE_CHARS=15e7;sleep2=e=>new Promise(n=>setTimeout(n,e));LOCK_FILE=(0,import_node_path15.join)((0,import_node_os11.tmpdir)(),"buoy-web-bench.lock");lockedHere=false;MIN_DROPPED_GAP_PP=1.5;MIN_FPS_GAP=2}});function nextLoad(e,n){const t=Math.max(e+1,e*n);const r=Math.pow(10,Math.max(0,Math.floor(Math.log10(t))-1));return Math.ceil(t/r)*r}function median(e){if(!e.length)return null;const n=[...e].sort((r,i)=>r-i);const t=Math.floor(n.length/2);return n.length%2?n[t]:Math.round((n[t-1]+n[t])/2)}function bracketResolved(e,n,t){if(n-e<=1)return true;if(e<=0)return false;return(n-e)/e<=t/100}async function rampOnce(e,n){const t=[];const r=(l,u,d,h)=>({status:l,stopReason:u,highestPass:d?{load:d.load,fps:d.fps??0}:null,lowestMiss:h?{load:h.load,fps:h.fps??0}:null,resolved:l==="below_one"||l==="bracketed"&&!!d&&!!h&&bracketResolved(d.load,h.load,n.precisionPct),steps:t});const i=(l,u,d)=>r("invalid",l.fps==null?"measurement_failed":"page_error",u,d);const o=async(l,u=false)=>{const d=await e(l);if(u)d.confirm=true;t.push(d);return d};let s=null;let a=null;let c=await o(n.start);if(!c.valid)return i(c,null,null);if(c.pass)s=c;else{a=c;let l=n.start;while(!s){if(l<=1)return r("below_one","performance",null,a);if(!n.timeLeft())return r("lower_bound","deadline",null,a);l=Math.max(1,Math.floor(l/2));c=await o(l);if(!c.valid)return i(c,null,a);if(c.pass)s=c;else a=c}}while(!a||a.load<=s.load){if(s.load>=n.max)return r("lower_bound","max",s,null);if(!n.timeLeft())return r("lower_bound","deadline",s,null);c=await o(Math.min(n.max,nextLoad(s.load,n.growth)));if(!c.valid)return i(c,s,null);if(c.pass){s=c;continue}if(!n.timeLeft())return r("bracketed","performance",s,c);const l=await o(c.load,true);if(!l.valid)return i(l,s,null);if(l.pass)s=l;else a=l}while(!bracketResolved(s.load,a.load,n.precisionPct)&&n.timeLeft()){const l=Math.round((s.load+a.load)/2);if(l<=s.load||l>=a.load)break;c=await o(l);if(!c.valid)break;if(c.pass)s=c;else a=c}return r("bracketed","performance",s,a)}async function runWebRamp(e,n=()=>{}){if(!e.cases?.length)throw new Error("Pass at least one case.");if(!e.param)throw new Error('Pass `param`, the query param that sets the load (e.g. "lights").');const t=(y,$)=>{if(y!=null&&!Number.isFinite(y))throw new Error(`${$} must be a finite number.`)};for(const[y,$]of Object.entries({start:e.start,growth:e.growth,max:e.max,targetFps:e.targetFps,precisionPct:e.precisionPct,rounds:e.rounds,settleMs:e.settleMs,measureMs:e.measureMs,cpuSlowdown:e.cpuSlowdown}))t($,y);const r=Math.max(1,Math.floor(e.start??100));const i=Math.min(4,Math.max(1.05,e.growth??1.3));const o=Math.max(r,Math.floor(e.max??1e9));const s=e.targetFps??55;const a=Math.min(50,Math.max(.5,e.precisionPct??4));const c=Math.max(1,Math.min(5,Math.floor(e.rounds??1)));const l=Math.max(0,e.settleMs??1e3);const u=Math.max(500,e.measureMs??2e3);const d=Math.max(1,e.cpuSlowdown??1);const h={width:e.viewport?.width??1280,height:e.viewport?.height??800,deviceScaleFactor:e.viewport?.deviceScaleFactor??1};const w=[];const p=Date.now();const g=p+(e.maxBatchMs??40*6e4);const m=()=>g-Date.now();const f=p>>>0;const b=await waitForHostLock(Math.min(e.lockWaitMs??20*6e4,Math.max(0,m())),n);let v=false;try{const y=await loadChromium(e.projectRoot??process.cwd());const $=await y.launch({headless:!e.headed,args:["--enable-gpu","--disable-backgrounding-occluded-windows","--disable-renderer-backgrounding","--disable-background-timer-throttling"]});try{const T={viewport:{width:h.width,height:h.height},deviceScaleFactor:h.deviceScaleFactor};let _=null;let x=60;{const S=await $.newContext(T);try{const k=await S.newPage();await k.goto("about:blank");_=await k.evaluate(GPU_RENDERER_JS)??null;const M=await withDeadline(k.evaluate(measureFramesJs(200,1e3)),1e4,async()=>({fps:60}));x=snapRefreshRate(M.fps)}finally{await closeWithin(S,5e3)}}n(`GPU ${_??"unknown"} \xB7 idle ${x} Hz`);if(_&&isSoftwareGpu(_))w.push(`Chrome is drawing with a software GPU (${_}), so ceilings are far lower than on a real screen.`);if(s>x*.95){w.push(`The target (${s} fps) is at or above this browser's idle frame rate (${x} Hz), so even an empty page can miss it. Use headed: true on a faster screen, or measure with a target your contract allows.`)}const I=e.cases.map(S=>({caseName:S.name,ceiling:null,atLeast:null,rounds:[],errors:[]}));const D=async(S,k,M,A)=>{const P=A.length;const R=caseUrl(e.url,{...k,params:{...k.params??{},[e.param]:String(M)}},e.path);const j=C=>Math.max(1e3,Math.min(C,m()+15e3));try{await S.goto(R,{waitUntil:"load",timeout:j(6e4)});if(e.readySelector)await S.waitForSelector(e.readySelector,{state:"attached",timeout:j(6e4)});const C=await withDeadline(S.evaluate(measureFramesJs(l,u)),l+u+6e4,async()=>{throw new Error("the page stopped drawing (no frames for 60 s)")});const O=A.length>P?A[A.length-1]:void 0;if(O)return{load:M,fps:C.fps,p95GapMs:C.p95,valid:false,pass:false,error:O};return{load:M,fps:C.fps,p95GapMs:C.p95,valid:true,pass:C.fps>=s}}catch(C){return{load:M,fps:null,p95GapMs:null,valid:false,pass:false,error:(C?.message??String(C)).split("\n")[0].slice(0,200)}}};let E=false;for(let S=0;S<c&&!E;S++){const k=shuffled(e.cases.map((M,A)=>({c:M,i:A})),f+S*7919>>>0);for(const{c:M,i:A}of k){const P=I[A];if(E||m()<=0){P.rounds.push({round:S+1,status:"skipped",stopReason:"not_run",highestPass:null,lowestMiss:null,resolved:false,steps:[]});continue}n(`round ${S+1}/${c} \xB7 ${M.name}`);let R;try{R=await $.newContext(T);const j=await R.newPage();j.on("pageerror",O=>P.errors.push(String(O?.message??O).slice(0,200)));if(d>1){const O=await R.newCDPSession(j);await O.send("Emulation.setCPUThrottlingRate",{rate:d})}const C=await rampOnce(O=>D(j,M,O,P.errors),{start:r,growth:i,max:o,precisionPct:a,timeLeft:()=>m()>0});P.rounds.push({round:S+1,...C});n(` ${M.name}: ${C.status} ${C.highestPass?.load??"-"}`)}catch(j){P.errors.push((j?.message??String(j)).split("\n")[0].slice(0,200));P.rounds.push({round:S+1,status:"invalid",stopReason:"measurement_failed",highestPass:null,lowestMiss:null,resolved:false,steps:[]})}finally{if(R&&!await closeWithin(R,1e4)){v=true;E=true;w.push(`${M.name}'s browser context didn't close, so the batch stopped to keep later runs clean.`)}}}}for(const S of I){const k=S.rounds.filter(A=>A.status==="bracketed"||A.status==="below_one");S.ceiling=median(k.map(A=>A.highestPass?.load??0));const M=S.rounds.filter(A=>A.status==="lower_bound"&&A.highestPass).map(A=>A.highestPass.load);S.atLeast=M.length?Math.max(...M):null}if(m()<=0)w.push("The batch hit its time limit. Rounds marked skipped or lower_bound didn't finish.");return{url:e.url,browser:`Chromium ${$.version()}${e.headed?"":" (headless)"}`,gpu:_,refreshHz:x,targetFps:s,cpuSlowdown:d,viewport:h,seed:f,results:I,warnings:w}}finally{if(!await closeWithin($,1e4))v=true}}finally{b(v)}}function formatWebRampMarkdown(e){const n=o=>o==null?"\u2014":o.toLocaleString("en-US");const t=o=>o?`${n(o.load)} @ ${o.fps.toFixed(1)}`:"\u2014";const r=[];r.push(`### Web ceiling \xB7 ${e.url}`);r.push(`${e.browser}${e.gpu?` \xB7 GPU: ${e.gpu}${isSoftwareGpu(e.gpu)?" \u26A0\uFE0F software":""}`:""} \xB7 ${e.viewport.width}\xD7${e.viewport.height} @${e.viewport.deviceScaleFactor}x \xB7 idle ${e.refreshHz} Hz \xB7 target ${e.targetFps} fps${e.cpuSlowdown>1?` \xB7 CPU slowed ${e.cpuSlowdown}x`:""}`);r.push("");r.push("**Ceiling** is the most load that held the target, timed from main-thread `requestAnimationFrame` callbacks (a stand-in for drawing speed; it can't see a canvas that stopped updating, so check the looks too). Each round ramps ~30% a step, confirms the first miss, then bisects. With several rounds the ceiling is their median. Ceilings within about 10% are a tie until more rounds agree.");r.push("");const i=Math.max(0,...e.results.map(o=>o.ceiling??0));r.push("| Case | Ceiling | Each round: highest pass @ fps \u2192 lowest miss @ fps | Notes |");r.push("|------|--------:|------------------------------------------------------|-------|");for(const o of e.results){const s=o.rounds.map(c=>{if(c.status==="skipped")return`r${c.round}: not run`;if(c.status==="invalid")return`r${c.round}: invalid (${c.stopReason}) after ${t(c.highestPass)}`;if(c.status==="lower_bound")return`r${c.round}: at least ${t(c.highestPass)} (${c.stopReason})`;if(c.status==="below_one")return`r${c.round}: even 1 missed (${t(c.lowestMiss)})`;return`r${c.round}: ${t(c.highestPass)} \u2192 ${t(c.lowestMiss)}${c.resolved?"":" (wide)"}`}).join("<br>");const a=[o.ceiling===i&&i>0?"best":"",o.atLeast!=null?`at least ${n(o.atLeast)}`:"",o.rounds.some(c=>c.status==="invalid")?"a round broke: check the page before trusting it":"",o.errors.length?`${o.errors.length} page error(s): ${o.errors[0]}`:""].filter(Boolean);r.push(`| ${o.caseName} | ${n(o.ceiling)} | ${s} | ${a.join("; ")} |`)}if(e.warnings.length){r.push("");for(const o of e.warnings)r.push(`- \u26A0\uFE0F ${o}`)}return r.join("\n")}var measureFramesJs;var init_webRamp=__esm({"src/webBench/webRamp.ts"(){"use strict";init_webBench();measureFramesJs=(e,n)=>`new Promise((resolve) => {
|
|
889
|
+
setTimeout(() => {
|
|
890
|
+
const deltas = [];
|
|
891
|
+
let start;
|
|
892
|
+
let last;
|
|
893
|
+
const loop = (now) => {
|
|
894
|
+
if (start === undefined) {
|
|
895
|
+
start = last = now;
|
|
896
|
+
requestAnimationFrame(loop);
|
|
897
|
+
return;
|
|
898
|
+
}
|
|
899
|
+
deltas.push(now - last);
|
|
900
|
+
last = now;
|
|
901
|
+
if (now - start < ${n}) requestAnimationFrame(loop);
|
|
902
|
+
else {
|
|
903
|
+
const total = deltas.reduce((a, b) => a + b, 0);
|
|
904
|
+
const sorted = [...deltas].sort((a, b) => a - b);
|
|
905
|
+
resolve({ fps: total > 0 ? (deltas.length * 1000) / total : 0, p95: sorted[Math.floor(sorted.length * 0.95)] || 0 });
|
|
906
|
+
}
|
|
907
|
+
};
|
|
908
|
+
requestAnimationFrame(loop);
|
|
909
|
+
}, ${e});
|
|
910
|
+
})`}});async function runWebShots(e,n=()=>{}){if(!e.cases?.length)throw new Error("Pass at least one case.");if(!e.outDir)throw new Error("Pass outDir, the folder to save screenshots in.");const t=[...new Set((e.atMs?.length?e.atMs:[500,2e3]).map(c=>Math.max(0,Math.round(c))))].sort((c,l)=>c-l);const r=(0,import_path.join)(e.outDir,new Date().toISOString().replace(/[:.]/g,"-"));(0,import_fs.mkdirSync)(r,{recursive:true});const i={width:e.viewport?.width??1280,height:e.viewport?.height??800,deviceScaleFactor:e.viewport?.deviceScaleFactor??1};const o={dir:"",files:[],pageErrors:[],diffs:[],outliers:[]};o.dir=r;const s=await waitForHostLock(e.lockWaitMs??20*6e4,n);let a=false;try{const c=await loadChromium(e.projectRoot??process.cwd());const l=await c.launch({headless:true,args:["--enable-gpu"]});try{for(const[u,d]of e.cases.entries()){let h;try{h=await l.newContext({viewport:{width:i.width,height:i.height},deviceScaleFactor:i.deviceScaleFactor});const w=await h.newPage();w.on("pageerror",g=>o.pageErrors.push({caseName:d.name,error:String(g?.message??g).slice(0,200)}));await w.goto(caseUrl(e.url,d,e.path),{waitUntil:"load",timeout:6e4});if(e.readySelector)await w.waitForSelector(e.readySelector,{state:"attached",timeout:6e4});const p=Date.now();for(const g of t){const m=p+g-Date.now();if(m>0)await w.waitForTimeout(m);const f=Date.now()-p;const b=(0,import_path.join)(r,`${String(u+1).padStart(2,"0")}-${safe(d.name)}-${g}ms.png`);try{if(e.clipSelector){const v=await w.$(e.clipSelector);if(!v)throw new Error(`clipSelector ${e.clipSelector} not found`);await v.screenshot({path:b})}else await w.screenshot({path:b});o.files.push({caseName:d.name,atMs:g,actualMs:f,file:b})}catch(v){o.files.push({caseName:d.name,atMs:g,actualMs:f,file:null,error:(v?.message??String(v)).split("\n")[0]})}}n(`${d.name}: ${t.length} shot(s)`)}catch(w){for(const p of t)o.files.push({caseName:d.name,atMs:p,file:null,error:(w?.message??String(w)).split("\n")[0]})}finally{if(h&&!await closeWithin(h,1e4))a=true}}if(e.cases.length>1){let u;try{u=await l.newContext({viewport:{width:400,height:300}});const d=await u.newPage();const h=e.cases[0].name;for(const f of t){const b=o.files.find(y=>y.caseName===h&&y.atMs===f&&y.file)?.file;if(!b)continue;const v=(0,import_fs.readFileSync)(b).toString("base64");for(const y of o.files.filter($=>$.caseName!==h&&$.atMs===f&&$.file)){const $=await d.evaluate(diffJs(v,(0,import_fs.readFileSync)(y.file).toString("base64")));if($)o.diffs.push({caseName:y.caseName,atMs:f,...$})}}const w=new Map;for(const f of o.diffs)w.set(f.caseName,[...w.get(f.caseName)??[],f.changedPct]);const p=[...w].map(([f,b])=>[f,b.reduce((v,y)=>v+y,0)/b.length]);const g=p.map(([,f])=>f).sort((f,b)=>f-b);const m=g.length?g[Math.floor(g.length/2)]:0;o.outliers=p.filter(([,f])=>f>Math.max(1,m*2)).map(([f])=>f)}catch{}finally{if(u)await closeWithin(u,1e4)}}}finally{if(!await closeWithin(l,1e4))a=true}}finally{s(a)}return o}var import_fs,import_path,safe,diffJs;var init_webShots=__esm({"src/webBench/webShots.ts"(){"use strict";import_fs=require("fs");import_path=require("path");init_webBench();safe=e=>e.replace(/[^\w.-]+/g,"_").slice(0,80);diffJs=(e,n)=>`(async () => {
|
|
911
|
+
const load = (s) => new Promise((res, rej) => { const i = new Image(); i.onload = () => res(i); i.onerror = rej; i.src = "data:image/png;base64," + s; });
|
|
912
|
+
const [ia, ib] = await Promise.all([load(${JSON.stringify(e)}), load(${JSON.stringify(n)})]);
|
|
913
|
+
const w = ia.naturalWidth, h = ia.naturalHeight;
|
|
914
|
+
const px = (img) => { const c = document.createElement("canvas"); c.width = w; c.height = h; const g = c.getContext("2d"); g.drawImage(img, 0, 0, w, h); return g.getImageData(0, 0, w, h).data; };
|
|
915
|
+
const da = px(ia), db = px(ib);
|
|
916
|
+
let sum = 0, changed = 0;
|
|
917
|
+
for (let i = 0; i < da.length; i += 4) {
|
|
918
|
+
const d = (Math.abs(da[i] - db[i]) + Math.abs(da[i + 1] - db[i + 1]) + Math.abs(da[i + 2] - db[i + 2])) / 3;
|
|
919
|
+
sum += d;
|
|
920
|
+
if (d > 32) changed++;
|
|
921
|
+
}
|
|
922
|
+
const n = da.length / 4;
|
|
923
|
+
return { meanDiff: Math.round((sum / n) * 100) / 100, changedPct: Math.round((changed / n) * 10000) / 100 };
|
|
924
|
+
})()`}});function setOptimizeDeadline(e){deadline=e}function optimizeNote(e=Date.now(),n=deadline){if(n==null)return null;const t=Math.round((n-e)/6e4);if(t>10){return`
|
|
925
|
+
|
|
926
|
+
\u23F1 **Buoy Optimize: ${t} min left** (deadline ${clock(n)}). You're not done. When this step ends, start the next round: forks of the best, a new idea family, or an untried idea from the bank. A good score or a written RESULTS.md is not a reason to stop.`}if(t>0){return`
|
|
927
|
+
|
|
928
|
+
\u23F1 **Buoy Optimize: ${t} min left** (deadline ${clock(n)}). Confirm the best checked version, install it and finish the report.`}return`
|
|
929
|
+
|
|
930
|
+
\u23F1 **Buoy Optimize: the deadline (${clock(n)}) has passed.** Leave the best checked version in place and report.`}var deadline,clock;var init_session=__esm({"src/optimize/session.ts"(){"use strict";deadline=null;clock=e=>new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"})}});function hasPro(e){if(readEntitlement().isPro)return true;return e.connectedDevices().some(n=>n.tier==="pro")}function registerWebBenchTools(e,n){e.registerTool("run_web_benchmark",{description:"Benchmark variants of a web page in a fresh headless Chromium (needs Playwright in the project). Each case is a path + query params on a running app; each run loads a fresh page, waits until ready, then records frame rate, frame gaps, long tasks, Long Animation Frames (with script names), layout shifts, DOM size, and Chrome's own main-thread, script, style and layout time. Cases run in rounds with the order shuffled each round. `cpuSlowdown` repeats everything with Chrome's CPU throttled (e.g. [1, 4, 6]) as a stand-in for slower phones; it doesn't slow the GPU. Blocks until done.",inputSchema:{url:import_zod26.z.string().describe("Origin of the running app, e.g. http://localhost:5173"),path:import_zod26.z.string().optional().describe("Default path for cases, e.g. /bench/lights"),cases:import_zod26.z.array(import_zod26.z.object({name:import_zod26.z.string(),path:import_zod26.z.string().optional(),params:import_zod26.z.record(import_zod26.z.string()).optional(),control:import_zod26.z.boolean().optional().describe("Does different work (e.g. an empty page). Shown, never the baseline or a candidate.")})).min(1).describe("Variants to compare. The first is the baseline."),runsPerCase:import_zod26.z.number().optional().describe("Measured runs per case (1\u201310). Default 3."),perCaseDurationMs:import_zod26.z.number().optional().describe("Recording length per run. Default 5000."),settleMs:import_zod26.z.number().optional().describe("Wait after the page is ready, before recording. Default 1000."),cpuSlowdown:import_zod26.z.array(import_zod26.z.number()).optional().describe("CPU throttling rates; 1 = none. Default [1]."),viewport:import_zod26.z.object({width:import_zod26.z.number(),height:import_zod26.z.number(),deviceScaleFactor:import_zod26.z.number().optional()}).optional().describe("Fixed viewport. Default 1280\xD7800 at 1x."),readySelector:import_zod26.z.string().optional().describe("CSS selector that must appear before a run counts as ready."),steps:import_zod26.z.array(import_zod26.z.union([import_zod26.z.object({click:import_zod26.z.string()}),import_zod26.z.object({press:import_zod26.z.string()}),import_zod26.z.object({type:import_zod26.z.object({selector:import_zod26.z.string(),text:import_zod26.z.string()})}),import_zod26.z.object({scroll:import_zod26.z.number()}),import_zod26.z.object({wait:import_zod26.z.number()}),import_zod26.z.object({expect:import_zod26.z.object({selector:import_zod26.z.string(),text:import_zod26.z.string().optional()})})])).optional().describe("Real input during each run, in order: {click: selector}, {press: key}, {type: {selector, text}}, {scroll: px}, {wait: ms}, {expect: {selector, text?}} (checked after the run; fails runs that skipped the work). Click targets are located before recording and must not move. Adds input delay, handler time and time to next paint per case."),traceDir:import_zod26.z.string().optional().describe("Save one Chrome trace per case here (extra, unranked runs)."),headed:import_zod26.z.boolean().optional().describe("Show the browser window. Default false."),allowPageErrors:import_zod26.z.boolean().optional().describe("Keep runs whose page threw an uncaught error. Default false: such runs fail."),projectRoot:import_zod26.z.string().optional().describe("Folder to load Playwright from. Default: the server's working directory."),outFile:import_zod26.z.string().optional().describe("Also save the full result and options as JSON here, to read again later."),extraRoundsWhenClose:import_zod26.z.number().optional().describe("If the two smoothest cases are too close to call, run up to this many extra rounds of just those two. Default 0."),maxBatchMs:import_zod26.z.number().optional().describe("Stop starting new runs after this long. Default 30 minutes."),budgets:import_zod26.z.object({droppedPct:import_zod26.z.number().optional(),inputMs:import_zod26.z.number().optional(),freezeMs:import_zod26.z.number().optional(),mainThreadPct:import_zod26.z.number().optional(),jsHeapMb:import_zod26.z.number().optional()}).optional().describe("Hard limits. The report says which cases meet all of them; an unmeasured limit counts as not met.")}},async t=>{if(!hasPro(n))return fail9(PRO_REQUIRED);try{const r=await runWebBench({url:t.url,path:t.path,cases:t.cases,runsPerCase:t.runsPerCase,durationMs:t.perCaseDurationMs,settleMs:t.settleMs,cpuSlowdown:t.cpuSlowdown,viewport:t.viewport,readySelector:t.readySelector,steps:t.steps,traceDir:t.traceDir,headed:t.headed,allowPageErrors:t.allowPageErrors,projectRoot:t.projectRoot,outFile:t.outFile,extraRoundsWhenClose:t.extraRoundsWhenClose,maxBatchMs:t.maxBatchMs,budgets:t.budgets},s=>process.stderr.write(`[buoy-mcp] web-bench: ${s}
|
|
931
|
+
`));const i={status:r.status,browser:r.browser,gpu:r.gpu??null,viewport:r.viewport,results:r.results.map(s=>({caseName:s.caseName,cpu:s.cpu,validRuns:s.validRuns,fpsMin:s.fpsMin,fpsMax:s.fpsMax,plannedRuns:s.plannedRuns,isBaseline:s.isBaseline,control:s.control===true,deltaDroppedPct:s.deltaDroppedPct,droppedRange:s.droppedMin==null?null:[s.droppedMin,s.droppedMax],flags:s.flags,budget:s.budget,median:s.median,failures:s.runs.filter(a=>a.failed).map(a=>a.failed)})),traces:r.traces,warnings:r.warnings,replay:r.replay};const o=`${formatWebBenchMarkdown(r)}
|
|
764
932
|
|
|
765
933
|
\`\`\`json
|
|
766
|
-
${JSON.stringify(
|
|
767
|
-
|
|
934
|
+
${JSON.stringify(i,null,2)}
|
|
935
|
+
\`\`\``;return r.status==="failed"?fail9(`Every case failed.
|
|
936
|
+
|
|
937
|
+
${o}`):text7(o)}catch(r){return fail9(r?.message??String(r))}});e.registerTool("find_web_ceiling",{description:"Find the most load each web variant can hold at a target frame rate, with no cap. For each case, a fresh headless Chromium (real GPU) opens the page with `param` set (e.g. ?lights=100), waits until ready, settles, then counts requestAnimationFrame callbacks. It raises the load ~30% a step until a valid sample misses `targetFps`, confirms the miss, then bisects to within a few percent; if the first load misses it searches down. A page error ends the round as invalid instead of counting as a miss. An app's own capped test is not the ceiling. Needs Playwright in the project. Blocks until done.",inputSchema:{url:import_zod26.z.string().describe("Origin of the running app, e.g. http://localhost:5173"),path:import_zod26.z.string().optional().describe("Default path for cases."),cases:import_zod26.z.array(import_zod26.z.object({name:import_zod26.z.string(),path:import_zod26.z.string().optional(),params:import_zod26.z.record(import_zod26.z.string()).optional()})).min(1).describe("Variants to ramp, e.g. [{name: 'baseline', params: {variant: 'baseline'}}, {name: 'atlas', params: {variant: 'atlas'}}]."),param:import_zod26.z.string().describe("Query param that sets the load, e.g. 'lights' or 'count'."),start:import_zod26.z.number().optional().describe("First load. Default 100."),growth:import_zod26.z.number().optional().describe("Growth per step. Default 1.3."),max:import_zod26.z.number().optional().describe("Highest load to try. Default 1,000,000,000."),targetFps:import_zod26.z.number().optional().describe("Frame rate each step must hold. Default 55."),precisionPct:import_zod26.z.number().optional().describe("Bisect until the pass/miss gap is within this percent. Default 4."),rounds:import_zod26.z.number().optional().describe("Ramps per case (1\u20135); the ceiling is the median of valid rounds. Default 1. Use 3 to settle close calls."),maxBatchMs:import_zod26.z.number().optional().describe("Stop the whole batch after this long. Default 40 minutes."),settleMs:import_zod26.z.number().optional().describe("Wait after ready before counting frames. Default 1000."),measureMs:import_zod26.z.number().optional().describe("How long to count frames per step. Default 2000."),cpuSlowdown:import_zod26.z.number().optional().describe("CPU throttling rate; 1 = none. Default 1."),viewport:import_zod26.z.object({width:import_zod26.z.number(),height:import_zod26.z.number(),deviceScaleFactor:import_zod26.z.number().optional()}).optional(),readySelector:import_zod26.z.string().optional().describe("CSS selector that must exist before counting frames."),headed:import_zod26.z.boolean().optional().describe("Show the browser window (uses the screen's refresh rate). Default false."),projectRoot:import_zod26.z.string().optional().describe("Folder to load Playwright from.")}},async t=>{if(!hasPro(n))return fail9(PRO_REQUIRED.replace("run_web_benchmark","find_web_ceiling"));try{const r=await runWebRamp(t,s=>process.stderr.write(`[buoy-mcp] web-ceiling: ${s}
|
|
938
|
+
`));const i=r.results.map(s=>({caseName:s.caseName,ceiling:s.ceiling,atLeast:s.atLeast,rounds:s.rounds.map(a=>({status:a.status,stopReason:a.stopReason,highestPass:a.highestPass,lowestMiss:a.lowestMiss,resolved:a.resolved})),errors:s.errors.slice(0,3)}));const o=`${formatWebRampMarkdown(r)}
|
|
768
939
|
|
|
769
940
|
\`\`\`json
|
|
770
|
-
${JSON.stringify(
|
|
771
|
-
|
|
941
|
+
${JSON.stringify({gpu:r.gpu,refreshHz:r.refreshHz,seed:r.seed,results:i},null,2)}
|
|
942
|
+
\`\`\``;return text7(o)}catch(r){return fail9(r?.message??String(r))}});e.registerTool("screenshot_web_variants",{description:"Screenshot every web variant at the same moments after it's ready, in a fresh headless Chromium (real GPU), and save PNGs in a new timestamped folder inside outDir. Use it to check each variant still looks right: open the files and compare them side by side with the baseline. Use the same params (e.g. the same count and pattern) for every case. Animated scenes differ by timing, so compare shapes, colors, glow and layout, and take several moments to catch frozen or broken motion.",inputSchema:{url:import_zod26.z.string().describe("Origin of the running app."),path:import_zod26.z.string().optional(),cases:import_zod26.z.array(import_zod26.z.object({name:import_zod26.z.string(),path:import_zod26.z.string().optional(),params:import_zod26.z.record(import_zod26.z.string()).optional()})).min(1),atMs:import_zod26.z.array(import_zod26.z.number()).optional().describe("Times after ready to capture, in ms. Default [500, 2000]."),outDir:import_zod26.z.string().describe("Folder to save the PNGs in."),viewport:import_zod26.z.object({width:import_zod26.z.number(),height:import_zod26.z.number(),deviceScaleFactor:import_zod26.z.number().optional()}).optional(),readySelector:import_zod26.z.string().optional(),clipSelector:import_zod26.z.string().optional().describe("Crop to this element, e.g. 'canvas'."),projectRoot:import_zod26.z.string().optional()}},async t=>{if(!hasPro(n))return fail9(PRO_REQUIRED.replace("run_web_benchmark","screenshot_web_variants"));try{const r=await runWebShots(t,c=>process.stderr.write(`[buoy-mcp] web-shots: ${c}
|
|
943
|
+
`));const i=r.files.map(c=>`- ${c.caseName} @ ${c.atMs} ms${c.actualMs!=null&&Math.abs(c.actualMs-c.atMs)>50?` (taken at ${c.actualMs} ms)`:""}: ${c.file??`failed (${c.error})`}`);const o=r.pageErrors.map(c=>`- ${c.caseName}: ${c.error}`);const s=t.cases[0]?.name;const a=r.diffs.length?`
|
|
944
|
+
|
|
945
|
+
**Difference from ${s}** (same moment; mean 0\u2013255, and % of pixels off by more than 32):
|
|
946
|
+
`+r.diffs.map(c=>`- ${c.caseName} @ ${c.atMs} ms: mean ${c.meanDiff}, ${c.changedPct}% changed${r.outliers.includes(c.caseName)?" \u26A0\uFE0F outlier":""}`).join("\n")+(r.outliers.length?`
|
|
947
|
+
|
|
948
|
+
\u26A0\uFE0F ${r.outliers.join(", ")} differ from ${s} far more than the other variants. Something may be missing or wrong (lights not drawn, wrong colors, frozen motion). Open those images first.`:""):"";return text7(`### Variant screenshots
|
|
949
|
+
|
|
950
|
+
${i.join("\n")}${o.length?`
|
|
951
|
+
|
|
952
|
+
**Page errors**
|
|
953
|
+
${o.join("\n")}`:""}${a}
|
|
954
|
+
|
|
955
|
+
Open the files and compare each variant with the baseline at the same moment. Put the baseline first in \`cases\` so the difference numbers compare against it. Animation makes some difference normal; a variant far from the rest needs a close look. A variant that looks wrong can't win.`)}catch(r){return fail9(r?.message??String(r))}});e.registerTool("start_optimize_session",{description:"Start the Buoy Optimize clock. Pass how long the session lasts (`minutes`) or when it ends (`deadline`, ISO time). After this, every Buoy tool result shows the time left, so the loop keeps going until the deadline. Call it once at the start of an optimize session. Pass minutes: 0 to stop the clock.",inputSchema:{minutes:import_zod26.z.number().optional().describe("Session length from now, in minutes."),deadline:import_zod26.z.string().optional().describe("When the session ends, as an ISO time, e.g. 2026-10-04T07:12:00-06:00.")}},async t=>{if(t.minutes===0){setOptimizeDeadline(null);return text7("Optimize clock stopped.")}const r=t.deadline?Date.parse(t.deadline):t.minutes!=null?Date.now()+t.minutes*6e4:NaN;if(!Number.isFinite(r))return fail9("Pass `minutes` (a number) or `deadline` (an ISO time).");if(r<=Date.now())return fail9("That deadline has already passed.");setOptimizeDeadline(r);return text7(`Optimize clock started. Deadline: ${new Date(r).toISOString()}.${optimizeNote()??""}`)})}var import_zod26,text7,fail9,PRO_REQUIRED;var init_webBench2=__esm({"src/tools/packs/webBench.ts"(){"use strict";import_zod26=require("zod");init_camera();init_webBench();init_webRamp();init_webShots();init_session();text7=e=>({content:[{type:"text",text:e}]});fail9=e=>({isError:true,content:[{type:"text",text:e}]});PRO_REQUIRED="`run_web_benchmark` is a Buoy Pro feature. Running benchmarks from an agent needs Pro.\n\n_Tell the user to sign in to Buoy Desktop with a Pro account, or open an app signed in to Pro. See https://buoy.gg/pricing. Don't try to work around it._"}});async function run4(e,n,t=2e4){try{const{stdout:r}=await execFileAsync16(e,n,{timeout:t});return r}catch(r){const i=r;throw new Error(`${e} ${n.slice(0,3).join(" ")} failed: ${(i.stderr||i.message||"").trim().split("\n").slice(-2).join(" ").slice(0,300)}`)}}async function rotate(e,n){if(e.platform==="android"){await adbShell(e.serial,"settings put system accelerometer_rotation 0");await adbShell(e.serial,`settings put system user_rotation ${ANDROID_ROTATION[n]}`);return`Rotated to ${n.replace("_"," ")} (auto-rotate is now off on this device; rotate to portrait to go back).`}await devicectl2(["device","orientation","set","--device",e.udid,IOS_ORIENTATION[n]]);return`Rotated the device to ${n.replace("_"," ")}. An app that only supports portrait keeps its screen upright.`}async function shake(e){if(e.platform==="ios"){await run4("xcrun",["simctl","spawn",e.udid,"notifyutil","-p","com.apple.UIKit.SimulatorShake"]);return"Sent a shake to the simulator (the same event as Device > Shake). Check the screen: an app only reacts if it listens for shakes."}if(e.platform==="android"){if(!/^emulator-\d+$/.test(e.serial))throw new Error("A physical Android phone can't be shaken from the computer. Use an emulator, or shake the phone.");for(const n of["0:25:0","0:-25:0","0:25:0","0:-25:0","0:9.81:0"]){await adb(e.serial,["emu","sensor","set","acceleration",n]);await new Promise(t=>setTimeout(t,80))}return"Shook the emulator (an accelerometer burst). Check the screen: an app only reacts if it listens for shakes."}throw new Error("A physical iPhone can't be shaken from the computer. Use a simulator, or shake the phone.")}async function setClipboard(e,n){if(e.platform==="ios"){await new Promise((t,r)=>{const i=(0,import_node_child_process18.spawn)("xcrun",["simctl","pbcopy",e.udid],{stdio:["pipe","ignore","pipe"]});let o="";i.stderr.on("data",s=>o+=s);i.on("error",r);i.on("exit",s=>s===0?t():r(new Error(`simctl pbcopy failed: ${o.trim()}`)));i.stdin.end(n)})}else if(e.platform==="ios-device"){const t=import_node_path16.default.join(import_node_os12.default.tmpdir(),`buoy-clip-${(0,import_node_crypto7.randomUUID)()}.txt`);await import_node_fs15.promises.writeFile(t,n,{mode:384});try{await devicectl2(["device","pasteboard","copy","--device",e.udid,"--type","public.utf8-plain-text","--file",t])}finally{await import_node_fs15.promises.unlink(t).catch(()=>void 0)}}else{throw new Error("Setting the clipboard from the computer isn't supported on Android. Use native_type to type the text instead.")}return e.platform==="ios-device"?"Put the text on the iPhone's clipboard. To paste it for real, long-press the field (native_tap with holdMs: 600) and tap Paste (native_tap with x and y; labels don't work on a phone).":'Put the text on the clipboard. To paste it for real, long-press the field (native_tap with holdMs: 600) and tap Paste (native_tap label: "Paste").'}async function biometrics(e,n,t){if(e.platform==="android"){if(!/^emulator-\d+$/.test(e.serial))throw new Error("Biometrics can be simulated on an Android emulator only.");const r=await adbShell(e.serial,"dumpsys fingerprint").catch(()=>"");if(n&&/"count"\s*:\s*0|enrolled[^\n]*\b0\b/i.test(r)){throw new Error("No fingerprint is enrolled on this emulator. Enroll one in Settings > Security, then try again.")}const i=t??(n?1:9731);await adb(e.serial,["emu","finger","touch",String(i)]);return n?`Touched fingerprint id ${i}. It matches only if that finger is enrolled in the emulator's Settings (enroll one there first if the app says no fingerprints).`:`Touched fingerprint id ${i}, meant to fail. It would match instead if id ${i} is enrolled; pass another fingerId if so.`}await devicectl2(["device","simulate","biometrics","--device",e.udid,n?"--success":"--failure"]);return n?"Simulated a matching Face ID / Touch ID.":"Simulated a Face ID / Touch ID that doesn't match."}var import_node_child_process18,import_node_util16,import_node_fs15,import_node_os12,import_node_path16,import_node_crypto7,execFileAsync16,devicectl2,IOS_ORIENTATION,ANDROID_ROTATION;var init_deviceGestures=__esm({"src/capture/deviceGestures.ts"(){"use strict";import_node_child_process18=require("child_process");import_node_util16=require("util");import_node_fs15=require("fs");import_node_os12=__toESM(require("os"));import_node_path16=__toESM(require("path"));import_node_crypto7=require("crypto");init_adb();execFileAsync16=(0,import_node_util16.promisify)(import_node_child_process18.execFile);devicectl2=e=>run4("xcrun",["devicectl",...e,"--quiet"]);IOS_ORIENTATION={portrait:"portrait",landscape_left:"landscapeLeft",landscape_right:"landscapeRight",upside_down:"portraitUpsideDown"};ANDROID_ROTATION={portrait:0,landscape_left:1,upside_down:2,landscape_right:3}}});function registerDeviceTools(e,n){e.registerTool("device_control",{_meta:coreTool(),description:"Do something to the device itself: rotate (orientation), shake (shake-to-undo, shake-to-report, dev menus), clipboard (text on the clipboard for a real paste), biometrics (Face ID / Touch ID / fingerprint match or fail). iOS Simulator, physical iPhone (rotate, clipboard) and Android (rotate, emulator shake and fingerprint). Returns the screen after when the app is connected (not for clipboard).",inputSchema:{action:import_zod27.z.enum(["rotate","shake","clipboard","biometrics"]),orientation:import_zod27.z.enum(["portrait","landscape_left","landscape_right","upside_down"]).optional().describe("rotate (required)."),text:import_zod27.z.string().optional().describe("clipboard (required). {{secret:NAME}} works here too."),match:import_zod27.z.boolean().optional().describe("biometrics: true for a match (default), false for a failed one."),fingerId:import_zod27.z.number().int().min(1).optional().describe("biometrics on an Android emulator: the finger id to touch: an enrolled one for a match (default 1), one that is not enrolled for a failure (default 9731)."),serial:import_zod27.z.string().optional().describe("Android: the adb serial, when several devices are connected."),deviceId:deviceIdInput}},async t=>{try{const{id:r,host:i,online:o}=await hostTarget(n,t.deviceId,{serial:t.serial},{allowOffline:t.action!=="clipboard"});let s;switch(t.action){case"rotate":if(!t.orientation)return fail2("rotate requires `orientation`.");s=await rotate(i,t.orientation);if(i.platform!=="android")forgetScreenSize(i.udid);break;case"shake":s=await shake(i);break;case"clipboard":if(t.text===void 0)return fail2("clipboard requires `text`.");s=await setClipboard(i,fillSecrets(t.text));break;case"biometrics":s=await biometrics(i,t.match!==false,t.fingerId);break}if(t.action!=="rotate"||i.platform!=="ios")await new Promise(c=>setTimeout(c,700));const a=o&&t.action!=="clipboard"?await observeAfterAction(n,r):"";return text(`${s} (${hostLabel(i)})${a}`)}catch(r){return fail2(errMsg2(r))}})}var import_zod27;var init_device=__esm({"src/tools/packs/device.ts"(){"use strict";import_zod27=require("zod");init_packKit();init_hostKit();init_secrets();init_interact();init_native();init_deviceGestures()}});function parseReact19Frames(e,n=10){const t=[];for(const r of e.split("\n")){if(t.length>=n)break;const i=parseReact19Stack(r);if(i)t.push(i)}return t}function parseReact19Stack(e){for(const n of e.split("\n")){if(/\b(?:react[-_]stack[-_](?:top|bottom)[-_]frame|jsxDEV(?:Impl)?|jsxWithValidation|createElement)\b/.test(n))continue;const t=n.trim();const r=/:(\d+):(\d+)\)?\s*$/.exec(t);if(!r)continue;const i=t.slice(0,r.index);const o=/\s\((?=https?:\/\/|file:\/\/|address at |\/|[A-Za-z]:[\\/])/.exec(i);let s;let a;if(o){s=i.slice(o.index+2);a=o.index}else{const d=/(?:^at\s+|@)((?:https?:\/\/|file:\/\/|\/|[A-Za-z]:[\\/]).*)$/.exec(i);if(!d)continue;s=d[1];a=d.index}const c=Object.assign([t,s,r[1],r[2]],{index:a});const l=Number(c[2]);const u=Number(c[3]);if(!Number.isSafeInteger(l)||l<1||!Number.isSafeInteger(u))continue;return{file:c[1].replace(/^address at\s+/,""),lineNumber:l,column:u,methodName:t.slice(0,c.index).replace(/^at\s+/,"").replace(/[(@\s]+$/,"")||"x"}}return null}function isBundleURL(e){return/^https?:\/\//i.test(e)}function relativeSourcePath(e,n=process.env.BUOY_PROJECT_ROOT||process.cwd()){let t=e;if(t.startsWith("file://")){try{t=(0,import_node_url2.fileURLToPath)(t)}catch{return e}}if(isBundleURL(t))return t;const r=/^[A-Za-z]:[\\/]/.test(t)&&/^[A-Za-z]:[\\/]/.test(n)?import_node_path17.default.win32:import_node_path17.default;if(!r.isAbsolute(t))return t;const i=r.relative(r.resolve(n),t);return i&&i!==".."&&!i.startsWith(`..${r.sep}`)&&!r.isAbsolute(i)?i.split(r.sep).join("/"):t}async function symbolicateFrame(e,n,t=fetch){const r=await t(`${n.replace(/\/$/,"")}/symbolicate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({stack:[e]}),signal:AbortSignal.timeout(5e3)});if(!r.ok)throw new Error(`Metro could not map this frame (HTTP ${r.status}).`);const i=await r.json();const o=i?.stack?.[0];if(typeof o?.file!=="string"||!o.file||isBundleURL(o.file)||typeof o.lineNumber!=="number"||!Number.isInteger(o.lineNumber)||o.lineNumber<1){throw new Error("Metro did not return a source file and line.")}return{fileName:o.file,lineNumber:o.lineNumber,...typeof o.column==="number"&&Number.isInteger(o.column)&&o.column>=0?{columnNumber:o.column}:{}}}async function symbolicateAppFrame(e,n,t=fetch){const r=await t(`${n.replace(/\/$/,"")}/symbolicate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({stack:e}),signal:AbortSignal.timeout(5e3)});if(!r.ok){const o=(await r.json().catch(()=>null))?.error;const s=typeof o==="string"&&o?` Metro said: ${o.slice(0,200)}`:"";const a=/serialized source map/i.test(s)?" Its cache looks stale; restarting Metro with --clear usually fixes this.":"";throw new Error(`Metro could not map these frames (HTTP ${r.status}).${s}${a}`)}const i=await r.json();for(const o of i?.stack??[]){if(typeof o?.file!=="string"||!o.file||isBundleURL(o.file)||LIBRARY.test(o.file))continue;if(typeof o.lineNumber!=="number"||!Number.isInteger(o.lineNumber)||o.lineNumber<1)continue;return{fileName:o.file,lineNumber:o.lineNumber,...typeof o.column==="number"&&o.column>=0?{columnNumber:o.column}:{}}}throw new Error("Every frame mapped into library code, none into the app.")}async function resolveEntry(e,n){if(!e.source&&e.rawStack&&n){const r=parseReact19Frames(e.rawStack).filter(i=>isBundleURL(i.file));if(r.length){try{return{...e,source:await symbolicateAppFrame(r,n)}}catch(i){const o=/library code/.test(errMsg2(i));return{...e,source:void 0,reason:o?"rendered by library code (no line in the app).":`Could not map the source frame: ${errMsg2(i)}`}}}}const t=e.source&&isBundleURL(e.source.fileName)?{file:e.source.fileName,lineNumber:e.source.lineNumber??0,column:e.source.columnNumber??0,methodName:"x"}:!e.source&&e.rawStack?parseReact19Stack(e.rawStack):null;if(e.source&&!isBundleURL(e.source.fileName))return e;if(!t)return{...e,source:void 0,reason:"React gave no source frame. Use a dev build."};if(!isBundleURL(t.file)){return{...e,source:{fileName:t.file,lineNumber:t.lineNumber,columnNumber:t.column}}}if(!n)return{...e,source:void 0,reason:"The dev server address is not known."};try{return{...e,source:await symbolicateFrame(t,n)}}catch(r){return{...e,source:void 0,reason:`Could not map the source frame: ${errMsg2(r)}`}}}function formatComponentSource(e,n){if(!e.found)return e.reason;let t="";const r=i=>{const o=i.source;let s;if(o){s=relativeSourcePath(o.fileName,n)+(o.lineNumber!=null?`:${o.lineNumber}`:"")+(o.lineNumber!=null&&o.columnNumber!=null?`:${o.columnNumber}`:"")}else if(i.reason?.startsWith("rendered by library")){s=i.reason}else{const a=i.reason??"React gave no source frame. Use a dev build.";s=a===t?"no source (same reason as above).":`no source. ${a}`;t=a}return`${i.name}: ${s} [memo: ${i.memo?"yes":"no"}; forwardRef: ${i.forwardRef?"yes":"no"}]`};return[r(e.component),...e.owners.slice(0,6).map(i=>` owner ${r(i)}`),"Lines after the name are where each component is used (its JSX call site in the parent's file)."].join("\n")}function registerSourceTools(e,n){e.registerTool("get_component_source",{description:"Find where a React view is used in code. Use its name, testID, text, or nativeTag from describe_screen. Get file paths, lines, and up to six owners. See memo and forwardRef flags too. These paths point to JSX calls. Needs a dev build and Buoy Pro.",inputSchema:{query:import_zod28.z.string().trim().min(1).optional().describe("A component name, testID, or text from describe_screen."),nativeTag:import_zod28.z.number().int().nonnegative().optional().describe("The nativeTag from describe_screen. Takes priority over query."),deviceId:deviceIdInput}},async({query:t,nativeTag:r,deviceId:i})=>{try{const o=n.requireProDevice(i);if(r==null&&!t?.trim())return fail2("Pass a query or nativeTag.");const s=await n.callAction("highlight-updates","getComponentSource",{query:t,nativeTag:r},o);if(!s)return fail2("The app gave no source result. Turn on highlight-updates or update Buoy.");if(!s.found)return text(s.reason);const a=n.devServerOrigin(o);const c=await Promise.all([s.component,...s.owners.slice(0,6)].map(d=>resolveEntry(d,a)));const l=s.component.definedIn?await resolveEntry({name:s.component.name,memo:false,forwardRef:false,source:s.component.definedIn.source,rawStack:s.component.definedIn.rawStack},a):null;const u=l?.source?`Its own JSX starts in: ${relativeSourcePath(l.source.fileName)}${l.source.lineNumber!=null?` (line ${l.source.lineNumber})`:""} (usually its definition; a helper that builds JSX can show here instead)
|
|
956
|
+
`:"";return text(u+formatComponentSource({found:true,component:c[0],owners:c.slice(1)}))}catch(o){return fail2(errMsg2(o))}})}var import_node_path17,import_node_url2,import_zod28,LIBRARY;var init_source=__esm({"src/tools/packs/source.ts"(){"use strict";import_node_path17=__toESM(require("path"));import_node_url2=require("url");import_zod28=require("zod");init_packKit();LIBRARY=/node_modules\/|\/react-native\/|\/Libraries\/|\/expo-router\//}});function sparkline(e){const n=Math.max(1,...e);return e.map(t=>SPARK_CHARS[Math.min(7,Math.floor(t/n*7.999))]).join("")}function formatTopMarkdown(e,n){const t=[];t.push(`## JS thread top (${(n/1e3).toFixed(1)}s sample)`);t.push("");t.push(`Thread busy: **${e.busyPct.toFixed(1)}%** of the trailing 5s window.`);if(e.freezeSummary.count>0){t.push(`Freezes (\u226550ms single-task blocks, last 60s): **${e.freezeSummary.count}**, worst **${e.freezeSummary.worstMs}ms** \u2014 during these, taps and JS animations stall.`)}if(!e.tiers.bridge){t.push("_New Architecture device: touch/React commit work appears as \u201Cunattributed\u201D; timers, rAF and Promise chains are fully attributed._")}t.push("");t.push("| # | task origin | api | 5s ms | % busy | calls | avg ms | max ms | freezes |");t.push("|---|---|---|---|---|---|---|---|---|");e.rows.slice(0,15).forEach((r,i)=>{const o=r.freezes>0?`\u26A0 ${r.freezes} (worst ${r.worstFreezeMs}ms)`:"\u2013";t.push(`| ${i+1} | ${r.label} | ${r.api} | ${r.windowMs.toFixed(1)} | ${r.pctOfBusy.toFixed(1)} | ${r.calls} | ${r.avgMs.toFixed(2)} | ${r.maxMs.toFixed(1)} | ${o} |`)});t.push("");t.push("_Drill into any row with `get_js_thread_origin_detail` using its `key` from the JSON below._");return t.join("\n")}function formatDetailMarkdown(e){const n=[];n.push(`## Origin detail \u2014 ${e.label}`);n.push("");n.push(`API: \`${e.api}\` \xB7 key: \`${e.key}\``);n.push("");n.push(`Activity last 5s (250ms buckets): \`${sparkline(e.buckets)}\` \u2014 ${e.windowMs.toFixed(1)}ms in window, ${e.pctOfBusy.toFixed(1)}% of busy time.`);n.push("");n.push("| runs | scheduled | avg/run | max/run | total | last run | freezes (60s) | worst freeze |");n.push("|---|---|---|---|---|---|---|---|");n.push(`| ${e.calls} | ${e.scheduleCount} | ${e.avgMs.toFixed(2)}ms | ${e.maxMs.toFixed(1)}ms | ${e.totalMs.toFixed(1)}ms | ${e.lastSeenAgoMs>0?`${Math.round(e.lastSeenAgoMs/1e3)}s ago`:"\u2014"} | ${e.freezes} | ${e.worstFreezeMs>0?`${e.worstFreezeMs}ms`:"\u2014"} |`);if(e.caller||e.file){n.push("");n.push(`Scheduled from: **${e.caller?`${e.caller}()`:"unknown caller"}**${e.file?` \u2014 ${e.file}${e.line!=null?`:${e.line}`:""}`:""}`);if(e.frames?.length){n.push(`Raw frames (Hermes bundle offsets): ${e.frames.map(t=>`${t.file}:${t.line}:${t.col}`).join(" \xB7 ")}`)}}else if(e.api!=="unattributed"&&e.api!=="other"){n.push("");n.push(e.promoted?"_Scheduling stack not captured yet \u2014 the next schedule from this site records it._":"_Not hot enough for stack capture yet (threshold: 25 schedules or 50ms total)._")}return n.join("\n")}function registerJsThreadTools(e,n){e.registerTool("get_js_thread_top",{description:"Sample instrumented JavaScript task origins and return available timing, busy percentage and freeze attribution. Coverage depends on installed hooks; unattributed work can remain. Requires @buoy-gg/js-top and Buoy Pro. The call waits for the sample: arrange the interaction during that window using an available concurrent driver or a person, rather than starting it after this call returns. clearFirst resets tracked statistics before sampling. Use get_js_thread_origin_detail for a returned row key and measure_renders for component render diagnostics.",inputSchema:{deviceId:deviceIdInput,durationMs:import_zod29.z.number().optional().describe("How long to sample before reading the table. Default 3000; clamped to 250\u201330000."),clearFirst:import_zod29.z.boolean().optional().describe("Reset tracked statistics before sampling. Hook coverage and attribution limits still apply.")}},async({deviceId:t,durationMs:r,clearFirst:i})=>{try{const o=n.requireProDevice(t);const s=Math.min(Math.max(r??3e3,250),3e4);const a=await n.callAction(JS_TOP_TOOL_ID,"sample",{durationMs:s,clearFirst:i===true},o);if(!a)return fail2("Device returned no snapshot \u2014 is @buoy-gg/js-top installed in the app?");const c=formatTopMarkdown(a,s);const l={busyPct:Math.round(a.busyPct*10)/10,freezeSummary:a.freezeSummary,tiers:a.tiers,rows:a.rows.slice(0,15).map(u=>({key:u.key,api:u.api,windowMs:Math.round(u.windowMs*10)/10,pctOfBusy:Math.round(u.pctOfBusy*10)/10,calls:u.calls,avgMs:Math.round(u.avgMs*100)/100,maxMs:Math.round(u.maxMs*10)/10,totalMs:Math.round(u.totalMs),freezes:u.freezes,worstFreezeMs:u.worstFreezeMs}))};return text(`${c}
|
|
772
957
|
|
|
773
958
|
\`\`\`json
|
|
774
|
-
${JSON.stringify(
|
|
775
|
-
\`\`\``)}catch(s){return fail2(errMsg2(s))}});e.registerTool("image_action",{description:"Request an action for a registered image ID: hard_reload, retry, evict_disk, flash, prove_savings or a supported simulation override. swap_url requires url; restore removes the override. Support depends on the component and platform. prove_savings attempts a WebP conversion at displayed size and reports available byte comparisons and a device-local URI; inspect visual quality and originalBytesSource before using the result. Other actions return an acknowledgement and, when available, a later record snapshot; that snapshot may precede load completion. A device-local URI is not necessarily accessible from the editor host.",inputSchema:{deviceId:deviceIdInput,id:import_zod29.z.number().describe("Record id from get_images."),action:import_zod29.z.enum(["hard_reload","retry","evict_disk","flash","prove_savings","force_error","force_loading","force_blank","swap_url","restore"]).describe("What to do."),url:import_zod29.z.string().optional().describe("Replacement URL (swap_url only).")}},async({deviceId:t,id:r,action:i,url:s})=>{try{const o=n.requireProDevice(t);if(i==="prove_savings"){const h=await n.callAction(IMAGES_TOOL_ID,"proveSavings",{id:r},o);if(!h)return fail2("Device returned nothing for proveSavings.");if(!h.ok)return fail2(h.message);const p=[`**prove_savings** on #${r}: ${h.message}`];if(h.originalBytes!=null)p.push(`Original: ${Math.round(h.originalBytes/1024)}KB (${h.originalBytesSource})`);if(h.optimizedBytes!=null)p.push(`Optimized: ${Math.round(h.optimizedBytes/1024)}KB \u2014 ${h.optimizedDims?.width}\xD7${h.optimizedDims?.height} WebP`);if(h.savedBytes!=null)p.push(`**Saved: ${Math.round(h.savedBytes/1024)}KB (${h.savedPct}%)**`);if(h.optimizedUri)p.push(`Preview in place: image_action {id:${r}, action:"swap_url", url:"${h.optimizedUri}"}`);return text(p.join("\n"))}const a=ACTION_MAP[i];if(!a)return fail2(`Unknown action: ${i}`);if(i==="swap_url"&&!s)return fail2("swap_url requires the `url` param.");const c=await n.callAction(IMAGES_TOOL_ID,a.action,{id:r,...a.params?.(s)??{}},o);const u=i==="flash"?0:1500;if(u>0)await new Promise(h=>setTimeout(h,u));const l=await n.callAction(IMAGES_TOOL_ID,"getDetail",{id:r},o).catch(()=>null);const d=[`**${i}** on #${r}: ${c?.message??(c?.ok===false?"failed":"done")}`];if(l){d.push("");d.push(`Now: status=${l.status}${l.errorCode?` (${l.errorCode})`:""} \xB7 cache=${cacheLabel(l)} \xB7 ms=${l.ms??"\u2013"} \xB7 loads=${l.loadCount}${l.overrideLabel?` \xB7 sim="${l.overrideLabel}"`:""}${l.mounted?"":" \xB7 UNMOUNTED"}`);if(l.error)d.push(`Error: ${l.error}`)}return text(d.join("\n"))}catch(o){return fail2(errMsg2(o))}});e.registerTool("set_image_simulation",{description:"Configure supported instrumented image loads: offline simulates network-load failures while bundled assets can still load; cold requests cache bypass; normal resets the network mode. Reload or remount existing images as needed. blankImages removes sources from integrated images; massAction targets registered mounted images. Can also clear the registry or supported Expo caches. These modes do not change device connectivity.",inputSchema:{deviceId:deviceIdInput,network:import_zod29.z.enum(["normal","offline","cold"]).optional().describe("Network simulation mode."),blankImages:import_zod29.z.boolean().optional().describe("Render integrated images without a source."),massAction:import_zod29.z.enum(["error","loading","blank","reload","flash","restore"]).optional().describe("Apply to registered mounted images: force error/loading/blank overrides, hard-reload all, flash all, or restore all overrides."),clearRegistry:import_zod29.z.boolean().optional().describe("Clear the captured image log."),clearExpoCaches:import_zod29.z.boolean().optional().describe("Clear expo-image memory + disk caches.")}},async({deviceId:t,network:r,blankImages:i,massAction:s,clearRegistry:o,clearExpoCaches:a})=>{try{const c=n.requireProDevice(t);const u=[];if(s){const l=await n.callAction(IMAGES_TOOL_ID,"massAction",{kind:s},c);u.push(l?.message??`mass ${s} applied`)}if(r){await n.callAction(IMAGES_TOOL_ID,"setNetworkMode",{mode:r},c);u.push(`network=${r}`)}if(i!=null){await n.callAction(IMAGES_TOOL_ID,"setBlankImages",{enabled:i},c);u.push(`blankImages=${i}`)}if(o){await n.callAction(IMAGES_TOOL_ID,"clearRecords",{},c);u.push("registry cleared")}if(a){const l=await n.callAction(IMAGES_TOOL_ID,"clearExpoCaches",{},c);u.push(l?.message??"expo caches cleared")}if(u.length===0)return fail2("Pass at least one of: network, blankImages, massAction, clearRegistry, clearExpoCaches.");return text(`Applied: ${u.join(" \xB7 ")}`)}catch(c){return fail2(errMsg2(c))}})}var import_zod29,IMAGES_TOOL_ID,ACTION_MAP;var init_images=__esm({"src/tools/packs/images.ts"(){"use strict";import_zod29=require("zod");init_packKit();IMAGES_TOOL_ID="images";ACTION_MAP={hard_reload:{action:"hardReload"},retry:{action:"retry"},evict_disk:{action:"evictDisk"},flash:{action:"flash"},restore:{action:"clearOverride"},force_error:{action:"setOverride",params:()=>({kind:"error"})},force_loading:{action:"setOverride",params:()=>({kind:"hang"})},force_blank:{action:"setOverride",params:()=>({kind:"blank"})},swap_url:{action:"setOverride",params:e=>({kind:"url",uri:e})}}}});function graphUnavailableNote(e){if(e.graphSupported&&e.graphCount!=null)return null;const n=(e.graphError??"").trim();const t=e.dev===true||!!n;if(t){return n?`\u26A0 Metro bundle graph unavailable (${n}) \u2014 showing runtime-registered assets only; never-loaded detection unavailable.`:"\u26A0 Metro bundle graph unavailable \u2014 showing runtime-registered assets only; never-loaded detection unavailable."}return"\u26A0 No Metro bundle graph (release build, or graph fetch failed) \u2014 showing runtime-registered assets only; never-loaded detection unavailable."}var init_assetsGraphNote=__esm({"src/tools/packs/assetsGraphNote.ts"(){"use strict"}});function kb2(e){if(e==null||e<=0)return"\u2013";if(e<1024)return`${e}B`;if(e<1024*1024)return`${(e/1024).toFixed(1)}KB`;return`${(e/(1024*1024)).toFixed(2)}MB`}function sizeLabel(e){if(e.sizeBytes==null)return"\u2013";return e.sizeSource==="measured"?kb2(e.sizeBytes):`~${kb2(e.sizeBytes)}`}function scalesLabel(e){if(!e.length)return"\u2013";return e.map(n=>`@${n}x`).join(" ")}function flagsLabel(e,n){const t=[];if(!e.loaded)t.push("UNUSED");if(n.overDecode.includes(e.id))t.push("OVERSIZE");if(n.duplicates.some(r=>r.ids.includes(e.id)))t.push("DUP");if(n.heavyGifs.includes(e.id)||n.heavyFonts.includes(e.id))t.push("HEAVY");if(n.scaleAnomalies.includes(e.id))t.push("BAD-SCALE");else if(n.scaleGaps.includes(e.id))t.push("LOW-RES");if(n.webpCandidates.includes(e.id))t.push("WEBP");return t.length?t.join(" "):"\u2013"}function formatListMarkdown2(e,n){const t=[];const r=e.stats;const i=e.scanStatus;t.push(`## Asset inventory (${e.total} assets, showing ${Math.min(n,e.records.length)}, largest first)`);t.push("");const s=Object.entries(r.byKind).filter(([,l])=>l.count>0).map(([l,d])=>`${d.count} ${l}${d.bytes>0?` (${kb2(d.bytes)})`:""}`);t.push(`${r.loaded} loaded \xB7 ${r.neverLoaded} never loaded \xB7 `+(r.totalBytes>0?`${kb2(r.totalBytes)} measured (${r.measuredCount}/${r.total})`:"sizes not measured")+` \xB7 ${s.join(" \xB7 ")}`);if(i.fontFamilies.length>0){t.push(`Loaded font families: ${i.fontFamilies.join(", ")}`)}const o=graphUnavailableNote(i);if(o)t.push(o);if(i.measuring)t.push("\u26A0 Size measurement in progress \u2014 byte totals are partial; re-run get_assets shortly.");const a=e.insights;const c=[];if(a.neverLoaded.length)c.push(`${a.neverLoaded.length} never loaded`);if(a.duplicates.length){const l=a.duplicates.reduce((d,h)=>d+(h.wastedBytes??0),0);c.push(`${a.duplicates.length} duplicate group(s)${l>0?` (${kb2(l)} wasted)`:""}`)}if(a.overDecode.length)c.push(`${a.overDecode.length} decode larger than 2\xD7 the screen`);if(a.webpCandidates.length)c.push(`${a.webpCandidates.length} WebP candidate(s)`);if(a.heavyGifs.length)c.push(`${a.heavyGifs.length} heavy GIF(s)`);if(a.heavyFonts.length)c.push(`${a.heavyFonts.length} heavy font(s)`);if(a.scaleGaps.length)c.push(`${a.scaleGaps.length} scale gap(s)`);if(a.scaleAnomalies.length)c.push(`${a.scaleAnomalies.length} scale anomaly(ies)`);if(c.length){t.push("");t.push(`**Findings:** ${c.join(" \xB7 ")}`)}const u=e.diff;if(u){const l=u.netBytes==null?"net unknown":Math.abs(u.netBytes)<1024?"\xB10 net":`${u.netBytes>=0?"+":"\u2212"}${kb2(Math.abs(u.netBytes))} net`;t.push("");t.push(`**Since baseline** (${new Date(u.baselineSavedAt).toISOString()}): ${u.added.length} added \xB7 ${u.removed.length} removed \xB7 ${u.grown.length} grew \xB7 ${l}`+(u.removed.length?` \u2014 removed: ${u.removed.slice(0,5).map(d=>`${d.name}.${d.type}`).join(", ")}${u.removed.length>5?"\u2026":""}`:""))}t.push("");t.push("| id | asset | kind | dims | scales | size | flags |");t.push("|---|---|---|---|---|---|---|");for(const l of e.records){const d=l.width!=null&&l.height!=null?`${Math.round(l.width)}\xD7${Math.round(l.height)}`:"\u2013";t.push(`| ${l.id} | ${l.name}.${l.type} | ${l.kind} | ${d} | ${scalesLabel(l.scales)} | ${sizeLabel(l)} | ${flagsLabel(l,a)} |`)}t.push("");t.push("_Sizes marked ~ are decoded-memory estimates (unmeasurable in this environment). Use `asset_action` for rescan / measure_sizes / detail / baseline ops._");return t.join("\n")}function registerAssetsTools(e,n){e.registerTool("get_assets",{description:"Inspect assets reported by the configured manifest, runtime registry and available Metro bundle graph. Includes available dimensions, scale coverage, byte sizes, observed load history, audit findings and saved-baseline differences. Size measurement and coverage depend on setup; not observed loading does not mean unused. Use get_images for instrumented runtime image loads. Requires @buoy-gg/assets on the device.",inputSchema:{deviceId:deviceIdInput,limit:import_zod30.z.number().optional().describe("Max records to return (largest first). Default 40, max 500."),kind:import_zod30.z.enum(["image","font","video","audio","data","other"]).optional().describe("Only assets of this kind."),unusedOnly:import_zod30.z.boolean().optional().describe("Only assets shipped in the bundle but never loaded at runtime.")}},async({deviceId:t,limit:r,kind:i,unusedOnly:s})=>{try{const o=n.requireProDevice(t);const a=Math.min(Math.max(r??40,1),500);const c=await n.callAction(ASSETS_TOOL_ID,"list",{limit:s?500:a,kind:i,loadedOnly:false},o);if(!c)return fail2("Device returned nothing \u2014 is @buoy-gg/assets installed in the app?");if(s){c.records=c.records.filter(d=>!d.loaded).slice(0,a)}const u=formatListMarkdown2(c,a);const l={stats:c.stats,scanStatus:c.scanStatus,insights:c.insights,diff:c.diff,records:c.records.map(d=>({id:d.id,name:d.name,type:d.type,kind:d.kind,hash:d.hash,width:d.width,height:d.height,scales:d.scales,loaded:d.loaded,sizeBytes:d.sizeBytes,sizeSource:d.sizeSource}))};return text(`${u}
|
|
959
|
+
${JSON.stringify(l)}
|
|
960
|
+
\`\`\``)}catch(o){return fail2(errMsg2(o))}});e.registerTool("get_js_thread_origin_detail",{description:'Inspect one js-top task origin in depth: schedules vs runs, avg/max/total exclusive ms, a 5s activity sparkline, freeze attribution, and the captured scheduling site (caller function + stack frames). Pass a row `key` from get_js_thread_top\'s JSON (e.g. "interval|pollFeed" or "unattributed" for the system row).',inputSchema:{deviceId:deviceIdInput,key:import_zod29.z.string().describe("Origin key from get_js_thread_top's JSON rows.")}},async({deviceId:t,key:r})=>{try{const i=n.requireProDevice(t);const o=await n.callAction(JS_TOP_TOOL_ID,"getOriginDetail",{key:r},i);if(!o){return fail2(`Origin "${r}" is not tracked (cleared, evicted, or never existed). Re-run get_js_thread_top for current keys.`)}const s=formatDetailMarkdown(o);return text(`${s}
|
|
961
|
+
|
|
962
|
+
\`\`\`json
|
|
963
|
+
${JSON.stringify(o)}
|
|
964
|
+
\`\`\``)}catch(i){return fail2(errMsg2(i))}});e.registerTool("clear_js_thread_stats",{description:"Reset the js-top task table, freeze history, and busy history on the device (fresh measurement window).",inputSchema:{deviceId:deviceIdInput}},async({deviceId:t})=>{try{const r=n.requireProDevice(t);await n.callAction(JS_TOP_TOOL_ID,"clear",{},r);return text("Cleared js-top stats.")}catch(r){return fail2(errMsg2(r))}})}var import_zod29,JS_TOP_TOOL_ID,SPARK_CHARS;var init_jsThread=__esm({"src/tools/packs/jsThread.ts"(){"use strict";import_zod29=require("zod");init_packKit();JS_TOP_TOOL_ID="js-top";SPARK_CHARS="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588"}});function uriTail(e){if(!e)return"(no source)";const n=e.match(/[?&]unstable_path=([^&?]+)/);const t=n?decodeURIComponent(n[1]):e;const r=t.split("?")[0]??t;const i=r.split("/").filter(Boolean);return i[i.length-1]??t}function verdictLabel(e){if(e.oversizeFactor==null)return"\u2013";if(e.oversizeFactor<.9)return`${e.oversizeFactor.toFixed(1)}\xD7 upscaled`;if(e.oversizeFactor<=1.1)return"right-sized";return`${e.oversizeFactor.toFixed(1)}\xD7 oversized (${e.wastedKB}KB wasted)`}function cacheLabel(e){if(e.cache)return e.cache;if(e.progressSeen)return"network";return"?"}function mb(e){return`${(e/(1024*1024)).toFixed(1)}MB`}function formatListMarkdown(e,n){const t=[];const r=e.stats;t.push(`## Images registry (${e.total} records, showing ${Math.min(n,e.records.length)})`);t.push("");t.push(`${r.loaded} loaded \xB7 ${r.errors} failed \xB7 ${r.loading} in flight \xB7 \u2248${mb(r.estDecodedBytes)} decoded`+(r.estWastedBytes>0?` \xB7 **${mb(r.estWastedBytes)} wasted on oversized sources**`:""));const i=e.insights;if(i){const s=[];if(i.duplicates.length>0)s.push(`${i.duplicates.length} duplicate URL(s): ${i.duplicates.slice(0,3).map(a=>`${uriTail(a.uri)}\xD7${a.count}`).join(", ")}`);if(i.retryStorms.length>0)s.push(`${i.retryStorms.length} retry storm(s): ${i.retryStorms.slice(0,3).map(a=>`#${a.id}(${a.loadCount} loads)`).join(", ")}`);if(i.queueSaturated)s.push("iOS image queue saturated (>4 concurrent loads)");if(i.missingAlt>0)s.push(`${i.missingAlt} image(s) missing alt/accessibilityLabel`);if(i.layoutShifters.length>0)s.push(`${i.layoutShifters.length} layout-shifting image(s): ${i.layoutShifters.slice(0,3).map(a=>`#${a.id}`).join(", ")} \u2014 reserve explicit dimensions`);if(s.length>0){t.push("");t.push(`**Insights:** ${s.join(" \xB7 ")}`)}}const o=e.captureStatus;if(o.rnDecoratorTooLate){t.push("");t.push('\u26A0 RN <Image> capture missed the module-load race \u2014 add `import "@buoy-gg/images/register"` as the FIRST import of the app entry file.')}if(e.globalModes.network!=="normal"||e.globalModes.blank){t.push("");t.push(`\u26A0 Simulation active: network=${e.globalModes.network}${e.globalModes.blank?", blank images ON":""} (set_image_simulation to reset).`)}t.push("");t.push("| id | image | lib | status | cache | ms | decoded px | shown dp | verdict | sim |");t.push("|---|---|---|---|---|---|---|---|---|---|");for(const s of e.records){const a=s.intrinsic?`${s.intrinsic.width}\xD7${s.intrinsic.height}`:"\u2013";const c=s.layout?`${s.layout.width}\xD7${s.layout.height}`:"\u2013";const l=s.status==="error"?`**error**${s.errorCode?` (${s.errorCode})`:""}`:s.status;t.push(`| ${s.id} | ${uriTail(s.uri)} | ${s.lib} | ${l}${s.mounted?"":" (unmounted)"} | ${cacheLabel(s)} | ${s.ms??"\u2013"} | ${a} | ${c} | ${verdictLabel(s)} | ${s.overrideLabel??"\u2013"} |`)}t.push("");t.push("_Act on a row with `image_action` using its `id` (hard_reload / retry / force_error / force_loading / force_blank / swap_url / flash / restore / evict_disk)._");return t.join("\n")}function registerImagesTools(e,n){e.registerTool("get_images",{description:"Inspect image loads reported through the Buoy image integration, including available cache origin, load timing, size estimates, errors and simulation overrides. Coverage depends on instrumented components and platform support. Requires @buoy-gg/images on the device.",inputSchema:{deviceId:deviceIdInput,limit:import_zod30.z.number().optional().describe("Max records to return (newest first). Default 30, max 200."),status:import_zod30.z.enum(["pending","loading","loaded","error"]).optional().describe("Only records in this state (e.g. 'error' for the failure log).")}},async({deviceId:t,limit:r,status:i})=>{try{const o=n.requireProDevice(t);const s=Math.min(Math.max(r??30,1),200);const a=await n.callAction(IMAGES_TOOL_ID,"list",{limit:s,status:i},o);if(!a)return fail2("Device returned nothing \u2014 is @buoy-gg/images installed in the app?");const c=formatListMarkdown(a,s);const l={stats:a.stats,insights:a.insights,captureStatus:a.captureStatus,globalModes:a.globalModes,records:a.records.map(u=>({id:u.id,uri:u.uri,lib:u.lib,status:u.status,mounted:u.mounted,cache:u.cache,ms:u.ms,intrinsic:u.intrinsic,layout:u.layout,oversizeFactor:u.oversizeFactor,wastedKB:u.wastedKB,error:u.error,errorCode:u.errorCode,overrideLabel:u.overrideLabel,loadCount:u.loadCount,hasAltText:u.hasAltText,layoutShifts:u.layoutShifts}))};return text(`${c}
|
|
776
965
|
|
|
777
966
|
\`\`\`json
|
|
778
967
|
${JSON.stringify(l)}
|
|
779
|
-
\`\`\``)}catch(o){return fail2(errMsg2(o))}});e.registerTool("asset_action",{description:"Drive the assets tool: rescan (re-walk the registry + merge the Metro bundle graph + refresh fonts + measure sizes \u2014 run this first if the inventory looks stale or empty), measure_sizes (re-measure byte sizes only), detail (full metadata for one asset by id: source dir, per-scale sizes, resolved URI, per-file graph paths), save_baseline (persist the current inventory for before/after comparison \u2014 save, make your change, then get_assets shows added/removed/grown/net bytes), clear_baseline, clear_records (wipe + rescan rebuilds).",inputSchema:{deviceId:deviceIdInput,action:import_zod30.z.enum(["rescan","measure_sizes","detail","save_baseline","clear_baseline","clear_records"]).describe("What to do."),id:import_zod30.z.number().optional().describe("Asset id from get_assets (detail only).")}},async({deviceId:t,action:r,id:i})=>{try{const s=n.requireProDevice(t);switch(r){case"rescan":{const o=await n.callAction(ASSETS_TOOL_ID,"rescan",{},s);const a=o?.scanStatus;if(!a)return fail2("Device returned nothing for rescan.");return text(`Rescan done: ${a.registryCount} registered at runtime`+(a.graphCount!=null?` \xB7 ${a.graphCount} in the bundle graph`:" \xB7 no bundle graph")+(a.graphError?` (graph: ${a.graphError})`:"")+` \xB7 ${a.fontFamilies.length} font families`+(a.measuring?" \xB7 size measurement running \u2014 get_assets in a moment":""))}case"measure_sizes":{const o=await n.callAction(ASSETS_TOOL_ID,"measureSizes",{},s);return text(`Measured ${o?.measured??0} of ${o?.total??0} assets.`)}case"detail":{if(i==null)return fail2("detail requires the `id` param (from get_assets).");const o=await n.callAction(ASSETS_TOOL_ID,"getDetail",{id:i},s);if(!o)return fail2(`Asset ${i} not found \u2014 re-run get_assets for current ids.`);const a=[`## ${o.name}.${o.type} (#${o.id})`,"",`- Kind: ${o.kind} \xB7 ${o.loaded?"loaded at runtime":"in bundle, NEVER loaded"} (${o.origin})`];if(o.width!=null)a.push(`- Dimensions: ${o.width}\xD7${o.height} logical \xB7 scales ${scalesLabel(o.scales)}`);if(o.sizesByScale){for(const[c,u]of Object.entries(o.sizesByScale)){a.push(`- Size @${c}x: ${kb2(u)}`)}}if(o.sizeBytes!=null)a.push(`- Total: ${sizeLabel(o)}`);if(o.estDecodedBytes)a.push(`- Decoded memory: ~${kb2(o.estDecodedBytes)} (RGBA)`);if(o.hash)a.push(`- Hash: ${o.hash}`);if(o.fileSystemLocation)a.push(`- Source dir: ${o.fileSystemLocation}`);if(o.files?.length)a.push(`- Files: ${o.files.join(", ")}`);if(o.uri)a.push(`- Resolved URI: ${o.uri}`);return text(a.join("\n"))}case"save_baseline":{const o=await n.callAction(ASSETS_TOOL_ID,"saveBaseline",{},s);return text(`Baseline saved (${o?.assets??0} assets). Make your change, then get_assets reports added/removed/grown/net bytes against it.`)}case"clear_baseline":{await n.callAction(ASSETS_TOOL_ID,"clearBaseline",{},s);return text("Baseline cleared.")}case"clear_records":{const o=await n.callAction(ASSETS_TOOL_ID,"clearRecords",{},s);return text(o?.message??"Inventory cleared.")}}}catch(s){return fail2(errMsg2(s))}})}var import_zod30,ASSETS_TOOL_ID;var init_assets=__esm({"src/tools/packs/assets.ts"(){"use strict";import_zod30=require("zod");init_packKit();init_assetsGraphNote();ASSETS_TOOL_ID="assets"}});function messageSocketUrl(e){return`${e.replace(/^http/,"ws").replace(/\/+$/,"")}/message`}function reloadViaDevServer(e){return new Promise(n=>{let t=false;const r=a=>{if(t)return;t=true;n(a)};let i;try{i=new import_ws2.WebSocket(messageSocketUrl(e))}catch(a){r({ok:false,error:a.message});return}const s=setTimeout(()=>{try{i.close()}catch{}r({ok:false,error:`dev server at ${e} did not accept a connection`})},CONNECT_TIMEOUT_MS);let o=false;i.on("open",()=>{try{i.send(JSON.stringify({version:2,method:"reload"}));o=true;clearTimeout(s);setTimeout(()=>{try{i.close()}catch{}r({ok:true})},250)}catch(a){clearTimeout(s);r({ok:false,error:a.message})}});i.on("error",a=>{clearTimeout(s);if(o)return;r({ok:false,error:a.message})})})}var import_ws2,CONNECT_TIMEOUT_MS;var init_devServerReload=__esm({"src/capture/devServerReload.ts"(){"use strict";import_ws2=require("ws");CONNECT_TIMEOUT_MS=3e3}});async function ping(e,n,t){try{const r=await e.callAction(APP_TOOL_ID,"ping",{},n,{timeoutMs:t,silent:true});e.noteDevServerOrigin(n,r?.devServerOrigin);return typeof r?.startedAt==="number"?r.startedAt:null}catch{return null}}function assertReloadSupported(e,n){if(n===ALL_DEVICES)return;const t=e.toolActions(APP_TOOL_ID).find(r=>r.deviceId===n);if(!t?.actions.includes(RELOAD_ACTION)){throw new Error(`This app doesn't expose remote reload \u2014 its @buoy-gg/core is too old. Upgrade @buoy-gg/core, then reload the app once by hand.`)}}async function waitForAppBack(e,n,t,r){const i=Date.now();await delay5(TEARDOWN_GRACE_MS);while(Date.now()-i<t){const s=await ping(e,n,PROBE_TIMEOUT_MS);if(s!==null&&s!==r)return Date.now()-i;await delay5(PROBE_INTERVAL_MS)}return null}function offlineDeviceId(e){if(!/is not connected right now/.test(e))return null;return/"([^"]+)"/.exec(e)?.[1]??null}async function reloadOffline(e,n,t,r){const i=offlineDeviceId(errMsg2(n));if(!i||!e.listDevices().some(l=>l.deviceId===i&&l.isPro))throw n;const s=e.devServerOrigin(i);let o="";if(s){const l=await reloadViaDevServer(s);if(l.ok){if(!r)return text(`"${i}" was not connected, so it was reloaded through its dev server (${s}). It is restarting.`);const d=await waitForAppBack(e,i,Math.min(t,12e3),null);if(d!=null){return text(`"${i}" was not connected, so it was reloaded through its dev server. Back after ${(d/1e3).toFixed(1)}s. All in-memory state was reset.`)}o=` Its dev server (${s}) took the reload, but the app did not come back.`}else{o=` Its dev server at ${s} could not reload it: ${l.error}.`}}const a=e.listDevices().find(l=>l.deviceId===i)?.platform;const c=rememberedHost(i);const u=c?await verifyHost(i,c).catch(()=>void 0):await findHost(i,a).catch(()=>void 0);if(u){try{await hostQuit(u).catch(()=>void 0);await hostLaunch(u);if(!r)return text(`"${i}" was not connected, so it was relaunched on its ${u.platform==="ios"?"simulator":"device"}.`);const l=await waitForAppBack(e,i,t,null);if(l!=null){return text(`"${i}" was not connected, so it was relaunched on its ${u.platform==="ios"?"simulator":"device"} (a cold start). Back after ${(l/1e3).toFixed(1)}s. All in-memory state was reset.`)}}catch{}}return fail2(`"${i}" is not connected and could not be brought back.${o} Open the app by hand, then run list_devices.`)}function registerReloadTools(e,n){e.registerTool("reload_app",{description:"Request a JS reload for a supported app using DevSettings in development or installed expo-updates where available. For an unresponsive app, can try its known dev server when reachable. Recovery is not guaranteed. Reload can discard in-memory state and evidence; collect needed observations first when possible. By default waits for reconnection up to timeoutMs. Requires configured @buoy-gg/core support and Buoy Pro.",inputSchema:{strategy:import_zod31.z.enum(["auto","dev-settings","expo-updates"]).optional().describe("Reload mechanism. 'auto' (default) uses DevSettings in dev builds and expo-updates otherwise. Force one only when debugging the reload itself."),wait:import_zod31.z.boolean().optional().describe("Wait for the app to come back before returning. Default true \u2014 turn off for fire-and-forget."),timeoutMs:import_zod31.z.number().optional().describe("How long to wait for the app to reconnect, in ms. Default 30000."),deviceId:import_zod31.z.string().optional().describe('The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out. Or "All" to reload every connected app.')}},async t=>{try{let r;try{r=n.requireProDevice(t.deviceId)}catch(l){return await reloadOffline(n,l,t.timeoutMs??DEFAULT_WAIT_MS,t.wait!==false)}assertReloadSupported(n,r);const i=t.wait===false?null:await ping(n,r,PROBE_TIMEOUT_MS);let s=null;let o=false;const a=async l=>{const d=n.devServerOrigin(r);if(!d){if(l)throw l;throw new Error("The app is not answering and no dev-server origin is known (it was never learned from a successful ping). Reload the app by hand.")}const h=await reloadViaDevServer(d);if(!h.ok){throw new Error(`The app is not answering (it looks crashed) and the dev server at ${d} could not be reached either: ${h.error}. Reload the app by hand.`)}o=true};if(n.isUnresponsive(r)&&n.devServerOrigin(r)){await a()}else{try{s=await n.callAction(APP_TOOL_ID,RELOAD_ACTION,{strategy:t.strategy??"auto"},r)}catch(l){await a(l)}}const c=o?` via the dev server (the app was unresponsive \u2014 its own reload could not be reached)`:s?.strategy?` via ${s.strategy}`:"";if(t.wait===false){return text(`Reload requested${c}. The app is restarting \u2014 its in-memory state is gone; re-read anything you cached.`)}const u=await waitForAppBack(n,r,t.timeoutMs??DEFAULT_WAIT_MS,i);if(u==null){return fail2(`Reload was accepted${c}, but the app hasn't reconnected yet. It may still be building the bundle (a cold Metro rebuild can take a while) \u2014 check the device, then run list_devices.`)}return text(`Reloaded the app${c} \u2014 back and connected after ${(u/1e3).toFixed(1)}s. All in-memory state was reset, so re-read any state you cached before this.`)}catch(r){return fail2(errMsg2(r))}})}var import_zod31,APP_TOOL_ID,RELOAD_ACTION,DEFAULT_WAIT_MS,TEARDOWN_GRACE_MS,PROBE_TIMEOUT_MS,PROBE_INTERVAL_MS,delay5;var init_reload=__esm({"src/tools/packs/reload.ts"(){"use strict";import_zod31=require("zod");init_packKit();init_devServerReload();init_config();init_hostDevice();APP_TOOL_ID="app";RELOAD_ACTION="reloadApp";DEFAULT_WAIT_MS=3e4;TEARDOWN_GRACE_MS=1200;PROBE_TIMEOUT_MS=1500;PROBE_INTERVAL_MS=400;delay5=e=>new Promise(n=>setTimeout(n,e))}});function hhmmss3(e){if(!e)return"--:--:--";const n=new Date(e);const t=r=>String(r).padStart(2,"0");return`${t(n.getHours())}:${t(n.getMinutes())}:${t(n.getSeconds())}`}async function otherBackends(e,n,t){const r=[];try{const i=await e.callAction("storage","mmkv.snapshot",{},n,t);for(const s of i??[]){const o=s.entries?.length??0;if(o>0)r.push(`MMKV "${s.id}": ${o} key${o===1?"":"s"}`)}}catch{}try{const i=await e.callAction("storage","secure.keys",{},n,t);if(i?.length)r.push(`SecureStore: ${i.length} key${i.length===1?"":"s"}`)}catch{}return r.length?`
|
|
968
|
+
\`\`\``)}catch(o){return fail2(errMsg2(o))}});e.registerTool("image_action",{description:"Request an action for a registered image ID: hard_reload, retry, evict_disk, flash, prove_savings or a supported simulation override. swap_url requires url; restore removes the override. Support depends on the component and platform. prove_savings attempts a WebP conversion at displayed size and reports available byte comparisons and a device-local URI; inspect visual quality and originalBytesSource before using the result. Other actions return an acknowledgement and, when available, a later record snapshot; that snapshot may precede load completion. A device-local URI is not necessarily accessible from the editor host.",inputSchema:{deviceId:deviceIdInput,id:import_zod30.z.number().describe("Record id from get_images."),action:import_zod30.z.enum(["hard_reload","retry","evict_disk","flash","prove_savings","force_error","force_loading","force_blank","swap_url","restore"]).describe("What to do."),url:import_zod30.z.string().optional().describe("Replacement URL (swap_url only).")}},async({deviceId:t,id:r,action:i,url:o})=>{try{const s=n.requireProDevice(t);if(i==="prove_savings"){const h=await n.callAction(IMAGES_TOOL_ID,"proveSavings",{id:r},s);if(!h)return fail2("Device returned nothing for proveSavings.");if(!h.ok)return fail2(h.message);const w=[`**prove_savings** on #${r}: ${h.message}`];if(h.originalBytes!=null)w.push(`Original: ${Math.round(h.originalBytes/1024)}KB (${h.originalBytesSource})`);if(h.optimizedBytes!=null)w.push(`Optimized: ${Math.round(h.optimizedBytes/1024)}KB \u2014 ${h.optimizedDims?.width}\xD7${h.optimizedDims?.height} WebP`);if(h.savedBytes!=null)w.push(`**Saved: ${Math.round(h.savedBytes/1024)}KB (${h.savedPct}%)**`);if(h.optimizedUri)w.push(`Preview in place: image_action {id:${r}, action:"swap_url", url:"${h.optimizedUri}"}`);return text(w.join("\n"))}const a=ACTION_MAP[i];if(!a)return fail2(`Unknown action: ${i}`);if(i==="swap_url"&&!o)return fail2("swap_url requires the `url` param.");const c=await n.callAction(IMAGES_TOOL_ID,a.action,{id:r,...a.params?.(o)??{}},s);const l=i==="flash"?0:1500;if(l>0)await new Promise(h=>setTimeout(h,l));const u=await n.callAction(IMAGES_TOOL_ID,"getDetail",{id:r},s).catch(()=>null);const d=[`**${i}** on #${r}: ${c?.message??(c?.ok===false?"failed":"done")}`];if(u){d.push("");d.push(`Now: status=${u.status}${u.errorCode?` (${u.errorCode})`:""} \xB7 cache=${cacheLabel(u)} \xB7 ms=${u.ms??"\u2013"} \xB7 loads=${u.loadCount}${u.overrideLabel?` \xB7 sim="${u.overrideLabel}"`:""}${u.mounted?"":" \xB7 UNMOUNTED"}`);if(u.error)d.push(`Error: ${u.error}`)}return text(d.join("\n"))}catch(s){return fail2(errMsg2(s))}});e.registerTool("set_image_simulation",{description:"Configure supported instrumented image loads: offline simulates network-load failures while bundled assets can still load; cold requests cache bypass; normal resets the network mode. Reload or remount existing images as needed. blankImages removes sources from integrated images; massAction targets registered mounted images. Can also clear the registry or supported Expo caches. These modes do not change device connectivity.",inputSchema:{deviceId:deviceIdInput,network:import_zod30.z.enum(["normal","offline","cold"]).optional().describe("Network simulation mode."),blankImages:import_zod30.z.boolean().optional().describe("Render integrated images without a source."),massAction:import_zod30.z.enum(["error","loading","blank","reload","flash","restore"]).optional().describe("Apply to registered mounted images: force error/loading/blank overrides, hard-reload all, flash all, or restore all overrides."),clearRegistry:import_zod30.z.boolean().optional().describe("Clear the captured image log."),clearExpoCaches:import_zod30.z.boolean().optional().describe("Clear expo-image memory + disk caches.")}},async({deviceId:t,network:r,blankImages:i,massAction:o,clearRegistry:s,clearExpoCaches:a})=>{try{const c=n.requireProDevice(t);const l=[];if(o){const u=await n.callAction(IMAGES_TOOL_ID,"massAction",{kind:o},c);l.push(u?.message??`mass ${o} applied`)}if(r){await n.callAction(IMAGES_TOOL_ID,"setNetworkMode",{mode:r},c);l.push(`network=${r}`)}if(i!=null){await n.callAction(IMAGES_TOOL_ID,"setBlankImages",{enabled:i},c);l.push(`blankImages=${i}`)}if(s){await n.callAction(IMAGES_TOOL_ID,"clearRecords",{},c);l.push("registry cleared")}if(a){const u=await n.callAction(IMAGES_TOOL_ID,"clearExpoCaches",{},c);l.push(u?.message??"expo caches cleared")}if(l.length===0)return fail2("Pass at least one of: network, blankImages, massAction, clearRegistry, clearExpoCaches.");return text(`Applied: ${l.join(" \xB7 ")}`)}catch(c){return fail2(errMsg2(c))}})}var import_zod30,IMAGES_TOOL_ID,ACTION_MAP;var init_images=__esm({"src/tools/packs/images.ts"(){"use strict";import_zod30=require("zod");init_packKit();IMAGES_TOOL_ID="images";ACTION_MAP={hard_reload:{action:"hardReload"},retry:{action:"retry"},evict_disk:{action:"evictDisk"},flash:{action:"flash"},restore:{action:"clearOverride"},force_error:{action:"setOverride",params:()=>({kind:"error"})},force_loading:{action:"setOverride",params:()=>({kind:"hang"})},force_blank:{action:"setOverride",params:()=>({kind:"blank"})},swap_url:{action:"setOverride",params:e=>({kind:"url",uri:e})}}}});function graphUnavailableNote(e){if(e.graphSupported&&e.graphCount!=null)return null;const n=(e.graphError??"").trim();const t=e.dev===true||!!n;if(t){return n?`\u26A0 Metro bundle graph unavailable (${n}) \u2014 showing runtime-registered assets only; never-loaded detection unavailable.`:"\u26A0 Metro bundle graph unavailable \u2014 showing runtime-registered assets only; never-loaded detection unavailable."}return"\u26A0 No Metro bundle graph (release build, or graph fetch failed) \u2014 showing runtime-registered assets only; never-loaded detection unavailable."}var init_assetsGraphNote=__esm({"src/tools/packs/assetsGraphNote.ts"(){"use strict"}});function kb2(e){if(e==null||e<=0)return"\u2013";if(e<1024)return`${e}B`;if(e<1024*1024)return`${(e/1024).toFixed(1)}KB`;return`${(e/(1024*1024)).toFixed(2)}MB`}function sizeLabel(e){if(e.sizeBytes==null)return"\u2013";return e.sizeSource==="measured"?kb2(e.sizeBytes):`~${kb2(e.sizeBytes)}`}function scalesLabel(e){if(!e.length)return"\u2013";return e.map(n=>`@${n}x`).join(" ")}function flagsLabel(e,n){const t=[];if(!e.loaded)t.push("UNUSED");if(n.overDecode.includes(e.id))t.push("OVERSIZE");if(n.duplicates.some(r=>r.ids.includes(e.id)))t.push("DUP");if(n.heavyGifs.includes(e.id)||n.heavyFonts.includes(e.id))t.push("HEAVY");if(n.scaleAnomalies.includes(e.id))t.push("BAD-SCALE");else if(n.scaleGaps.includes(e.id))t.push("LOW-RES");if(n.webpCandidates.includes(e.id))t.push("WEBP");return t.length?t.join(" "):"\u2013"}function formatListMarkdown2(e,n){const t=[];const r=e.stats;const i=e.scanStatus;t.push(`## Asset inventory (${e.total} assets, showing ${Math.min(n,e.records.length)}, largest first)`);t.push("");const o=Object.entries(r.byKind).filter(([,u])=>u.count>0).map(([u,d])=>`${d.count} ${u}${d.bytes>0?` (${kb2(d.bytes)})`:""}`);t.push(`${r.loaded} loaded \xB7 ${r.neverLoaded} never loaded \xB7 `+(r.totalBytes>0?`${kb2(r.totalBytes)} measured (${r.measuredCount}/${r.total})`:"sizes not measured")+` \xB7 ${o.join(" \xB7 ")}`);if(i.fontFamilies.length>0){t.push(`Loaded font families: ${i.fontFamilies.join(", ")}`)}const s=graphUnavailableNote(i);if(s)t.push(s);if(i.measuring)t.push("\u26A0 Size measurement in progress \u2014 byte totals are partial; re-run get_assets shortly.");const a=e.insights;const c=[];if(a.neverLoaded.length)c.push(`${a.neverLoaded.length} never loaded`);if(a.duplicates.length){const u=a.duplicates.reduce((d,h)=>d+(h.wastedBytes??0),0);c.push(`${a.duplicates.length} duplicate group(s)${u>0?` (${kb2(u)} wasted)`:""}`)}if(a.overDecode.length)c.push(`${a.overDecode.length} decode larger than 2\xD7 the screen`);if(a.webpCandidates.length)c.push(`${a.webpCandidates.length} WebP candidate(s)`);if(a.heavyGifs.length)c.push(`${a.heavyGifs.length} heavy GIF(s)`);if(a.heavyFonts.length)c.push(`${a.heavyFonts.length} heavy font(s)`);if(a.scaleGaps.length)c.push(`${a.scaleGaps.length} scale gap(s)`);if(a.scaleAnomalies.length)c.push(`${a.scaleAnomalies.length} scale anomaly(ies)`);if(c.length){t.push("");t.push(`**Findings:** ${c.join(" \xB7 ")}`)}const l=e.diff;if(l){const u=l.netBytes==null?"net unknown":Math.abs(l.netBytes)<1024?"\xB10 net":`${l.netBytes>=0?"+":"\u2212"}${kb2(Math.abs(l.netBytes))} net`;t.push("");t.push(`**Since baseline** (${new Date(l.baselineSavedAt).toISOString()}): ${l.added.length} added \xB7 ${l.removed.length} removed \xB7 ${l.grown.length} grew \xB7 ${u}`+(l.removed.length?` \u2014 removed: ${l.removed.slice(0,5).map(d=>`${d.name}.${d.type}`).join(", ")}${l.removed.length>5?"\u2026":""}`:""))}t.push("");t.push("| id | asset | kind | dims | scales | size | flags |");t.push("|---|---|---|---|---|---|---|");for(const u of e.records){const d=u.width!=null&&u.height!=null?`${Math.round(u.width)}\xD7${Math.round(u.height)}`:"\u2013";t.push(`| ${u.id} | ${u.name}.${u.type} | ${u.kind} | ${d} | ${scalesLabel(u.scales)} | ${sizeLabel(u)} | ${flagsLabel(u,a)} |`)}t.push("");t.push("_Sizes marked ~ are decoded-memory estimates (unmeasurable in this environment). Use `asset_action` for rescan / measure_sizes / detail / baseline ops._");return t.join("\n")}function registerAssetsTools(e,n){e.registerTool("get_assets",{description:"Inspect assets reported by the configured manifest, runtime registry and available Metro bundle graph. Includes available dimensions, scale coverage, byte sizes, observed load history, audit findings and saved-baseline differences. Size measurement and coverage depend on setup; not observed loading does not mean unused. Use get_images for instrumented runtime image loads. Requires @buoy-gg/assets on the device.",inputSchema:{deviceId:deviceIdInput,limit:import_zod31.z.number().optional().describe("Max records to return (largest first). Default 40, max 500."),kind:import_zod31.z.enum(["image","font","video","audio","data","other"]).optional().describe("Only assets of this kind."),unusedOnly:import_zod31.z.boolean().optional().describe("Only assets shipped in the bundle but never loaded at runtime.")}},async({deviceId:t,limit:r,kind:i,unusedOnly:o})=>{try{const s=n.requireProDevice(t);const a=Math.min(Math.max(r??40,1),500);const c=await n.callAction(ASSETS_TOOL_ID,"list",{limit:o?500:a,kind:i,loadedOnly:false},s);if(!c)return fail2("Device returned nothing \u2014 is @buoy-gg/assets installed in the app?");if(o){c.records=c.records.filter(d=>!d.loaded).slice(0,a)}const l=formatListMarkdown2(c,a);const u={stats:c.stats,scanStatus:c.scanStatus,insights:c.insights,diff:c.diff,records:c.records.map(d=>({id:d.id,name:d.name,type:d.type,kind:d.kind,hash:d.hash,width:d.width,height:d.height,scales:d.scales,loaded:d.loaded,sizeBytes:d.sizeBytes,sizeSource:d.sizeSource}))};return text(`${l}
|
|
969
|
+
|
|
970
|
+
\`\`\`json
|
|
971
|
+
${JSON.stringify(u)}
|
|
972
|
+
\`\`\``)}catch(s){return fail2(errMsg2(s))}});e.registerTool("asset_action",{description:"Drive the assets tool: rescan (re-walk the registry + merge the Metro bundle graph + refresh fonts + measure sizes \u2014 run this first if the inventory looks stale or empty), measure_sizes (re-measure byte sizes only), detail (full metadata for one asset by id: source dir, per-scale sizes, resolved URI, per-file graph paths), save_baseline (persist the current inventory for before/after comparison \u2014 save, make your change, then get_assets shows added/removed/grown/net bytes), clear_baseline, clear_records (wipe + rescan rebuilds).",inputSchema:{deviceId:deviceIdInput,action:import_zod31.z.enum(["rescan","measure_sizes","detail","save_baseline","clear_baseline","clear_records"]).describe("What to do."),id:import_zod31.z.number().optional().describe("Asset id from get_assets (detail only).")}},async({deviceId:t,action:r,id:i})=>{try{const o=n.requireProDevice(t);switch(r){case"rescan":{const s=await n.callAction(ASSETS_TOOL_ID,"rescan",{},o);const a=s?.scanStatus;if(!a)return fail2("Device returned nothing for rescan.");return text(`Rescan done: ${a.registryCount} registered at runtime`+(a.graphCount!=null?` \xB7 ${a.graphCount} in the bundle graph`:" \xB7 no bundle graph")+(a.graphError?` (graph: ${a.graphError})`:"")+` \xB7 ${a.fontFamilies.length} font families`+(a.measuring?" \xB7 size measurement running \u2014 get_assets in a moment":""))}case"measure_sizes":{const s=await n.callAction(ASSETS_TOOL_ID,"measureSizes",{},o);return text(`Measured ${s?.measured??0} of ${s?.total??0} assets.`)}case"detail":{if(i==null)return fail2("detail requires the `id` param (from get_assets).");const s=await n.callAction(ASSETS_TOOL_ID,"getDetail",{id:i},o);if(!s)return fail2(`Asset ${i} not found \u2014 re-run get_assets for current ids.`);const a=[`## ${s.name}.${s.type} (#${s.id})`,"",`- Kind: ${s.kind} \xB7 ${s.loaded?"loaded at runtime":"in bundle, NEVER loaded"} (${s.origin})`];if(s.width!=null)a.push(`- Dimensions: ${s.width}\xD7${s.height} logical \xB7 scales ${scalesLabel(s.scales)}`);if(s.sizesByScale){for(const[c,l]of Object.entries(s.sizesByScale)){a.push(`- Size @${c}x: ${kb2(l)}`)}}if(s.sizeBytes!=null)a.push(`- Total: ${sizeLabel(s)}`);if(s.estDecodedBytes)a.push(`- Decoded memory: ~${kb2(s.estDecodedBytes)} (RGBA)`);if(s.hash)a.push(`- Hash: ${s.hash}`);if(s.fileSystemLocation)a.push(`- Source dir: ${s.fileSystemLocation}`);if(s.files?.length)a.push(`- Files: ${s.files.join(", ")}`);if(s.uri)a.push(`- Resolved URI: ${s.uri}`);return text(a.join("\n"))}case"save_baseline":{const s=await n.callAction(ASSETS_TOOL_ID,"saveBaseline",{},o);return text(`Baseline saved (${s?.assets??0} assets). Make your change, then get_assets reports added/removed/grown/net bytes against it.`)}case"clear_baseline":{await n.callAction(ASSETS_TOOL_ID,"clearBaseline",{},o);return text("Baseline cleared.")}case"clear_records":{const s=await n.callAction(ASSETS_TOOL_ID,"clearRecords",{},o);return text(s?.message??"Inventory cleared.")}}}catch(o){return fail2(errMsg2(o))}})}var import_zod31,ASSETS_TOOL_ID;var init_assets=__esm({"src/tools/packs/assets.ts"(){"use strict";import_zod31=require("zod");init_packKit();init_assetsGraphNote();ASSETS_TOOL_ID="assets"}});function messageSocketUrl(e){return`${e.replace(/^http/,"ws").replace(/\/+$/,"")}/message`}function reloadViaDevServer(e){return new Promise(n=>{let t=false;const r=a=>{if(t)return;t=true;n(a)};let i;try{i=new import_ws2.WebSocket(messageSocketUrl(e))}catch(a){r({ok:false,error:a.message});return}const o=setTimeout(()=>{try{i.close()}catch{}r({ok:false,error:`dev server at ${e} did not accept a connection`})},CONNECT_TIMEOUT_MS);let s=false;i.on("open",()=>{try{i.send(JSON.stringify({version:2,method:"reload"}));s=true;clearTimeout(o);setTimeout(()=>{try{i.close()}catch{}r({ok:true})},250)}catch(a){clearTimeout(o);r({ok:false,error:a.message})}});i.on("error",a=>{clearTimeout(o);if(s)return;r({ok:false,error:a.message})})})}var import_ws2,CONNECT_TIMEOUT_MS;var init_devServerReload=__esm({"src/capture/devServerReload.ts"(){"use strict";import_ws2=require("ws");CONNECT_TIMEOUT_MS=3e3}});async function ping(e,n,t){try{const r=await e.callAction(APP_TOOL_ID2,"ping",{},n,{timeoutMs:t,silent:true});e.noteDevServerOrigin(n,r?.devServerOrigin);return typeof r?.startedAt==="number"?r.startedAt:null}catch{return null}}function assertReloadSupported(e,n){if(n===ALL_DEVICES)return;const t=e.toolActions(APP_TOOL_ID2).find(r=>r.deviceId===n);if(!t?.actions.includes(RELOAD_ACTION)){throw new Error(`This app doesn't expose remote reload \u2014 its @buoy-gg/core is too old. Upgrade @buoy-gg/core, then reload the app once by hand.`)}}async function waitForAppBack(e,n,t,r){const i=Date.now();await delay7(TEARDOWN_GRACE_MS2);while(Date.now()-i<t){const o=await ping(e,n,PROBE_TIMEOUT_MS);if(o!==null&&o!==r)return Date.now()-i;await delay7(PROBE_INTERVAL_MS)}return null}function offlineDeviceId(e){if(!/is not connected right now/.test(e))return null;return/"([^"]+)"/.exec(e)?.[1]??null}async function reloadOffline(e,n,t,r){const i=offlineDeviceId(errMsg2(n));if(!i||!e.listDevices().some(u=>u.deviceId===i&&u.isPro))throw n;const o=e.devServerOrigin(i);let s="";if(o){const u=await reloadViaDevServer(o);if(u.ok){if(!r)return text(`"${i}" was not connected, so it was reloaded through its dev server (${o}). It is restarting.`);const d=await waitForAppBack(e,i,Math.min(t,12e3),null);if(d!=null){return text(`"${i}" was not connected, so it was reloaded through its dev server. Back after ${(d/1e3).toFixed(1)}s. All in-memory state was reset.`)}s=` Its dev server (${o}) took the reload, but the app did not come back.`}else{s=` Its dev server at ${o} could not reload it: ${u.error}.`}}const a=e.listDevices().find(u=>u.deviceId===i)?.platform;const c=rememberedHost(i);const l=c?await verifyHost(i,c).catch(()=>void 0):await findHost(i,a).catch(()=>void 0);if(l){try{await hostQuit(l).catch(()=>void 0);await hostLaunch(l);if(!r)return text(`"${i}" was not connected, so it was relaunched on its ${l.platform==="ios"?"simulator":"device"}.`);const u=await waitForAppBack(e,i,t,null);if(u!=null){return text(`"${i}" was not connected, so it was relaunched on its ${l.platform==="ios"?"simulator":"device"} (a cold start). Back after ${(u/1e3).toFixed(1)}s. All in-memory state was reset.`)}}catch{}}return fail2(`"${i}" is not connected and could not be brought back.${s} Open the app by hand, then run list_devices.`)}function registerReloadTools(e,n){e.registerTool("reload_app",{description:"Request a JS reload for a supported app using DevSettings in development or installed expo-updates where available. For an unresponsive app, can try its known dev server when reachable. Recovery is not guaranteed. Reload can discard in-memory state and evidence; collect needed observations first when possible. By default waits for reconnection up to timeoutMs. Requires configured @buoy-gg/core support and Buoy Pro.",inputSchema:{strategy:import_zod32.z.enum(["auto","dev-settings","expo-updates"]).optional().describe("Reload mechanism. 'auto' (default) uses DevSettings in dev builds and expo-updates otherwise. Force one only when debugging the reload itself."),wait:import_zod32.z.boolean().optional().describe("Wait for the app to come back before returning. Default true \u2014 turn off for fire-and-forget."),timeoutMs:import_zod32.z.number().optional().describe("How long to wait for the app to reconnect, in ms. Default 30000."),deviceId:import_zod32.z.string().optional().describe('The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out. Or "All" to reload every connected app.')}},async t=>{try{let r;try{r=n.requireProDevice(t.deviceId)}catch(u){return await reloadOffline(n,u,t.timeoutMs??DEFAULT_WAIT_MS2,t.wait!==false)}assertReloadSupported(n,r);const i=t.wait===false?null:await ping(n,r,PROBE_TIMEOUT_MS);let o=null;let s=false;const a=async u=>{const d=n.devServerOrigin(r);if(!d){if(u)throw u;throw new Error("The app is not answering and no dev-server origin is known (it was never learned from a successful ping). Reload the app by hand.")}const h=await reloadViaDevServer(d);if(!h.ok){throw new Error(`The app is not answering (it looks crashed) and the dev server at ${d} could not be reached either: ${h.error}. Reload the app by hand.`)}s=true};if(n.isUnresponsive(r)&&n.devServerOrigin(r)){await a()}else{try{o=await n.callAction(APP_TOOL_ID2,RELOAD_ACTION,{strategy:t.strategy??"auto"},r)}catch(u){await a(u)}}const c=s?` via the dev server (the app was unresponsive \u2014 its own reload could not be reached)`:o?.strategy?` via ${o.strategy}`:"";if(t.wait===false){return text(`Reload requested${c}. The app is restarting \u2014 its in-memory state is gone; re-read anything you cached.`)}const l=await waitForAppBack(n,r,t.timeoutMs??DEFAULT_WAIT_MS2,i);if(l==null){return fail2(`Reload was accepted${c}, but the app hasn't reconnected yet. It may still be building the bundle (a cold Metro rebuild can take a while) \u2014 check the device, then run list_devices.`)}return text(`Reloaded the app${c} \u2014 back and connected after ${(l/1e3).toFixed(1)}s. All in-memory state was reset, so re-read any state you cached before this.`)}catch(r){return fail2(errMsg2(r))}})}var import_zod32,APP_TOOL_ID2,RELOAD_ACTION,DEFAULT_WAIT_MS2,TEARDOWN_GRACE_MS2,PROBE_TIMEOUT_MS,PROBE_INTERVAL_MS,delay7;var init_reload=__esm({"src/tools/packs/reload.ts"(){"use strict";import_zod32=require("zod");init_packKit();init_devServerReload();init_config();init_hostDevice();APP_TOOL_ID2="app";RELOAD_ACTION="reloadApp";DEFAULT_WAIT_MS2=3e4;TEARDOWN_GRACE_MS2=1200;PROBE_TIMEOUT_MS=1500;PROBE_INTERVAL_MS=400;delay7=e=>new Promise(n=>setTimeout(n,e))}});function hhmmss3(e){if(!e)return"--:--:--";const n=new Date(e);const t=r=>String(r).padStart(2,"0");return`${t(n.getHours())}:${t(n.getMinutes())}:${t(n.getSeconds())}`}async function otherBackends(e,n,t){const r=[];try{const i=await e.callAction("storage","mmkv.snapshot",{},n,t);for(const o of i??[]){const s=o.entries?.length??0;if(s>0)r.push(`MMKV "${o.id}": ${s} key${s===1?"":"s"}`)}}catch{}try{const i=await e.callAction("storage","secure.keys",{},n,t);if(i?.length)r.push(`SecureStore: ${i.length} key${i.length===1?"":"s"}`)}catch{}return r.length?`
|
|
780
973
|
${r.join(" \xB7 ")} \u2014 read with get_storage`:""}async function section(e,n){try{const t=await n();return t?`${e}
|
|
781
|
-
${t}`:null}catch(t){const r=
|
|
974
|
+
${t}`:null}catch(t){const r=errMsg8(t);if(/not responding|timed out|got no answer/i.test(r)){return`${e}
|
|
782
975
|
(no answer \u2014 see the note above)`}return`${e}
|
|
783
|
-
(unavailable: ${
|
|
784
|
-
_Values: get_storage includeValues:true_`}const b=new Map(f);let v=STORAGE_VALUE_BUDGET;const y=
|
|
785
|
-
\u2026+${
|
|
976
|
+
(unavailable: ${cap2(r,120)})`}}function registerTriageTools(e,n){e.registerTool("get_triage",{description:"Summarize available runtime observations for a connected app: captured console errors, recent network requests, configured storage and screen information. Use the returned sections and errors to choose follow-up tools. Missing data or an unresponsive app does not prove a crash; crash output may be unavailable. Requires Buoy Pro.",inputSchema:{deviceId:import_zod33.z.string().optional().describe("Target device id (auto-selected if one is connected).")}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=n.connectedDevices().find(g=>g.deviceId===r);const o=new Set((i?.tools??[]).map(g=>g.toolId));const s=`**${i?.deviceName??r}** (${i?.platform??"?"}, id \`${r}\`) \u2014 tools: ${[...o].join(", ")||"none"}`;const a={timeoutMs:PROBE_TIMEOUT_MS2};const[c,l,u,d]=await Promise.all([section("**Console \u2014 recent errors/warnings:**",async()=>{if(!o.has("console"))return null;const{payload:g}=await n.getSnapshot("console",r,a);const m=g;const f=Array.isArray(m)?m:m?.entries??[];const b=f.filter(y=>y.level==="error"||y.level==="warning");const v=b.slice(-8);if(v.length===0){return`(none \u2014 ${f.length} entries captured)`}return v.map(y=>`${hhmmss3(y.timestamp)} [${y.level==="error"?"ERR":"warn"}] ${cap2((y.message??"").split("\n").map($=>$.trim()).filter(Boolean).slice(0,3).join(" \u23CE "),220)}`).join("\n")}),section("**Network \u2014 recent requests:**",async()=>{if(!o.has("network"))return null;const{payload:g}=await n.getSnapshot("network",r,a);const m=Array.isArray(g)?g:g?.events??[];if(m.length===0)return"(no requests captured yet)";const f=m.slice(-8);return f.map(b=>{const v=b.error||(b.status??0)>=400?"\u274C":"\u2705";const y=b.path??b.url??"?";const $=b.error??b.status??"pending";return`${v} ${b.method??"GET"} ${cap2(String(y),80)} \u2192 ${$}${b.duration?` (${Math.round(b.duration)}ms)`:""}`}).join("\n")}),section("**Storage \u2014 persisted values:**",async()=>{if(!o.has("storage"))return null;const g=await n.callAction("storage","async.getAllKeys",{},r,a);if(!Array.isArray(g)||g.length===0){return"(no app keys)"}const m=g.slice(0,MAX_STORAGE_KEYS);let f=[];try{f=await n.callAction("storage","async.multiGet",{keys:m},r,a)??[]}catch{return`${m.map(_=>`\`${_}\``).join(", ")}
|
|
977
|
+
_Values: get_storage includeValues:true_`}const b=new Map(f);let v=STORAGE_VALUE_BUDGET;const y=m.map(_=>{const x=b.get(_);if(x==null)return`- \`${_}\` = (null)`;if(x.length>MAX_STORAGE_VALUE){return`- \`${_}\` = (${(x.length/1024).toFixed(1)} KB \u2014 read with get_storage)`}if(v<=0)return`- \`${_}\` = (not shown \u2014 triage budget spent; read with get_storage)`;v-=x.length;return`- \`${_}\` = ${x}`});const $=g.length-m.length;const T=await otherBackends(n,r,a);return`${y.join("\n")}${$>0?`
|
|
978
|
+
\u2026+${$} more keys`:""}${T}`}),section("**Screen \u2014 what's visible now:**",async()=>{if(!o.has("highlight-updates"))return null;const g=await n.callAction("highlight-updates","describeScreen",{},r,a);const m=(g?.elements??[]).filter(f=>f.interactive);if(m.length===0)return"(nothing interactive on screen)";return m.slice(0,20).map(f=>`\u2022 ${f.name}${f.text||f.label?` "${cap2(f.text??f.label??"",60)}"`:""}${f.testID?` [testID=${f.testID}]`:""}`).join("\n")})]);const h=n.isUnresponsive(r);const w=h?`
|
|
786
979
|
|
|
787
|
-
\u{1F6D1} ${n.unresponsiveNote(r)}`:"";const
|
|
980
|
+
\u{1F6D1} ${n.unresponsiveNote(r)}`:"";const p=[c,l,u,d].filter(Boolean).join("\n\n");return text8(`${s}${w}
|
|
788
981
|
|
|
789
|
-
${
|
|
982
|
+
${p}
|
|
790
983
|
|
|
791
|
-
_Drill in with get_console, get_network_requests (includeBodies:true for response bodies), get_storage (includeValues:true), describe_screen._`)}catch(r){return fail9(errMsg7(r))}})}var import_zod32,text7,fail9,errMsg7,PROBE_TIMEOUT_MS2,MAX_STORAGE_KEYS,MAX_STORAGE_VALUE,STORAGE_VALUE_BUDGET,MAX_LINE,cap;var init_triage=__esm({"src/tools/packs/triage.ts"(){"use strict";import_zod32=require("zod");text7=e=>({content:[{type:"text",text:e}]});fail9=e=>({isError:true,content:[{type:"text",text:e}]});errMsg7=e=>e instanceof Error?e.message:String(e);PROBE_TIMEOUT_MS2=5e3;MAX_STORAGE_KEYS=20;MAX_STORAGE_VALUE=400;STORAGE_VALUE_BUDGET=1600;MAX_LINE=160;cap=(e,n=MAX_LINE)=>e.length>n?`${e.slice(0,n)}\u2026`:e}});async function listSavedFlows(){try{return(await import_node_fs15.promises.readdir(FLOW_DIR())).filter(e=>e.endsWith(".json")).map(e=>e.slice(0,-5))}catch{return[]}}function matches(e,n){if(e.testID&&e.testID===n)return true;const t=n.toLowerCase();return[e.testID,e.text,e.label,e.name].filter(Boolean).some(r=>String(r).toLowerCase().includes(t))}function formatElement2(e){const n=e.text??e.label;return`${e.interactive?"\u2022 ":" "}${e.name}${n?` "${n}"`:""}${e.testID?` [testID=${e.testID}]`:""}`}function normalizeStep(e){if(!e||typeof e!=="object"||Array.isArray(e))return e;const n={...e};const t=o=>{if(!o||typeof o!=="object"||Array.isArray(o))return o;const a=o;return[a.testID,a.text,a.query,a.label,a.name].find(c=>typeof c==="string")??o};for(const o of["tap","into","waitFor","waitGone","expect","expectGone"])n[o]=t(n[o]);for(const o of Object.keys(n))if(n[o]===void 0)delete n[o];if(typeof n.into==="string")return n;const r=typeof n.type==="string"&&STEP_KINDS.includes(n.type)?"type":typeof n.action==="string"&&STEP_KINDS.includes(n.action)?"action":null;if(!r)return n;const i=n[r];delete n[r];const s=[n.query,n.text,n.target,n.selector,n.element,n.testID].map(t).find(o=>typeof o==="string");for(const o of["query","text","target","selector","element","testID"])delete n[o];if(i==="reload")n.reload=true;else if(i==="wait")n.waitMs=n.waitMs??n.ms??n.durationMs??n.timeoutMs;else if(s!==void 0&&n[i]===void 0)n[i]=s;delete n.ms;delete n.durationMs;return n}function registerFlowTools(e,n){e.registerTool("run_flow",{description:"Run supported UI actions and element checks in sequence, with per-step results. Stops on the first failed step unless continueOnFailure is true. Depending on include, attempts to return the final element tree and newly observed captured network/console entries. Background activity can appear in that output; it does not establish causation. Actions use exposed app handlers, not physical gestures. Review failures and check the expected behavior. To wait for something slow, use waitFor or waitGone with a timeoutMs, not a long waitMs. Requires Buoy Pro and the app interaction integration.",inputSchema:{steps:import_zod33.z.array(stepSchema).min(1).optional().describe("Steps to run, in order. Leave out when replaying a saved flow."),flow:import_zod33.z.string().optional().describe("Replay a saved flow by name (from .buoy/flows in the project) instead of passing steps."),save:import_zod33.z.string().optional().describe('Save these steps under this name when the flow passes, so it can be replayed with flow:"name".'),include:import_zod33.z.enum(["all","screen","none"]).optional().describe("What to report after the flow: 'all' (default) = available final element tree + newly observed captured network/console entries; 'screen' = available final element tree only; 'none' = step results only."),updateSnapshots:import_zod33.z.boolean().optional().describe("Save every snapshot step's screen as its new baseline instead of comparing."),continueOnFailure:import_zod33.z.boolean().optional().describe("Keep going after a failed step instead of stopping. Default false."),deviceId:deviceIdInput}},async t=>{const r=Date.now();try{let i=t.steps;if(t.flow){if(!FLOW_NAME.test(t.flow))return fail10(`Flow names use letters, numbers, - and _ (got "${t.flow}").`);try{i=JSON.parse(await import_node_fs15.promises.readFile(import_node_path17.default.join(FLOW_DIR(),`${t.flow}.json`),"utf8")).steps}catch{const _=await listSavedFlows();return fail10(`No saved flow "${t.flow}". ${_.length?`Saved flows: ${_.join(", ")}.`:'No flows are saved yet; run one with save:"name" first.'}`)}}if(!i||i.length===0)return fail10('Pass steps, or flow:"name" to replay a saved flow.');if(t.save&&!FLOW_NAME.test(t.save))return fail10(`Flow names use letters, numbers, - and _ (got "${t.save}").`);const s=n.requireProDevice(t.deviceId);const o=t.include??"all";const a=async()=>{const _=await n.callAction(UI_TOOL_ID2,"describeScreen",{},s);return _?.elements??[]};const c=async()=>{try{const _=await n.callAction(APP_TOOL_ID2,"ping",{},s,{timeoutMs:REALM_PROBE_MS,silent:true});return typeof _?.startedAt==="number"?_.startedAt:null}catch{return null}};const u=async(_,$)=>{const k=Date.now();while(Date.now()-k<$){const T=await c();if(T!==null&&T!==_)return Date.now()-k;await delay6(POLL_MS)}return null};const l=new Set;const d=new Set;const h=new Set((n.connectedDevices().find(_=>_.deviceId===s)?.tools??[]).map(_=>_.toolId));if(o==="all"){if(h.has("console")){const{payload:_}=await n.getSnapshot("console",s).catch(()=>({payload:null}));const $=_?.entries??[];for(const k of $)l.add(k.id)}if(h.has("network")){const{payload:_}=await n.getSnapshot("network",s).catch(()=>({payload:null}));const $=Array.isArray(_)?_:_?.events??[];for(const k of $)d.add(k.id)}}const p=async(_,$)=>{const k=Date.now();let T=false;for(;;){if(Date.now()-k>=$||Date.now()-r>MAX_FLOW_MS){return{ok:false,ms:Date.now()-k,unread:!T}}let A;try{A=await a();T=true}catch{await delay6(POLL_MS);continue}if(_(A))return{ok:true,ms:Date.now()-k,unread:false};await delay6(POLL_MS)}};const m=_=>`could not read the screen within ${_}ms, so this step is unknown`;const g=[];let w=null;let f=0;for(let _=0;_<i.length;_++){const $=i[_];const k=`${_+1}`;const T=$.timeoutMs??DEFAULT_WAIT_MS2;if(Date.now()-r>MAX_FLOW_MS){g.push(`${k} \u2717 flow exceeded ${MAX_FLOW_MS/1e3}s \u2014 stopped here`);w=_;break}const A=[];const I=[];const R=$.reload||$.tap||$.type!==void 0||$.waitMs||$.waitFor||$.waitGone||$.expect||$.expectGone||$.snapshot;if(!R){g.push(`${_+1} \u2717 step does nothing \u2014 give it a tap/type/wait/expect${$.set!==void 0?" (`set` needs `tap` naming the control)":""}`);w=w??_;if(!t.continueOnFailure)break;continue}try{if($.reload){const M=await c();await n.callAction(APP_TOOL_ID2,"reloadApp",{strategy:"auto"},s);await delay6(TEARDOWN_GRACE_MS2);const S=await u(M,Math.max(T,2e4));if(S==null){A.push("app did not come back after reload")}else{I.push(`reloaded (${S}ms)`);await p(x=>x.length>0,1e4)}}if($.type!==void 0){const M=$.into??$.tap;if(!M){A.push("`type` needs `into` (which input to type into)")}else{const S=await n.callAction(UI_TOOL_ID2,"tapElement",{...selector(M),text:fillSecrets($.type)},s);if(!S?.tapped){A.push(S?.reason??`could not type into "${M}"`)}else if(S.matched?.via&&S.matched.via!=="onChangeText"){A.push(`"${M}" is not a text input \u2014 it ran ${S.matched.via} instead, and the text was not entered`)}else{I.push(`typed ${JSON.stringify($.type)} into "${M}"`)}}}else if($.tap){const M={...selector($.tap)};if($.longPress)M.longPress=true;if($.set!==void 0)M.value=$.set;const S=await n.callAction(UI_TOOL_ID2,"tapElement",M,s);if(!S?.tapped){A.push(S?.reason??`no element matched "${$.tap}"`)}else{const x=S.matched;const E=x?.text??x?.label??x?.name??$.tap;if($.set!==void 0&&x?.via&&x.via!=="onValueChange"){A.push(`"${E}" is not a toggle/slider \u2014 it ran ${x.via} instead, so it was not set to ${JSON.stringify($.set)}`)}else{I.push($.set!==void 0?`set "${E}" \u2192 ${JSON.stringify(x?.value??$.set)}`:`${$.longPress?"long-pressed":"tapped"} "${E}"`)}}}if(!A.length&&$.waitMs){await delay6($.waitMs);I.push(`waited ${$.waitMs}ms`)}if(!A.length&&$.waitFor){const M=await p(S=>S.some(x=>matches(x,$.waitFor)),T);if(M.ok)I.push(`"${$.waitFor}" appeared (${M.ms}ms)`);else A.push(M.unread?m(T):`"${$.waitFor}" never appeared within ${T}ms`)}if(!A.length&&$.waitGone){const M=await p(S=>!S.some(x=>matches(x,$.waitGone)),T);if(M.ok)I.push(`"${$.waitGone}" gone (${M.ms}ms)`);else A.push(M.unread?m(T):`"${$.waitGone}" was still there after ${T}ms`)}if(!A.length&&$.expect){const M=await p(S=>S.some(x=>matches(x,$.expect)),$.timeoutMs??ASSERT_SETTLE_MS);if(M.ok)I.push(`"${$.expect}" is on screen`);else A.push(M.unread?m($.timeoutMs??ASSERT_SETTLE_MS):`expected "${$.expect}" on screen \u2014 not found`)}if(!A.length&&$.expectGone){const M=await p(S=>!S.some(x=>matches(x,$.expectGone)),$.timeoutMs??ASSERT_SETTLE_MS);if(M.ok)I.push(`"${$.expectGone}" is gone`);else A.push(M.unread?m($.timeoutMs??ASSERT_SETTLE_MS):`expected "${$.expectGone}" to be gone \u2014 still on screen`)}if(!A.length&&$.snapshot){const{outcome:M}=await runBaseline(n,$.snapshot,{deviceId:s,update:t.updateSnapshots});const S=$.maxChange??.05;if(M.changed&&(M.texts>0||M.percent>S)){A.push(`${M.summary}${M.texts>0?"":` (more than ${S}%)`}. Run screenshot_component with baseline "${$.snapshot}" to see the diff, or updateSnapshots: true if it is expected.`)}else I.push(M.summary)}}catch(M){A.push(errMsg8(M))}if(A.length){g.push(`${k} \u2717 ${describeStep($)} \u2014 ${A.join("; ")}`);w=w??_;if(!t.continueOnFailure)break}else{f++;g.push(`${k} \u2713 ${I.join(", ")||describeStep($)}`)}}const b=((Date.now()-r)/1e3).toFixed(1);const v=w===null?`**Flow: ${f}/${i.length} steps OK (${b}s)**`:`**Flow FAILED at step ${w+1} \u2014 ${f}/${i.length} steps OK (${b}s)**`;const y=[v,g.join("\n")];if(o!=="none"){try{const _=await a();const $=_.filter(k=>k.interactive).slice(0,30);y.push(`**Screen now (${$.length} interactive of ${_.length}):**
|
|
792
|
-
${$.map(formatElement2).join("\n")}`)}catch(_){y.push(`**Screen now:** unavailable \u2014 ${cap2(errMsg8(_))}`)}}if(o==="all"){if(h.has("network")){const{payload:_}=await n.getSnapshot("network",s).catch(()=>({payload:null}));const $=Array.isArray(_)?_:_?.events??[];const k=$.filter(T=>!d.has(T.id)).slice(-15);if(k.length){y.push(`**Network during this flow (${k.length}):**
|
|
793
|
-
`+k.map(T=>`${T.error||(T.status??0)>=400?"\u274C":"\u2705"} ${T.method??"GET"} ${T.path??T.url??"?"} \u2192 ${T.error??T.status??"pending"}`).join("\n"))}}if(h.has("console")){const{payload:_}=await n.getSnapshot("console",s).catch(()=>({payload:null}));const $=_?.entries??[];const k=$.filter(T=>!l.has(T.id)&&(T.level==="error"||T.level==="warning")).slice(-10);if(k.length){y.push(`**Console during this flow (${k.length}):**
|
|
794
|
-
`+k.map(T=>`[${T.level==="error"?"ERR":"warn"}] ${cap2(firstLines(scrubSecrets(T.message??"")),220)}`).join("\n"))}}}if(t.save&&w===null){await import_node_fs15.promises.mkdir(FLOW_DIR(),{recursive:true});const _=import_node_path17.default.join(FLOW_DIR(),`${t.save}.json`);await import_node_fs15.promises.writeFile(_,JSON.stringify({steps:i},null,2)+"\n");y.push(`Saved as flow "${t.save}" (${import_node_path17.default.relative(process.cwd(),_)}). Replay with run_flow({flow:"${t.save}"}).`)}else if(t.save){y.push(`Not saved: the flow failed. Fix it, then run it again with save:"${t.save}".`)}return w===null?text8(y.join("\n\n")):{...text8(y.join("\n\n")),isError:true}}catch(i){return fail10(errMsg8(i))}})}function selector(e){return/\s/.test(e)?{query:e}:{testID:e,query:e}}function describeStep(e){if(e.tap)return`tap "${e.tap}"`;if(e.type!==void 0)return`type into "${e.into??"?"}"`;if(e.reload)return"reload";if(e.waitFor)return`waitFor "${e.waitFor}"`;if(e.waitGone)return`waitGone "${e.waitGone}"`;if(e.expect)return`expect "${e.expect}"`;if(e.expectGone)return`expectGone "${e.expectGone}"`;if(e.snapshot)return`snapshot "${e.snapshot}"`;return"step"}var import_zod33,import_node_fs15,import_node_path17,FLOW_DIR,FLOW_NAME,UI_TOOL_ID2,APP_TOOL_ID2,text8,fail10,errMsg8,delay6,POLL_MS,DEFAULT_WAIT_MS2,ASSERT_SETTLE_MS,TEARDOWN_GRACE_MS2,REALM_PROBE_MS,MAX_FLOW_MS,STEP_KINDS,stepSchema,cap2,firstLines;var init_flow=__esm({"src/tools/packs/flow.ts"(){"use strict";init_screenshot();init_secrets();import_zod33=require("zod");init_packKit();import_node_fs15=require("fs");import_node_path17=__toESM(require("path"));FLOW_DIR=()=>import_node_path17.default.join(process.cwd(),".buoy","flows");FLOW_NAME=/^[A-Za-z0-9_-]{1,64}$/;UI_TOOL_ID2="highlight-updates";APP_TOOL_ID2="app";text8=e=>({content:[{type:"text",text:e}]});fail10=e=>({isError:true,content:[{type:"text",text:e}]});errMsg8=e=>e instanceof Error?e.message:String(e);delay6=e=>new Promise(n=>setTimeout(n,e));POLL_MS=250;DEFAULT_WAIT_MS2=5e3;ASSERT_SETTLE_MS=2e3;TEARDOWN_GRACE_MS2=1200;REALM_PROBE_MS=1500;MAX_FLOW_MS=12e4;STEP_KINDS=["tap","waitFor","waitGone","expect","expectGone","reload","wait"];stepSchema=import_zod33.z.preprocess(normalizeStep,import_zod33.z.object({tap:import_zod33.z.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),longPress:import_zod33.z.boolean().optional().describe("Make `tap` a long-press instead."),type:import_zod33.z.string().optional().describe("Text to type (needs `into`)."),into:import_zod33.z.string().optional().describe("Target text input for `type`: testID or fuzzy text."),set:import_zod33.z.union([import_zod33.z.number(),import_zod33.z.boolean()]).optional().describe("Set a toggle (true/false) or slider (number) \u2014 pair with `tap` as the target."),reload:import_zod33.z.boolean().optional().describe("Reload the JS bundle before this step's action."),waitMs:import_zod33.z.number().min(0).max(3e4).optional().describe("Fixed pause after the action, in ms (max 30000). To wait for a result (a slow request, a new screen), use waitFor with timeoutMs instead: it stops as soon as the element shows."),waitFor:import_zod33.z.string().optional().describe("Wait until an element matching this appears (default 5s)."),waitGone:import_zod33.z.string().optional().describe("Wait until no element matches this (default 5s)."),expect:import_zod33.z.string().optional().describe("Assert an element matching this IS on screen (waits up to 2s for it); fails the flow if not."),expectGone:import_zod33.z.string().optional().describe("Assert nothing matches this (waits up to 2s for it to go); fails the flow if something does."),snapshot:import_zod33.z.string().optional().describe("Compare the whole screen to the baseline with this name (saved on the first run, like screenshot_component baseline). Fails the step on a text change or a change bigger than maxChange."),maxChange:import_zod33.z.number().min(0).max(100).optional().describe("snapshot: allowed changed share of the screen, in percent. Default 0.05."),timeoutMs:import_zod33.z.number().min(0).max(6e4).optional().describe("Budget for this step's waitFor/waitGone/expect, max 60000. Default 5000 (2000 for expect).")}).describe("One flow step. Order within a step: reload \u2192 tap/type/set \u2192 waitMs \u2192 waitFor/waitGone \u2192 expect."));cap2=(e,n=160)=>{const t=scrubSecrets(e);return t.length>n?`${t.slice(0,n)}\u2026`:t};firstLines=(e,n=3)=>e.split("\n").map(t=>t.trim()).filter(Boolean).slice(0,n).join(" \u23CE ")}});function selector2(e){return/\s/.test(e)?{query:e}:{testID:e,query:e}}function dominant(e){if(!e)return"unknown";let n="unknown";let t=-1;for(const[r,i]of Object.entries(e)){if((i??0)>t){t=i??0;n=r}}return n}function formatCapture(e,n){const t=e.summary;const r=t.wastedRenders??0;const i=t.totalRenders>0?Math.round(r/t.totalRenders*100):0;const s=[];const o=t.totalRenderMs??0;s.push(`**${t.totalRenders} component renders across ${t.totalCommits} commits in ${(e.windowMs/1e3).toFixed(1)}s**`+(o>0?` \xB7 ${o.toFixed(1)}ms of render work`:"")+` \xB7 ${r} wasted (${i}%)`);const a=Object.entries(t.causes??{}).filter(([,d])=>(d??0)>0).sort((d,h)=>(h[1]??0)-(d[1]??0)).map(([d,h])=>`${d} ${h}`).join(" \xB7 ");if(a)s.push(`causes: ${a}`);s.push("");s.push("| component | self ms | renders | cause | dragged along by | changed props |");s.push("|---|---:|---:|---|---|---|");const c=[...t.topComponents].sort((d,h)=>(h.totalMs??0)-(d.totalMs??0)||h.renders-d.renders).slice(0,n);for(const d of c){s.push(`| ${d.name} | ${(d.totalMs??0).toFixed(1)} | ${d.renders} | ${dominant(d.causes)} | ${d.parentName??"\u2014"} | ${(d.changedProps??[]).join(", ")||"\u2014"} |`)}if(t.topComponents.length>n){s.push(`_\u2026+${t.topComponents.length-n} more components_`)}const u=new Set(c.map(d=>dominant(d.causes)));const l=[...u].filter(d=>CAUSE_HINT[d]).map(d=>`\`${d}\` = ${CAUSE_HINT[d]}`);if(l.length){s.push("");s.push(l.join(" \xB7 "))}s.push("");s.push("`wasted` classifies parent cascades and identity-only prop changes. Investigate whether these renders are needed before changing them. Rows are sorted by **self ms**. Compare timing and render counts for the measured workload, and check behavior before deciding whether memoization helps.");return s.join("\n")}function formatDelta(e,n){const t=(l,d)=>{const h=d-l;return`${l} \u2192 ${d} (${h>0?"+":""}${h})`};const r=e.summary;const i=n.summary;const s=[`**vs "${e.label}"**`];s.push(`- total renders: ${t(r.totalRenders,i.totalRenders)}`);s.push(`- wasted: ${t(r.wastedRenders??0,i.wastedRenders??0)}`);const o=new Map(r.topComponents.map(l=>[l.name,l.renders]));const a=[];for(const l of i.topComponents.slice(0,20)){const d=o.get(l.name)??0;if(d!==l.renders)a.push(`${l.name} ${t(d,l.renders)}`);o.delete(l.name)}for(const[l,d]of o){if(d>0)a.push(`${l} ${t(d,0)}`)}if(a.length)s.push(`- per component: ${a.slice(0,10).join(" \xB7 ")}`);const c=i.totalRenders<r.totalRenders;const u=i.totalRenders>r.totalRenders;s.push(u?"\n\u26A0\uFE0F MORE renders than before \u2014 this change made this interaction worse. Re-render fixes routinely move cost instead of removing it; check the other interactions too before moving on.":c?"\n\u2705 Fewer renders than before on this interaction. Measure the OTHER interactions too \u2014 a fix that helps typing can cost taps.":"\n\u2796 No change on this interaction.");return s.join("\n")}function registerRenderTools(e,n){e.registerTool("measure_renders",{description:"Measure captured component renders during supplied interaction steps or an idle window. Returns available timings, render counts, reported reasons and changed props. The wasted count is a diagnostic classification, not proof a render can be removed. Check interaction warnings before comparing runs. Use the same steps and comparable conditions with compareToPrevious:true after editing; the comparison alone does not prove correctness or overall performance. Requires Buoy Pro and a highlight-updates integration exposing beginMeasurement. Use run_benchmark_batch to compare route-based variants.",inputSchema:{steps:import_zod34.z.array(stepSchema2).max(20).optional().describe("The interaction to measure, e.g. [{tap:'favorite-deal-2', repeat:5}] or [{type:'bench', into:'deals-search'}]. Omit to sample the screen idle \u2014 only useful for churn that happens with nobody touching it."),idleMs:import_zod34.z.number().min(500).max(2e4).optional().describe(`Idle sample length when no steps are given. Default ${DEFAULT_IDLE_MS}.`),label:import_zod34.z.string().optional().describe('Name this measurement, e.g. "before fix". Shown in the next comparison.'),compareToPrevious:import_zod34.z.boolean().optional().describe("Compare with the previous measurement on this device. Use equivalent steps and conditions; review warnings and behavior separately."),top:import_zod34.z.number().min(1).max(40).optional().describe(`Components to list. Default ${DEFAULT_TOP}.`),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=n.connectedDevices().find(w=>w.deviceId===r);const s=(i?.tools??[]).find(w=>w.toolId===UI_TOOL_ID3);if(!s){return fail11("This app doesn't expose the highlight-updates tool, so renders can't be measured. Install @buoy-gg/highlight-updates.")}if(!(s.actions??[]).includes("beginMeasurement")){return fail11("This app's @buoy-gg/highlight-updates is too old to measure renders (needs the version with beginMeasurement). Upgrade it, then try again. Meanwhile run_benchmark_batch with captureRenders can still give counts if you have a test route.")}const o=await n.callAction(UI_TOOL_ID3,"beginMeasurement",{},r);if(o&&o.ok===false){return fail11(`Can't measure renders: ${o.reason??"capture unavailable"}`)}await delay7(SETTLE_MS);const a=Date.now();const c=[];if(t.steps?.length){for(const w of t.steps){const f=w.repeat??1;for(let b=0;b<f;b++){if(w.type!==void 0){const v=w.into??w.tap;if(!v){c.push("a `type` step needs `into`");continue}const y=await n.callAction(UI_TOOL_ID3,"tapElement",{...selector2(v),text:w.type},r);if(!y?.tapped)c.push(y?.reason??`could not type into "${v}"`);else if(y.matched?.via&&y.matched.via!=="onChangeText"){c.push(`"${v}" is not a text input \u2014 it ran ${y.matched.via}, nothing was typed`)}}else if(w.tap){const v=await n.callAction(UI_TOOL_ID3,"tapElement",selector2(w.tap),r);if(!v?.tapped)c.push(v?.reason??`no element matched "${w.tap}"`)}if(w.waitMs)await delay7(w.waitMs)}}await delay7(SETTLE_MS)}else{await delay7(t.idleMs??DEFAULT_IDLE_MS)}const u=Date.now()-a;const l=await n.callAction(UI_TOOL_ID3,"endMeasurement",{},r);const d=l?.summary;if(!d){return fail11("The capture window closed without returning anything. If the app reloaded mid-measurement, try again.")}const h={label:t.label??(t.steps?.length?"interaction":"idle"),windowMs:u,summary:d};const p=lastCapture.get(r);lastCapture.set(r,h);const m=t.steps?.length?t.steps.map(w=>(w.type!==void 0?`type "${w.type}"`:`tap "${w.tap}"`)+(w.repeat?` \xD7${w.repeat}`:"")).join(", "):`idle ${(u/1e3).toFixed(1)}s`;const g=[`**measure_renders \u2014 ${m}**`,"",formatCapture(h,t.top??DEFAULT_TOP)];if(t.compareToPrevious){g.push("",p?formatDelta(p,h):"_No previous measurement on this device to compare against._")}if(c.length)g.push("",`\u26A0\uFE0F ${c.join("; ")}`);if(d.totalRenders===0){g.push("","_Nothing re-rendered in this window. If you expected renders, check the app is on the screen you meant and that the steps actually hit something._")}else if(!t.compareToPrevious){g.push("","_Compare another run using the same steps and `compareToPrevious:true`; check behavior and interaction warnings as well._")}return text9(g.join("\n"))}catch(r){return fail11(errMsg9(r))}})}var import_zod34,UI_TOOL_ID3,text9,fail11,errMsg9,delay7,DEFAULT_IDLE_MS,SETTLE_MS,DEFAULT_TOP,lastCapture,stepSchema2,CAUSE_HINT;var init_renders=__esm({"src/tools/packs/renders.ts"(){"use strict";import_zod34=require("zod");init_packKit();UI_TOOL_ID3="highlight-updates";text9=e=>({content:[{type:"text",text:e}]});fail11=e=>({isError:true,content:[{type:"text",text:e}]});errMsg9=e=>e instanceof Error?e.message:String(e);delay7=e=>new Promise(n=>setTimeout(n,e));DEFAULT_IDLE_MS=3e3;SETTLE_MS=400;DEFAULT_TOP=12;lastCapture=new Map;stepSchema2=import_zod34.z.object({tap:import_zod34.z.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),type:import_zod34.z.string().optional().describe("Text to type (needs `into`)."),into:import_zod34.z.string().optional().describe("Target text input for `type`: testID or fuzzy text."),waitMs:import_zod34.z.number().min(0).max(1e4).optional().describe("Pause after the action, in ms."),repeat:import_zod34.z.number().min(1).max(20).optional().describe("Do this step N times (default 1). Useful for 'tap it five times'.")}).describe("One interaction to measure. Keep it to the thing you're asking about.");CAUSE_HINT={propsUnstable:"props changed by IDENTITY only (a fresh function/object from the parent) \u2014 fix upstream, not in the child",parent:"parent re-rendered and nothing of its own changed \u2014 a pure cascade",props:"props genuinely changed value",hooks:"its own state/hooks changed",mount:"first render"}}});function resolveMode(e){const n=(e??"").trim().toLowerCase();if(n==="always"||n==="never"||n==="auto")return n;return"auto"}var import_node_fs16,import_node_path18,WATCHED_EXT,IGNORED_DIRS,DEBOUNCE_MS,EditWatcher,editWatcher;var init_editWatcher=__esm({"src/verify/editWatcher.ts"(){"use strict";import_node_fs16=__toESM(require("fs"));import_node_path18=__toESM(require("path"));WATCHED_EXT=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".json"]);IGNORED_DIRS=new Set(["node_modules",".git",".expo","ios","android","dist","lib","build",".next","coverage","__snapshots__"]);DEBOUNCE_MS=400;EditWatcher=class{constructor(){this.watcher=null;this.changed=new Set;this.lastEditAt=0;this.nudgedForCurrentBatch=false;this.mode="auto";this.started=false}start(e,n){this.mode=n;if(n==="never"||this.started)return;this.started=true;try{this.watcher=import_node_fs16.default.watch(e,{recursive:true},(t,r)=>{if(!r)return;const i=String(r);if(i.split(import_node_path18.default.sep).some(s=>IGNORED_DIRS.has(s)))return;if(!WATCHED_EXT.has(import_node_path18.default.extname(i)))return;this.noteEdit(i)});this.watcher.on("error",()=>this.stop())}catch{this.stop()}}noteEdit(e){const n=Date.now();if(n-this.lastEditAt>DEBOUNCE_MS)this.nudgedForCurrentBatch=false;this.lastEditAt=n;if(this.changed.size<50)this.changed.add(e)}stop(){try{this.watcher?.close()}catch{}this.watcher=null}markVerified(){this.changed.clear();this.nudgedForCurrentBatch=false}hasUnverifiedEdits(){return this.changed.size>0}nudge(){if(this.mode==="never"||!this.hasUnverifiedEdits())return null;if(this.mode==="auto"){if(this.nudgedForCurrentBatch)return null;this.nudgedForCurrentBatch=true}const e=[...this.changed];const n=e.slice(0,3).join(", ");const t=e.length>3?` +${e.length-3} more`:"";return`
|
|
984
|
+
_Drill in with get_console, get_network_requests (includeBodies:true for response bodies), get_storage (includeValues:true), describe_screen._`)}catch(r){return fail10(errMsg8(r))}})}var import_zod33,text8,fail10,errMsg8,PROBE_TIMEOUT_MS2,MAX_STORAGE_KEYS,MAX_STORAGE_VALUE,STORAGE_VALUE_BUDGET,MAX_LINE,cap2;var init_triage=__esm({"src/tools/packs/triage.ts"(){"use strict";import_zod33=require("zod");text8=e=>({content:[{type:"text",text:e}]});fail10=e=>({isError:true,content:[{type:"text",text:e}]});errMsg8=e=>e instanceof Error?e.message:String(e);PROBE_TIMEOUT_MS2=5e3;MAX_STORAGE_KEYS=20;MAX_STORAGE_VALUE=400;STORAGE_VALUE_BUDGET=1600;MAX_LINE=160;cap2=(e,n=MAX_LINE)=>e.length>n?`${e.slice(0,n)}\u2026`:e}});function selector2(e){return/\s/.test(e)?{query:e}:{testID:e,query:e}}function dominant(e){if(!e)return"unknown";let n="unknown";let t=-1;for(const[r,i]of Object.entries(e)){if((i??0)>t){t=i??0;n=r}}return n}function formatCapture(e,n){const t=e.summary;const r=t.wastedRenders??0;const i=t.totalRenders>0?Math.round(r/t.totalRenders*100):0;const o=[];const s=t.totalRenderMs??0;o.push(`**${t.totalRenders} component renders across ${t.totalCommits} commits in ${(e.windowMs/1e3).toFixed(1)}s**`+(s>0?` \xB7 ${s.toFixed(1)}ms of render work`:"")+` \xB7 ${r} wasted (${i}%)`);const a=Object.entries(t.causes??{}).filter(([,d])=>(d??0)>0).sort((d,h)=>(h[1]??0)-(d[1]??0)).map(([d,h])=>`${d} ${h}`).join(" \xB7 ");if(a)o.push(`causes: ${a}`);o.push("");o.push("| component | self ms | renders | cause | dragged along by | changed props |");o.push("|---|---:|---:|---|---|---|");const c=[...t.topComponents].sort((d,h)=>(h.totalMs??0)-(d.totalMs??0)||h.renders-d.renders).slice(0,n);for(const d of c){o.push(`| ${d.name} | ${(d.totalMs??0).toFixed(1)} | ${d.renders} | ${dominant(d.causes)} | ${d.parentName??"\u2014"} | ${(d.changedProps??[]).join(", ")||"\u2014"} |`)}if(t.topComponents.length>n){o.push(`_\u2026+${t.topComponents.length-n} more components_`)}const l=new Set(c.map(d=>dominant(d.causes)));const u=[...l].filter(d=>CAUSE_HINT[d]).map(d=>`\`${d}\` = ${CAUSE_HINT[d]}`);if(u.length){o.push("");o.push(u.join(" \xB7 "))}o.push("");o.push("`wasted` classifies parent cascades and identity-only prop changes. Investigate whether these renders are needed before changing them. Rows are sorted by **self ms**. Compare timing and render counts for the measured workload, and check behavior before deciding whether memoization helps.");return o.join("\n")}function formatDelta(e,n){const t=(u,d)=>{const h=d-u;return`${u} \u2192 ${d} (${h>0?"+":""}${h})`};const r=e.summary;const i=n.summary;const o=[`**vs "${e.label}"**`];o.push(`- total renders: ${t(r.totalRenders,i.totalRenders)}`);o.push(`- wasted: ${t(r.wastedRenders??0,i.wastedRenders??0)}`);const s=new Map(r.topComponents.map(u=>[u.name,u.renders]));const a=[];for(const u of i.topComponents.slice(0,20)){const d=s.get(u.name)??0;if(d!==u.renders)a.push(`${u.name} ${t(d,u.renders)}`);s.delete(u.name)}for(const[u,d]of s){if(d>0)a.push(`${u} ${t(d,0)}`)}if(a.length)o.push(`- per component: ${a.slice(0,10).join(" \xB7 ")}`);const c=i.totalRenders<r.totalRenders;const l=i.totalRenders>r.totalRenders;o.push(l?"\n\u26A0\uFE0F MORE renders than before \u2014 this change made this interaction worse. Re-render fixes routinely move cost instead of removing it; check the other interactions too before moving on.":c?"\n\u2705 Fewer renders than before on this interaction. Measure the OTHER interactions too \u2014 a fix that helps typing can cost taps.":"\n\u2796 No change on this interaction.");return o.join("\n")}function registerRenderTools(e,n){e.registerTool("measure_renders",{description:"Measure captured component renders during supplied interaction steps or an idle window. Returns available timings, render counts, reported reasons and changed props. The wasted count is a diagnostic classification, not proof a render can be removed. Check interaction warnings before comparing runs. Use the same steps and comparable conditions with compareToPrevious:true after editing; the comparison alone does not prove correctness or overall performance. Requires Buoy Pro and a highlight-updates integration exposing beginMeasurement. Use run_benchmark_batch to compare route-based variants.",inputSchema:{steps:import_zod34.z.array(stepSchema2).max(20).optional().describe("The interaction to measure, e.g. [{tap:'favorite-deal-2', repeat:5}] or [{type:'bench', into:'deals-search'}]. Omit to sample the screen idle \u2014 only useful for churn that happens with nobody touching it."),idleMs:import_zod34.z.number().min(500).max(2e4).optional().describe(`Idle sample length when no steps are given. Default ${DEFAULT_IDLE_MS}.`),label:import_zod34.z.string().optional().describe('Name this measurement, e.g. "before fix". Shown in the next comparison.'),compareToPrevious:import_zod34.z.boolean().optional().describe("Compare with the previous measurement on this device. Use equivalent steps and conditions; review warnings and behavior separately."),top:import_zod34.z.number().min(1).max(40).optional().describe(`Components to list. Default ${DEFAULT_TOP}.`),deviceId:deviceIdInput}},async t=>{try{const r=n.requireProDevice(t.deviceId);const i=n.connectedDevices().find(m=>m.deviceId===r);const o=(i?.tools??[]).find(m=>m.toolId===UI_TOOL_ID3);if(!o){return fail11("This app doesn't expose the highlight-updates tool, so renders can't be measured. Install @buoy-gg/highlight-updates.")}if(!(o.actions??[]).includes("beginMeasurement")){return fail11("This app's @buoy-gg/highlight-updates is too old to measure renders (needs the version with beginMeasurement). Upgrade it, then try again. Meanwhile run_benchmark_batch with captureRenders can still give counts if you have a test route.")}const s=await n.callAction(UI_TOOL_ID3,"beginMeasurement",{},r);if(s&&s.ok===false){return fail11(`Can't measure renders: ${s.reason??"capture unavailable"}`)}await delay8(SETTLE_MS);const a=Date.now();const c=[];if(t.steps?.length){for(const m of t.steps){const f=m.repeat??1;for(let b=0;b<f;b++){if(m.type!==void 0){const v=m.into??m.tap;if(!v){c.push("a `type` step needs `into`");continue}const y=await n.callAction(UI_TOOL_ID3,"tapElement",{...selector2(v),text:m.type},r);if(!y?.tapped)c.push(y?.reason??`could not type into "${v}"`);else if(y.matched?.via&&y.matched.via!=="onChangeText"){c.push(`"${v}" is not a text input \u2014 it ran ${y.matched.via}, nothing was typed`)}}else if(m.tap){const v=await n.callAction(UI_TOOL_ID3,"tapElement",selector2(m.tap),r);if(!v?.tapped)c.push(v?.reason??`no element matched "${m.tap}"`)}if(m.waitMs)await delay8(m.waitMs)}}await delay8(SETTLE_MS)}else{await delay8(t.idleMs??DEFAULT_IDLE_MS)}const l=Date.now()-a;const u=await n.callAction(UI_TOOL_ID3,"endMeasurement",{},r);const d=u?.summary;if(!d){return fail11("The capture window closed without returning anything. If the app reloaded mid-measurement, try again.")}const h={label:t.label??(t.steps?.length?"interaction":"idle"),windowMs:l,summary:d};const w=lastCapture.get(r);lastCapture.set(r,h);const p=t.steps?.length?t.steps.map(m=>(m.type!==void 0?`type "${m.type}"`:`tap "${m.tap}"`)+(m.repeat?` \xD7${m.repeat}`:"")).join(", "):`idle ${(l/1e3).toFixed(1)}s`;const g=[`**measure_renders \u2014 ${p}**`,"",formatCapture(h,t.top??DEFAULT_TOP)];if(t.compareToPrevious){g.push("",w?formatDelta(w,h):"_No previous measurement on this device to compare against._")}if(c.length)g.push("",`\u26A0\uFE0F ${c.join("; ")}`);if(d.totalRenders===0){g.push("","_Nothing re-rendered in this window. If you expected renders, check the app is on the screen you meant and that the steps actually hit something._")}else if(!t.compareToPrevious){g.push("","_Compare another run using the same steps and `compareToPrevious:true`; check behavior and interaction warnings as well._")}return text9(g.join("\n"))}catch(r){return fail11(errMsg9(r))}})}var import_zod34,UI_TOOL_ID3,text9,fail11,errMsg9,delay8,DEFAULT_IDLE_MS,SETTLE_MS,DEFAULT_TOP,lastCapture,stepSchema2,CAUSE_HINT;var init_renders=__esm({"src/tools/packs/renders.ts"(){"use strict";import_zod34=require("zod");init_packKit();UI_TOOL_ID3="highlight-updates";text9=e=>({content:[{type:"text",text:e}]});fail11=e=>({isError:true,content:[{type:"text",text:e}]});errMsg9=e=>e instanceof Error?e.message:String(e);delay8=e=>new Promise(n=>setTimeout(n,e));DEFAULT_IDLE_MS=3e3;SETTLE_MS=400;DEFAULT_TOP=12;lastCapture=new Map;stepSchema2=import_zod34.z.object({tap:import_zod34.z.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),type:import_zod34.z.string().optional().describe("Text to type (needs `into`)."),into:import_zod34.z.string().optional().describe("Target text input for `type`: testID or fuzzy text."),waitMs:import_zod34.z.number().min(0).max(1e4).optional().describe("Pause after the action, in ms."),repeat:import_zod34.z.number().min(1).max(20).optional().describe("Do this step N times (default 1). Useful for 'tap it five times'.")}).describe("One interaction to measure. Keep it to the thing you're asking about.");CAUSE_HINT={propsUnstable:"props changed by IDENTITY only (a fresh function/object from the parent) \u2014 fix upstream, not in the child",parent:"parent re-rendered and nothing of its own changed \u2014 a pure cascade",props:"props genuinely changed value",hooks:"its own state/hooks changed",mount:"first render"}}});function resolveMode(e){const n=(e??"").trim().toLowerCase();if(n==="always"||n==="never"||n==="auto")return n;return"auto"}var import_node_fs16,import_node_path18,WATCHED_EXT,IGNORED_DIRS,DEBOUNCE_MS,EditWatcher,editWatcher;var init_editWatcher=__esm({"src/verify/editWatcher.ts"(){"use strict";import_node_fs16=__toESM(require("fs"));import_node_path18=__toESM(require("path"));WATCHED_EXT=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".json"]);IGNORED_DIRS=new Set(["node_modules",".git",".expo","ios","android","dist","lib","build",".next","coverage","__snapshots__"]);DEBOUNCE_MS=400;EditWatcher=class{constructor(){this.watcher=null;this.changed=new Set;this.lastEditAt=0;this.nudgedForCurrentBatch=false;this.mode="auto";this.started=false}start(e,n){this.mode=n;if(n==="never"||this.started)return;this.started=true;try{this.watcher=import_node_fs16.default.watch(e,{recursive:true},(t,r)=>{if(!r)return;const i=String(r);if(i.split(import_node_path18.default.sep).some(o=>IGNORED_DIRS.has(o)))return;if(!WATCHED_EXT.has(import_node_path18.default.extname(i)))return;this.noteEdit(i)});this.watcher.on("error",()=>this.stop())}catch{this.stop()}}noteEdit(e){const n=Date.now();if(n-this.lastEditAt>DEBOUNCE_MS)this.nudgedForCurrentBatch=false;this.lastEditAt=n;if(this.changed.size<50)this.changed.add(e)}stop(){try{this.watcher?.close()}catch{}this.watcher=null}markVerified(){this.changed.clear();this.nudgedForCurrentBatch=false}hasUnverifiedEdits(){return this.changed.size>0}nudge(){if(this.mode==="never"||!this.hasUnverifiedEdits())return null;if(this.mode==="auto"){if(this.nudgedForCurrentBatch)return null;this.nudgedForCurrentBatch=true}const e=[...this.changed];const n=e.slice(0,3).join(", ");const t=e.length>3?` +${e.length-3} more`:"";return`
|
|
795
985
|
|
|
796
986
|
---
|
|
797
987
|
\u26A0\uFE0F **${e.length} source file${e.length===1?"":"s"} changed since anything was last checked on the device** (${n}${t}).
|
|
798
|
-
For a behavior change, repeat the affected interaction and check the expected result. Use \`measure_renders\` with the same steps and \`compareToPrevious: true\` for render comparisons, or \`run_flow\` for supported behavior checks. Report what was checked and any remaining limits. This reminder tracks edits and tool calls; clearing it does not prove the change is correct.`}};editWatcher=new EditWatcher}});function createMcpServer(e){const n=new import_mcp.McpServer({name:"buoy",version:VERSION},{capabilities:{tools:{}},instructions:SERVER_INSTRUCTIONS});editWatcher.start(process.cwd(),resolveMode(process.env.BUOY_VERIFY));const t=n.registerTool.bind(n);n.registerTool=((r,i,
|
|
988
|
+
For a behavior change, repeat the affected interaction and check the expected result. Use \`measure_renders\` with the same steps and \`compareToPrevious: true\` for render comparisons, or \`run_flow\` for supported behavior checks. Report what was checked and any remaining limits. This reminder tracks edits and tool calls; clearing it does not prove the change is correct.`}};editWatcher=new EditWatcher}});function createMcpServer(e){const n=new import_mcp.McpServer({name:"buoy",version:VERSION},{capabilities:{tools:{}},instructions:SERVER_INSTRUCTIONS});editWatcher.start(process.cwd(),resolveMode(process.env.BUOY_VERIFY));const t=n.registerTool.bind(n);n.registerTool=((r,i,o)=>t(r,i,(async(...s)=>{const a=s[0];if(r==="list_devices"){}else if(a?.deviceId)await e.awaitBroker();else await e.settleDeviceChoice();noteAgentCall(e,r,a);const c=async()=>{const m=await o(...s);for(const f of m?.content??[]){if(f.type==="text"&&typeof f.text==="string")f.text=scrubSecrets(f.text)}return m};let l=await c();const u=m=>{const f=m;return f?.isError===true&&(f.content?.[0]?.text??"").startsWith(NOT_READY_MARK)};if(u(l)){const m=l.content[0].text;const f=/"([^"]+)"/.exec(m)?.[1];const b=Date.now()+NOT_READY_WAIT_MS;while(Date.now()<b){await new Promise(v=>setTimeout(v,250));if(f?e.accessState(f)==="ready":e.connectedDevices().some(v=>v.isPro))break}l=await c()}const d=l?.isError===true;let h=null;if(VERIFYING_TOOLS.has(r)&&!d)editWatcher.markVerified();else h=editWatcher.nudge();const w=optimizeNote();const p=[h,w].filter(m=>!!m);if(!p.length)return l;const g=l;if(Array.isArray(g?.content)){return{...g,content:[...g.content,...p.map(m=>({type:"text",text:m}))]}}return l})));registerTriageTools(n,e);registerFlowTools(n,e);registerRenderTools(n,e);registerGenericTools(n,e);registerPerfMonitorTools(n,e);registerEventsTools(n,e);registerNetworkTools(n,e);registerReactQueryTools(n,e);registerZustandTools(n,e);registerJotaiTools(n,e);registerReduxTools(n,e);registerStorageTools(n,e);registerRoutesTools(n,e);registerConsoleTools(n,e);registerSentryTools(n,e);registerTimeMachineTools(n,e);registerClockTools(n,e);registerPermissionsTools(n,e);registerLifecycleTools(n,e);registerLocationTools(n,e);registerScenariosTools(n,e);registerScreenshotTools(n,e);registerCameraTools(n);registerWebBenchTools(n,e);registerInteractTools(n,e);registerNativeTools(n,e);registerRecordingTools(n,e);registerDeviceTools(n,e);registerSourceTools(n,e);registerJsThreadTools(n,e);registerImagesTools(n,e);registerAssetsTools(n,e);registerReloadTools(n,e);return n}var import_mcp,import_zod35,NOT_READY_WAIT_MS,SERVER_INSTRUCTIONS,VERIFYING_TOOLS,deviceIdField;var init_server=__esm({"src/server.ts"(){"use strict";import_mcp=require("@modelcontextprotocol/sdk/server/mcp.js");import_zod35=require("zod");init_SyncClient();init_generic();init_perfMonitor();init_events();init_network();init_reactQuery();init_zustand();init_jotai();init_redux();init_storage();init_routes();init_console();init_sentry();init_timeMachine();init_clock();init_permissions();init_lifecycle();init_location();init_scenarios();init_screenshot();init_camera2();init_webBench2();init_interact();init_native();init_recording();init_device();init_source();init_secrets();init_jsThread();init_images();init_assets();init_reload();init_triage();init_flow();init_renders();init_session();init_editWatcher();init_version();NOT_READY_WAIT_MS=6e3;SERVER_INSTRUCTIONS=`Buoy MCP connects your editor to supported Buoy tools through the configured broker.
|
|
799
989
|
|
|
800
990
|
Start with account and connection setup. Use \`list_devices\` to select an app and inspect
|
|
801
991
|
its available tools. App data and action tools require Buoy Pro. If access fails, explain
|
|
@@ -900,7 +1090,7 @@ Include restart or persistence checks when relevant to the change. Use appropria
|
|
|
900
1090
|
checks for documentation-only work. Report actual checks, observations and remaining limits.
|
|
901
1091
|
BUOY_VERIFY reminders track selected edits and tool calls; clearing a reminder is not a
|
|
902
1092
|
test result. Stay within the user's authorized task and preserve existing project work.`;VERIFYING_TOOLS=new Set(["measure_renders","scenario_action","run_flow","run_benchmark_batch","run_web_benchmark","find_web_ceiling","screenshot_web_variants","get_triage","tap_element","describe_screen","get_console","get_network_requests","get_events","get_snapshot"]);deviceIdField={deviceId:import_zod35.z.string().optional().describe('Target device id (from list_devices). Omit to auto-select when exactly one device is connected. Use "All" to broadcast.')}}});var flowRun_exports={};__export(flowRun_exports,{formatFlowResults:()=>formatFlowResults,parseFlowRunArgs:()=>parseFlowRunArgs,runFlows:()=>runFlows});function parseFlowRunArgs(e){const n={names:[]};for(let t=0;t<e.length;t++){const r=e[t];if(r==="--device")n.deviceId=e[++t];else if(r==="--update-snapshots")n.updateSnapshots=true;else if(r==="--json")n.json=true;else if(r==="--wait")n.waitMs=Number(e[++t])*1e3;else if(r==="--all")continue;else if(!r.startsWith("--"))n.names.push(r);else throw new Error(`Unknown option ${r}.`)}return n}async function savedFlowNames(){const e=import_node_path20.default.join(process.cwd(),".buoy","flows");return(await import_node_fs18.promises.readdir(e).catch(()=>[])).filter(n=>n.endsWith(".json")).map(n=>n.replace(/\.json$/,"")).sort()}async function runFlows(e,n=t=>process.stderr.write(`${t}
|
|
903
|
-
`)){const t=e.names.length?e.names:await savedFlowNames();if(t.length===0)throw new Error('No saved flows. Save one with run_flow and save:"name", or pass a flow name.');const r=process.env.BUOY_BROKER_PORT;const i=new SyncClient({url:process.env.BUOY_BROKER_URL,port:r?Number(r):void 0,autoSpawnBroker:process.env.BUOY_NO_SPAWN!=="1"});const
|
|
1093
|
+
`)){const t=e.names.length?e.names:await savedFlowNames();if(t.length===0)throw new Error('No saved flows. Save one with run_flow and save:"name", or pass a flow name.');const r=process.env.BUOY_BROKER_PORT;const i=new SyncClient({url:process.env.BUOY_BROKER_URL,port:r?Number(r):void 0,autoSpawnBroker:process.env.BUOY_NO_SPAWN!=="1"});const o=createMcpServer(i);const[s,a]=import_inMemory.InMemoryTransport.createLinkedPair();const c=new import_client.Client({name:"buoy-flow-run",version:"1"});try{await o.connect(a);await c.connect(s);await i.start();const l=Date.now()+(e.waitMs??6e4);while(Date.now()<l&&!i.connectedDevices().some(d=>d.isPro&&(!e.deviceId||d.deviceId===e.deviceId))){await new Promise(d=>setTimeout(d,500))}if(!i.connectedDevices().some(d=>d.isPro)){throw new Error("No Buoy Pro app connected. Start the app (with Buoy) on a simulator or device, then run again.")}const u=[];for(const d of t){const h=Date.now();n(`\u25B6 ${d}`);const w=await c.callTool({name:"run_flow",arguments:{flow:d,include:"none",...e.deviceId?{deviceId:e.deviceId}:{},...e.updateSnapshots?{updateSnapshots:true}:{}}},void 0,{timeout:10*6e4});const p=(w.content??[]).filter(m=>m.type==="text").map(m=>m.text).join("\n");const g=w.isError!==true;u.push({name:d,passed:g,ms:Date.now()-h,report:p});n(`${g?"\u2713":"\u2717"} ${d} (${((Date.now()-h)/1e3).toFixed(1)}s)`)}return u}finally{await c.close().catch(()=>void 0);await Promise.race([i.stop().catch(()=>void 0),new Promise(l=>setTimeout(l,2e3))])}}function formatFlowResults(e){const n=e.filter(r=>!r.passed);const t=[`${e.length-n.length} of ${e.length} flows passed.`];for(const r of n){t.push("",`\u2717 ${r.name}`,r.report.trim(),` Rerun: npx @buoy-gg/mcp flow run ${r.name}`)}return t.join("\n")}var import_node_fs18,import_node_path20,import_client,import_inMemory;var init_flowRun=__esm({"src/flowRun.ts"(){"use strict";import_node_fs18=require("fs");import_node_path20=__toESM(require("path"));import_client=require("@modelcontextprotocol/sdk/client/index.js");import_inMemory=require("@modelcontextprotocol/sdk/inMemory.js");init_SyncClient();init_server()}});var import_stdio=require("@modelcontextprotocol/sdk/server/stdio.js");init_hidStream();init_recorder();init_SyncClient();init_server();var import_node_child_process19=require("child_process");var import_node_fs17=__toESM(require("fs"));var import_node_os13=__toESM(require("os"));var import_node_path19=__toESM(require("path"));init_version();function defaultEnv(){return{BUOY_VERIFY:"auto"}}var PUBLIC_REGISTRY="https://registry.npmjs.org";var PROBE_TIMEOUT_MS3=3e3;function runInit(e={}){const n=e.cwd??process.cwd();const t=e.skillSrcDir??import_node_path19.default.resolve(__dirname,"../skill");const r=e.log??(s=>process.stdout.write(s+"\n"));const i=resolveEntry2(e,r);const o=[];upsertMcpConfig(import_node_path19.default.join(n,".mcp.json"),"mcpServers",i,n,o);import_node_fs17.default.mkdirSync(import_node_path19.default.join(n,".cursor"),{recursive:true});upsertMcpConfig(import_node_path19.default.join(n,".cursor","mcp.json"),"mcpServers",i,n,o);if(import_node_fs17.default.existsSync(import_node_path19.default.join(n,".vscode"))){upsertMcpConfig(import_node_path19.default.join(n,".vscode","mcp.json"),"servers",i,n,o)}installSkills(t,n,o);appendDebuggingGuide(import_node_path19.default.join(n,"CLAUDE.md"),n,o);appendDebuggingGuide(import_node_path19.default.join(n,"AGENTS.md"),n,o);r("Buoy MCP configuration written:");for(const s of o)r(" \u2022 "+s);r("");r("Next steps:");r(" 1. Restart your editor (or reconnect the MCP server) to load `buoy`.");r(" 2. Complete account setup, then open an app with the required Buoy tools and sync integration.");r(" 3. Confirm the device and tools are available. MCP data/action access requires Pro.");if(i.command==="npx"){r("");r(`The editor launches the server with \`npx -y ${PACKAGE_NAME}@latest\`, so it stays`);r(`Registry access may be needed. Re-run \`npx -y ${PACKAGE_NAME}@latest init\` to refresh configuration.`)}else if(!e.cliPath){r("");r(`This uses a pinned local install (no network on startup). To update it later,`);r(`To update the local package, run: npx -y ${i.args[0]?.replace(/dist[/\\]cli\.js$/,"")??""}@latest init --local`)}}function resolveEntry2(e,n){if(e.cliPath){return{type:"stdio",command:"node",args:[e.cliPath],env:defaultEnv()}}const t=e.mode??"auto";if(t==="npx"){return npxEntry()}if(t==="local"){return localEntry(e,n)}const r=probeRegistry();if(r.reachable){return npxEntry()}n(`\u26A0 npm registry ${r.registry?`(${r.registry}) `:""}looks unreachable \u2014 \`npx @latest\` would hang your editor at startup. Falling back to a pinned local install.`);return localEntry(e,n)}function npxEntry(){return{type:"stdio",command:"npx",args:["-y",`${PACKAGE_NAME}@latest`],env:defaultEnv()}}function localEntry(e,n){const t=e.installDir??process.env.BUOY_MCP_HOME??import_node_path19.default.join(import_node_os13.default.homedir(),".buoy-mcp");const r=e.registry??PUBLIC_REGISTRY;const i=installLocalCopy(t,r,n);if(i){return{type:"stdio",command:"node",args:[i],env:defaultEnv()}}n("\u26A0 local install failed \u2014 writing the npx entry instead (see the error above).");return npxEntry()}function installLocalCopy(e,n,t){const r=`${PACKAGE_NAME}@${VERSION==="0.0.0-dev"?"latest":VERSION}`;import_node_fs17.default.mkdirSync(e,{recursive:true});const i=process.platform==="win32"?"npm.cmd":"npm";t(`Installing ${r} into ${e} from ${n} \u2026`);const o=(0,import_node_child_process19.spawnSync)(i,["install",r,"--prefix",e,"--registry",n,`--@buoy-gg:registry=${n}`,"--no-audit","--no-fund","--loglevel=error"],{stdio:["ignore","ignore","inherit"],encoding:"utf8"});if(o.status!==0){t(`\u26A0 npm install exited with code ${o.status??"?"}${o.error?` (${o.error.message})`:""}.`);return null}const s=import_node_path19.default.join(e,"node_modules",PACKAGE_NAME,"dist","cli.js");if(!import_node_fs17.default.existsSync(s)){t(`\u26A0 install finished but ${s} is missing.`);return null}return s}function probeRegistry(){const e=effectiveRegistry();if(!e)return{reachable:false,registry:null};if(/^https?:\/\/registry\.npmjs\.org\/?$/i.test(e)){return{reachable:true,registry:e}}return{reachable:hostReachable(e),registry:e}}function effectiveRegistry(){const e=npmConfigGet("@buoy-gg:registry");if(e)return e;const n=npmConfigGet("registry");return n??PUBLIC_REGISTRY}function npmConfigGet(e){const n=process.platform==="win32"?"npm.cmd":"npm";const t=(0,import_node_child_process19.spawnSync)(n,["config","get",e],{encoding:"utf8",timeout:PROBE_TIMEOUT_MS3});if(t.status!==0||typeof t.stdout!=="string")return null;const r=t.stdout.trim();if(!r||r==="undefined"||r==="null")return null;return r}function hostReachable(e){const n=(0,import_node_child_process19.spawnSync)(process.execPath,["-e",REACHABILITY_PROBE,e,String(PROBE_TIMEOUT_MS3)],{encoding:"utf8",timeout:PROBE_TIMEOUT_MS3+2e3});return n.status===0}var REACHABILITY_PROBE=`
|
|
904
1094
|
const url = process.argv[1];
|
|
905
1095
|
const ms = Number(process.argv[2]) || 3000;
|
|
906
1096
|
const c = new AbortController();
|
|
@@ -913,7 +1103,7 @@ fetch(url, { method: 'HEAD', signal: c.signal })
|
|
|
913
1103
|
clearTimeout(t);
|
|
914
1104
|
process.exit(1);
|
|
915
1105
|
});
|
|
916
|
-
`;function upsertMcpConfig(e,n,t,r,i){let
|
|
1106
|
+
`;function upsertMcpConfig(e,n,t,r,i){let o={};if(import_node_fs17.default.existsSync(e)){try{o=JSON.parse(import_node_fs17.default.readFileSync(e,"utf8"))}catch{import_node_fs17.default.copyFileSync(e,e+".bak");i.push(`existing ${rel(e,r)} was invalid JSON \u2014 backed up to ${rel(e,r)}.bak`);o={}}}else{import_node_fs17.default.mkdirSync(import_node_path19.default.dirname(e),{recursive:true})}const s=o[n]&&typeof o[n]==="object"?o[n]:{};const a="buoy"in s;s.buoy=t;o[n]=s;import_node_fs17.default.writeFileSync(e,JSON.stringify(o,null,2)+"\n");i.push(`${a?"updated":"added"} \`buoy\` in ${rel(e,r)}`)}var GUIDE_HEADING="# Debugging with Buoy";var DEBUGGING_GUIDE=`${GUIDE_HEADING}
|
|
917
1107
|
|
|
918
1108
|
Use Buoy to inspect a connected app when runtime evidence helps the task.
|
|
919
1109
|
Complete account, tool integration and connection setup first. MCP data and
|
|
@@ -946,14 +1136,14 @@ only source review or a build was performed.
|
|
|
946
1136
|
reminders, \`always\` repeats until checked, and \`never\` disables them.
|
|
947
1137
|
A reminder is not a test result. Choose checks appropriate to the change;
|
|
948
1138
|
prose-only edits do not require running device actions.
|
|
949
|
-
`;function appendDebuggingGuide(e,n,t){let r="";if(import_node_fs17.default.existsSync(e)){try{r=import_node_fs17.default.readFileSync(e,"utf8")}catch{t.push(`\u26A0 could not read ${rel(e,n)} \u2014 skipped the debugging guide`);return}if(r.includes(GUIDE_HEADING)){t.push(`${rel(e,n)} already has the "${GUIDE_HEADING}" block; preserved existing text. Review it against the current bundled guidance before relying on older instructions.`);return}}const i=r===""?"":r.endsWith("\n")?"\n":"\n\n";try{import_node_fs17.default.writeFileSync(e,r+i+DEBUGGING_GUIDE);t.push(`${r?"appended":"created"} "${GUIDE_HEADING}" block in ${rel(e,n)}`)}catch{t.push(`\u26A0 could not write ${rel(e,n)} \u2014 skipped the debugging guide`)}}function installSkills(e,n,t){if(!import_node_fs17.default.existsSync(e)){t.push("\u26A0 no bundled skills found \u2014 skipped");return}const r=import_node_fs17.default.readdirSync(e,{withFileTypes:true}).filter(i=>i.isDirectory()&&import_node_fs17.default.existsSync(import_node_path19.default.join(e,i.name,"SKILL.md")));if(r.length===0){t.push("\u26A0 no skills with a SKILL.md found \u2014 skipped");return}for(const i of r){const
|
|
950
|
-
`);stopAllRecordingsNow();setTimeout(()=>process.exit(0),2e3).unref();void(async()=>{await n.stop().catch(()=>{});await t.close().catch(()=>{});process.exit(0)})()};process.stdin.once("end",()=>
|
|
951
|
-
`);n.start().then(
|
|
952
|
-
`)).catch(
|
|
953
|
-
`))}async function brokerHasProApp(){const e=process.env.BUOY_BROKER_PORT;const n=new SyncClient({url:process.env.BUOY_BROKER_URL,port:e?Number(e):void 0,autoSpawnBroker:false});try{const t=await Promise.race([n.start().then(()=>true,()=>false),new Promise(r=>setTimeout(()=>r(false),4e3))]);if(!t)return false;for(let r=0;r<10;r++){if(n.connectedDevices().some(i=>i.tier==="pro"))return true;await new Promise(i=>setTimeout(i,300))}return false}finally{await Promise.race([n.stop().catch(()=>{}),new Promise(t=>setTimeout(t,2e3))])}}if(process.argv[2]==="web-bench"){void(async()=>{try{const e=process.argv.slice(3);const n=e.find(
|
|
954
|
-
`));const c=a.status==="failed"||a.browserLeftRunning?1:0;const
|
|
955
|
-
`,()=>process.exit(1));setTimeout(()=>process.exit(1),5e3).unref()}})()}else if(process.argv[2]==="flow"&&process.argv[3]==="run"){void(async()=>{try{const{parseFlowRunArgs:e,runFlows:n,formatFlowResults:t}=await Promise.resolve().then(()=>(init_flowRun(),flowRun_exports));const r=e(process.argv.slice(4));const i=await n(r);const
|
|
956
|
-
`,()=>process.exit(
|
|
1139
|
+
`;function appendDebuggingGuide(e,n,t){let r="";if(import_node_fs17.default.existsSync(e)){try{r=import_node_fs17.default.readFileSync(e,"utf8")}catch{t.push(`\u26A0 could not read ${rel(e,n)} \u2014 skipped the debugging guide`);return}if(r.includes(GUIDE_HEADING)){t.push(`${rel(e,n)} already has the "${GUIDE_HEADING}" block; preserved existing text. Review it against the current bundled guidance before relying on older instructions.`);return}}const i=r===""?"":r.endsWith("\n")?"\n":"\n\n";try{import_node_fs17.default.writeFileSync(e,r+i+DEBUGGING_GUIDE);t.push(`${r?"appended":"created"} "${GUIDE_HEADING}" block in ${rel(e,n)}`)}catch{t.push(`\u26A0 could not write ${rel(e,n)} \u2014 skipped the debugging guide`)}}function installSkills(e,n,t){if(!import_node_fs17.default.existsSync(e)){t.push("\u26A0 no bundled skills found \u2014 skipped");return}const r=import_node_fs17.default.readdirSync(e,{withFileTypes:true}).filter(i=>i.isDirectory()&&import_node_fs17.default.existsSync(import_node_path19.default.join(e,i.name,"SKILL.md")));if(r.length===0){t.push("\u26A0 no skills with a SKILL.md found \u2014 skipped");return}for(const i of r){const o=import_node_path19.default.join(e,i.name);const s=import_node_path19.default.join(n,".claude","skills",i.name);copyDir(o,s);t.push(`installed the ${i.name} skill \u2192 ${rel(import_node_path19.default.join(s,"SKILL.md"),n)}`)}}function copyDir(e,n){import_node_fs17.default.mkdirSync(n,{recursive:true});for(const t of import_node_fs17.default.readdirSync(e,{withFileTypes:true})){const r=import_node_path19.default.join(e,t.name);const i=import_node_path19.default.join(n,t.name);if(t.isDirectory())copyDir(r,i);else import_node_fs17.default.copyFileSync(r,i)}}function rel(e,n){const t=import_node_path19.default.relative(n,e);return t&&!t.startsWith("..")?t:e}console.log=(...e)=>console.error(...e);console.info=(...e)=>console.error(...e);console.debug=(...e)=>console.error(...e);async function main(){const e=process.env.BUOY_BROKER_PORT;const n=new SyncClient({url:process.env.BUOY_BROKER_URL,port:e?Number(e):void 0,autoSpawnBroker:process.env.BUOY_NO_SPAWN!=="1"});const t=createMcpServer(n);const r=new import_stdio.StdioServerTransport;let i=false;const o=s=>{if(i)return;i=true;process.stderr.write(`[buoy-mcp] shutting down (${s})
|
|
1140
|
+
`);stopAllRecordingsNow();stopAllHidStreamsNow();setTimeout(()=>process.exit(0),2e3).unref();void(async()=>{await n.stop().catch(()=>{});await t.close().catch(()=>{});process.exit(0)})()};process.stdin.once("end",()=>o("stdin closed"));process.stdin.once("close",()=>o("stdin closed"));t.server.onclose=()=>o("transport closed");process.on("SIGINT",()=>o("SIGINT"));process.on("SIGTERM",()=>o("SIGTERM"));process.on("SIGHUP",()=>o("SIGHUP"));await t.connect(r);process.stderr.write(`[buoy-mcp] serving MCP over stdio; connecting to broker\u2026
|
|
1141
|
+
`);n.start().then(s=>process.stderr.write(`[buoy-mcp] broker ${s}
|
|
1142
|
+
`)).catch(s=>process.stderr.write(`[buoy-mcp] broker connection failed: ${s?.message??s} \u2014 tools will report no devices until it recovers
|
|
1143
|
+
`))}async function brokerHasProApp(){const e=process.env.BUOY_BROKER_PORT;const n=new SyncClient({url:process.env.BUOY_BROKER_URL,port:e?Number(e):void 0,autoSpawnBroker:false});try{const t=await Promise.race([n.start().then(()=>true,()=>false),new Promise(r=>setTimeout(()=>r(false),4e3))]);if(!t)return false;for(let r=0;r<10;r++){if(n.connectedDevices().some(i=>i.tier==="pro"))return true;await new Promise(i=>setTimeout(i,300))}return false}finally{await Promise.race([n.stop().catch(()=>{}),new Promise(t=>setTimeout(t,2e3))])}}if(process.argv[2]==="web-bench"){void(async()=>{try{const e=process.argv.slice(3);const n=e.find(u=>!u.startsWith("--"));if(!n)throw new Error("usage: buoy-mcp web-bench <config.json> [--json]");const{readFileSync:t}=await import("fs");const{runWebBench:r,formatWebBenchMarkdown:i}=await Promise.resolve().then(()=>(init_webBench(),webBench_exports));const{readEntitlement:o}=await Promise.resolve().then(()=>(init_camera(),camera_exports));if(!o().isPro&&!await brokerHasProApp()){throw new Error("web-bench is a Buoy Pro feature. Sign in to Buoy Desktop with a Pro account, or open an app signed in to Pro. See https://buoy.gg/pricing.")}const s=JSON.parse(t(n,"utf8"));const a=await r({...s,durationMs:s.durationMs??s.perCaseDurationMs},u=>process.stderr.write(`[web-bench] ${u}
|
|
1144
|
+
`));const c=a.status==="failed"||a.browserLeftRunning?1:0;const l=(e.includes("--json")?JSON.stringify(a,null,2):i(a))+"\n";setTimeout(()=>process.exit(c),5e3).unref();process.stdout.write(l,()=>process.exit(c))}catch(e){process.stderr.write(`[buoy-mcp] web-bench failed: ${e?.message??e}
|
|
1145
|
+
`,()=>process.exit(1));setTimeout(()=>process.exit(1),5e3).unref()}})()}else if(process.argv[2]==="flow"&&process.argv[3]==="run"){void(async()=>{try{const{parseFlowRunArgs:e,runFlows:n,formatFlowResults:t}=await Promise.resolve().then(()=>(init_flowRun(),flowRun_exports));const r=e(process.argv.slice(4));const i=await n(r);const o=r.json?JSON.stringify(i,null,2):t(i);const s=i.every(a=>a.passed)?0:1;setTimeout(()=>process.exit(s),5e3).unref();process.stdout.write(`${o}
|
|
1146
|
+
`,()=>process.exit(s))}catch(e){process.stderr.write(`[buoy-mcp] flow run failed: ${e?.message??e}
|
|
957
1147
|
`,()=>process.exit(1));setTimeout(()=>process.exit(1),5e3).unref()}})()}else if(process.argv[2]==="init"){try{const e=process.argv.slice(3);let n="auto";if(e.includes("--local"))n="local";else if(e.includes("--npx"))n="npx";const t=e.indexOf("--registry");const r=t!==-1?e[t+1]:void 0;runInit({mode:n,registry:r});process.exit(0)}catch(e){process.stderr.write(`[buoy-mcp] init failed: ${e?.message??e}
|
|
958
1148
|
`);process.exit(1)}}else{main().catch(e=>{process.stderr.write(`[buoy-mcp] fatal: ${e?.message??e}
|
|
959
1149
|
`);process.exit(1)})}
|