@buoy-gg/mcp 7.0.51 → 7.0.53
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-27P7ATNT.mjs +427 -0
- package/dist/chunk-ALXRBSW6.mjs +146 -0
- package/dist/cli.js +178 -111
- package/dist/cli.mjs +2 -2
- package/dist/index.js +174 -107
- package/dist/index.mjs +1 -1
- package/dist/webBench-2IFT74EV.mjs +1 -0
- package/package.json +3 -3
- package/skill/buoy-optimize/MEASURING.md +100 -0
- package/skill/buoy-optimize/SKILL.md +99 -97
- package/dist/chunk-EKM5ZZKU.mjs +0 -139
- package/dist/chunk-ZP243U3K.mjs +0 -367
- package/dist/webBench-K5MAFWO3.mjs +0 -1
package/dist/chunk-ZP243U3K.mjs
DELETED
|
@@ -1,367 +0,0 @@
|
|
|
1
|
-
import{describeDevices as Ur,describeDiagnosis as zr,describeInputs as Wr,proRequired as Jr,readEntitlement as ut,run as X}from"./chunk-RYFN5J56.mjs";import{formatWebBenchMarkdown as Gr,runWebBench as Vr}from"./chunk-EKM5ZZKU.mjs";import{DEFAULT_BROKER_PORT as Kr}from"@buoy-gg/sync-broker";var dt=Kr;var Ht=`http://localhost:${dt}`;var Yt=15e3;var Hr=2500;var Yr=1200;var Qt=2e4;var Qr=3e4;var Xt=5e3;var Xr=15*6e4;var ht="Dashboard";var Z="All";import{readFileSync as Zt,writeFileSync as Zr,mkdirSync as es,renameSync as ts,unlinkSync as ns}from"fs";import{dirname as rs,join as en,resolve as ss}from"path";import{homedir as os}from"os";import{createHash as as}from"crypto";import{validateLicense as is,isAcceptedValidation as cs,isTransientLicenseError as ls,resolveTier as us,isRecognizedAccount as ds,isBuoyToken as hs,verifyFreeToken as ps,resolveAccountAccess as ms,signCache as Ne,verifyCacheSignature as fs,LICENSE_LAUNCH_VALIDATION_TTL as tn,LICENSE_REVALIDATION_INTERVAL as me,LICENSE_TRANSIENT_RETRY_DELAYS as nn,KEYGEN_CONFIG as gs,createNodeSession as vs,CLI_AUDIENCE as ws,exchangeServiceKey as bs,isServiceKey as ys,normalizeLicenseKey as rn,checkDevToken as $s,isDevToken as ks}from"@buoy-gg/license/headless";var sn=["BUOY_LICENSE_KEY","BUOY_KEY","EXPO_PUBLIC_BUOY_KEY","VITE_BUOY_KEY","REACT_APP_BUOY_KEY"];function pt(e,n=process.env){for(const t of sn)if(n[t]!==void 0)return rn(n[t])||null;for(const t of[".env.development.local",".env.local",".env"]){let r;try{r=Zt(en(e,t),"utf8")}catch{continue}const s=new Map;for(const o of r.split(/\r?\n/)){const a=o.match(/^\s*(?:export\s+)?([A-Z_][A-Z_0-9]*)\s*=\s*(.*)$/);if(!a)continue;const i=a[2].trim();const c=i.match(/^(['"])(.*?)\1\s*(?:#.*)?$/);s.set(a[1],c?c[2]:i.split("#")[0].trim())}for(const o of sn)if(s.has(o))return rn(s.get(o))||null}return null}var _s=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=ss(n.projectDir??process.env.BUOY_PROJECT_DIR??process.cwd());const t=as("sha256").update(this.projectDir).digest("hex").slice(0,20);this.cacheFile=n.cacheFile??en(os(),".buoy",`account-${t}.json`);this.session=n.session!==void 0?n.session:vs({audience:ws,openBrowser:()=>{throw new Error("The MCP does not open a browser. Run `npx buoy login`.")}})}hasKeyAccess(){return ms({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(Zt(this.cacheFile,"utf8"));if(e.valid&&fs(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=pt(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<tn&&this.nextCheck===0){this.nextCheck=this.cache.lastValidatedAt+tn;return}this.busy=true;const n=this.generation;try{if(ks(e)){const i=$s(e);if(!i.ok){this.cache=null;this.removeCache()}else{const c=Math.min(Date.now(),i.claims.iat*1e3);const u=i.claims.tier==="free"?"free":"pro";this.cache=Ne({licenseKey:e,licenseId:`dev:${i.claims.sid}`,valid:true,tier:u,isPro:u==="pro",expiresAt:new Date(i.claims.exp*1e3).toISOString(),cachedAt:c,lastValidatedAt:Date.now()});this.persistCache()}this.nextCheck=Date.now()+me;return}if(ys(e)){const i=await bs(e,{origin:process.env.BUOY_SITE_URL||"https://buoy.gg"});if(n!==this.generation||pt(this.projectDir)!==e)return;if(!i.ok){if(i.reason==="rejected"){this.cache=null;this.removeCache();this.nextCheck=Date.now()+me}else{this.nextCheck=Date.now()+(nn[this.retry++]??me)}return}const c=Date.now();const u=i.claims.exp*1e3;this.cache=Ne({licenseKey:e,licenseId:`service:${i.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(hs(e)){const i=ps(e);if(!i){this.cache=null;this.removeCache()}else{const c=Date.now();this.cache=Ne({licenseKey:e,licenseId:`token:${i.accountHash}`,valid:true,tier:"free",isPro:false,expiresAt:null,cachedAt:c,lastValidatedAt:c});this.persistCache()}this.nextCheck=Date.now()+me;return}const t=await is(e);if(n!==this.generation||pt(this.projectDir)!==e)return;const r=t.data?.relationships?.product?.data?.id;const s=t.meta.code==="EXPIRED"&&(ds(t.data)||this.cache?.licenseKey===e);if(r&&r!==gs.productId||!s&&!cs(t)){this.cache=null;this.removeCache();this.nextCheck=Date.now()+me;return}const o=s?"free":us(t.data);const a=Date.now();this.cache=Ne({licenseKey:e,licenseId:t.data?.id??"",valid:true,tier:o,isPro:o==="pro",expiresAt:s?null:t.data.attributes.expiry,cachedAt:a,lastValidatedAt:a});this.persistCache();this.retry=0;this.nextCheck=a+me}catch(t){if(n!==this.generation)return;const r=ls(t)?nn[this.retry++]:void 0;this.nextCheck=Date.now()+(r??me)}finally{this.busy=false;this.notify()}}persistCache(){try{es(rs(this.cacheFile),{recursive:true,mode:448});Zr(`${this.cacheFile}.tmp`,JSON.stringify(this.cache),{mode:384});ts(`${this.cacheFile}.tmp`,this.cacheFile)}catch{}}removeCache(){try{ns(this.cacheFile)}catch{}}};import Ss from"http";import{randomUUID as xs}from"crypto";import{io as As}from"socket.io-client";import{createBroker as Ts,brokerTokenPath as mt,readBrokerToken as Ms,writeBrokerToken as Is,DASHBOARD_TOKEN_REQUIRED as Ds}from"@buoy-gg/sync-broker";function Rs(e,n){return e==="app"&&(n==="ping"||n==="reloadApp")}function on(e){return e>=2}function Os(e){if(Rs(e.toolId,e.action)){return{timeoutMs:e.fullMs,usedFullBudget:false}}if(!on(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 Cs(e){if(e.consecutiveTimeouts>=2)return true;if(e.lastOkAt>0&&e.now-e.lastOkAt>e.unresponsiveAfterMs){return true}return false}var Fs=class{constructor(e={}){this.socket=null;this.admitted=false;this.lockedDevices=new Set;this.hostAccount=null;this.broker=null;this.capabilities=new Map;this.devices=[];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.originProbed=new Set;this.lastSeen=new Map;this.deviceConnections=new Map;this.port=e.port??dt;this.url=e.url??(e.port?`http://localhost:${e.port}`:Ht);this.actionTimeoutMs=e.actionTimeoutMs??Yt;this.log=e.log??(n=>process.stderr.write(`[buoy-mcp] ${n}
|
|
2
|
-
`));this.autoSpawn=e.autoSpawnBroker??true}async start(){const e=await an(this.url);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 _s(()=>this.broker?.refreshAccess());this.hostAccount.start();this.broker=Ts({canUseDesktop:this.hostAccount.hasAccess,port:this.port,onError:t=>this.log(`broker error: ${t.code??t.message}`)});await Es(this.url);try{Is(this.broker.dashboardToken,mt(this.port))}catch(t){this.log(`could not write the broker token file: ${t.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=As(this.url,{transports:["websocket"],query:{deviceName:ht},auth:i=>{const c=this.broker?.dashboardToken??Ms(mt(this.port));i(c?{dashboardToken:c}:{})},reconnection:true,reconnectionDelay:500,timeout:4e3});this.socket=t;let r=false;const s=()=>{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",i=>{const c=!!i&&typeof i==="object"&&i.protocol===1&&i.ready===true;this.setAdmission(c);if(c){clearTimeout(o);this.rearmWatches();s()}});t.on("connect",()=>{t.emit("buoy:access:request")});t.on("disconnect",()=>this.setAdmission(false,true));const a=i=>i.message===Ds;t.once("connect_error",i=>{if(r)return;r=true;clearTimeout(o);n(new Error(a(i)?`The broker at ${this.url} refused this MCP as a dashboard: the token in ${mt(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}: ${i.message}`))});t.on("connect_error",i=>{if(!a(i)||t.active)return;setTimeout(()=>{if(this.socket===t&&!t.connected)t.connect()},1e3).unref?.()});t.on("devtool-capabilities",i=>{if(!this.admitted||this.lockedDevices.has(i.persistentDeviceId))return;this.capabilities.set(i.persistentDeviceId,i);void this.learnDevServerOrigin(i.persistentDeviceId)});t.on("all-devices-update",i=>{if(!this.admitted)return;if(!Array.isArray(i))return;let c=false;for(const l of i){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=i;const u=Date.now();for(const l of i)if(l.deviceId)this.lastSeen.set(l.deviceId,u);this.pruneStaleDevices();if(c)this.rearmWatches();else this.rearmReconnectedDevices(i)});t.on("devtool-sync",i=>{if(!this.admitted||this.lockedDevices.has(i.persistentDeviceId))return;const c=ce(i.persistentDeviceId,i.toolId);this.snapshots.set(c,i.payload);this.snapshotAt.set(c,Date.now());const u=this.snapshotWaiters.get(c);if(u&&u.length){this.snapshotWaiters.set(c,[]);for(const l of u)l(i.payload)}});t.on("devtool-action-result",i=>{if(!this.admitted)return;const c=this.pendingActions.get(i.requestId);if(!c)return;this.pendingActions.delete(i.requestId);clearTimeout(c.timer);c.resolve(i)})})}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.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.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 s of r)s(void 0)}for(const[t,r]of this.pendingActions)if(r.target===e||r.target===Z){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()-Xr;for(const[n,t]of this.lastSeen){if(t>e)continue;if(this.devices.some(s=>s.deviceId===n))continue;this.lastSeen.delete(n);this.capabilities.delete(n);this.health.delete(n);this.devServerOrigins.delete(n);this.originProbed.delete(n);const r=`${n}::`;for(const s of[...this.snapshots.keys()]){if(s.startsWith(r)){this.snapshots.delete(s);this.snapshotAt.delete(s)}}for(const s of[...this.watching.keys()]){if(s.startsWith(r))this.watching.delete(s)}}}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!==ht&&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=this.connectedDevices();const t=n.filter(o=>!this.lockedDevices.has(o.deviceId));if(t.length===0){if(n.length>0){throw new Error(`Devices are connected (${n.map(o=>o.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(t.length===1)return t[0].deviceId;const r=t.filter(o=>o.tools.length>0);if(r.length===1)return r[0].deviceId;if(r.length===0){const o=t.map(a=>a.deviceName).join(", ");throw new Error(`Connected devices (${o}) are not exposing any Buoy tools yet. Make sure the app is in the foreground with devtools mounted, then retry.`)}const s=r.map(o=>`${o.deviceName} (${o.deviceId})`).join(", ");throw new Error(`Multiple devices connected \u2014 specify deviceId. Connected: ${s}`)}requireProDevice(e){this.requireAdmission();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===Z){if(!this.connectedDevices().some(o=>o.isPro))throw new Error(t());return Z}const r=this.resolveDevice(e);const s=this.connectedDevices().find(o=>o.deviceId===r);if(!s?.isPro)throw new Error(t(s));return r}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 on(this.healthOf(e).consecutiveTimeouts)}timeoutFor(e,n,t){const r=this.healthOf(e);const{timeoutMs:s,usedFullBudget:o}=Os({consecutiveTimeouts:r.consecutiveTimeouts,lastFullBudgetAt:r.lastFullBudgetAt,now:Date.now(),fullMs:this.actionTimeoutMs,shortMs:Hr,recoveryProbeMs:Qt,toolId:n,action:t});if(o)r.lastFullBudgetAt=Date.now();return s}unresponsiveNote(e){const n=this.healthOf(e);const t=n.lastOkAt?Math.round((Date.now()-n.lastOkAt)/1e3):null;const r=Cs({consecutiveTimeouts:n.consecutiveTimeouts,lastOkAt:n.lastOkAt,now:Date.now(),unresponsiveAfterMs:Qr});const s=[`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)s.push(`Last captured error: ${o}`);s.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 s.join(" ")}lastFatalFor(e){const n=this.snapshots.get(ce(e,"console"));const t=n?.entries;if(!Array.isArray(t))return null;for(let r=t.length-1;r>=0;r--){const s=t[r];if(s?.fatal||s?.level==="error"){const o=(s.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(ce(n,e));return t?Date.now()-t:null}noteDevServerOrigin(e,n){if(typeof n==="string"&&/^https?:\/\//.test(n)){this.devServerOrigins.set(e,n)}}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{}}devServerOrigin(e){this.requireAdmission();const n=this.devServerOrigins.get(e);if(n)return n;const t=this.snapshots.get(ce(e,"app"));if(typeof t?.devServerOrigin==="string")return t.devServerOrigin;return null}ensureWatching(e,n){const t=ce(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 s=this.deviceConnections.get(t);this.deviceConnections.set(t,r);if(s===void 0||s===r)continue;for(const{toolId:o,targetDeviceId:a}of this.watching.values()){if(a===t)this.sendWatch(o,a)}}}unwatch(e,n){const t=ce(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(ce(n,e))}async getSnapshot(e,n,t={}){const r=this.resolveDevice(n);const s=ce(r,e);this.ensureWatching(e,r);let o=t.timeoutMs??Xt;if(t.timeoutMs===void 0&&this.isUnresponsive(r)){const u=this.healthOf(r);if(Date.now()-u.lastFullBudgetAt>Qt){u.lastFullBudgetAt=Date.now()}else{o=Yr}}const a=this.waitForSnapshot(s,o);this.socket?.emit("request-devtool-state",{toolId:e,targetDeviceId:r});const i=await a;this.requireAdmission();this.requireDeviceAccount(r);if(i!==void 0){if(!t.silent)this.noteOk(r);return{deviceId:r,payload:i}}if(!t.silent)this.noteTimeout(r);const c=this.snapshots.get(s);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)}`)}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 s=setTimeout(()=>{const a=(this.snapshotWaiters.get(e)??[]).filter(i=>i!==o);this.snapshotWaiters.set(e,a);t(void 0)},n);const o=a=>{clearTimeout(s);t(a)};r.push(o);this.snapshotWaiters.set(e,r)})}async callAction(e,n,t,r,s={}){this.requireAdmission();const o=r===Z?Z:this.resolveDevice(r);if(!this.socket)throw new Error("SyncClient is not connected");const a=xs();const i=s.timeoutMs??this.timeoutFor(o,e,n);const c=await new Promise((u,l)=>{const d=setTimeout(()=>{this.pendingActions.delete(a);if(o!==Z&&!s.silent)this.noteTimeout(o);l(new Error(`Action "${e}.${n}" got no answer in ${i}ms. `+(o===Z?"No device responded.":this.unresponsiveNote(o))))},i);this.pendingActions.set(a,{resolve:u,reject:l,timer:d,target:o});this.socket.emit("devtool-action",{requestId:a,toolId:e,targetDeviceId:o,action:n,params:t??{}})});if(o!==Z&&!s.silent)this.noteOk(o);if(!c.ok){throw new Error(c.error||`Action "${e}.${n}" failed on device`)}return c.result}};var ce=(e,n)=>`${e}::${n}`;function an(e,n=800){return new Promise(t=>{const r=Ss.get(e,s=>{s.resume();t((s.statusCode??0)>0)});r.setTimeout(n,()=>{r.destroy();t(false)});r.on("error",()=>t(false))})}async function Es(e,n=20){for(let t=0;t<n;t++){if(await an(e,300))return;await Bs(50)}throw new Error(`Spawned broker never became reachable at ${e}`)}var Bs=e=>new Promise(n=>setTimeout(n,e));var fe="7.0.51"?"7.0.51":"0.0.0-dev";var le="@buoy-gg/mcp";import{promises as cn}from"fs";import Ps from"os";import js from"path";var qs=24*60*60*1e3;var Ns=1500;var Ls=`https://registry.npmjs.org/${le}/latest`;var ln=js.join(Ps.tmpdir(),"buoy-mcp-update-check.json");function Us(e,n){const t=o=>o.split("-")[0].split(".").map(a=>Number(a)||0);const r=t(e);const s=t(n);for(let o=0;o<3;o++){const a=r[o]??0;const i=s[o]??0;if(a>i)return true;if(a<i)return false}return false}async function zs(){try{const e=await cn.readFile(ln,"utf8");const n=JSON.parse(e);if(typeof n.checkedAt==="number"&&typeof n.latest==="string"){return n}}catch{}return null}async function Ws(e){const n=new AbortController;const t=setTimeout(()=>n.abort(),Ns);try{const r=await fetch(Ls,{signal:n.signal});if(!r.ok)return null;const s=await r.json();const o=typeof s.version==="string"?s.version:null;if(o){await cn.writeFile(ln,JSON.stringify({checkedAt:e,latest:o})).catch(()=>{})}return o}catch{return null}finally{clearTimeout(t)}}async function Js(e){const n=await zs();if(n&&e-n.checkedAt<qs)return n.latest;return Ws(e)}async function un(e=Date.now()){if(fe==="0.0.0-dev")return null;try{const n=await Js(e);if(n&&Us(n,fe)){return`A newer buoy-mcp is available (${n}; you're on ${fe}). Update by re-running: npx -y ${le}@latest init \u2014 then restart your editor.`}}catch{}return null}import{z as ee}from"zod";function Re(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function ft(e){return{isError:true,content:[{type:"text",text:e}]}}function dn(e,n){e.registerTool("list_devices",{description:"List the React Native devices connected to the Buoy broker and the dev tools each one exposes (toolId, version, available actions). Start here.",inputSchema:{}},async()=>{const t=await un();const r=n.listDevices();if(r.length===0){return Re({devices:[],hint:"No devices connected. Open the app with Buoy devtools running, then retry.",...t?{updateAvailable:t}:{}})}const s=r.filter(c=>c.isConnected);const o=s.some(c=>c.isPro);const a=s.some(c=>c.tier!=="locked");const i=s.filter(c=>c.collision);return Re({devices:r,...i.length>0?{warning:`${i.map(c=>`"${c.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.`}:{},...o?{}:{hint:a?"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."},...t?{updateAvailable:t}:{}})});e.registerTool("list_tool_actions",{description:"List the actions a given tool exposes, and which connected devices offer it. Use the action names with call_action.",inputSchema:{toolId:ee.string().describe('The tool id, e.g. "perf-monitor", "network", "react-query".')}},async({toolId:t})=>{const r=n.toolActions(t);if(r.length===0){return ft(`No connected device exposes tool "${t}". Call list_devices to see available tools.`)}return Re({toolId:t,offerings:r})});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:ee.string().describe("The tool id to read state from."),deviceId:ee.string().optional().describe("Target device id. Omit to auto-select when one device is connected."),timeoutMs:ee.number().optional().describe("How long to wait for a fresh snapshot before falling back to the cached one.")}},async({toolId:t,deviceId:r,timeoutMs:s})=>{try{const o=n.requireProDevice(r);const{payload:a}=await n.getSnapshot(t,o,{timeoutMs:s});return Re({toolId:t,deviceId:o,snapshot:a})}catch(o){return ft(hn(o))}});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:ee.string().describe('The tool id, e.g. "perf-monitor".'),action:ee.string().describe('The action name, e.g. "startRecording", "clearAll".'),params:ee.record(ee.unknown()).optional().describe("JSON params object for the action (shape depends on the action)."),deviceId:ee.string().optional().describe('Target device id. Omit to auto-select one device, or "All" to broadcast.'),timeoutMs:ee.number().optional().describe("Max time to wait for the device's result.")}},async({toolId:t,action:r,params:s,deviceId:o,timeoutMs:a})=>{try{const i=n.requireProDevice(o);const c=await n.callAction(t,r,s,i,{timeoutMs:a});return Re({toolId:t,action:r,ok:true,result:c??null})}catch(i){return ft(hn(i))}})}function hn(e){return e instanceof Error?e.message:String(e)}var xe=(e,n,t)=>Math.max(n,Math.min(t,e));var pn="__batch_warmup__";var Gs={nominal:"\u{1F7E2} nominal",fair:"\u{1F7E1} fair",serious:"\u{1F7E0} serious",critical:"\u{1F534} critical",unknown:"\u2014"};var Ae={perCaseDurationMs:5e3,settleMs:600,navTimeoutMs:5e3,runsPerCase:3,coolDownMs:2e3,discardWarmupRuns:0};function Te(e,n,t){return e??n??t}function Le(e,n={}){const t=[];const r=(e.targetRoute||"").trim();if(!r)throw new Error("targetRoute is required (the screen to benchmark).");let s=(e.bounceRoute||"").trim();if(!s)s=r==="/"?"/_buoy_bounce":"/";if(s===r){throw new Error(`bounceRoute ("${s}") 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 k=(d.name||"").trim()||`case ${h+1}`;return{id:`case-${h}`,name:k,params:d.params??{},route:d.route}});const a=xe(Math.round(Te(e.runsPerCase,n.runsPerCase,Ae.runsPerCase)),1,10);const i=xe(Math.round(Te(e.coolDownMs,n.coolDownMs,Ae.coolDownMs)),0,3e4);const c=xe(Math.round(Te(e.discardWarmupRuns,n.discardWarmupRuns,Ae.discardWarmupRuns)),0,a-1);const u=e.shuffleCases??n.shuffleCases??o.length>3;if(o.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(a===1){t.push("runsPerCase=1 \u2014 no median/variance; a single noisy run can mislead. 3+ is recommended.")}const l={targetRoute:r,bounceRoute:s,perCaseDurationMs:xe(Math.round(Te(e.perCaseDurationMs,n.perCaseDurationMs,Ae.perCaseDurationMs)),1e3,6e4),settleMs:xe(Math.round(Te(e.settleMs,n.settleMs,Ae.settleMs)),0,1e4),navTimeoutMs:xe(Math.round(Te(e.navTimeoutMs,n.navTimeoutMs,Ae.navTimeoutMs)),1e3,3e4),cases:o,runsPerCase:a,coolDownMs:i,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 mn(e){const n=c=>c>=1e3?`${(c/1e3).toFixed(c%1e3?1:0)}s`:`${c}ms`;const t=e.runsPerCase??1;const r=gt(e);const s=r/6e4;const o=s>=1?`~${s.toFixed(1)} min`:`~${Math.round(r/1e3)}s`;const a=[`**${n(e.perCaseDurationMs)} measured per page**`,t>1?`**${t} runs each** (median taken)`:`**1 run each** (no median \u2014 noisier)`,e.reloadBetweenCases?"**full reload between pages** (no state leaks across tests)":"no reload between pages",e.shuffleCases?"shuffled order (cancels thermal bias)":"fixed order",e.captureRenders!==false?"render capture on (per-component why-data)":"render capture off"];const i=e.settleMs+e.perCaseDurationMs+(e.coolDownMs??0)+1800;return`${a.join(", ")}. That's ~${n(i)} wall-clock per page; for ${e.cases.length} page(s) \xD7 ${t} run(s), **${o}** total.`}function gt(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 Vs(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 Ks(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 Hs(e){const n=e.filter(r=>!r.batchFailureReason&&!r.discardedWarmup).sort((r,s)=>(r.runIndex??0)-(s.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 Ys(e,n){const t=e.find(s=>s.isBaseline);if(t)return t;const r=n?.[0]?.name;if(r){const s=e.filter(o=>o.caseName===r);if(s.length===1)return s[0]}return e[0]}function Ue(e,n,t,r=[]){const s=e.filter(p=>p.batchId===n);const o=new Map(r.map(p=>[p.index,p.reason]));const a=Array.from(new Set(s.map(p=>p.batchIndex??0))).sort((p,m)=>p-m);const i=p=>{const m=s.filter(_=>(_.batchIndex??0)===p);if(m.length===0)return void 0;const v=m.filter(_=>!_.batchFailureReason&&!_.discardedWarmup);const w=v.filter(_=>_.webRun?.fps!=null);if(w.length>0&&w.length===v.length){const _=[...w].sort((T,I)=>T.webRun.fps-I.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 m.find(_=>_.batchFailureReason)??m[0]};const c=p=>typeof p==="number"?p:null;const u=a.map(p=>{const m=i(p);const v=s.filter(z=>(z.batchIndex??0)===p);const w=v.length;const _=v.filter(z=>!z.batchFailureReason&&!z.discardedWarmup);const T=z=>z.webRun?z.webRun.fps??z.jsFpsAvg:z.uiFpsAvg;const I=_.map(T).filter(z=>typeof z==="number");const F=m?.name??t?.[p]?.name??`case ${p+1}`;const lt=s.some(z=>(z.batchIndex??0)===p&&z.isBaseline===true);const C=o.get(p)??m?.batchFailureReason;const E=v.every(z=>z.batchFailureReason||z.discardedWarmup);const B=Boolean(C)||!m||E;const Q={batchIndex:p,caseName:F,params:m?.params??{},runs:w,failed:B,...m?.route?{route:m.route}:{},...lt?{isBaseline:true}:{},failureReason:B?C??(E&&m?"only warmup runs were saved":"no run recorded"):void 0,uiFps:c(m?.uiFpsAvg),jsFps:c(m?.jsFpsAvg),cpu:c(m?.cpuAvg),memMb:c(m?.memMaxMb),jsJank:c(m?.jsJankFrames),uiJank:c(m?.uiJankFrames),deviceMaxRefreshRate:c(m?.deviceMaxRefreshRate),deltaUiFps:null,deltaJsFps:null,validRuns:_.length,fpsMin:I.length?H(Math.min(...I),1):null,fpsMax:I.length?H(Math.max(...I),1):null,...m?.thermalState?{thermalState:m.thermalState}:{},renderCommits:c(m?.renderCommits),renderWasted:m?.renderWasted,topRenderers:m?.topRenderers??[]};const P=m?.webRun;if(!P)return{...Q,flags:B?[]:Vs(Q)};const Vt=[...P.longTasksSupported?[]:["long tasks"],...P.heapSupported?[]:["JS heap"],...P.loaf===null?["long animation frames"]:[]];const Kt={...Q,platform:"web",uiFps:null,uiJank:null,jsJank:null,cpu:null,memMb:P.heapSupported?Q.memMb:null,deviceMaxRefreshRate:Math.max(Q.deviceMaxRefreshRate??0,P.refreshHz??0)||null,longTaskPct:P.longTaskPct,frameGapP95Ms:P.frameGapP95Ms,frameGapMaxMs:P.frameGapMaxMs,edgeSilenceMs:P.edgeSilenceMs??null,jsFps:P.fps??Q.jsFps,longFrames:P.longFrames,...Vt.length?{missingMetrics:Vt}:{},loafBlockingMs:P.loaf?.blockingMs??null,styleLayoutMs:P.loaf?.styleLayoutMs??null,forcedLayoutMs:P.loaf?.forcedLayoutMs??null,topScripts:P.loaf?.topScripts??[],worstInteractionMs:P.interactions?.worstMs??null,layoutShift:P.layoutShift??null,domNodes:P.domNodesEnd??null,domGrowth:Hs(v),pageLoad:P.pageLoad??null,refreshCalibrated:P.refreshCalibrated??null};return{...Kt,flags:B?[]:Ks({...Kt,frames:P.frames})}}).filter(p=>p.caseName!==pn).map((p,m)=>({...p,batchIndex:m}));const l=Ys(u,t);if(l){l.isBaseline=true;for(const p of u){if(p===l)continue;if(p.uiFps!=null&&l.uiFps!=null)p.deltaUiFps=H(p.uiFps-l.uiFps,1);if(p.jsFps!=null&&l.jsFps!=null)p.deltaJsFps=H(p.jsFps-l.jsFps,1)}}const d=u.filter(p=>!p.failed);const h=(p,m)=>{let v;let w=NaN;for(const _ of d){const T=p(_);if(T==null)continue;if(v===void 0||m(T,w)){v=_;w=T}}return v?.caseName};const k=p=>p.platform==="web"?p.longFrames??null:p.jsJank==null&&p.uiJank==null?null:(p.jsJank??0)+(p.uiJank??0);const b={uiFps:h(p=>p.uiFps,(p,m)=>p>m),jsFps:h(p=>p.jsFps,(p,m)=>p>m),lowestCpu:h(p=>p.cpu,(p,m)=>p<m),lowestMem:h(p=>p.memMb,(p,m)=>p<m),fewestJank:h(k,(p,m)=>p<m),fewestLongTasks:h(p=>p.longTaskPct??null,(p,m)=>p<m)};const g=d.filter(p=>p.flags.length>0).map(p=>({caseName:p.caseName,flags:p.flags}));const y=d.filter(p=>p.flags.length===0).sort((p,m)=>(m.uiFps??m.jsFps??0)-(p.uiFps??p.jsFps??0)||(p.cpu??p.longTaskPct??Infinity)-(m.cpu??m.longTaskPct??Infinity)||(p.memMb??Infinity)-(m.memMb??Infinity)).map(p=>p.caseName);return{batchId:n,baselineName:l?.caseName??null,deviceMaxRefreshRate:d.find(p=>p.deviceMaxRefreshRate!=null)?.deviceMaxRefreshRate??null,rows:u,leaders:b,flagged:g,balanced:y}}function Qs(e){const n=e.filter(a=>!a.failed);if(n.length===0)return[];const t=n.map(a=>a.pageLoad?.navigationId);if(t.some(a=>a==null)||new Set(t).size!==t.length)return[];if(n.some(a=>(a.pageLoad?.pageAgeMs??Infinity)>3e4))return[];const r=a=>(a??"").replace(/\/+$/,"")||"/";const s=a=>{const i=a.pageLoad;if(!i?.loadPath||r(i.loadPath)!==r(a.route))return false;const c=new URLSearchParams(i.loadSearch??"");const u=[...c.keys()];if(new Set(u).size!==u.length)return false;const l=Object.entries(a.params);return u.length===l.length&&l.every(([d,h])=>c.get(d)===h)};if(n.some(a=>!s(a)))return[];const o=a=>a==null?"\u2014":String(Math.round(a));return[`**Page load** (each case started on a fresh page load):`,"",`| Case | TTFB ms | FCP ms | LCP ms | DOM ready ms | Script KB | Total KB |`,`|------|--------:|-------:|-------:|-------------:|----------:|---------:|`,...n.map(a=>{const i=a.pageLoad;return`| ${a.caseName} | ${o(i.ttfbMs)} | ${o(i.fcpMs)} | ${o(i.lcpMs)} | ${o(i.domContentLoadedMs)} | ${o(i.scriptKb)} | ${o(i.totalKb)} |`}),"",`_KB is bytes over the network. 0 can mean the file came from cache, so compare cold loads with cold loads._`]}function fn(e){const n=o=>o.platform==="web"?o.jsFps:o.uiFps;const t=e.filter(o=>!o.failed&&n(o)!=null&&o.fpsMin!=null&&o.fpsMax!=null).sort((o,a)=>(n(a)??0)-(n(o)??0));if(t.length<2)return null;const[r,s]=t;if((r.validRuns??0)<2||(s.validRuns??0)<2){return`**Too few runs to separate the top cases.** ${r.caseName} and ${s.caseName} each need 2+ valid runs before their FPS gap means anything.`}if((s.fpsMax??0)>=(r.fpsMin??0)||(n(r)??0)-(n(s)??0)<=2){return`**Too close to call:** ${r.caseName} (${r.fpsMin}\u2013${r.fpsMax} FPS) and ${s.caseName} (${s.fpsMin}\u2013${s.fpsMax} FPS) overlap or sit within 2 FPS. No clear winner between them; more runs may separate them.`}return null}function ze(e){const n=(h,k=1)=>h==null?"\u2014":h.toFixed(k);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")){Zs(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 s=e.rows.some(h=>h.thermalState);const o=s?" Thermal |":"";const a=s?"-------|":"";r.push(`| # | Case | UI FPS | JS FPS | CPU % | Mem MB | JS jank | UI jank |${o} Flags |`);r.push(`|---|------|-------:|-------:|------:|-------:|--------:|--------:|${a}-------|`);for(const h of e.rows){const k=s?` ${Gs[h.thermalState??"unknown"]??"\u2014"} |`:"";if(h.failed){r.push(`| ${h.batchIndex} | ${h.caseName} | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 |${k} \u274C FAILED (${h.failureReason}) |`);continue}const b=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)} |${k} ${b} |`)}const i=fn(e.rows);if(i){r.push("");r.push(i)}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 k=h.topRenderers.map(y=>`${y.name} \xD7${y.renders} (${y.totalMs}ms${y.cause?`, ${y.cause}`:""})`).join(", ");const b=h.renderCommits!=null?`${h.renderCommits} commits`:"";const g=h.renderWasted!=null?`${h.renderWasted} wasted`:"";return`- **${h.caseName}** \u2014 ${[b,g,k].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 vt(e,n){const t=(r,s)=>({a:{avg:H(r.avg,1),p95:H(r.p95,1)},b:{avg:H(s.avg,1),p95:H(s.p95,1)},deltaAvg:H(s.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},...gn(e.renders,n.renders)}}function Xs(e,n){const t=(a,i,c)=>({a:a??null,b:i??null,delta:a!=null&&i!=null?H(i-a,1):null,better:c});const r=a=>a.webRun.heapSupported?H(a.stats.memoryUsage.max,1):null;const s=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(s.fps??e.stats.jsFps.avg,o.fps??n.stats.jsFps.avg,"higher"),frameGapP95Ms:t(s.frameGapP95Ms,o.frameGapP95Ms,"lower"),frameGapMaxMs:t(s.frameGapMaxMs,o.frameGapMaxMs,"lower"),longFrames:t(s.longFrames,o.longFrames,"lower"),longTaskPct:t(s.longTaskPct,o.longTaskPct,"lower"),slowFrameBlockingMs:t(s.loaf?.blockingMs,o.loaf?.blockingMs,"lower"),styleLayoutPaintMs:t(s.loaf?.styleLayoutMs,o.loaf?.styleLayoutMs,"lower"),forcedLayoutMs:t(s.loaf?.forcedLayoutMs,o.loaf?.forcedLayoutMs,"lower"),worstInteractionMs:t(s.interactions?.worstMs,o.interactions?.worstMs,"lower"),layoutShift:t(s.layoutShift,o.layoutShift,"lower"),domNodes:t(s.domNodesEnd,o.domNodesEnd,"lower"),jsHeapMb:t(r(e),r(n),"lower"),topScripts:{a:s.loaf?.topScripts??[],b:o.loaf?.topScripts??[]},...gn(e.renders,n.renders)}}function gn(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 H(e,n){const t=Math.pow(10,n);return Math.round(e*t)/t}function Zs(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 s=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(s.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(...s)}const o=Qs(e.rows);if(o.length){n.push("");n.push(...o)}const a=fn(e.rows);if(a){n.push("");n.push(a)}const i=Array.from(new Set(e.rows.flatMap(l=>l.missingMetrics??[])));if(i.length){n.push("");n.push(`**Not measured in this browser:** ${i.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._`)}import{z as O}from"zod";import{z as eo}from"zod";var $=e=>({content:[{type:"text",text:e}]});var f=e=>({isError:true,content:[{type:"text",text:e}]});var M=e=>e instanceof Error?e.message:String(e);var A=eo.string().optional().describe("Target device id (auto-selected if one is connected).");function to(e,n){return typeof e==="number"&&e>0?e:n}function no(e){return e?`${e}
|
|
3
|
-
|
|
4
|
-
`:""}function vn(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 Oe(e,n){return async t=>{try{const r=e.requireProDevice(t.deviceId);return await n(t,r)}catch(r){return f(M(r))}}}var j="perf-monitor";var Ce=1500;var Fe=e=>new Promise(n=>setTimeout(n,e));var We=e=>({content:[{type:"text",text:JSON.stringify(e,null,2)}]});var ro=O.object({name:O.string().describe("Display name for this variant (becomes the saved run's name)."),params:O.record(O.string()).optional().describe('Query params applied to the route for this case, e.g. { "renderer": "v2", "count": "100" }.'),route:O.string().optional().describe("Optional per-case route override; defaults to targetRoute.")});async function wt(e,n){try{const t=await e.callAction(j,"getAutomationConfig",{},n);if(!t)return{};const{perCaseDurationMs:r,settleMs:s,navTimeoutMs:o,runsPerCase:a,coolDownMs:i,discardWarmupRuns:c,shuffleCases:u,reloadBetweenCases:l,captureRenders:d}=t;return{perCaseDurationMs:r,settleMs:s,navTimeoutMs:o,runsPerCase:a,coolDownMs:i,discardWarmupRuns:c,shuffleCases:u,reloadBetweenCases:l,captureRenders:d}}catch{return{}}}async function re(e,n){const{payload:t}=await e.getSnapshot(j,n,{timeoutMs:4e3});return t}function bt(e){const n=new Set;for(const t of e??[])if(t.batchId)n.add(t.batchId);return n}function wn(e,n){return(e??[]).filter(t=>t.batchId===n).length}function so(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 ge(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,s])=>({index:r,reason:s}))}function oo(e){const n=e.cases.length+(e.discardWarmupCase===true?1:0);return n*(e.runsPerCase??1)}var ao=1e4;function io(e){return!!e&&e!=="idle"&&e!=="done"&&e!=="cancelled"}async function bn(e,n,t,r=ao){const s=Date.now();while(Date.now()-s<r){const o=await re(e,n).catch(()=>null);if(o&&!io(o.live?.automation?.phase))return true;await Fe(Ce)}t(`automation still busy after ${Math.round(r/1e3)}s`);return false}async function co(e,n,t){const{preBatchIds:r,expectedRuns:s,maxWaitMs:o,log:a}=t;const i=t.reloadsBetweenCases?10:3;const c=Date.now();let u="";let l=false;let d=0;while(Date.now()-c<o){let b;try{b=await re(e,n)}catch{await Fe(Ce);continue}const g=b.index??[];const y=b.live?.automation?.phase??"idle";const p=b.live?.automationCompleted;if(p?.phase==="cancelled"&&!r.has(p.batchId)){return{batchId:p.batchId,failures:[],cancelled:true}}if(p?.phase==="done"&&!r.has(p.batchId)){return{batchId:p.batchId,failures:p.failures??ge(g,p.batchId)}}if(y!=="idle")l=true;if(y!==u){u=y;a(`automation phase: ${y}`)}const m=[...bt(g)].find(v=>!r.has(v));if(m){const v=wn(g,m);if(s>0&&v>=s){await bn(e,n,a);a(`batch ${m} complete (${v}/${s} runs saved)`);return{batchId:m,failures:ge(g,m)}}const w=(g??[]).filter(F=>F.batchId===m&&F.name!==pn).length;const _=b.live?.pendingBatchId===m;const T=Boolean(b.live&&"pendingBatchId"in b.live);const I=!t.reloadsBetweenCases||T;if(y==="idle"&&l&&w>0&&!_&&I){if(++d>=i){a(`batch ${m} settled (${v} runs, automation idle)`);return{batchId:m,failures:ge(g,m)}}}else{d=0}}await Fe(Ce)}const h=await re(e,n).catch(()=>null);const k=h?[...bt(h.index)].find(b=>!r.has(b)):void 0;if(k&&h)return{batchId:k,failures:ge(h.index,k),timedOut:true};throw new Error(`Batch did not start within ${Math.round(o/1e3)}s (last phase: ${u||"idle"}). Check get_automation_status \u2014 the device may not have navigated.`)}function yn(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:O.string().describe('The screen to benchmark, e.g. "/perf-test". Reads case params to pick a variant.'),cases:O.array(ro).min(1).describe("The variants to compare. Case #0 is the baseline for deltas."),bounceRoute:O.string().optional().describe('Screen to bounce to between runs so the test screen fully remounts. Defaults to "/" (or a stub if target is "/").'),runsPerCase:O.number().optional().describe("Runs per case; the median becomes the canonical result. Default 3 (1\u201310)."),perCaseDurationMs:O.number().optional().describe("How long to record each run. Default 5000."),settleMs:O.number().optional().describe("Idle gap after navigation before recording. Default 600."),coolDownMs:O.number().optional().describe("Idle between runs/cases for thermal recovery. Default 2000."),navTimeoutMs:O.number().optional().describe("Max wait for navigation per run. Default 5000."),discardWarmupRuns:O.number().optional().describe("Discard first N runs of each case before taking the median. Default 0."),shuffleCases:O.boolean().optional().describe("Interleave and shuffle case order to reduce order-related bias. Default on for >3 cases."),reloadBetweenCases:O.boolean().optional().describe("Fully reload JS between cases (needs <AutomationResumer/> mounted). Default false."),captureRenders:O.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:O.string().optional().describe("Target device id. Omit to auto-select when one device is connected."),maxWaitMs:O.number().optional().describe("Safety cap for how long to wait for completion. Defaults to ~3\xD7 the estimate + 60s.")}},async t=>{const r=s=>process.stderr.write(`[buoy-mcp] ${s}
|
|
5
|
-
`);try{const s=n.requireProDevice(t.deviceId);const o=await wt(n,s);const{config:a,warnings:i}=Le(t,o);const c=gt(a);const u=t.maxWaitMs??c*3+6e4;const l=oo(a);if(!await bn(n,s,r)){return f("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(j,"acknowledgeAutomation",{},s).catch(()=>{});await n.callAction(j,"setEnabled",{enabled:true},s).catch(()=>{});await n.callAction(j,"refreshIndex",{},s).catch(()=>{});const d=await re(n,s);const h=bt(d.index);r(`starting batch: ${a.cases.length} cases \xD7 ${a.runsPerCase} runs (~${Math.round(c/1e3)}s estimated) on ${s}`);await n.callAction(j,"startAutomation",{config:a},s);const k=await co(n,s,{preBatchIds:h,expectedRuns:l,maxWaitMs:u,log:r,reloadsBetweenCases:a.reloadBetweenCases===true});if(k.cancelled){await n.callAction(j,"acknowledgeAutomation",{},s).catch(()=>{});return f(`Batch ${k.batchId} was cancelled before completing.`)}await n.callAction(j,"refreshIndex",{},s).catch(()=>{});const b=await re(n,s);const g=Ue(b.index??[],k.batchId,a.cases,k.failures);await n.callAction(j,"acknowledgeAutomation",{},s).catch(()=>{});await n.callAction(j,"setEnabled",{enabled:false},s).catch(()=>{});if(g.rows.length===0){const m=n.connectedDevices().some(_=>_.deviceId===s);const v=b.live?.pendingBatchId===k.batchId;const w=!m?`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.`:k.timedOut?`No runs were saved before the wait cap (${Math.round(u/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 f(`Benchmark batch ${k.batchId||"(no id)"} saved no runs. ${w}`)}const y=ze(g);const p={batchId:k.batchId,leaders:g.leaders,balanced:g.balanced,flagged:g.flagged,rows:g.rows,failures:k.failures,warnings:i,estimateMs:c,...k.timedOut?{note:"Wait cap hit \u2014 results may be partial (some runs may still be saving)."}:{}};return $(`${y}
|
|
6
|
-
|
|
7
|
-
\`\`\`json
|
|
8
|
-
${JSON.stringify(p,null,2)}
|
|
9
|
-
\`\`\``)}catch(s){return f(M(s))}});e.registerTool("get_automation_status",{description:"Get the perf-monitor automation batch status (current phase + last completed batch) without waiting.",inputSchema:{deviceId:O.string().optional().describe("Target device id (auto-selected if one is connected).")}},async({deviceId:t})=>{try{const r=n.requireProDevice(t);const s=await re(n,r);return We({deviceId:r,automation:s.live?.automation??{phase:"idle"},automationCompleted:s.live?.automationCompleted??null})}catch(r){return f(M(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:A,maxWaitMs:O.number().optional().describe("Max time to wait. Default 600000 (10 min).")}},async({deviceId:t,maxWaitMs:r})=>{const s=a=>process.stderr.write(`[buoy-mcp] ${a}
|
|
10
|
-
`);const o=r??6e5;try{const a=n.requireProDevice(t);const i=Date.now();let c=false;let u=0;let l=-1;let d=null;while(Date.now()-i<o){let b;try{b=await re(n,a)}catch{await Fe(Ce);continue}const g=b.live?.automationCompleted;if(g?.phase==="cancelled")return f(`Batch ${g.batchId} was cancelled.`);if(g?.phase==="done"){d={batchId:g.batchId,failures:g.failures??ge(b.index,g.batchId)};break}const y=b.live?.automation?.phase??"idle";if(y!=="idle")c=true;const p=so(b.index);if(y==="idle"&&p){const m=wn(b.index,p);if(m===l){if(c&&++u>=3){d={batchId:p,failures:ge(b.index,p)};break}if(!c&&Date.now()-i>4e3){d={batchId:p,failures:ge(b.index,p)};break}}else{u=0;l=m}}else{u=0}await Fe(Ce)}if(!d)return f("No automation batch completed within the wait window.");await n.callAction(j,"refreshIndex",{},a).catch(()=>{});const h=await re(n,a);const k=Ue(h.index??[],d.batchId,void 0,d.failures);if(k.rows.length===0){await n.callAction(j,"acknowledgeAutomation",{},a).catch(()=>{});return f(`Batch ${d.batchId} saved no measured runs (only a warmup, or nothing). Check get_automation_status and run it again.`)}await n.callAction(j,"acknowledgeAutomation",{},a).catch(()=>{});return $(`${ze(k)}
|
|
11
|
-
|
|
12
|
-
\`\`\`json
|
|
13
|
-
${JSON.stringify(k,null,2)}
|
|
14
|
-
\`\`\``)}catch(a){return f(M(a))}});e.registerTool("get_batch_report",{description:"Re-rank a previously-run benchmark batch by its batchId (from the saved recordings index).",inputSchema:{batchId:O.string().describe("The batch id to report on."),deviceId:A}},async({batchId:t,deviceId:r})=>{try{const s=n.requireProDevice(r);await n.callAction(j,"refreshIndex",{},s).catch(()=>{});const o=await re(n,s);const a=(o.index??[]).filter(c=>c.batchId===t);if(a.length===0)return f(`No saved runs found for batch "${t}".`);const i=Ue(o.index??[],t);if(i.rows.length===0)return f(`Batch "${t}" has no measured runs, only a warmup.`);return $(`${ze(i)}
|
|
15
|
-
|
|
16
|
-
\`\`\`json
|
|
17
|
-
${JSON.stringify(i,null,2)}
|
|
18
|
-
\`\`\``)}catch(s){return f(M(s))}});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:O.string().describe("First (baseline) report id."),reportIdB:O.string().describe("Second report id to compare against the baseline."),deviceId:A}},async({reportIdA:t,reportIdB:r,deviceId:s})=>{try{const o=n.requireProDevice(s);const[a,i]=await Promise.all([n.callAction(j,"loadReport",{id:t},o),n.callAction(j,"loadReport",{id:r},o)]);if(!a)return f(`Report "${t}" not found.`);if(!i)return f(`Report "${r}" not found.`);const c=a.metadata.webRun;const u=i.metadata.webRun;if(c&&u){return We(Xs({name:a.metadata.name,stats:a.stats,webRun:c,renders:a.renders},{name:i.metadata.name,stats:i.stats,webRun:u,renders:i.renders}))}if(c||u){return We({...vt({name:a.metadata.name,stats:a.stats,renders:a.renders},{name:i.metadata.name,stats:i.stats,renders:i.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 We(vt({name:a.metadata.name,stats:a.stats,renders:a.renders},{name:i.metadata.name,stats:i.stats,renders:i.renders}))}catch(o){return f(M(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:O.number().optional().describe("How many pages/variants you plan to test, for a total-time estimate. Default 1."),deviceId:A}},async({pages:t,deviceId:r})=>{try{const s=n.requireProDevice(r);const o=await wt(n,s);const a=Math.max(1,Math.round(t??1));const{config:i}=Le({targetRoute:"/_preview",cases:Array.from({length:a},(u,l)=>({name:`page ${l+1}`}))},o);const c=Object.keys(o).length>0?"this device's saved settings":"default profile (none saved)";return $(`**Benchmark settings (${c}):** ${mn(i)}
|
|
19
|
-
|
|
20
|
-
\`\`\`json
|
|
21
|
-
${JSON.stringify(o,null,2)}
|
|
22
|
-
\`\`\``)}catch(s){return f(M(s))}});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:O.number().optional().describe("Recording length per page (ms)."),settleMs:O.number().optional().describe("Idle after navigation before recording (ms)."),coolDownMs:O.number().optional().describe("Idle between runs/cases (ms)."),navTimeoutMs:O.number().optional().describe("Max wait for navigation per run (ms)."),runsPerCase:O.number().optional().describe("Runs per page; median is the canonical result (1\u201310)."),discardWarmupRuns:O.number().optional().describe("Discard first N runs of each page before the median."),shuffleCases:O.boolean().optional().describe("Interleave and shuffle case order to reduce order-related bias."),reloadBetweenCases:O.boolean().optional().describe("Fully reload JS between pages (needs <AutomationResumer/> mounted)."),captureRenders:O.boolean().optional().describe("Capture per-component render counts/durations during each run."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=await n.callAction(j,"getAutomationConfig",{},r)??{};const o=["perCaseDurationMs","settleMs","coolDownMs","navTimeoutMs","runsPerCase","discardWarmupRuns","shuffleCases","reloadBetweenCases","captureRenders"];const a={};for(const d of o){const h=t[d];if(h!==void 0)a[d]=h}if(Object.keys(a).length===0){return f("No settings provided to save. Pass at least one field (e.g. perCaseDurationMs).")}const i={...s,...a};const c=await n.callAction(j,"setAutomationConfig",{config:i},r);const u=await wt(n,r);const{config:l}=Le({targetRoute:"/_preview",cases:[{name:"page 1"}]},u);return $(`Saved. **New benchmark settings:** ${mn(l)}
|
|
23
|
-
|
|
24
|
-
\`\`\`json
|
|
25
|
-
${JSON.stringify(c??u,null,2)}
|
|
26
|
-
\`\`\``)}catch(r){return f(M(r))}})}import{z as ve}from"zod";var lo="events";var uo={storage:["storage-async","storage-mmkv"],"react-query":["react-query","react-query-query","react-query-mutation"]};function ho(e){if(!e||e.length===0)return void 0;return[...new Set(e.flatMap(n=>uo[n]??[n]))]}function $n(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:ve.number().optional().describe("Most-recent N events to include. Default 25."),sources:ve.array(ve.string()).optional().describe('Only these sources. Coarse names accepted: "network", "redux", "react-query", "storage", "route", "render", "zustand", "jotai". Omit for all.'),status:ve.enum(["all","errors","success","pending"]).optional().describe("Filter by status. Default all."),includeData:ve.boolean().optional().describe("Include each event's full raw payload (HEAVY \u2014 network bodies, state trees). Default false (compact)."),format:ve.enum(["markdown","json","text","mermaid"]).optional().describe("Output format. Default markdown."),preset:ve.enum(["llm","bugReport","json","errors","minimal","mermaid"]).optional().describe("Start from a named Copy-Settings preset (then your other args override it)."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s={};const o=ho(t.sources);if(o)s.filterSources=o;if(t.status)s.filterMode=t.status;if(t.includeData!==void 0)s.includeEventData=t.includeData;if(t.format)s.format=t.format==="text"?"plaintext":t.format;const a=await n.callAction(lo,"exportEvents",{preset:t.preset,settings:s,limit:t.limit??25},r);if(!a||typeof a.output!=="string"){return f("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 i=a.includedData?"":" \u2014 compact view; pass includeData:true, a specific source, or a bigger limit for full payloads";const c=`
|
|
27
|
-
|
|
28
|
-
_Showing ${a.returned} of ${a.totalAvailable} captured event(s)${i}._`;return $((a.output||"(no events captured)")+c)}catch(r){return f(M(r))}})}import{z as Ee}from"zod";var po="query";var mo="react-query";async function yt(e,n,t,r){try{return await e.callAction(po,n,t,r)}catch(s){const o=M(s);if(!/unknown tool/i.test(o))throw s;return await e.callAction(mo,n,t,r)}}var fo={fresh:"\u{1F7E2}",stale:"\u{1F7E1}",fetching:"\u{1F504}",error:"\u{1F534}",inactive:"\u26AA\uFE0F",paused:"\u23F8\uFE0F",disabled:"\u{1F6AB}"};function go(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 kn(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:Ee.boolean().optional().describe("Include each query's full cached data payload (HEAVY). Default false."),staleOnly:Ee.boolean().optional().describe("Only stale queries. Default false."),limit:Ee.number().optional().describe("Most-recently-updated N queries. Default 25."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=await yt(n,"listQueries",{includeData:t.includeData??false,staleOnly:t.staleOnly??false,limit:t.limit??25},r);if(!s||!Array.isArray(s.queries)){return f("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(s.queries.length===0){return $(`React Query cache is empty (0 of ${s.total} queries${t.staleOnly?" match staleOnly":""}).`)}const o=s.queries.map((u,l)=>{const d=fo[u.status]??"\u2022";const h=`${l+1}. ${d} ${u.status} \xB7 \`${u.queryHash}\` \xB7 ${u.observers} obs \xB7 ${go(u.updatedAt)}`;const k=u.error?` \u2014 \u26A0\uFE0F ${u.error}`:"";const b=s.includedData?`
|
|
29
|
-
data: ${JSON.stringify(u.data)}`:"";return h+k+b});const a=s.queries.filter(u=>u.isStale).length;const i=`**React Query cache \u2014 ${s.total} queries (showing ${s.returned}, ${a} stale):**`;const c=s.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 $(`${i}
|
|
30
|
-
|
|
31
|
-
${o.join("\n")}${c}`)}catch(r){return f(M(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:Ee.enum(["invalidate","refetch","reset","remove","clear"]).describe("invalidate/refetch/reset/remove a single query (needs queryHash); clear empties the whole query cache."),queryHash:Ee.string().optional().describe("The target query's hash (from get_react_query, shown in backticks). Required for all actions except clear."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);if(t.action==="clear"){await yt(n,"clearQueryCache",{},r);return $("Requested clearing of the connected React Query cache. Read it again to confirm.")}if(!t.queryHash){return f(`'${t.action}' needs a queryHash. Call get_react_query first and use a row's hash (in backticks).`)}await yt(n,t.action,{queryHash:t.queryHash},r);return $(`Requested ${t.action} on query \`${t.queryHash}\`.`)}catch(r){return f(M(r))}})}import{z as we}from"zod";var $t="zustand";function _n(e,n){e.registerTool("get_zustand_state",{description:'Read registered Zustand stores, available state keys, change counts and persistence metadata. includeValues:true requests values. Use get_events with sources:["zustand"] for retained changes.',inputSchema:{includeValues:we.boolean().optional().describe("Include each store's full current state object (HEAVY). Default false (keys only)."),limit:we.number().optional().describe("First N stores. Default all."),deviceId:A}},Oe(n,async(t,r)=>{const s=await n.callAction($t,"listStores",{includeValues:t.includeValues??false,limit:t.limit},r);if(!s||!Array.isArray(s.stores)){return f(vn({toolId:$t,mcpTool:"get_zustand_state",action:"listStores"}))}if(s.stores.length===0){return $("No Zustand stores are registered (call watchStores to register them).")}const o=s.stores.map((i,c)=>{const u=i.isPersisted?` \xB7 persisted${i.persistName?` (${i.persistName})`:""}`:"";const l=s.includedValues?`
|
|
32
|
-
${JSON.stringify(i.currentState)}`:` \xB7 keys: ${(i.keys??[]).join(", ")||"\u2014"}`;return`${c+1}. **${i.name}** \xB7 ${i.changes} changes${u}${l}`});const a=s.includedValues?"":"\n\n_Compact view (keys only). Pass includeValues:true for full state. Mutate with zustand_action({store, state})._";return $(`**Zustand stores \u2014 ${s.total} (showing ${s.returned}):**
|
|
33
|
-
|
|
34
|
-
${o.join("\n")}${a}`)}));e.registerTool("zustand_action",{description:"Set the state of a Zustand store (time-travel / reset / tweak during debugging). Targets a store by name (from get_zustand_state). By default replaces the whole state; pass replace:false to merge a partial.",inputSchema:{store:we.string().describe("Store name to target (from get_zustand_state)."),state:we.record(we.string(),we.unknown()).describe("The new state object."),replace:we.boolean().optional().describe("Replace the whole state (default true) or merge a partial (false)."),deviceId:A}},Oe(n,async(t,r)=>{await n.callAction($t,"setState",{storeName:t.store,state:t.state,replace:t.replace??true},r);return $(`Requested state update on Zustand store "${t.store}" (${t.replace===false?"merged":"replaced"}).`)}))}import{z as Je}from"zod";var kt="jotai";function Sn(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:Je.boolean().optional().describe("Include each atom's current value (HEAVY). Default false."),limit:Je.number().optional().describe("First N atoms. Default all."),deviceId:A}},Oe(n,async(t,r)=>{const s=await n.callAction(kt,"listAtoms",{includeValues:t.includeValues??false,limit:t.limit},r);if(!s||!Array.isArray(s.atoms)){return f(vn({toolId:kt,mcpTool:"get_jotai_state",action:"listAtoms"}))}if(s.atoms.length===0){return $("No Jotai atoms are being watched (call watchAtoms to register them).")}const o=s.atoms.map((i,c)=>{const u=i.writable?"writable":"read-only";const l=s.includedValues?`
|
|
35
|
-
${JSON.stringify(i.currentValue)}`:"";return`${c+1}. **${i.label}** \xB7 ${i.changes} changes \xB7 ${u}${l}`});const a=s.includedValues?"":"\n\n_Compact view. Pass includeValues:true for current values. Set a writable atom with jotai_action({atom, value})._";return $(`**Jotai atoms \u2014 ${s.total} (showing ${s.returned}):**
|
|
36
|
-
|
|
37
|
-
${o.join("\n")}${a}`)}));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:Je.string().describe("Atom label to set (from get_jotai_state; must be writable)."),value:Je.unknown().describe("The new value (any JSON \u2014 number, string, object, etc.)."),deviceId:A}},Oe(n,async(t,r)=>{await n.callAction(kt,"setAtom",{label:t.atom,value:t.value},r);return $(`Requested update of Jotai atom "${t.atom}" to ${JSON.stringify(t.value)}.`)}))}import{z as _t}from"zod";var xn="redux";function An(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."}}var vo="\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 Tn(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:_t.boolean().optional().describe("Include the full current state tree (HEAVY). Default false (slice names only)."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=await n.callAction(xn,"getState",{includeValues:t.includeValues??false},r);if(!s){return f("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(!s.available)return f(An(s.reason));const o=s.slices.length?s.slices.join(", "):"(none)";const a=s.capture==="top-level-only"?vo:"";if(t.includeValues){return $(`**Redux store \u2014 slices: ${o}**
|
|
38
|
-
|
|
39
|
-
\`\`\`json
|
|
40
|
-
${JSON.stringify(s.state,null,2)}
|
|
41
|
-
\`\`\`${a}`)}return $(`**Redux store \u2014 slices: ${o}**
|
|
42
|
-
|
|
43
|
-
_Compact view. Pass includeValues:true for the full state tree. Dispatch with redux_dispatch({type, payload})._${a}`)}catch(r){return f(M(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:_t.string().describe('The action type, e.g. "counter/increment" or "auth/logout".'),payload:_t.unknown().optional().describe("Optional action payload (any JSON)."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s={type:t.type};if(t.payload!==void 0)s.payload=t.payload;const o=await n.callAction(xn,"dispatch",{action:s},r);if(!o||!o.dispatched)return f(An(o?.reason));return $(`Dispatched \`${t.type}\`${t.payload!==void 0?` with payload ${JSON.stringify(t.payload)}`:""}.`)}catch(r){return f(M(r))}})}import{z as Me}from"zod";var ue="storage";function St(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 Mn(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:Me.string().optional().describe("Only keys containing this substring (case-insensitive)."),includeValues:Me.boolean().optional().describe("Include each key's value (truncated). Default false (keys only)."),limit:Me.number().optional().describe("Max keys per backend section. Default 100."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=t.pattern?.toLowerCase();const o=typeof t.limit==="number"&&t.limit>0?t.limit:100;const a=b=>!s||b.toLowerCase().includes(s);const i=[];const c=await n.callAction(ue,"async.getAllKeys",{},r);if(!Array.isArray(c)){return f("No storage result from the device. The storage tool may be inactive.")}const u=c.filter(a).slice(0,o);if(u.length>0){let b;if(t.includeValues){const g=await n.callAction(ue,"async.multiGet",{keys:u},r);const y=new Map((g??[]).map(([p,m])=>[p,m]));b=u.map(p=>`- \`${p}\` = ${St(y.get(p)??null)}`)}else{b=u.map(g=>`- \`${g}\``)}i.push(`**AsyncStorage (${u.length}/${c.length} keys):**
|
|
44
|
-
${b.join("\n")}`)}const l=await n.callAction(ue,"mmkv.snapshot",{},r).catch(()=>null);for(const b of l??[]){const g=b.entries.filter(m=>a(m.key)).slice(0,o);if(g.length===0)continue;const y=g.map(m=>t.includeValues?`- \`${m.key}\` (${m.valueType}) = ${St(m.value)}`:`- \`${m.key}\``);const p=[b.encrypted&&"encrypted",b.readOnly&&"read-only"].filter(Boolean).join(", ");i.push(`**MMKV \`${b.id}\`${p?` (${p})`:""} (${g.length}/${b.entries.length} keys):**
|
|
45
|
-
${y.join("\n")}`)}const d=await n.callAction(ue,"secure.keys",{},r).catch(()=>null);const h=(d??[]).filter(b=>a(b.key)).slice(0,o);if(h.length>0){const b=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 y=await n.callAction(ue,"secure.get",{key:g.key},r).catch(()=>null);return`- \`${g.key}\` = ${St(y)}`}));i.push(`**SecureStore (${h.length} registered keys):**
|
|
46
|
-
${b.join("\n")}`)}if(i.length===0){return $(`No storage keys${s?` matching "${t.pattern}"`:""} in any backend.`)}const k=t.includeValues?"":"\n\n_Keys only. Pass includeValues:true for values, or a pattern to filter. Modify AsyncStorage with storage_action._";return $(`${i.join("\n\n")}${k}`)}catch(r){return f(M(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:Me.enum(["set","remove","clear"]).describe("set/remove a key, or clear supported app AsyncStorage keys."),key:Me.string().optional().describe("The key (required for set and remove)."),value:Me.string().optional().describe("The string value to store (required for set; JSON-encode objects)."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);if(t.action==="clear"){await n.callAction(ue,"clearAppStorage",{},r);return $("Requested clearing of supported app AsyncStorage keys. Read storage again to confirm.")}if(!t.key){return f(`'${t.action}' needs a key.`)}if(t.action==="remove"){await n.callAction(ue,"async.removeItem",{key:t.key},r);return $(`Requested removal of storage key "${t.key}".`)}if(t.value===void 0){return f("'set' needs a value (a string).")}await n.callAction(ue,"async.setItem",{key:t.key,value:t.value},r);return $(`Requested update of storage key "${t.key}".`)}catch(r){return f(M(r))}})}import{z as xt}from"zod";var In="route-events";function Dn(e,n=[]){for(const t of e??[]){if(t.path)n.push(t.path);if(t.children?.length)Dn(t.children,n)}return n}function Rn(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:xt.boolean().optional().describe("Also list available configured route paths (can be long). Default false."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:s}=await n.getSnapshot(In,r);const o=Array.isArray(s)?{events:s}:s??{};const a=Array.isArray(o.stack)?o.stack:[];const i=a.find(d=>d.isFocused)??a[a.length-1];const c=i?.pathname??"(unknown)";const u=[`**Current route:** \`${c}\``];if(a.length){const d=a.map((h,k)=>`${k+1}. \`${h.pathname??h.name??"?"}\`${h.isFocused?" \u2190 focused":""}`);u.push(`
|
|
47
|
-
**Navigation stack** (top last):
|
|
48
|
-
${d.join("\n")}`)}const l=Dn(o.sitemap?.routes);if(t.includeSitemap){const d=l.slice(0,200);u.push(`
|
|
49
|
-
**Sitemap (${l.length} routes${d.length<l.length?`, showing ${d.length}`:""}):**
|
|
50
|
-
${d.map(h=>`- \`${h}\``).join("\n")}`)}else{u.push(`
|
|
51
|
-
**Sitemap:** ${l.length} routes _(pass includeSitemap:true to list them)_`)}u.push("\n_Navigate with navigate({ path })._");return $(u.join("\n"))}catch(r){return f(M(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:xt.string().describe("The concrete path to navigate to, e.g. '/pokemon/25'."),replace:xt.boolean().optional().describe("Replace the current screen instead of pushing (use when resetting, e.g. to '/')."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);await n.callAction(In,"navigate",{path:t.path,replace:t.replace===true},r);return $(`Navigated to \`${t.path}\`${t.replace?" (replaced current screen)":""}.`)}catch(r){return f(M(r))}})}import{z as At}from"zod";var wo="console";var On={verbose:0,info:1,warning:2,error:3};var bo={verbose:"\xB7",info:"info",warning:"warn",error:"ERR"};function yo(e){const n=new Date(e);const t=(r,s=2)=>String(r).padStart(s,"0");return`${t(n.getHours())}:${t(n.getMinutes())}:${t(n.getSeconds())}.${t(n.getMilliseconds(),3)}`}function Cn(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:At.enum(["verbose","info","warning","error"]).optional().describe("Minimum level to include (severity threshold). e.g. 'warning' = warnings + errors. Default all."),limit:At.number().optional().describe("Most-recent N entries. Default 50."),pattern:At.string().optional().describe("Only entries whose message contains this substring (case-insensitive)."),deviceId:A}},Oe(n,async(t,r)=>{const{payload:s,stale:o}=await n.getSnapshot(wo,r);const a=no(o);const i=Array.isArray(s)?{entries:s}:s??{};const c=Array.isArray(i.entries)?i.entries:[];const u=t.level?On[t.level]:0;const l=t.pattern?.toLowerCase();const d=c.filter(m=>On[m.level]>=u&&(!l||(m.message??"").toLowerCase().includes(l)));const h=[...d].sort((m,v)=>m.id-v.id);const k=to(t.limit,50);const b=h.slice(-k);if(b.length===0){return $(`${a}No console entries${t.level?` at level \u2265 ${t.level}`:""}${l?` matching "${t.pattern}"`:""} (${c.length} total captured).`)}const g=b.map(m=>`${yo(m.timestamp)} [${bo[m.level]??m.level}] ${m.message}`);const y=t.level?`, level \u2265 ${t.level}`:"";const p=`**Console \u2014 ${c.length} entries (showing ${b.length}${y}):**`;return $(`${a}${p}
|
|
52
|
-
|
|
53
|
-
\`\`\`
|
|
54
|
-
${g.join("\n")}
|
|
55
|
-
\`\`\`
|
|
56
|
-
|
|
57
|
-
_Tail of recent logs. Use get_snapshot for available console entry details._`)}))}import{z as Tt}from"zod";import{execFile as $o}from"child_process";import{promisify as ko}from"util";import{promises as Ge}from"fs";import Fn from"os";import En from"path";import{randomUUID as Bn}from"crypto";var Pn=ko($o);var Ve=(e,n,t)=>Math.min(Math.max(e,n),t);function _o(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 So(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 xo(){if(process.platform!=="darwin"){return{ok:false,error:"Screenshotting a component requires macOS with Xcode's iOS Simulator (uses `xcrun simctl`)."}}const e=En.join(Fn.tmpdir(),`buoy-mcp-sim-${Bn()}.png`);try{await Pn("xcrun",["simctl","io","booted","screenshot","--type=png",e],{timeout:15e3})}catch(n){return{ok:false,error:_o(n)}}try{const n=await Ge.readFile(e);const t=So(n);if(!t)return{ok:false,error:"Captured file wasn't a valid PNG."};return{ok:true,srcPath:e,width:t.width,height:t.height}}catch(n){return{ok:false,error:`Failed to read screenshot: ${n.message}`}}}async function Ao(e,n,t){const r=Ve(Math.round(t.x),0,Math.max(0,n.width-1));const s=Ve(Math.round(t.y),0,Math.max(0,n.height-1));const o=Ve(Math.round(t.width),1,n.width-r);const a=Ve(Math.round(t.height),1,n.height-s);const i=En.join(Fn.tmpdir(),`buoy-mcp-crop-${Bn()}.png`);try{await Pn("sips",["-c",String(a),String(o),"--cropOffset",String(s),String(r),e,"--out",i],{timeout:1e4});const c=await Ge.readFile(i);return{ok:true,buffer:c,width:o,height:a}}catch(c){const u=c;return{ok:false,error:`Crop failed: ${u?.stderr||u?.message||c}`}}finally{await Ge.unlink(i).catch(()=>{});await Ge.unlink(e).catch(()=>{})}}function To(e,n,t){if(t!=null){const o=e.find(a=>a.nativeTag===t);if(o)return o}const r=(n??"").trim().toLowerCase();if(!r)return void 0;let s;for(const o of e){const a=[o.testID,o.label,o.text,o.name].filter(Boolean).map(u=>u.toLowerCase());let i=0;for(const u of a){if(u===r)i=Math.max(i,100);else if(u.startsWith(r))i=Math.max(i,50);else if(u.includes(r))i=Math.max(i,25)}const c=o.tap;if(c&&c.x>=0&&c.x<=1&&c.y>=0&&c.y<=1)i+=20;else if(c)i-=40;if(i<=0)continue;if(!s||i>s.score)s={el:o,score:i}}return s?.el}function Mo(e,n){return{x:e.x*n.width,y:e.y*n.height,width:e.width*n.width,height:e.height*n.height}}var Mt="highlight-updates";var Io=12;var Do=6;var Ke=e=>({isError:true,content:[{type:"text",text:e}]});var Ro=e=>e instanceof Error?e.message:String(e);function Oo(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 Co(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`
|
|
58
|
-
|
|
59
|
-
Closest matches (retry with a more precise query, or pass nativeTag directly):
|
|
60
|
-
${n.join("\n")}`}function jn(e,n){e.registerTool("screenshot_component",{description:"Locate a supported React Native component and attempt a cropped iOS Simulator screenshot. Select by query or an exact nativeTag. Uses measured bounds or an available fiber-walk fallback and can attempt scrolling. Inspect the match and crop before treating it as visual evidence. Requires Buoy Pro, a compatible highlight-updates integration, and the MCP server on the same Mac as the booted iOS Simulator.",inputSchema:{query:Tt.string().optional().describe('Fuzzy match against testID, nativeID, accessibilityLabel, component name, or view type \u2014 e.g. "submit-button".'),nativeTag:Tt.number().optional().describe("An exact nativeTag (from a previous call's candidates) to skip fuzzy matching."),scrollIntoView:Tt.boolean().optional().describe("Attempt to scroll an off-screen component into view before capture. Default true; inspect the result."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);await n.callAction(Mt,"setSilentTracking",{enabled:true},r).catch(()=>{});const s=await n.callAction(Mt,"locateComponent",{query:t.query,nativeTag:t.nativeTag,scrollIntoView:t.scrollIntoView??true,margin:Io},r);let o=s;if(!o.matched&&(o.reason==="no-renders"||o.reason==="no-match")){const g=await n.callAction(Mt,"describeScreen",{},r).catch(()=>null);const y=g?.elements?To(g.elements,t.query,t.nativeTag):void 0;if(y?.frame&&g?.screen){o={matched:true,live:true,rect:Mo(y.frame,g.screen),screen:g.screen,nativeTag:y.nativeTag??void 0,componentName:y.name,testID:y.testID}}else if(o.reason==="no-renders"){o={matched:false,reason:"no-match",candidates:o.candidates}}}if(!o.matched||!o.rect||!o.screen){return Ke(Oo(o,t.query)+Co(o.candidates))}const a=await xo();if(!a.ok||!a.srcPath||!a.width||!a.height){return Ke(a.error??"Screenshot capture failed.")}const i=a.width/o.screen.width;const c=o.rect;const u=Do;const l=await Ao(a.srcPath,{width:a.width,height:a.height},{x:(c.x-u)*i,y:(c.y-u)*i,width:(c.width+u*2)*i,height:(c.height+u*2)*i});if(!l.ok||!l.buffer){return Ke(l.error??"Crop failed.")}const d=o.componentName||"component";const h=o.testID?` (testID: "${o.testID}")`:"";const k=o.inView===false?"\n\nNote: the component is partly off-screen even after scrolling, so the crop is clamped to the screen edge.":"";const b=`Captured "${d}"${h} \u2014 ${l.width}\xD7${l.height}px.${k}`;return{content:[{type:"image",data:l.buffer.toString("base64"),mimeType:"image/png"},{type:"text",text:b}]}}catch(r){return Ke(Ro(r))}})}import{McpServer as Fo}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as Eo}from"zod";import{z as D}from"zod";var W="network";var qn=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"};function Bo(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 Po(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 jo(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 qo(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 Nn(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 No(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}var Ln=8;async function Un(e,n,t,r=Ln){const s=n.filter(c=>c.id&&(c.requestBodyOmitted===true&&c.requestData===void 0||c.responseBodyOmitted===true&&c.responseData===void 0));const o=new Map;if(s.length===0)return{bodies:o,skipped:0};const a=s.slice(0,r);const i=await Promise.allSettled(a.map(c=>e.callAction(W,"getEventBody",{id:c.id},t)));i.forEach((c,u)=>{const l=a[u].id;const d=c.status==="fulfilled"?c.value:null;o.set(l,d?{...d}:{unresolved:true})});return{bodies:o,skipped:s.length-a.length}}async function Lo(e,n){let t=null;try{t=await e.callAction(W,"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 zn(e){return e>0?`
|
|
61
|
-
|
|
62
|
-
_${e} more withheld ${e===1?"body was":"bodies were"} not fetched (cap ${Ln} per listing, they are large). Get one in full with its id._`:""}function Wn(e,n){const t=e.id?n.get(e.id):void 0;const r=(s,o,a)=>{const i=s??o;if(i!==void 0&&i!==null)return No(i);if(!a)return"(none)";return t?.unresolved?"(withheld \u2014 the device did not answer getEventBody)":"(none)"};return`
|
|
63
|
-
\u2514\u2500 request: ${r(e.requestData,t?.requestData,e.requestBodyOmitted)}
|
|
64
|
-
\u2514\u2500 response: ${r(e.responseData,t?.responseData,e.responseBodyOmitted)}`}function Jn(e,n,t){const r=n.path||n.url;const s=[`${n.duration!==void 0?`${Math.round(n.duration)}ms`:"\u2014"}`,qo(n.responseSize),n.host??"",n.requestClient??""].filter(Boolean);const o=n.operationName?` (${n.operationName})`:"";return`${e}. \`${n.id}\` ${Po(n)} ${jo(n)} ${n.method} ${r}${o}${t?` ${t}`:""}
|
|
65
|
-
\u2514\u2500 ${s.join(" \xB7 ")}`}function Uo(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:D.enum(["get","set"]).describe("Read the effective profile or select one."),profile:D.enum(["normal","offline","slow","verySlow"]).optional().describe("Required for set."),deviceId:A}},async t=>{try{if(t.action==="set"&&!t.profile)return f("Set requires a profile.");const r=n.resolveDevice(t.deviceId);const s=await n.callAction(W,t.action==="get"?"getNetworkConditions":"setNetworkConditions",t.action==="set"?{profile:t.profile}:void 0,r);if(!s||typeof s!=="object"||!("profile"in s))return f("The device did not report its effective network conditions.");return $(JSON.stringify(s))}catch(r){return f(M(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:D.number().optional().describe("Most-recent N requests. Default 25."),pattern:D.string().optional().describe("Only requests whose URL contains this substring (case-insensitive)."),status:D.enum(["all","errors","success","pending"]).optional().describe("Filter by outcome. Default all."),flagged:D.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:D.boolean().optional().describe("Include truncated request/response bodies. Default false (compact)."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:s}=await n.getSnapshot(W,r);const{events:o,saved:a}=Bo(s);const i=typeof t.limit==="number"&&t.limit>0?t.limit:25;const c=t.pattern?.toLowerCase();const u=new Set;const l=new Set;for(const g of a){if(g.pinned)u.add(g.event?.id);if(g.saved)l.add(g.event?.id);if(g.pinned)u.add(g.liveId);if(g.saved)l.add(g.liveId)}if(t.flagged){const g=a.filter(v=>t.flagged==="pinned"?v.pinned:t.flagged==="saved"?v.saved:v.pinned||v.saved);const y=g.filter(v=>v.event&&Nn(v.event,t.status)).filter(v=>!c||(v.event.url??"").toLowerCase().includes(c)).slice(0,i);if(y.length===0){return $(`No ${t.flagged==="any"?"pinned or saved":t.flagged} requests on ${r}.
|
|
66
|
-
|
|
67
|
-
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 p=t.includeBodies?await Un(n,y.map(v=>v.event),r):{bodies:new Map,skipped:0};const m=y.map((v,w)=>{const _=[v.pinned?"\u{1F4CC} pinned":"",v.saved?"\u{1F516} saved":""].filter(Boolean).join(" ");const T=v.event.id?.startsWith("saved:")?" \xB7 from an earlier app run":"";const I=v.bodyTruncated?" \xB7 body truncated":"";let F=Jn(w+1,v.event,_);F+=`
|
|
68
|
-
\u2514\u2500 key \`${v.key}\`${T}${I}`;if(t.includeBodies)F+=Wn(v.event,p.bodies);return F}).join("\n");return $(`**Kept requests on ${r}** \u2014 ${y.length} of ${g.length}
|
|
69
|
-
|
|
70
|
-
${m}
|
|
71
|
-
|
|
72
|
-
_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._${zn(p.skipped)}`)}const d=o.filter(g=>Nn(g,t.status)).filter(g=>!c||(g.url??"").toLowerCase().includes(c)).slice(0,i);if(d.length===0){const g=o.length===0?await Lo(n,r):"No request matched the filter.";return $(`No requests on ${r}. ${g}`)}const h=t.includeBodies?await Un(n,d,r):{bodies:new Map,skipped:0};const k=d.map((g,y)=>{const p=[u.has(g.id)?"\u{1F4CC}":"",l.has(g.id)?"\u{1F516}":""].filter(Boolean).join("");let m=Jn(y+1,g,p);if(t.includeBodies)m+=Wn(g,h.bodies);return m}).join("\n");const b=a.length>0?` \xB7 ${a.length} kept (flagged:'any' to list)`:"";return $(`**Network requests on ${r}** \u2014 ${d.length} of ${o.length}${b}
|
|
73
|
-
|
|
74
|
-
${k}
|
|
75
|
-
|
|
76
|
-
_\u{1F4CC} pinned \xB7 \u{1F516} saved. Act on one with its id, e.g. network_action({action:"pin", id:"${d[0].id}"})._${zn(h.skipped)}`)}catch(r){return f(M(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:D.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:D.string().optional().describe("Request id for pin/unpin/save/unsave \u2014 from get_network_requests."),key:D.string().optional().describe("Kept-record key for `remove` \u2014 from get_network_requests({flagged:'any'})."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=["pin","unpin","save","unsave"].includes(t.action);if(s&&!t.id){return f(`"${t.action}" needs an \`id\`. List requests with get_network_requests to get one.`)}if(t.action==="remove"&&!t.key){return f('"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(W,"setPinned",{id:t.id,pinned:t.action==="pin"},r);if(o===null)return f(`No request "${t.id}" on ${r}. It may have been cleared or aged out \u2014 re-list with get_network_requests.`);const a=typeof o==="object"&&o!==null&&o.reason==="pin-cap";if(a)return f(`Pin limit reached on ${r}. Unpin something first (network_action({action:"clearPinned"}) drops them all).`);return $(`${t.action==="pin"?"\u{1F4CC} Pinned":"Unpinned"} \`${t.id}\` on ${r}.`)}case"save":case"unsave":{const o=await n.callAction(W,"setSaved",{id:t.id,saved:t.action==="save"},r);if(o===null)return f(`No request "${t.id}" on ${r}. It may have been cleared or aged out \u2014 re-list with get_network_requests.`);const a=typeof o==="object"&&o!==null&&o.reason==="saved-cap";if(a)return f(`Saved-request limit reached on ${r}. Remove one first, or network_action({action:"clearSaved"}).`);return $(`${t.action==="save"?"\u{1F516} Saved":"Unsaved"} \`${t.id}\` on ${r}.`)}case"remove":await n.callAction(W,"removeSavedRecord",{key:t.key},r);return $(`Removed kept record \`${t.key}\` on ${r}.`);case"clearPinned":await n.callAction(W,"clearPinnedRequests",{},r);return $(`Unpinned all requests on ${r} (saved ones kept).`);case"clearSaved":await n.callAction(W,"clearSavedRequests",{},r);return $(`Cleared saved requests on ${r} (pinned ones kept).`);case"clearRequests":await n.callAction(W,"clearEvents",{},r);return $(`Clear request sent to ${r}. Re-list to confirm the live capture list; this action does not clear retained records.`)}}catch(r){return f(M(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:D.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:D.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:D.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:D.array(D.string()).optional().describe("For `add`: restrict to these HTTP methods. Omit for any."),kind:D.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:D.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:D.union([D.string(),D.record(D.unknown()),D.array(D.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:D.record(D.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:D.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:D.record(D.string()).optional().describe("For kind 'respond': response headers to send."),failKind:D.enum(["network","timeout"]).optional().describe("For kind 'fail': 'network' (default) or 'timeout'."),delayMs:D.number().optional().describe("Latency before the outcome, in ms. Works with every kind."),times:D.number().optional().describe("Auto-disable the rule after N matches. Use 1 for 'make the next call fail' so it can't linger."),alternate:D.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:D.string().optional().describe("Label shown in the developer's UI."),enabled:D.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:D.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:D.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:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);switch(t.action){case"add":{if(!t.urlPattern&&!t.fromRequestId){return f("`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 s=await n.callAction(W,"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=s;if(!o?.ok){return f(o?.error??`Could not add the rule on ${r}.`)}const a=o.rule?.urlPattern??t.urlPattern;const i=o.rule?.enabled===false?`
|
|
77
|
-
|
|
78
|
-
It is switched OFF \u2014 arm it with network_override({action:"enable", id:"${o.rule?.id}"}).`:"";return $(`Override added on ${r} \u2014 \`${o.rule?.id}\` matching \`${a}\`.${i}
|
|
79
|
-
|
|
80
|
-
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 f('`remove` needs an `id`. List them with network_override({action:"list"}).')}await n.callAction(W,"deleteOverrideRule",{id:t.id},r);return $(`Removed override \`${t.id}\` on ${r}.`)}case"clear":await n.callAction(W,"clearOverrideRules",{},r);return $(`Removed all override rules on ${r}. Other interception or simulation settings may still apply.`);case"enable":case"disable":{const s=t.action==="enable";if(t.id){await n.callAction(W,"setOverrideRuleEnabled",{id:t.id,enabled:s},r);return $(`Rule \`${t.id}\` was requested ${s?"ON":"OFF"} on ${r}. The other rules and the master switch are unchanged.`)}await n.callAction(W,"setOverridesEnabled",{enabled:s},r);return $(s?`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 s=await n.callAction(W,"listOverrideRules",{},r);const o=s?.rules??[];if(t.id){const i=o.find(c=>c.id===t.id);if(!i){return f(`No override rule \`${t.id}\` on ${r}. List them with network_override({action:"list"}).`)}return $(`**Override rule \`${i.id}\`** on ${r}${qn(s)}
|
|
81
|
-
|
|
82
|
-
\`\`\`json
|
|
83
|
-
${JSON.stringify(i,null,2)}
|
|
84
|
-
\`\`\``)}if(o.length===0){return $(`No override rules on ${r}.
|
|
85
|
-
|
|
86
|
-
Add one with network_override({action:"add", urlPattern:"https://api.example.com/test*", status:500}) to force an error state.`)}const a=o.map((i,c)=>{const u=i.kind==="respond"?`\u2192 ${i.status??200}${i.statusText?` ${i.statusText}`:""}`:i.kind==="fail"?`\u2192 ${i.failKind==="timeout"?"timeout":"network error"}`:"\u2192 real response";const l=[i.methods?.length?i.methods.join("/"):"any method",u,i.kind==="respond"&&i.body?`body ${i.body.length}B`:"",i.headers&&Object.keys(i.headers).length?`${Object.keys(i.headers).length} header(s)`:"",i.delayMs?`${i.delayMs}ms delay`:"",i.alternate?"every other request":"",typeof i.times==="number"?`${i.times}\xD7 then off`:"",`${i.hits} hit${i.hits===1?"":"s"}`,i.seen!=null&&i.seen!==i.hits?`${i.seen} matched`:"",i.enabled?"":"DISABLED"].filter(Boolean);return`${c+1}. \`${i.id}\`${i.name?` ${i.name}`:""}
|
|
87
|
-
\u2514\u2500 \`${i.urlPattern}\` \xB7 ${l.join(" \xB7 ")}`});return $(`**Override rules on ${r}**${qn(s)}
|
|
88
|
-
|
|
89
|
-
${a.join("\n")}
|
|
90
|
-
|
|
91
|
-
Full detail incl. body: network_override({action:"list", id:"${o[0]?.id}"}).`)}case"debug":{const s=await n.callAction(W,"debugOverrides",{url:t.url},r);if(!s){return f(`${r} did not answer the diagnostics call \u2014 the network tool may not be mounted.`)}return $(`**Override diagnostics on ${r}**${t.url?` for \`${t.url}\``:""}
|
|
92
|
-
|
|
93
|
-
\`\`\`json
|
|
94
|
-
${JSON.stringify(s,null,2)}
|
|
95
|
-
\`\`\`
|
|
96
|
-
|
|
97
|
-
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 f(M(r))}})}import{z as de}from"zod";var He="sentry";var be=e=>({content:[{type:"text",text:e}]});var Ye=e=>({isError:true,content:[{type:"text",text:e}]});var Qe=e=>e instanceof Error?e.message:String(e);function Gn(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 Vn(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 It(e,n){if(n==="bytes")return Vn(e);if(e>=1e6)return`${(e/1e6).toFixed(1)}M`;if(e>=1e3)return`${(e/1e3).toFixed(1)}k`;return String(e)}var zo={errors:5e3,spans:5e6,replays:50,logBytes:5*1024**3,attachmentBytes:1*1024**3};var Wo={errors:"count",spans:"count",replays:"count",logBytes:"bytes",attachmentBytes:"bytes"};function Xe(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 Jo(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:de.string().optional().describe("Only envelopes containing this item type, e.g. 'event' for errors or 'transaction' for traces."),limit:de.number().optional().describe("Most-recent N envelopes. Default 25."),deviceId:de.string().optional().describe("Target device id (auto-selected if one is connected).")}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:s,stale:o}=await n.getSnapshot(He,r);const a=o?`${o}
|
|
98
|
-
|
|
99
|
-
`:"";const i=s??{};const c=Array.isArray(i.envelopes)?i.envelopes:[];const u=t.type?c.filter(b=>b.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 be(`${a}No Sentry envelopes${t.type?` containing a '${t.type}' item`:""} (${c.length} captured this session).${Xe(i.status)}`)}const h=d.map(b=>{const g=b.items.map(v=>v.type).join("+");const y=b.items.reduce((v,w)=>v+(w.spanCount??0),0);const p=y>0?` \xB7 ${y} span${y===1?"":"s"}`:"";const m=`${b.id}. ${Gn(b.timestamp)} [${g}] ${Vn(b.totalBytes)}${p}`;return`${m}
|
|
100
|
-
\u2514\u2500 ${b.items[0]?.summary??"envelope"}`});const k=`**Sentry \u2014 ${c.length} envelope${c.length===1?"":"s"} sent (showing ${d.length}${t.type?`, type '${t.type}'`:""}):**`;return be(`${a}${k}${Xe(i.status)}
|
|
101
|
-
|
|
102
|
-
${h.join("\n")}
|
|
103
|
-
|
|
104
|
-
_Full payloads (exception, breadcrumbs, contexts) via get_snapshot('sentry'). Billing units via get_sentry_cost._`)}catch(r){return Ye(Qe(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:de.string().optional().describe("Target device id (auto-selected if one is connected).")}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:s,stale:o}=await n.getSnapshot(He,r);const a=o?`${o}
|
|
105
|
-
|
|
106
|
-
`:"";const i=s??{};const c=i.usage;if(!c?.session){return be(`${a}No usage is available in this capture.${Xe(i.status)}`)}const u=c.session;const l=c.projectedMonthly;const d=Object.keys(u);const h=d.map(y=>{const p=Wo[y];const m=It(u[y],p);if(!l)return`- ${y}: ${m} this session`;const v=l[y];const w=zo[y];const _=w>0?Math.round(v/w*100):null;const T=_===null?" (no configured reference quota)":` \u2014 ${_}% of the configured reference quota of ${It(w,p)}`;return`- ${y}: ${m} this session \u2192 ~${It(v,p)}/mo${T}`});const k=c.windowMs?` over ${Math.round(c.windowMs/1e3)}s`:"";const b=c.topContributors?.length?`
|
|
107
|
-
|
|
108
|
-
**What produced it:**
|
|
109
|
-
${c.topContributors.map(y=>`- ${y.label} \u2014 ${y.units} ${y.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 be(`${a}**Sentry usage estimate \u2014 ${i.envelopes?.length??0} envelopes${k}:**
|
|
110
|
-
|
|
111
|
-
${h.join("\n")}${b}${g}`)}catch(r){return Ye(Qe(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:de.number().optional().describe("Most-recent N drop records. Default 30."),deviceId:de.string().optional().describe("Target device id (auto-selected if one is connected).")}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:s,stale:o}=await n.getSnapshot(He,r);const a=o?`${o}
|
|
112
|
-
|
|
113
|
-
`:"";const i=s??{};const c=i.drops?.summary??[];const u=i.drops?.recent??[];if(c.length===0){return be(`${a}No drops are reported in the available capture.${Xe(i.status)}
|
|
114
|
-
|
|
115
|
-
_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(b=>`- ${b.reason}: ${b.units} unit${b.units===1?"":"s"} across ${b.records} record${b.records===1?"":"s"}`);const k=d.map(b=>`${Gn(b.timestamp)} [${b.reason}] ${b.category}${b.quantity>1?` \xD7${b.quantity}`:""} \u2014 ${b.detail} (${b.source})`);return be(`${a}**Sentry drops \u2014 by reason:**
|
|
116
|
-
|
|
117
|
-
${h.join("\n")}
|
|
118
|
-
|
|
119
|
-
**Recent (${d.length}):**
|
|
120
|
-
|
|
121
|
-
\`\`\`
|
|
122
|
-
${k.join("\n")}
|
|
123
|
-
\`\`\`
|
|
124
|
-
|
|
125
|
-
_"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 Ye(Qe(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:de.enum(["clear"]).describe("The action to perform."),deviceId:de.string().optional().describe("Target device id (auto-selected if one is connected).")}},async t=>{try{const r=n.requireProDevice(t.deviceId);await n.callAction(He,"clearEnvelopes",{},r);return be("Cleared the Sentry inspector \u2014 envelopes and drop records. Drive your flow, then read get_sentry_envelopes or get_sentry_cost.")}catch(r){return Ye(Qe(r))}})}import{z as se}from"zod";var Kn="time-machine";function Hn(e){return e<1024?`${e} B`:`${(e/1024).toFixed(1)} KB`}function Yn(e){const n=Object.entries(e.results).map(([r,s])=>{const o=s.skipped.slice(0,3).map(i=>`
|
|
126
|
-
\xB7 ${i.id}: ${i.reason}`).join("");const a=s.warnings.slice(0,3).map(i=>`
|
|
127
|
-
\u26A0 ${i}`).join("");return` ${s.ok?"\u2713":"\u2715"} ${r} \u2014 applied ${s.applied}${s.skipped.length?`, skipped ${s.skipped.length}`:""}${o}${a}`});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":""}):
|
|
128
|
-
${n.join("\n")}`}function Go(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:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:s}=await n.getSnapshot(Kn,r);const o=s??{};const a=o.snapshots??[];const i=o.providers??[];const c=i.map(d=>{const h=d.canCapture?d.canRestore?"capture+restore":"capture only":"unavailable";return`- ${d.label} (${d.id}): ${h}${d.detail?` \u2014 ${d.detail}`:""}`});if(o.route){c.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 u=a.map(d=>{const h=Object.values(d.sources).reduce((g,y)=>g+y.warnings.length,0);const k=d.baseline?"baseline: clear supported providers and request reload":`${Hn(d.sizeBytes)} \xB7 ${Object.keys(d.sources).join(", ")}`;const b=d.route?` \xB7 route ${d.route.href}`:"";return`- \`${d.id}\` **${d.name}** \u2014 ${new Date(d.createdAt).toISOString()} \xB7 ${k}${b}${h?` \xB7 \u26A0 ${h}`:""}`});const l=[`**Time Machine \u2014 ${a.length} snapshot(s):**`,u.length?u.join("\n"):"_none yet \u2014 capture one with time_machine_action_",`**Sources:**
|
|
129
|
-
${c.join("\n")||"_no providers registered_"}`];if(o.lastOutcome)l.push(`**Last restore:**
|
|
130
|
-
${Yn(o.lastOutcome)}`);return $(l.join("\n\n"))}catch(r){return f(M(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:se.enum(["capture","capture_baseline","preview","restore","delete","rename"]).describe("What to do."),id:se.string().optional().describe("Snapshot id (required for restore/delete/rename; from get_time_machine)."),name:se.string().optional().describe("Snapshot name (for capture and rename)."),mode:se.enum(["live","reload"]).optional().describe("Restore mode. Default 'live'."),excludeKeys:se.array(se.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:se.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:se.array(se.string()).optional().describe("Capture/restore only these source ids (default all)."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=(o,a)=>n.callAction(Kn,o,a,r);switch(t.action){case"capture":{const o=await s("capture",{name:t.name??"",sourceIds:t.sourceIds});const a=o.snapshot;const i=Object.entries(a.sources).flatMap(([c,u])=>u.warnings.map(l=>`
|
|
131
|
-
\u26A0 ${c}: ${l}`)).join("");return $(`Captured \`${a.id}\` "${a.name}" \u2014 ${Hn(a.sizeBytes)} \xB7 ${Object.keys(a.sources).join(", ")}${i}`)}case"capture_baseline":{const o=await s("captureBaseline",{});return $(`Captured baseline \`${o.snapshot.id}\` \u2014 restoring it wipes app storage and reloads.`)}case"preview":{if(!t.id)return f("preview requires `id` (from get_time_machine).");const o=await s("preview",{id:t.id});const a=[];let i=0;for(const u of o.sources){const l={};for(const k of u.items){l[k.verdict]=(l[k.verdict]??0)+1}const d=(l.added??0)+(l.removed??0)+(l.changed??0)+(l["too-large"]??0);i+=d;const h=Object.entries(l).filter(([k])=>k!=="unchanged").map(([k,b])=>`${b} ${k}`);a.push(`- **${u.label}**: ${h.length?h.join(", "):"no changes"}${u.error?` \u2014 \u26A0 ${u.error}`:""}`);for(const k of u.items.filter(b=>b.verdict!=="unchanged").slice(0,8)){a.push(` ${k.verdict==="added"?"+":k.verdict==="removed"?"\u2212":k.verdict==="wont-apply"?"\u2298":"\u2248"} ${k.label}${k.reason?` (${k.reason})`:""}`)}for(const k of u.notes)a.push(` \xB7 ${k}`)}const c=i===0?"**Restore would change NOTHING** (states identical or nothing applicable).":`**Restore would apply ${i} change(s):**`;return $(`${c}
|
|
132
|
-
${a.join("\n")}`)}case"restore":{if(!t.id)return f("restore requires `id` (from get_time_machine).");const o=await s("restore",{id:t.id,mode:t.mode??"live",excludeKeys:t.excludeKeys,restoreRoute:t.restoreRoute});return $(Yn(o))}case"delete":{if(!t.id)return f("delete requires `id`.");await s("delete",{id:t.id});return $(`Deleted snapshot \`${t.id}\`.`)}case"rename":{if(!t.id||!t.name)return f("rename requires `id` and `name`.");await s("rename",{id:t.id,name:t.name});return $(`Renamed \`${t.id}\` to "${t.name}".`)}}}catch(r){return f(M(r))}})}import{z as J}from"zod";var Qn="clock";function ye(e){const n=e<0?"-":"+";let t=Math.abs(Math.round(e/1e3));if(t===0)return"0s";const r=[];for(const[s,o]of[["d",86400],["h",3600],["m",60],["s",1]]){if(t>=o){r.push(`${Math.floor(t/o)}${s}`);t%=o}if(r.length===2)break}return n+r.join(" ")}function Xn(e){const n=[e.active?`**App clock: ${e.virtualIso}** (${e.mode}${e.rate!==1?`, ${e.rate}\xD7`:""}), ${ye(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: ${ye(e.lastJump.byMs)}${e.lastJump.firedTimers?`, ran ${e.lastJump.firedTimers} due timer(s)`:""}`)}n.push(...Vo(e));n.push(`Settings: persist=${e.settings.persist} showChip=${e.settings.showChip} fireTimersOnJump=${e.settings.fireTimersOnJump}`);return n.join("\n")}function Vo(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 s of n.tokens){const o=s.expiresAt!==void 0?s.expiresAt-e.virtualNow:void 0;const a=s.serverExpiresAt!==void 0?s.serverExpiresAt-e.realNow:void 0;const i=s.neverExpires?"never expires":o===void 0?"expiry unknown":o>0?`expires in ${ye(o).slice(1)} on the app's clock`:`expired ${ye(-o).slice(1)} ago on the app's clock`;const c=a!==void 0&&o!==void 0&&Math.abs(a-o)>2e3?a>0?`; the server accepts it for ${ye(a).slice(1)} more`:"; the server no longer accepts it":"";const u=[s.hint??s.formatLabel,s.expirySource?`expiry from ${s.expirySource}`:null,s.issuedBy?`issued by ${s.issuedBy}`:null,s.claims.sub?`sub ${s.claims.sub}`:null,`${s.uses} request(s)`,s.refreshes?`${s.refreshes} refresh(es)`:null,s.expiredSends?`SENT ${s.expiredSends}\xD7 AFTER EXPIRY`:null,s.rejected?`rejected ${s.rejected}\xD7`:null,s.looping?`REFRESH LOOP (${s.recentRefreshes} new tokens in 20s)`:null].filter(Boolean);t.push(`- [${s.id}] ${s.label} \u2192 ${s.host}: ${i}${c} (${u.join(", ")})`)}const r=n.check;if(r){const s=r.status==="refreshed"?`refreshed${r.kind==="401"&&r.forcedAt?" after the forced 401":""}${r.newIssuedBy?` via ${r.newIssuedBy}`:""}${r.newLifetimeMs?`; new token lasts ${ye(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 (${ye(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"}): ${s}${o}`)}return t}function Ko(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:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=await n.callAction(Qn,"getState",{},r);return $(Xn(s))}catch(r){return f(M(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:J.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:J.union([J.string(),J.number()]).optional().describe("set_time (required) / freeze (optional): target time."),by:J.union([J.string(),J.number()]).optional().describe("shift (required): signed duration like '+1d', '-2h30m', '90s', or ms."),freeze:J.boolean().optional().describe("set_time: stop the clock at `time`. Default false."),fireTimers:J.boolean().optional().describe("shift: run app timers that come due inside a forward jump. Default on."),rate:J.number().optional().describe("set_rate (required): speed multiplier, 0.1-86400; 1 is normal."),persist:J.boolean().optional().describe("settings: keep the override across reloads."),showChip:J.boolean().optional().describe("settings: show the floating clock chip while overridden."),fireTimersOnJump:J.boolean().optional().describe("settings: default for shift's fireTimers."),token:J.string().optional().describe("jump_to_token_expiry / fail_next_request: token id from get_clock. Default: the most recently used token."),leadMs:J.number().optional().describe("jump_to_token_expiry: land this many ms before expiry. Default 10000."),status:J.number().optional().describe("fail_next_request: 401 (default) or 403."),times:J.number().optional().describe("fail_next_request: how many requests to fail, 1-10. Default 1."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=(a,i={})=>n.callAction(Qn,a,i,r);let o;switch(t.action){case"set_time":if(t.time===void 0)return f("set_time requires `time`.");o=await s("setTime",{time:t.time,freeze:t.freeze??false});break;case"shift":if(t.by===void 0)return f("shift requires `by`, e.g. '+1d'.");o=await s("shift",{by:t.by,...t.fireTimers!==void 0?{fireTimers:t.fireTimers}:{}});break;case"freeze":o=await s("freeze",t.time!==void 0?{time:t.time}:{});break;case"resume":o=await s("resume");break;case"set_rate":if(t.rate===void 0)return f("set_rate requires `rate`.");o=await s("setRate",{rate:t.rate});break;case"reset":o=await s("reset");break;case"settings":o=await s("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 s("jumpToTokenExpiry",{...t.token?{token:t.token}:{},...t.leadMs!==void 0?{leadMs:t.leadMs}:{}});break;case"fail_next_request":o=await s("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 s("stopTokenCheck");break}return $(Xn(o))}catch(r){return f(M(r))}})}import{execFile as Ho}from"child_process";import{promisify as Yo}from"util";import{z as G}from"zod";var Dt="permissions";var Qo=Yo(Ho);var Zn=["location","locationBackground","camera","microphone","notifications","photos","contacts","calendar","reminders","tracking","motion","bluetooth"];function er(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 s of e.permissions){const o=[s.override?`override **${s.override}**`:"not overridden",`system ${s.real??"unknown"}`,s.calls?`asked ${s.calls}\xD7`:"not asked yet",s.sources.length?`via ${s.sources.join(", ")}`:null,`can be: ${s.states.join(", ")}`].filter(Boolean);t.push(`- ${s.id} (${s.label}): ${o.join("; ")}`);if(s.warning)t.push(` \u26A0 ${s.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 s of e.log.slice(0,n)){const o=new Date(s.at).toISOString().slice(11,19);const a=s.error??s.returned??"no answer";t.push(`- ${o} ${s.source}.${s.method} \u2192 ${a}${s.overridden?" (override)":""}${s.real&&s.real!==s.returned?`, system ${s.real}`:""}${s.answer?`, answered ${s.answer}`:""}`)}}if(e.host.bundleId){t.push(`Host: ${e.host.isSimulator?"simulator/emulator":e.host.isSimulator===false?"physical device":"unknown device"} "${e.host.deviceName??"?"}", app ${e.host.bundleId}`)}return t.join("\n")}var Xo={location:"location",locationBackground:"location-always",camera:"camera",microphone:"microphone",photos:"photos",contacts:"contacts",calendar:"calendar",reminders:"reminders",motion:"motion"};var tr={location:["ACCESS_FINE_LOCATION","ACCESS_COARSE_LOCATION"],locationBackground:["ACCESS_BACKGROUND_LOCATION"],camera:["CAMERA"],microphone:["RECORD_AUDIO"],notifications:["POST_NOTIFICATIONS"],photos:["READ_MEDIA_IMAGES","READ_MEDIA_VIDEO"],contacts:["READ_CONTACTS","WRITE_CONTACTS"],calendar:["READ_CALENDAR","WRITE_CALENDAR"],motion:["ACTIVITY_RECOGNITION"],bluetooth:["BLUETOOTH_SCAN","BLUETOOTH_CONNECT"]};async function Ie(e,n){const{stdout:t}=await Qo(e,n,{timeout:2e4});return t}async function Zo(e,n){if(n)return n;const t=JSON.parse(await Ie("xcrun",["simctl","list","devices","booted","-j"]));const r=Object.values(t.devices).flat();const s=r.filter(o=>o.name===e.host.deviceName);if(s.length===1)return s[0].udid;if(!e.host.deviceName&&r.length===1)return r[0].udid;throw new Error(s.length===0?`No booted simulator is named "${e.host.deviceName??"?"}". Pass \`udid\`.`:`${s.length} booted simulators are named "${e.host.deviceName}". Pass \`udid\`.`)}async function ea(e){if(e)return e;const n=await Ie("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 ta(e,n,t,r){const s=e.host.bundleId;if(!s)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":Xo[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 Zo(e,r.udid);await Ie("xcrun",["simctl","privacy",u,n,c,s]);return`simctl privacy ${n} ${c} for ${s} on ${u}.${n==="grant"?"":" iOS ends the app's process when a permission is revoked or reset; relaunch it."}`}const o=await ea(r.serial);const a=t==="all"?Object.values(tr).flat():tr[t];if(!a)throw new Error(`No Android permission is known for ${t}.`);const i=[];for(const c of a){const u=`android.permission.${c}`;try{if(n==="grant")await Ie("adb",["-s",o,"shell","pm","grant",s,u]);else{await Ie("adb",["-s",o,"shell","pm","revoke",s,u]);if(n==="reset"){await Ie("adb",["-s",o,"shell","pm","clear-permission-flags",s,u,"user-set","user-fixed"])}}i.push(c)}catch{}}if(i.length===0)throw new Error(`None of ${a.join(", ")} could be changed. Is it declared in the app's manifest?`);return`adb ${n} ${i.join(", ")} for ${s} on ${o}.${n==="grant"?"":" Android restarts the app's process when a permission is revoked."}`}function na(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:G.number().optional().describe("How many recent calls to list. Default 12."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=await n.callAction(Dt,"getState",{},r);return $(er(s,t.logLimit??12))}catch(r){return f(M(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:G.enum(["set","clear","reset","answer","settings","request_real","return_from_settings","clear_log"]).describe("What to do."),permission:G.string().optional().describe(`set / clear / request_real (required): ${Zn.join(", ")}, or android:<android.permission.NAME>.`),state:G.enum(["undetermined","granted","limited","denied","blocked","restricted"]).optional().describe("set (required): the state the app sees."),answer:G.enum(["ask","allow","limited","deny"]).optional().describe("answer (required): how a request from 'not asked' is answered while overridden."),notifyApp:G.boolean().optional().describe("settings: send background \u2192 active after each change. Default on."),interceptSettings:G.boolean().optional().describe("settings: stand in for Settings while overridden. Default on."),enforce:G.boolean().optional().describe("settings: fail calls that need a refused permission. Default on."),persist:G.boolean().optional().describe("settings: keep overrides across reloads. Default on."),showChip:G.boolean().optional().describe("settings: show the floating chip while overridden. Default on."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=(a,i={})=>n.callAction(Dt,a,i,r);let o;switch(t.action){case"set":if(!t.permission||!t.state)return f("set requires `permission` and `state`.");o=await s("setOverride",{permission:t.permission,state:t.state});break;case"clear":if(!t.permission)return f("clear requires `permission`.");o=await s("clearOverride",{permission:t.permission});break;case"reset":o=await s("resetAll");break;case"answer":if(!t.answer)return f("answer requires `answer`: ask, allow, limited or deny.");o=await s("updateSettings",{requestAnswer:t.answer});break;case"settings":o=await s("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 f("request_real requires `permission`.");o=await s("requestReal",{permission:t.permission});break;case"return_from_settings":o=await s("simulateReturnFromSettings");break;case"clear_log":o=await s("clearLog");break}return $(er(o))}catch(r){return f(M(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:G.enum(["grant","revoke","reset"]).describe("grant, revoke, or reset to not asked."),permission:G.string().describe(`${Zn.join(", ")}, or all.`),udid:G.string().optional().describe("iOS: the simulator udid, when its name is ambiguous."),serial:G.string().optional().describe("Android: the adb serial, when several devices are connected."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=await n.callAction(Dt,"getState",{},r);const o=await ta(s,t.action,t.permission,{udid:t.udid,serial:t.serial});return $(o)}catch(r){return f(M(r))}})}import{execFile as ra}from"child_process";import{promisify as sa}from"util";import{z as q}from"zod";var nr="lifecycle";var oa=sa(ra);function Be(e){if(e==null)return"can't count";return e===0?"none":String(e)}function Ze(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 ${Be(e.listeners.appState)}, memory warning ${Be(e.listeners.memoryWarning)}, deep link ${Be(e.listeners.deepLink)}`+(e.platform==="android"?`, window focus ${Be(e.listeners.focus)}`:"")+(e.batteryLibraries.length?`, battery ${Be(e.listeners.battery)} (${e.batteryLibraries.join(", ")})`:", battery: no battery library installed")+".");if(e.report){const r=e.report;n.push(`
|
|
133
|
-
**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 s=Object.entries(r.counts).map(([o,a])=>`${a} ${o}`).join(", ");if(!r.unavailable)n.push(`Counts: ${s||"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?`
|
|
134
|
-
Relaunch: checking where the app landed (was on ${r.before??"unknown"}).`:`
|
|
135
|
-
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(`
|
|
136
|
-
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 $e(e){const{stdout:n}=await oa("xcrun",["simctl",...e],{timeout:2e4});return n}async function aa(e,n){if(process.platform!=="darwin")throw new Error("Real lifecycle events need macOS with the iOS Simulator.");if(e.platform!=="ios"||e.host.isSimulator!==true){throw new Error("Real lifecycle events work on an iOS simulator only (Android support is not built yet). Leave `real` off to simulate from inside the app.")}if(n)return n;const t=JSON.parse(await $e(["list","devices","booted","-j"]));const r=Object.values(t.devices).flat().filter(s=>s.name===e.host.deviceName);if(r.length===1)return r[0].udid;throw new Error(r.length===0?`No booted simulator is named "${e.host.deviceName??"?"}". Pass \`udid\`.`:`${r.length} booted simulators are named "${e.host.deviceName}". Pass \`udid\`.`)}function rr(e){if(!e.host.bundleId)throw new Error("The app did not report its bundle id (needs expo-application).");return e.host.bundleId}var ia=e=>new Promise(n=>setTimeout(n,e));function ca(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:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=await n.callAction(nr,"getState",{},r);return $(Ze(s))}catch(r){return f(M(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 or react-native-device-info), 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` on an iOS simulator, background/return/relaunch/color_scheme/open_url use `xcrun simctl` for the real OS event instead (relaunch then kills the process, a real cold start). Read get_lifecycle afterwards for the report.",inputSchema:{action:q.enum(["background","interrupt","return","memory_warning","open_url","press_back","color_scheme","battery","reset_battery","relaunch","recipe","clear_report","reset","settings"]).describe("What to do."),duration:q.union([q.string(),q.number()]).optional().describe("background / interrupt: return by itself after this long ('5s', '5m', ms). Omit to stay until return."),skipWait:q.boolean().optional().describe("background / interrupt: move the app clock forward by `duration` and return at once. Needs @buoy-gg/clock."),url:q.string().optional().describe("open_url (required): the link, with its scheme."),scheme:q.enum(["light","dark","system"]).optional().describe("color_scheme (required). 'system' ends the simulated scheme."),mode:q.enum(["js","native"]).optional().describe("color_scheme: 'js' emits the change to JS listeners (default); 'native' overrides the app's native appearance too."),level:q.number().optional().describe("battery: 0 to 1 (or a percentage above 1)."),lowPowerMode:q.boolean().optional().describe("battery: low power mode on or off."),state:q.enum(["unplugged","charging","full","unknown"]).optional().describe("battery: charging state."),id:q.string().optional().describe("recipe (required): a recipe id from get_lifecycle, e.g. 'away-31m'."),showChip:q.boolean().optional().describe("settings: show the floating status chip while simulating."),reportWindow:q.union([q.string(),q.number()]).optional().describe("settings: how long reports keep collecting after the app returns ('5s')."),real:q.boolean().optional().describe("iOS simulator only: cause the real OS event through xcrun simctl (background, return, relaunch, color_scheme, open_url)."),udid:q.string().optional().describe("real: the simulator udid, when its name is ambiguous."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=(a,i={})=>n.callAction(nr,a,i,r);if(t.real){const a=await s("getState");const i=await aa(a,t.udid);let c;switch(t.action){case"background":await $e(["launch",i,"com.apple.Preferences"]);c="Sent to the background for real (Settings opened on top). Use return with real: true.";break;case"return":await $e(["launch",i,rr(a)]);c="Brought back to the foreground for real.";break;case"relaunch":{const l=rr(a);await s("prepareRelaunch");await $e(["terminate",i,l]);await $e(["launch",i,l]);c="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 f("color_scheme requires `scheme`.");if(t.scheme==="system")return f("With real: true, pass light or dark; the simulator has no system value to go back to.");await $e(["ui",i,"appearance",t.scheme]);c=`Simulator appearance set to ${t.scheme} (affects every app on this simulator).`;break;case"open_url":if(!t.url)return f("open_url requires `url`.");await $e(["openurl",i,t.url]);c='Opened through the OS. A custom scheme may first show an "Open in" prompt on the simulator.';break;default:return f(`${t.action} has no real (host-side) version. iOS has no command-line memory warning; leave \`real\` off to simulate it.`)}await ia(1200);const u=t.action==="relaunch"||t.action==="background"?a:await s("getState");return $(`${c}
|
|
137
|
-
|
|
138
|
-
${Ze(u)}`)}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 f("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 f("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 $(`Relaunching: the app's JS restarts now. Read get_lifecycle in a few seconds for where it landed.
|
|
139
|
-
|
|
140
|
-
${Ze(o)}`);case"recipe":if(!t.id)return f("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}return $(Ze(o))}catch(r){return f(M(r))}})}import{execFile as la}from"child_process";import{promisify as ua}from"util";import{z as R}from"zod";var sr=ua(la);var or="location";function De(e){if(e==null||!Number.isFinite(e))return"?";return e<1e3?`${Math.round(e)} m`:`${(e/1e3).toFixed(e<1e4?1:0)} km`}function Rt(e){return`${e.latitude.toFixed(5)}, ${e.longitude.toFixed(5)}`}function ar(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 a=o?Rt(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, ${De(e.progress.along)} of ${De(e.progress.length)}${n.route.loop?" (loops)":""} \u2192 ${a}`)}else if(n.mode==="fixed"){t.push(`**Location: pinned** ${n.place.label?`"${n.place.label}" `:""}\u2192 ${a}`)}else{t.push(`**Location: real position**, with overrides below`)}if(o){t.push(`Reported: \xB1${De(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 ${De(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 a of o.regions){t.push(`- ${a.identifier}${a.label?` (${a.label})`:""}: ${a.state}, radius ${De(a.radius)}${a.distance!=null?`, ${De(a.distance)} from center`:""} (${Rt(a)})`)}}else{t.push(`Background location task "${o.name}" (${o.intercepted?"simulated":"native"}, ${o.runs} runs)`)}}const s=e.log.slice(-10);if(s.length){t.push("Recent:");for(const o of s)t.push(`- [${o.kind}] ${o.text}${o.detail?` (${o.detail})`:""}`)}if(e.places.length)t.push(`App places: ${e.places.map(o=>o.label??Rt(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 da(){const{stdout:e}=await sr("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 ha(e){if(process.platform!=="darwin")throw new Error("sim_location needs macOS with Xcode's iOS Simulator.");const n=await da();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 pa(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:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=await n.callAction(or,"getState",{},r);return $(ar(s))}catch(r){return f(M(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:R.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:R.number().optional().describe("set_location: latitude, -90 to 90."),longitude:R.number().optional().describe("set_location: longitude, -180 to 180."),label:R.string().optional().describe("set_location: a name to show for the place."),query:R.string().optional().describe("set_location: 'lat, lon' text or a Google/Apple Maps link."),place:R.string().optional().describe("set_location: a place name from get_location (app places and built-ins)."),points:R.array(R.object({latitude:R.number(),longitude:R.number()})).optional().describe("start_route: two or more points to travel through."),route:R.string().optional().describe("start_route: a preset id (walk, run, drive, highway, tunnel, loop) or an app route id."),to:R.string().optional().describe("start_route: travel in a straight line to this place name or 'lat, lon'."),speed:R.number().optional().describe("start_route / set_speed: meters per second (1.4 walk, 13.4 city, 30 highway)."),heading:R.number().optional().describe("start_route with a preset: direction to head, degrees from north. tune: heading reported while pinned."),loop:R.boolean().optional().describe("start_route with points: start over after the last point."),meters:R.number().optional().describe("seek_route: meters from the route's start."),fraction:R.number().optional().describe("seek_route: 0 to 1 along the route."),identifier:R.string().optional().describe("enter_region / exit_region (required): the region's identifier from get_location."),task:R.string().optional().describe("enter_region / exit_region: the geofencing task name, when two tasks share an identifier."),conditions:R.enum(["good","weak","no-signal","off"]).optional().describe("conditions (required): good, weak, no-signal or off."),on:R.boolean().optional().describe("signal / services (required): true = working, false = off."),accuracy:R.number().optional().describe("tune: reported accuracy radius in meters."),jitter:R.number().optional().describe("tune: GPS drift in meters (0 = none)."),interval:R.number().optional().describe("tune: ms between updates to live watches (default 1000)."),persist:R.boolean().optional().describe("settings: keep the override across reloads."),showChip:R.boolean().optional().describe("settings: show the floating location chip while overridden."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=(i,c={})=>n.callAction(or,i,c,r);const o=(...i)=>{const c={};for(const u of i)if(t[u]!==void 0)c[u]=t[u];return c};let a;switch(t.action){case"set_location":a=await s("setLocation",o("latitude","longitude","label","query","place"));break;case"start_route":a=await s("startRoute",o("points","route","to","speed","heading","loop"));break;case"pause_route":a=await s("pauseRoute");break;case"resume_route":a=await s("resumeRoute");break;case"stop_route":a=await s("stopRoute");break;case"seek_route":a=await s("seekRoute",o("meters","fraction"));break;case"set_speed":if(t.speed===void 0)return f("set_speed requires `speed` in m/s.");a=await s("setSpeed",{speed:t.speed});break;case"enter_region":case"exit_region":if(!t.identifier)return f(`${t.action} requires \`identifier\`; get_location lists the regions.`);a=await s(t.action==="enter_region"?"enterRegion":"exitRegion",o("identifier","task"));break;case"conditions":if(!t.conditions)return f("conditions requires `conditions`: good, weak, no-signal or off.");a=await s("setConditions",{conditions:t.conditions});break;case"signal":if(t.on===void 0)return f("signal requires `on`.");a=await s("setSignal",{on:t.on});break;case"services":if(t.on===void 0)return f("services requires `on`.");a=await s("setServices",{on:t.on});break;case"tune":a=await s("tune",o("accuracy","jitter","heading","interval"));break;case"use_real":a=await s("useRealLocation");break;case"reset":a=await s("reset");break;case"settings":a=await s("updateSettings",o("persist","showChip"));break;case"clear_log":a=await s("clearLog");break}return $(ar(a))}catch(r){return f(M(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:R.enum(["set","route","clear"]).describe("What to do."),latitude:R.number().optional().describe("set: latitude."),longitude:R.number().optional().describe("set: longitude."),points:R.array(R.object({latitude:R.number(),longitude:R.number()})).optional().describe("route: two or more waypoints."),speed:R.number().optional().describe("route: meters per second. Default 20."),interval:R.number().optional().describe("route: seconds between updates. Default 1."),udid:R.string().optional().describe("The simulator's UDID. Required when several are booted.")}},async t=>{try{const r=await ha(t.udid);const s=(...o)=>sr("xcrun",["simctl","location",r,...o],{timeout:15e3});switch(t.action){case"set":if(t.latitude===void 0||t.longitude===void 0)return f("set requires `latitude` and `longitude`.");await s("set",`${t.latitude},${t.longitude}`);return $(`Simulator ${r} location set to ${t.latitude}, ${t.longitude}.`);case"route":{const o=t.points??[];if(o.length<2)return f("route requires two or more `points`.");const a=[`--speed=${t.speed??20}`,`--interval=${t.interval??1}`];await s("start",...a,...o.map(i=>`${i.latitude},${i.longitude}`));return $(`Simulator ${r} is moving through ${o.length} points at ${t.speed??20} m/s.`)}case"clear":await s("clear");return $(`Simulator ${r} location cleared.`)}}catch(r){return f(M(r))}})}import{z as x}from"zod";var ir="scenarios";var ke=e=>({content:[{type:"text",text:e}]});var te=e=>({isError:true,content:[{type:"text",text:e}]});var cr=e=>e instanceof Error?e.message:String(e);function ma(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 et(e){const n=e.vars?.length?`
|
|
141
|
-
variables: ${e.vars.map(ma).join("; ")}`:"";const t=e.stepLines?.length?`
|
|
142
|
-
${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 s=e.expectedOutcome?`
|
|
143
|
-
expected: ${e.expectedOutcome}`:"";return`- \`${e.id}\` **${e.name}** \u2014 ${r}${n}${s}${t}`}function lr(e,n,t){if(!n.length)return`**${e} (0):**
|
|
144
|
-
_none_`;if(!t.length){return`**${e} (${n.length}):**
|
|
145
|
-
${n.map(et).join("\n")}`}const r=[`**${e} (${n.length}):**`];for(const o of t){const a=n.filter(i=>(i.folder??"").toLowerCase()===o.toLowerCase());if(!a.length)continue;r.push(`_${o} (${a.length})_
|
|
146
|
-
${a.map(et).join("\n")}`)}const s=n.filter(o=>!o.folder);if(s.length){r.push(`_Ungrouped (${s.length})_
|
|
147
|
-
${s.map(et).join("\n")}`)}return r.join("\n")}function fa(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:
|
|
148
|
-
${e.effects.map(t=>` \xB7 ${t.label} [${t.kind}]`).join("\n")}`].filter(Boolean).join("\n")}function ga(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:x.string().optional().describe("Target device id (auto-selected if one is connected).")}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:s}=await n.getSnapshot(ir,r);const o=s??{};const a=o.code??[];const i=o.device??[];const c=o.drafts??[];const u=o.folders??[];const l=[];l.push(o.active?`\u26A0\uFE0F **SIMULATED \u2014 a scenario is active.** The app is showing bent state right now.
|
|
149
|
-
${fa(o.active)}`:"**No scenario active** \u2014 the app is showing real data.");if(u.length){l.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.`)}l.push(lr("Shipped with this app",a,u));l.push(lr("Saved on this device",i,u));if(c.length){l.push(`**Drafts awaiting review on the device (${c.length}):** these are INERT and cannot run until a human accepts them on the device.
|
|
150
|
-
${c.map(et).join("\n")}`)}return ke(l.join("\n\n"))}catch(r){return te(cr(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:x.enum(["preview","run","deactivate","save","setFolder","delete"]).describe("What to do."),folder:x.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:x.string().optional().describe("Scenario id (required for preview/run/delete; from get_scenarios)."),params:x.record(x.union([x.string(),x.number(),x.boolean()])).optional().describe("Variable values for preview/run, e.g. {storeId:'220'}. Declared defaults fill in the rest."),scenario:x.object({id:x.string().describe("Stable kebab-case id."),name:x.string().describe("Human name; may contain {{variable}} placeholders."),description:x.string().optional(),expectedOutcome:x.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:x.string().optional(),authoredAgainst:x.string().optional().describe("App version this was written against."),folder:x.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:x.array(x.string()).optional(),vars:x.array(x.object({key:x.string(),label:x.string().optional(),type:x.enum(["string","number","boolean","enum"]),options:x.array(x.union([x.string(),x.number(),x.boolean()])).optional(),default:x.union([x.string(),x.number(),x.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:x.array(x.object({id:x.string().optional(),tool:x.string().describe("Tool id: network | storage | impersonate | route-events | query | time-machine"),action:x.string().describe("Action name on that tool, e.g. upsertOverrideRule, async.setItem, startImpersonation, navigate."),params:x.unknown().optional(),label:x.string().optional()})).describe("Steps, in order."),undoSteps:x.array(x.object({id:x.string().optional(),tool:x.string(),action:x.string(),params:x.unknown().optional(),label:x.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:x.string().optional().describe("Target device id (auto-selected if one is connected).")}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=(o,a)=>n.callAction(ir,o,a,r);switch(t.action){case"preview":{if(!t.id)return te("preview requires `id` (from get_scenarios).");const o=await s("preview",{id:t.id,params:t.params??{}});const a=[`**Dry run \u2014 \`${t.id}\`** (nothing has been changed)`,`variables: ${Object.entries(o.values).map(([i,c])=>`${i}=${String(c)}`).join(", ")||"none"}`,`**Would do:**
|
|
151
|
-
${o.willDo.map(i=>` \xB7 ${i.label} [${i.durability}]`).join("\n")}`];if(o.expectedOutcome)a.push(`**Expected outcome:** ${o.expectedOutcome}`);if(o.conflict){a.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)a.push(`**Warnings:**
|
|
152
|
-
${o.warnings.map(i=>` \xB7 ${i}`).join("\n")}`);a.push(o.ok?"Pre-flight checks passed. Review the intended effects before running.":`\u274C **Cannot run:**
|
|
153
|
-
${o.errors.map(i=>` \xB7 ${i}`).join("\n")}`);return ke(a.join("\n\n"))}case"run":{if(!t.id)return te("run requires `id` (from get_scenarios).");const o=await s("run",{id:t.id,params:t.params??{}});if(o.preflightErrors?.length){return te(`Pre-flight refused to run \`${t.id}\` \u2014 nothing was changed:
|
|
154
|
-
${o.preflightErrors.map(i=>` \xB7 ${i}`).join("\n")}`)}const a=(o.steps??[]).map(i=>{const c=i.skipped?"\u2013":i.ok?"\u2713":"\u2717";const u=i.error?`
|
|
155
|
-
${i.error}`:"";return` ${c} ${i.label} (${i.ms}ms)${u}`}).join("\n");if(!o.ok){return te(`Run FAILED \u2014 it stopped at the failing step and nothing after it ran. The steps before it DID apply:
|
|
156
|
-
${a}
|
|
157
|
-
|
|
158
|
-
The device is now in a partial state. Deactivate to reverse what landed, or fix the step and run again.`)}return ke([`\u2705 **Scenario active \u2014 ${o.name??t.id}**`,a,`**Reported effects:**
|
|
159
|
-
${(o.effects??[]).map(i=>` \xB7 ${i.label} [${i.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 s("deactivate",{});const a=o.report;const i=[`Removed ${a.removedRules} override rule(s)`,a.stoppedImpersonation?"Ended impersonation":null,a.undoStepsRan?`Ran ${a.undoStepsRan} undo step(s)`:null].filter(Boolean);const c=a.unrestoredState??[];const u=(a.unrestoredStorageKeys.length?`
|
|
160
|
-
|
|
161
|
-
\u26A0\uFE0F **NOT restored:** ${a.unrestoredStorageKeys.join(", ")} \u2014 a storage write has no automatic inverse. The app still holds these values.`:"")+(c.length?`
|
|
162
|
-
|
|
163
|
-
\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=a.errors.length?`
|
|
164
|
-
|
|
165
|
-
Errors: ${a.errors.join("; ")}`:"";return ke(`**Deactivated.**
|
|
166
|
-
${i.map(d=>` \xB7 ${d}`).join("\n")}${u}${l}`)}case"save":{if(!t.scenario)return te("save requires `scenario`.");const o=await s("save",{scenario:t.scenario});if(!o.ok){return te(`Save rejected:
|
|
167
|
-
${(o.errors??[o.error??"unknown error"]).map(a=>` \xB7 ${a}`).join("\n")}`)}return ke(`Saved \`${o.id}\` **as a draft**.
|
|
168
|
-
|
|
169
|
-
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 te("setFolder requires `id` (from get_scenarios).");const o=await s("setFolder",{id:t.id,folder:t.folder});return ke(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 te("delete requires `id`.");await s("delete",{id:t.id});return ke(`Deleted \`${t.id}\` from the device library.`)}}}catch(r){return te(cr(r))}})}import{z as oe}from"zod";var V=e=>({content:[{type:"text",text:e}]});var _e=e=>ut().isPro?null:ae(Jr(e));var ae=e=>({isError:true,content:[{type:"text",text:e}]});function va(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:oe.enum(["barcode","image","video","camera","screen","pattern"]).describe("What the camera should show."),value:oe.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:oe.enum(["qr","pdf417","aztec","code128"]).optional().describe("Barcode symbology; defaults to qr.")}},async n=>{const t=_e("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 s=await X(r);if(!s.ok){return ae(s.error??s.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 V(`The simulator camera is now showing ${o}, at ${s.data?.fps??0} fps.
|
|
170
|
-
|
|
171
|
-
_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=_e("camera_status");if(n)return n;const t=await X(["status"]);if(!t.ok||!t.data){return ae(t.error??"could not read the simulator camera status")}const{publishing:r,fps:s,codes:o}=t.data;if(!r){return V("The simulator camera is not publishing anything.\n\n_Set a source with `camera_source` first._")}return V([`Publishing at ${s} fps.`,o.length?`Currently decoding: ${o.map(a=>`\`${a}\``).join(", ")}`:"No barcode in the current frame.","","_A code shown here is what the app receives. If the app is not reacting to it, the problem is in the app, not the camera \u2014 `camera_diagnose` will say whether the app is even reading the feed._"].join("\n"))});e.registerTool("camera_launch",{description:"Relaunch a simulator app with the camera attached. A camera can only be attached when a process starts, so an app that is already running cannot be given one \u2014 this terminates and relaunches it.",inputSchema:{bundleId:oe.string().describe("The app's bundle identifier."),udid:oe.string().optional().describe("Simulator udid, if more than one is booted.")}},async n=>{const t=_e("camera_launch");if(t)return t;const r=["launch",n.bundleId];if(n.udid)r.push("--udid",n.udid);const s=await X(r);if(!s.ok){return ae(s.error??s.data?.error??"could not launch the app")}return V(`Relaunched \`${n.bundleId}\` with the camera attached${s.data?.pid?` (pid ${s.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:oe.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 X(t);if(!r.data?.checks){return ae(r.error??"could not run the simulator camera diagnosis")}const s=ut();const o=s.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 V(zr(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=_e("camera_stop");if(n)return n;const t=await X(["stop"]);if(!t.ok){return ae(t.error??t.data?.error??"could not stop the camera")}return V("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:oe.string().optional().describe("Which simulator's apps to list. Only needed when several are booted.")}},async n=>{const t=_e("camera_devices");if(t)return t;const r=await X(["devices"]);if(!r.ok||!r.data){return ae(r.error??"could not list booted simulators")}const s=r.data.devices??[];let o=null;if(s.length===1||n.udid){const a=await X(["apps",...n.udid?["--udid",n.udid]:[]]);o=a.ok?a.data?.apps??[]:null}return V(Ur(s,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=_e("camera_inputs");if(n)return n;const[t,r]=await Promise.all([X(["cameras"]),X(["windows"])]);if(!t.ok&&!r.ok){return ae(t.error??r.error??"could not list the Mac's cameras or windows")}return V(Wr(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:oe.enum(["on","off","status"]).describe("Turn it on, off, or report the current state."),udid:oe.string().optional().describe("Which simulator. Only needed when several are booted.")}},async n=>{const t=_e("camera_zero_setup");if(t)return t;const r=await X(["zero-setup",n.action,...n.udid?["--udid",n.udid]:[]]);if(!r.ok){return ae(r.error??r.data?.error??"could not change zero-setup mode")}const s=r.data??{};if(n.action==="status"){if(!s.enabled)return V("Zero-setup mode is **off**.");return V(s.foreign?`Zero-setup is on, but **another tool owns it** (\`${s.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 V("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 V("Zero-setup mode is **off**.")})}import{z as S}from"zod";var wa=e=>({content:[{type:"text",text:e}]});var Ot=e=>({isError:true,content:[{type:"text",text:e}]});var ba="`run_web_benchmark` is a Buoy Pro feature. Running benchmarks from an agent needs Pro.\n\n_Tell the user to sign in to Buoy Desktop with a Pro account, or open an app signed in to Pro. See https://buoy.gg/pricing. Don't try to work around it._";function ya(e){if(ut().isPro)return true;return e.connectedDevices().some(n=>n.tier==="pro")}function $a(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:S.string().describe("Origin of the running app, e.g. http://localhost:5173"),path:S.string().optional().describe("Default path for cases, e.g. /bench/lights"),cases:S.array(S.object({name:S.string(),path:S.string().optional(),params:S.record(S.string()).optional(),control:S.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:S.number().optional().describe("Measured runs per case (1\u201310). Default 3."),perCaseDurationMs:S.number().optional().describe("Recording length per run. Default 5000."),settleMs:S.number().optional().describe("Wait after the page is ready, before recording. Default 1000."),cpuSlowdown:S.array(S.number()).optional().describe("CPU throttling rates; 1 = none. Default [1]."),viewport:S.object({width:S.number(),height:S.number(),deviceScaleFactor:S.number().optional()}).optional().describe("Fixed viewport. Default 1280\xD7800 at 1x."),readySelector:S.string().optional().describe("CSS selector that must appear before a run counts as ready."),steps:S.array(S.union([S.object({click:S.string()}),S.object({press:S.string()}),S.object({type:S.object({selector:S.string(),text:S.string()})}),S.object({scroll:S.number()}),S.object({wait:S.number()}),S.object({expect:S.object({selector:S.string(),text:S.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:S.string().optional().describe("Save one Chrome trace per case here (extra, unranked runs)."),headed:S.boolean().optional().describe("Show the browser window. Default false."),allowPageErrors:S.boolean().optional().describe("Keep runs whose page threw an uncaught error. Default false: such runs fail."),projectRoot:S.string().optional().describe("Folder to load Playwright from. Default: the server's working directory."),outFile:S.string().optional().describe("Also save the full result and options as JSON here, to read again later."),extraRoundsWhenClose:S.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:S.number().optional().describe("Stop starting new runs after this long. Default 30 minutes."),budgets:S.object({droppedPct:S.number().optional(),inputMs:S.number().optional(),freezeMs:S.number().optional(),mainThreadPct:S.number().optional(),jsHeapMb:S.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(!ya(n))return Ot(ba);try{const r=await Vr({url:t.url,path:t.path,cases:t.cases,runsPerCase:t.runsPerCase,durationMs:t.perCaseDurationMs,settleMs:t.settleMs,cpuSlowdown:t.cpuSlowdown,viewport:t.viewport,readySelector:t.readySelector,steps:t.steps,traceDir:t.traceDir,headed:t.headed,allowPageErrors:t.allowPageErrors,projectRoot:t.projectRoot,outFile:t.outFile,extraRoundsWhenClose:t.extraRoundsWhenClose,maxBatchMs:t.maxBatchMs,budgets:t.budgets},a=>process.stderr.write(`[buoy-mcp] web-bench: ${a}
|
|
172
|
-
`));const s={status:r.status,browser:r.browser,viewport:r.viewport,results:r.results.map(a=>({caseName:a.caseName,cpu:a.cpu,validRuns:a.validRuns,fpsMin:a.fpsMin,fpsMax:a.fpsMax,plannedRuns:a.plannedRuns,isBaseline:a.isBaseline,control:a.control===true,deltaDroppedPct:a.deltaDroppedPct,droppedRange:a.droppedMin==null?null:[a.droppedMin,a.droppedMax],flags:a.flags,budget:a.budget,median:a.median,failures:a.runs.filter(i=>i.failed).map(i=>i.failed)})),traces:r.traces,warnings:r.warnings,replay:r.replay};const o=`${Gr(r)}
|
|
173
|
-
|
|
174
|
-
\`\`\`json
|
|
175
|
-
${JSON.stringify(s,null,2)}
|
|
176
|
-
\`\`\``;return r.status==="failed"?Ot(`Every case failed.
|
|
177
|
-
|
|
178
|
-
${o}`):wa(o)}catch(r){return Ot(r?.message??String(r))}})}import{z as K}from"zod";var ur="highlight-updates";var Ct=e=>({content:[{type:"text",text:e}]});var tt=e=>({isError:true,content:[{type:"text",text:e}]});var dr=e=>e instanceof Error?e.message:String(e);function ka(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}var Ft=0;var hr=3;var _a="\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 Sa(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:K.boolean().optional().describe("Only return tappable (onPress) elements. Default false (include labels/text for context)."),includeBuoy:K.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."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=await n.callAction(ur,"describeScreen",{includeBuoy:t.includeBuoy},r);const o=s?.elements??[];const a=t.interactiveOnly?o.filter(u=>u.interactive):o;if(a.length===0){return Ct("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 i=s.hiddenBuoy?` Buoy's own overlay (${s.hiddenBuoy} element${s.hiddenBuoy===1?"":"s"}) is left out \u2014 pass includeBuoy:true to see it.`:"";const c=`Screen ${s.screen.width}\xD7${s.screen.height} \u2014 ${a.length} element${a.length===1?"":"s"} (\u2022 = tappable). Tap with tap_element({ testID | query | nativeTag }).${i}`;return Ct(`${c}
|
|
179
|
-
|
|
180
|
-
${a.map(ka).join("\n")}`)}catch(r){return tt(dr(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:K.number().optional().describe("Exact nativeTag from describe_screen (most precise)."),testID:K.string().optional().describe("Exact testID of the element."),query:K.string().optional().describe('Fuzzy match against testID / label / visible text / component name \u2014 e.g. "Sign in".'),value:K.union([K.number(),K.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:K.string().optional().describe("For a text input: the string to set via onChangeText."),longPress:K.boolean().optional().describe("Invoke the element's onLongPress instead of onPress. Fails with a clear reason if the element has no onLongPress handler."),scrollIntoView:K.boolean().optional().describe("Attempt to scroll an off-screen target into view. Default true; inspect the action result."),includeBuoy:K.boolean().optional().describe("Let a fuzzy `query` match Buoy's own overlay. Default false \u2014 an exact nativeTag/testID always may."),deviceId:A}},async t=>{try{if(t.nativeTag==null&&!t.testID&&!t.query){return tt("Provide one of: nativeTag, testID, or query (from describe_screen).")}const r=n.requireProDevice(t.deviceId);const s=await n.callAction(ur,"tapElement",{nativeTag:t.nativeTag,testID:t.testID,query:t.query,value:t.value,text:t.text,longPress:t.longPress,scrollIntoView:t.scrollIntoView,includeBuoy:t.includeBuoy},r);Ft+=1;const o=Ft>=hr&&Ft%hr===0?_a:"";if(s?.tapped&&s.matched){const i=s.matched;const c=i.text??i.label??i.name;const u=i.testID?` [testID=${i.testID}]`:i.nativeTag!=null?` #${i.nativeTag}`:"";const l=s.scrolled?" (scrolled into view)":"";const d=i.via==="onValueChange"?`Set "${c}"${u} \u2192 ${JSON.stringify(i.value)}`:i.via==="onChangeText"?`Typed ${JSON.stringify(i.value)} into "${c}"${u}`:i.via==="onLongPress"?`Long-pressed "${c}"${u}`:`Tapped "${c}"${u}`;const h=s.effect;const k=!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 b=s.alsoMatched?.length?`
|
|
181
|
-
Also matched equally well (the choice was a coin toss \u2014 re-tap by #nativeTag if this was wrong):
|
|
182
|
-
`+s.alsoMatched.map(g=>`- ${g.name}${g.text?` "${g.text}"`:""}${g.testID?` [testID=${g.testID}]`:""}${g.nativeTag!=null?` #${g.nativeTag}`:""}`).join("\n"):"";return Ct(`${d}${l}.${k}${b}${o}`)}let a=s?.reason??"Tap failed.";if(s?.candidates?.length){a+="\n\nTappable candidates:\n"+s.candidates.map(i=>`- ${i.name}${i.text?` "${i.text}"`:""}${i.testID?` [testID=${i.testID}]`:""}${i.nativeTag!=null?` #${i.nativeTag}`:""}`).join("\n")}return tt(a)}catch(r){return tt(dr(r))}})}import{z as Et}from"zod";var Bt="js-top";var xa="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function Aa(e){const n=Math.max(1,...e);return e.map(t=>xa[Math.min(7,Math.floor(t/n*7.999))]).join("")}function Ta(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,s)=>{const o=r.freezes>0?`\u26A0 ${r.freezes} (worst ${r.worstFreezeMs}ms)`:"\u2013";t.push(`| ${s+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 Ma(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): \`${Aa(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 Ia(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:A,durationMs:Et.number().optional().describe("How long to sample before reading the table. Default 3000; clamped to 250\u201330000."),clearFirst:Et.boolean().optional().describe("Reset tracked statistics before sampling. Hook coverage and attribution limits still apply.")}},async({deviceId:t,durationMs:r,clearFirst:s})=>{try{const o=n.requireProDevice(t);const a=Math.min(Math.max(r??3e3,250),3e4);const i=await n.callAction(Bt,"sample",{durationMs:a,clearFirst:s===true},o);if(!i)return f("Device returned no snapshot \u2014 is @buoy-gg/js-top installed in the app?");const c=Ta(i,a);const u={busyPct:Math.round(i.busyPct*10)/10,freezeSummary:i.freezeSummary,tiers:i.tiers,rows:i.rows.slice(0,15).map(l=>({key:l.key,api:l.api,windowMs:Math.round(l.windowMs*10)/10,pctOfBusy:Math.round(l.pctOfBusy*10)/10,calls:l.calls,avgMs:Math.round(l.avgMs*100)/100,maxMs:Math.round(l.maxMs*10)/10,totalMs:Math.round(l.totalMs),freezes:l.freezes,worstFreezeMs:l.worstFreezeMs}))};return $(`${c}
|
|
183
|
-
|
|
184
|
-
\`\`\`json
|
|
185
|
-
${JSON.stringify(u)}
|
|
186
|
-
\`\`\``)}catch(o){return f(M(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:A,key:Et.string().describe("Origin key from get_js_thread_top's JSON rows.")}},async({deviceId:t,key:r})=>{try{const s=n.requireProDevice(t);const o=await n.callAction(Bt,"getOriginDetail",{key:r},s);if(!o){return f(`Origin "${r}" is not tracked (cleared, evicted, or never existed). Re-run get_js_thread_top for current keys.`)}const a=Ma(o);return $(`${a}
|
|
187
|
-
|
|
188
|
-
\`\`\`json
|
|
189
|
-
${JSON.stringify(o)}
|
|
190
|
-
\`\`\``)}catch(s){return f(M(s))}});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:A}},async({deviceId:t})=>{try{const r=n.requireProDevice(t);await n.callAction(Bt,"clear",{},r);return $("Cleared js-top stats.")}catch(r){return f(M(r))}})}import{z as ne}from"zod";var ie="images";function pr(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 s=r.split("/").filter(Boolean);return s[s.length-1]??t}function Da(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 mr(e){if(e.cache)return e.cache;if(e.progressSeen)return"network";return"?"}function fr(e){return`${(e/(1024*1024)).toFixed(1)}MB`}function Ra(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${fr(r.estDecodedBytes)} decoded`+(r.estWastedBytes>0?` \xB7 **${fr(r.estWastedBytes)} wasted on oversized sources**`:""));const s=e.insights;if(s){const a=[];if(s.duplicates.length>0)a.push(`${s.duplicates.length} duplicate URL(s): ${s.duplicates.slice(0,3).map(i=>`${pr(i.uri)}\xD7${i.count}`).join(", ")}`);if(s.retryStorms.length>0)a.push(`${s.retryStorms.length} retry storm(s): ${s.retryStorms.slice(0,3).map(i=>`#${i.id}(${i.loadCount} loads)`).join(", ")}`);if(s.queueSaturated)a.push("iOS image queue saturated (>4 concurrent loads)");if(s.missingAlt>0)a.push(`${s.missingAlt} image(s) missing alt/accessibilityLabel`);if(s.layoutShifters.length>0)a.push(`${s.layoutShifters.length} layout-shifting image(s): ${s.layoutShifters.slice(0,3).map(i=>`#${i.id}`).join(", ")} \u2014 reserve explicit dimensions`);if(a.length>0){t.push("");t.push(`**Insights:** ${a.join(" \xB7 ")}`)}}const o=e.captureStatus;if(o.rnDecoratorTooLate){t.push("");t.push('\u26A0 RN <Image> capture missed the module-load race \u2014 add `import "@buoy-gg/images/register"` as the FIRST import of the app entry file.')}if(e.globalModes.network!=="normal"||e.globalModes.blank){t.push("");t.push(`\u26A0 Simulation active: network=${e.globalModes.network}${e.globalModes.blank?", blank images ON":""} (set_image_simulation to reset).`)}t.push("");t.push("| id | image | lib | status | cache | ms | decoded px | shown dp | verdict | sim |");t.push("|---|---|---|---|---|---|---|---|---|---|");for(const a of e.records){const i=a.intrinsic?`${a.intrinsic.width}\xD7${a.intrinsic.height}`:"\u2013";const c=a.layout?`${a.layout.width}\xD7${a.layout.height}`:"\u2013";const u=a.status==="error"?`**error**${a.errorCode?` (${a.errorCode})`:""}`:a.status;t.push(`| ${a.id} | ${pr(a.uri)} | ${a.lib} | ${u}${a.mounted?"":" (unmounted)"} | ${mr(a)} | ${a.ms??"\u2013"} | ${i} | ${c} | ${Da(a)} | ${a.overrideLabel??"\u2013"} |`)}t.push("");t.push("_Act on a row with `image_action` using its `id` (hard_reload / retry / force_error / force_loading / force_blank / swap_url / flash / restore / evict_disk)._");return t.join("\n")}var Oa={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 Ca(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:A,limit:ne.number().optional().describe("Max records to return (newest first). Default 30, max 200."),status:ne.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:s})=>{try{const o=n.requireProDevice(t);const a=Math.min(Math.max(r??30,1),200);const i=await n.callAction(ie,"list",{limit:a,status:s},o);if(!i)return f("Device returned nothing \u2014 is @buoy-gg/images installed in the app?");const c=Ra(i,a);const u={stats:i.stats,insights:i.insights,captureStatus:i.captureStatus,globalModes:i.globalModes,records:i.records.map(l=>({id:l.id,uri:l.uri,lib:l.lib,status:l.status,mounted:l.mounted,cache:l.cache,ms:l.ms,intrinsic:l.intrinsic,layout:l.layout,oversizeFactor:l.oversizeFactor,wastedKB:l.wastedKB,error:l.error,errorCode:l.errorCode,overrideLabel:l.overrideLabel,loadCount:l.loadCount,hasAltText:l.hasAltText,layoutShifts:l.layoutShifts}))};return $(`${c}
|
|
191
|
-
|
|
192
|
-
\`\`\`json
|
|
193
|
-
${JSON.stringify(u)}
|
|
194
|
-
\`\`\``)}catch(o){return f(M(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:A,id:ne.number().describe("Record id from get_images."),action:ne.enum(["hard_reload","retry","evict_disk","flash","prove_savings","force_error","force_loading","force_blank","swap_url","restore"]).describe("What to do."),url:ne.string().optional().describe("Replacement URL (swap_url only).")}},async({deviceId:t,id:r,action:s,url:o})=>{try{const a=n.requireProDevice(t);if(s==="prove_savings"){const h=await n.callAction(ie,"proveSavings",{id:r},a);if(!h)return f("Device returned nothing for proveSavings.");if(!h.ok)return f(h.message);const k=[`**prove_savings** on #${r}: ${h.message}`];if(h.originalBytes!=null)k.push(`Original: ${Math.round(h.originalBytes/1024)}KB (${h.originalBytesSource})`);if(h.optimizedBytes!=null)k.push(`Optimized: ${Math.round(h.optimizedBytes/1024)}KB \u2014 ${h.optimizedDims?.width}\xD7${h.optimizedDims?.height} WebP`);if(h.savedBytes!=null)k.push(`**Saved: ${Math.round(h.savedBytes/1024)}KB (${h.savedPct}%)**`);if(h.optimizedUri)k.push(`Preview in place: image_action {id:${r}, action:"swap_url", url:"${h.optimizedUri}"}`);return $(k.join("\n"))}const i=Oa[s];if(!i)return f(`Unknown action: ${s}`);if(s==="swap_url"&&!o)return f("swap_url requires the `url` param.");const c=await n.callAction(ie,i.action,{id:r,...i.params?.(o)??{}},a);const u=s==="flash"?0:1500;if(u>0)await new Promise(h=>setTimeout(h,u));const l=await n.callAction(ie,"getDetail",{id:r},a).catch(()=>null);const d=[`**${s}** 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=${mr(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 $(d.join("\n"))}catch(a){return f(M(a))}});e.registerTool("set_image_simulation",{description:"Configure supported instrumented image loads: offline simulates network-load failures while bundled assets can still load; cold requests cache bypass; normal resets the network mode. Reload or remount existing images as needed. blankImages removes sources from integrated images; massAction targets registered mounted images. Can also clear the registry or supported Expo caches. These modes do not change device connectivity.",inputSchema:{deviceId:A,network:ne.enum(["normal","offline","cold"]).optional().describe("Network simulation mode."),blankImages:ne.boolean().optional().describe("Render integrated images without a source."),massAction:ne.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:ne.boolean().optional().describe("Clear the captured image log."),clearExpoCaches:ne.boolean().optional().describe("Clear expo-image memory + disk caches.")}},async({deviceId:t,network:r,blankImages:s,massAction:o,clearRegistry:a,clearExpoCaches:i})=>{try{const c=n.requireProDevice(t);const u=[];if(o){const l=await n.callAction(ie,"massAction",{kind:o},c);u.push(l?.message??`mass ${o} applied`)}if(r){await n.callAction(ie,"setNetworkMode",{mode:r},c);u.push(`network=${r}`)}if(s!=null){await n.callAction(ie,"setBlankImages",{enabled:s},c);u.push(`blankImages=${s}`)}if(a){await n.callAction(ie,"clearRecords",{},c);u.push("registry cleared")}if(i){const l=await n.callAction(ie,"clearExpoCaches",{},c);u.push(l?.message??"expo caches cleared")}if(u.length===0)return f("Pass at least one of: network, blankImages, massAction, clearRegistry, clearExpoCaches.");return $(`Applied: ${u.join(" \xB7 ")}`)}catch(c){return f(M(c))}})}import{z as Pe}from"zod";function Fa(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 Se="assets";function he(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 gr(e){if(e.sizeBytes==null)return"\u2013";return e.sizeSource==="measured"?he(e.sizeBytes):`~${he(e.sizeBytes)}`}function vr(e){if(!e.length)return"\u2013";return e.map(n=>`@${n}x`).join(" ")}function Ea(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 Ba(e,n){const t=[];const r=e.stats;const s=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(([,l])=>l.count>0).map(([l,d])=>`${d.count} ${l}${d.bytes>0?` (${he(d.bytes)})`:""}`);t.push(`${r.loaded} loaded \xB7 ${r.neverLoaded} never loaded \xB7 `+(r.totalBytes>0?`${he(r.totalBytes)} measured (${r.measuredCount}/${r.total})`:"sizes not measured")+` \xB7 ${o.join(" \xB7 ")}`);if(s.fontFamilies.length>0){t.push(`Loaded font families: ${s.fontFamilies.join(", ")}`)}const a=Fa(s);if(a)t.push(a);if(s.measuring)t.push("\u26A0 Size measurement in progress \u2014 byte totals are partial; re-run get_assets shortly.");const i=e.insights;const c=[];if(i.neverLoaded.length)c.push(`${i.neverLoaded.length} never loaded`);if(i.duplicates.length){const l=i.duplicates.reduce((d,h)=>d+(h.wastedBytes??0),0);c.push(`${i.duplicates.length} duplicate group(s)${l>0?` (${he(l)} wasted)`:""}`)}if(i.overDecode.length)c.push(`${i.overDecode.length} decode larger than 2\xD7 the screen`);if(i.webpCandidates.length)c.push(`${i.webpCandidates.length} WebP candidate(s)`);if(i.heavyGifs.length)c.push(`${i.heavyGifs.length} heavy GIF(s)`);if(i.heavyFonts.length)c.push(`${i.heavyFonts.length} heavy font(s)`);if(i.scaleGaps.length)c.push(`${i.scaleGaps.length} scale gap(s)`);if(i.scaleAnomalies.length)c.push(`${i.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"}${he(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} | ${vr(l.scales)} | ${gr(l)} | ${Ea(l,i)} |`)}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 Pa(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:A,limit:Pe.number().optional().describe("Max records to return (largest first). Default 40, max 500."),kind:Pe.enum(["image","font","video","audio","data","other"]).optional().describe("Only assets of this kind."),unusedOnly:Pe.boolean().optional().describe("Only assets shipped in the bundle but never loaded at runtime.")}},async({deviceId:t,limit:r,kind:s,unusedOnly:o})=>{try{const a=n.requireProDevice(t);const i=Math.min(Math.max(r??40,1),500);const c=await n.callAction(Se,"list",{limit:o?500:i,kind:s,loadedOnly:false},a);if(!c)return f("Device returned nothing \u2014 is @buoy-gg/assets installed in the app?");if(o){c.records=c.records.filter(d=>!d.loaded).slice(0,i)}const u=Ba(c,i);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 $(`${u}
|
|
195
|
-
|
|
196
|
-
\`\`\`json
|
|
197
|
-
${JSON.stringify(l)}
|
|
198
|
-
\`\`\``)}catch(a){return f(M(a))}});e.registerTool("asset_action",{description:"Drive the assets tool: rescan (re-walk the registry + merge the Metro bundle graph + refresh fonts + measure sizes \u2014 run this first if the inventory looks stale or empty), measure_sizes (re-measure byte sizes only), detail (full metadata for one asset by id: source dir, per-scale sizes, resolved URI, per-file graph paths), save_baseline (persist the current inventory for before/after comparison \u2014 save, make your change, then get_assets shows added/removed/grown/net bytes), clear_baseline, clear_records (wipe + rescan rebuilds).",inputSchema:{deviceId:A,action:Pe.enum(["rescan","measure_sizes","detail","save_baseline","clear_baseline","clear_records"]).describe("What to do."),id:Pe.number().optional().describe("Asset id from get_assets (detail only).")}},async({deviceId:t,action:r,id:s})=>{try{const o=n.requireProDevice(t);switch(r){case"rescan":{const a=await n.callAction(Se,"rescan",{},o);const i=a?.scanStatus;if(!i)return f("Device returned nothing for rescan.");return $(`Rescan done: ${i.registryCount} registered at runtime`+(i.graphCount!=null?` \xB7 ${i.graphCount} in the bundle graph`:" \xB7 no bundle graph")+(i.graphError?` (graph: ${i.graphError})`:"")+` \xB7 ${i.fontFamilies.length} font families`+(i.measuring?" \xB7 size measurement running \u2014 get_assets in a moment":""))}case"measure_sizes":{const a=await n.callAction(Se,"measureSizes",{},o);return $(`Measured ${a?.measured??0} of ${a?.total??0} assets.`)}case"detail":{if(s==null)return f("detail requires the `id` param (from get_assets).");const a=await n.callAction(Se,"getDetail",{id:s},o);if(!a)return f(`Asset ${s} not found \u2014 re-run get_assets for current ids.`);const i=[`## ${a.name}.${a.type} (#${a.id})`,"",`- Kind: ${a.kind} \xB7 ${a.loaded?"loaded at runtime":"in bundle, NEVER loaded"} (${a.origin})`];if(a.width!=null)i.push(`- Dimensions: ${a.width}\xD7${a.height} logical \xB7 scales ${vr(a.scales)}`);if(a.sizesByScale){for(const[c,u]of Object.entries(a.sizesByScale)){i.push(`- Size @${c}x: ${he(u)}`)}}if(a.sizeBytes!=null)i.push(`- Total: ${gr(a)}`);if(a.estDecodedBytes)i.push(`- Decoded memory: ~${he(a.estDecodedBytes)} (RGBA)`);if(a.hash)i.push(`- Hash: ${a.hash}`);if(a.fileSystemLocation)i.push(`- Source dir: ${a.fileSystemLocation}`);if(a.files?.length)i.push(`- Files: ${a.files.join(", ")}`);if(a.uri)i.push(`- Resolved URI: ${a.uri}`);return $(i.join("\n"))}case"save_baseline":{const a=await n.callAction(Se,"saveBaseline",{},o);return $(`Baseline saved (${a?.assets??0} assets). Make your change, then get_assets reports added/removed/grown/net bytes against it.`)}case"clear_baseline":{await n.callAction(Se,"clearBaseline",{},o);return $("Baseline cleared.")}case"clear_records":{const a=await n.callAction(Se,"clearRecords",{},o);return $(a?.message??"Inventory cleared.")}}}catch(o){return f(M(o))}})}import{z as nt}from"zod";import{WebSocket as ja}from"ws";var qa=3e3;function Na(e){return`${e.replace(/^http/,"ws").replace(/\/+$/,"")}/message`}function La(e){return new Promise(n=>{let t=false;const r=i=>{if(t)return;t=true;n(i)};let s;try{s=new ja(Na(e))}catch(i){r({ok:false,error:i.message});return}const o=setTimeout(()=>{try{s.close()}catch{}r({ok:false,error:`dev server at ${e} did not accept a connection`})},qa);let a=false;s.on("open",()=>{try{s.send(JSON.stringify({version:2,method:"reload"}));a=true;clearTimeout(o);setTimeout(()=>{try{s.close()}catch{}r({ok:true})},250)}catch(i){clearTimeout(o);r({ok:false,error:i.message})}});s.on("error",i=>{clearTimeout(o);if(a)return;r({ok:false,error:i.message})})})}var Pt="app";var wr="reloadApp";var Ua=3e4;var za=1200;var br=1500;var Wa=400;var yr=e=>new Promise(n=>setTimeout(n,e));async function $r(e,n,t){try{const r=await e.callAction(Pt,"ping",{},n,{timeoutMs:t,silent:true});e.noteDevServerOrigin(n,r?.devServerOrigin);return typeof r?.startedAt==="number"?r.startedAt:null}catch{return null}}function Ja(e,n){if(n===Z)return;const t=e.toolActions(Pt).find(r=>r.deviceId===n);if(!t?.actions.includes(wr)){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 Ga(e,n,t,r){const s=Date.now();await yr(za);while(Date.now()-s<t){const o=await $r(e,n,br);if(o!==null&&o!==r)return Date.now()-s;await yr(Wa)}return null}function Va(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:nt.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:nt.boolean().optional().describe("Wait for the app to come back before returning. Default true \u2014 turn off for fire-and-forget."),timeoutMs:nt.number().optional().describe("How long to wait for the app to reconnect, in ms. Default 30000."),deviceId:nt.string().optional().describe('Target device id (auto-selected if one is connected). Use "All" to reload every connected app.')}},async t=>{try{const r=n.requireProDevice(t.deviceId);Ja(n,r);const s=t.wait===false?null:await $r(n,r,br);let o=null;let a=false;const i=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 La(d);if(!h.ok){throw new Error(`The app is not answering (it looks crashed) and the dev server at ${d} could not be reached either: ${h.error}. Reload the app by hand.`)}a=true};if(n.isUnresponsive(r)&&n.devServerOrigin(r)){await i()}else{try{o=await n.callAction(Pt,wr,{strategy:t.strategy??"auto"},r)}catch(l){await i(l)}}const c=a?` via the dev server (the app was unresponsive \u2014 its own reload could not be reached)`:o?.strategy?` via ${o.strategy}`:"";if(t.wait===false){return $(`Reload requested${c}. The app is restarting \u2014 its in-memory state is gone; re-read anything you cached.`)}const u=await Ga(n,r,t.timeoutMs??Ua,s);if(u==null){return f(`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 $(`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 f(M(r))}})}import{z as Ka}from"zod";var Ha=e=>({content:[{type:"text",text:e}]});var Ya=e=>({isError:true,content:[{type:"text",text:e}]});var kr=e=>e instanceof Error?e.message:String(e);var Qa=5e3;var Xa=20;var Za=400;var ei=1600;var ti=160;var rt=(e,n=ti)=>e.length>n?`${e.slice(0,n)}\u2026`:e;function ni(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 ri(e,n,t){const r=[];try{const s=await e.callAction("storage","mmkv.snapshot",{},n,t);for(const o of s??[]){const a=o.entries?.length??0;if(a>0)r.push(`MMKV "${o.id}": ${a} key${a===1?"":"s"}`)}}catch{}try{const s=await e.callAction("storage","secure.keys",{},n,t);if(s?.length)r.push(`SecureStore: ${s.length} key${s.length===1?"":"s"}`)}catch{}return r.length?`
|
|
199
|
-
${r.join(" \xB7 ")} \u2014 read with get_storage`:""}async function st(e,n){try{const t=await n();return t?`${e}
|
|
200
|
-
${t}`:null}catch(t){const r=kr(t);if(/not responding|timed out|got no answer/i.test(r)){return`${e}
|
|
201
|
-
(no answer \u2014 see the note above)`}return`${e}
|
|
202
|
-
(unavailable: ${rt(r,120)})`}}function si(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:Ka.string().optional().describe("Target device id (auto-selected if one is connected).")}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=n.connectedDevices().find(g=>g.deviceId===r);const o=new Set((s?.tools??[]).map(g=>g.toolId));const a=`**${s?.deviceName??r}** (${s?.platform??"?"}, id \`${r}\`) \u2014 tools: ${[...o].join(", ")||"none"}`;const i={timeoutMs:Qa};const[c,u,l,d]=await Promise.all([st("**Console \u2014 recent errors/warnings:**",async()=>{if(!o.has("console"))return null;const{payload:g}=await n.getSnapshot("console",r,i);const y=g;const p=Array.isArray(y)?y:y?.entries??[];const m=p.filter(w=>w.level==="error"||w.level==="warning");const v=m.slice(-8);if(v.length===0){return`(none \u2014 ${p.length} entries captured)`}return v.map(w=>`${ni(w.timestamp)} [${w.level==="error"?"ERR":"warn"}] ${rt((w.message??"").split("\n").map(_=>_.trim()).filter(Boolean).slice(0,3).join(" \u23CE "),220)}`).join("\n")}),st("**Network \u2014 recent requests:**",async()=>{if(!o.has("network"))return null;const{payload:g}=await n.getSnapshot("network",r,i);const y=Array.isArray(g)?g:g?.events??[];if(y.length===0)return"(no requests captured yet)";const p=y.slice(-8);return p.map(m=>{const v=m.error||(m.status??0)>=400?"\u274C":"\u2705";const w=m.path??m.url??"?";const _=m.error??m.status??"pending";return`${v} ${m.method??"GET"} ${rt(String(w),80)} \u2192 ${_}${m.duration?` (${Math.round(m.duration)}ms)`:""}`}).join("\n")}),st("**Storage \u2014 persisted values:**",async()=>{if(!o.has("storage"))return null;const g=await n.callAction("storage","async.getAllKeys",{},r,i);if(!Array.isArray(g)||g.length===0){return"(no app keys)"}const y=g.slice(0,Xa);let p=[];try{p=await n.callAction("storage","async.multiGet",{keys:y},r,i)??[]}catch{return`${y.map(I=>`\`${I}\``).join(", ")}
|
|
203
|
-
_Values: get_storage includeValues:true_`}const m=new Map(p);let v=ei;const w=y.map(I=>{const F=m.get(I);if(F==null)return`- \`${I}\` = (null)`;if(F.length>Za){return`- \`${I}\` = (${(F.length/1024).toFixed(1)} KB \u2014 read with get_storage)`}if(v<=0)return`- \`${I}\` = (not shown \u2014 triage budget spent; read with get_storage)`;v-=F.length;return`- \`${I}\` = ${F}`});const _=g.length-y.length;const T=await ri(n,r,i);return`${w.join("\n")}${_>0?`
|
|
204
|
-
\u2026+${_} more keys`:""}${T}`}),st("**Screen \u2014 what's visible now:**",async()=>{if(!o.has("highlight-updates"))return null;const g=await n.callAction("highlight-updates","describeScreen",{},r,i);const y=(g?.elements??[]).filter(p=>p.interactive);if(y.length===0)return"(nothing interactive on screen)";return y.slice(0,20).map(p=>`\u2022 ${p.name}${p.text||p.label?` "${rt(p.text??p.label??"",60)}"`:""}${p.testID?` [testID=${p.testID}]`:""}`).join("\n")})]);const h=n.isUnresponsive(r);const k=h?`
|
|
205
|
-
|
|
206
|
-
\u{1F6D1} ${n.unresponsiveNote(r)}`:"";const b=[c,u,l,d].filter(Boolean).join("\n\n");return Ha(`${a}${k}
|
|
207
|
-
|
|
208
|
-
${b}
|
|
209
|
-
|
|
210
|
-
_Drill in with get_console, get_network_requests (includeBodies:true for response bodies), get_storage (includeValues:true), describe_screen._`)}catch(r){return Ya(kr(r))}})}import{z as N}from"zod";var jt="highlight-updates";var _r="app";var oi=e=>({content:[{type:"text",text:e}]});var ai=e=>({isError:true,content:[{type:"text",text:e}]});var qt=e=>e instanceof Error?e.message:String(e);var ot=e=>new Promise(n=>setTimeout(n,e));var Sr=250;var ii=5e3;var xr=2e3;var ci=1200;var li=1500;var Nt=12e4;function at(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 ui(e){const n=e.text??e.label;return`${e.interactive?"\u2022 ":" "}${e.name}${n?` "${n}"`:""}${e.testID?` [testID=${e.testID}]`:""}`}var di=N.object({tap:N.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),longPress:N.boolean().optional().describe("Make `tap` a long-press instead."),type:N.string().optional().describe("Text to type (needs `into`)."),into:N.string().optional().describe("Target text input for `type`: testID or fuzzy text."),set:N.union([N.number(),N.boolean()]).optional().describe("Set a toggle (true/false) or slider (number) \u2014 pair with `tap` as the target."),reload:N.boolean().optional().describe("Reload the JS bundle before this step's action."),waitMs:N.number().min(0).max(3e4).optional().describe("Fixed pause after the action, in ms (max 30000)."),waitFor:N.string().optional().describe("Wait until an element matching this appears (default 5s)."),waitGone:N.string().optional().describe("Wait until no element matches this (default 5s)."),expect:N.string().optional().describe("Assert an element matching this IS on screen (waits up to 2s for it); fails the flow if not."),expectGone:N.string().optional().describe("Assert nothing matches this (waits up to 2s for it to go); fails the flow if something does."),timeoutMs:N.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.");function hi(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. Requires Buoy Pro and the app interaction integration.",inputSchema:{steps:N.array(di).min(1).describe("Steps to run, in order."),include:N.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."),continueOnFailure:N.boolean().optional().describe("Keep going after a failed step instead of stopping. Default false."),deviceId:A}},async t=>{const r=Date.now();try{const s=n.requireProDevice(t.deviceId);const o=t.include??"all";const a=async()=>{const v=await n.callAction(jt,"describeScreen",{},s);return v?.elements??[]};const i=async()=>{try{const v=await n.callAction(_r,"ping",{},s,{timeoutMs:li,silent:true});return typeof v?.startedAt==="number"?v.startedAt:null}catch{return null}};const c=async(v,w)=>{const _=Date.now();while(Date.now()-_<w){const T=await i();if(T!==null&&T!==v)return Date.now()-_;await ot(Sr)}return null};const u=new Set;const l=new Set;const d=new Set((n.connectedDevices().find(v=>v.deviceId===s)?.tools??[]).map(v=>v.toolId));if(o==="all"){if(d.has("console")){const{payload:v}=await n.getSnapshot("console",s).catch(()=>({payload:null}));const w=v?.entries??[];for(const _ of w)u.add(_.id)}if(d.has("network")){const{payload:v}=await n.getSnapshot("network",s).catch(()=>({payload:null}));const w=Array.isArray(v)?v:v?.events??[];for(const _ of w)l.add(_.id)}}const h=async(v,w)=>{const _=Date.now();for(;;){if(Date.now()-_>=w||Date.now()-r>Nt){return{ok:false,ms:Date.now()-_}}let T=[];try{T=await a()}catch{}if(v(T))return{ok:true,ms:Date.now()-_};await ot(Sr)}};const k=[];let b=null;let g=0;for(let v=0;v<t.steps.length;v++){const w=t.steps[v];const _=`${v+1}`;const T=w.timeoutMs??ii;if(Date.now()-r>Nt){k.push(`${_} \u2717 flow exceeded ${Nt/1e3}s \u2014 stopped here`);b=v;break}const I=[];const F=[];const lt=w.reload||w.tap||w.type!==void 0||w.waitMs||w.waitFor||w.waitGone||w.expect||w.expectGone;if(!lt){k.push(`${v+1} \u2717 step does nothing \u2014 give it a tap/type/wait/expect${w.set!==void 0?" (`set` needs `tap` naming the control)":""}`);b=b??v;if(!t.continueOnFailure)break;continue}try{if(w.reload){const C=await i();await n.callAction(_r,"reloadApp",{strategy:"auto"},s);await ot(ci);const E=await c(C,Math.max(T,2e4));if(E==null){I.push("app did not come back after reload")}else{F.push(`reloaded (${E}ms)`);await h(B=>B.length>0,1e4)}}if(w.type!==void 0){const C=w.into??w.tap;if(!C){I.push("`type` needs `into` (which input to type into)")}else{const E=await n.callAction(jt,"tapElement",{...Ar(C),text:w.type},s);if(!E?.tapped){I.push(E?.reason??`could not type into "${C}"`)}else if(E.matched?.via&&E.matched.via!=="onChangeText"){I.push(`"${C}" is not a text input \u2014 it ran ${E.matched.via} instead, and the text was not entered`)}else{F.push(`typed ${JSON.stringify(w.type)} into "${C}"`)}}}else if(w.tap){const C={...Ar(w.tap)};if(w.longPress)C.longPress=true;if(w.set!==void 0)C.value=w.set;const E=await n.callAction(jt,"tapElement",C,s);if(!E?.tapped){I.push(E?.reason??`no element matched "${w.tap}"`)}else{const B=E.matched;const Q=B?.text??B?.label??B?.name??w.tap;if(w.set!==void 0&&B?.via&&B.via!=="onValueChange"){I.push(`"${Q}" is not a toggle/slider \u2014 it ran ${B.via} instead, so it was not set to ${JSON.stringify(w.set)}`)}else{F.push(w.set!==void 0?`set "${Q}" \u2192 ${JSON.stringify(B?.value??w.set)}`:`${w.longPress?"long-pressed":"tapped"} "${Q}"`)}}}if(!I.length&&w.waitMs){await ot(w.waitMs);F.push(`waited ${w.waitMs}ms`)}if(!I.length&&w.waitFor){const C=await h(E=>E.some(B=>at(B,w.waitFor)),T);if(C.ok)F.push(`"${w.waitFor}" appeared (${C.ms}ms)`);else I.push(`"${w.waitFor}" never appeared within ${T}ms`)}if(!I.length&&w.waitGone){const C=await h(E=>!E.some(B=>at(B,w.waitGone)),T);if(C.ok)F.push(`"${w.waitGone}" gone (${C.ms}ms)`);else I.push(`"${w.waitGone}" was still there after ${T}ms`)}if(!I.length&&w.expect){const C=await h(E=>E.some(B=>at(B,w.expect)),w.timeoutMs??xr);if(C.ok)F.push(`"${w.expect}" is on screen`);else I.push(`expected "${w.expect}" on screen \u2014 not found`)}if(!I.length&&w.expectGone){const C=await h(E=>!E.some(B=>at(B,w.expectGone)),w.timeoutMs??xr);if(C.ok)F.push(`"${w.expectGone}" is gone`);else I.push(`expected "${w.expectGone}" to be gone \u2014 still on screen`)}}catch(C){I.push(qt(C))}if(I.length){k.push(`${_} \u2717 ${Tr(w)} \u2014 ${I.join("; ")}`);b=b??v;if(!t.continueOnFailure)break}else{g++;k.push(`${_} \u2713 ${F.join(", ")||Tr(w)}`)}}const y=((Date.now()-r)/1e3).toFixed(1);const p=b===null?`**Flow: ${g}/${t.steps.length} steps OK (${y}s)**`:`**Flow FAILED at step ${b+1} \u2014 ${g}/${t.steps.length} steps OK (${y}s)**`;const m=[p,k.join("\n")];if(o!=="none"){try{const v=await a();const w=v.filter(_=>_.interactive).slice(0,30);m.push(`**Screen now (${w.length} interactive of ${v.length}):**
|
|
211
|
-
${w.map(ui).join("\n")}`)}catch(v){m.push(`**Screen now:** unavailable \u2014 ${Mr(qt(v))}`)}}if(o==="all"){if(d.has("network")){const{payload:v}=await n.getSnapshot("network",s).catch(()=>({payload:null}));const w=Array.isArray(v)?v:v?.events??[];const _=w.filter(T=>!l.has(T.id)).slice(-15);if(_.length){m.push(`**Network during this flow (${_.length}):**
|
|
212
|
-
`+_.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(d.has("console")){const{payload:v}=await n.getSnapshot("console",s).catch(()=>({payload:null}));const w=v?.entries??[];const _=w.filter(T=>!u.has(T.id)&&(T.level==="error"||T.level==="warning")).slice(-10);if(_.length){m.push(`**Console during this flow (${_.length}):**
|
|
213
|
-
`+_.map(T=>`[${T.level==="error"?"ERR":"warn"}] ${Mr(pi(T.message??""),220)}`).join("\n"))}}}return oi(m.join("\n\n"))}catch(s){return ai(qt(s))}})}function Ar(e){return/\s/.test(e)?{query:e}:{testID:e,query:e}}function Tr(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}"`;return"step"}var Mr=(e,n=160)=>e.length>n?`${e.slice(0,n)}\u2026`:e;var pi=(e,n=3)=>e.split("\n").map(t=>t.trim()).filter(Boolean).slice(0,n).join(" \u23CE ");import{z as Y}from"zod";var je="highlight-updates";var mi=e=>({content:[{type:"text",text:e}]});var qe=e=>({isError:true,content:[{type:"text",text:e}]});var fi=e=>e instanceof Error?e.message:String(e);var it=e=>new Promise(n=>setTimeout(n,e));var Ir=3e3;var Dr=400;var Rr=12;var Or=new Map;var gi=Y.object({tap:Y.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),type:Y.string().optional().describe("Text to type (needs `into`)."),into:Y.string().optional().describe("Target text input for `type`: testID or fuzzy text."),waitMs:Y.number().min(0).max(1e4).optional().describe("Pause after the action, in ms."),repeat:Y.number().min(1).max(20).optional().describe("Do this step N times (default 1). Useful for 'tap it five times'.")}).describe("One interaction to measure. Keep it to the thing you're asking about.");function Cr(e){return/\s/.test(e)?{query:e}:{testID:e,query:e}}function Fr(e){if(!e)return"unknown";let n="unknown";let t=-1;for(const[r,s]of Object.entries(e)){if((s??0)>t){t=s??0;n=r}}return n}var Er={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 vi(e,n){const t=e.summary;const r=t.wastedRenders??0;const s=t.totalRenders>0?Math.round(r/t.totalRenders*100):0;const o=[];const a=t.totalRenderMs??0;o.push(`**${t.totalRenders} component renders across ${t.totalCommits} commits in ${(e.windowMs/1e3).toFixed(1)}s**`+(a>0?` \xB7 ${a.toFixed(1)}ms of render work`:"")+` \xB7 ${r} wasted (${s}%)`);const i=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(i)o.push(`causes: ${i}`);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} | ${Fr(d.causes)} | ${d.parentName??"\u2014"} | ${(d.changedProps??[]).join(", ")||"\u2014"} |`)}if(t.topComponents.length>n){o.push(`_\u2026+${t.topComponents.length-n} more components_`)}const u=new Set(c.map(d=>Fr(d.causes)));const l=[...u].filter(d=>Er[d]).map(d=>`\`${d}\` = ${Er[d]}`);if(l.length){o.push("");o.push(l.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 wi(e,n){const t=(l,d)=>{const h=d-l;return`${l} \u2192 ${d} (${h>0?"+":""}${h})`};const r=e.summary;const s=n.summary;const o=[`**vs "${e.label}"**`];o.push(`- total renders: ${t(r.totalRenders,s.totalRenders)}`);o.push(`- wasted: ${t(r.wastedRenders??0,s.wastedRenders??0)}`);const a=new Map(r.topComponents.map(l=>[l.name,l.renders]));const i=[];for(const l of s.topComponents.slice(0,20)){const d=a.get(l.name)??0;if(d!==l.renders)i.push(`${l.name} ${t(d,l.renders)}`);a.delete(l.name)}for(const[l,d]of a){if(d>0)i.push(`${l} ${t(d,0)}`)}if(i.length)o.push(`- per component: ${i.slice(0,10).join(" \xB7 ")}`);const c=s.totalRenders<r.totalRenders;const u=s.totalRenders>r.totalRenders;o.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 o.join("\n")}function bi(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:Y.array(gi).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:Y.number().min(500).max(2e4).optional().describe(`Idle sample length when no steps are given. Default ${Ir}.`),label:Y.string().optional().describe('Name this measurement, e.g. "before fix". Shown in the next comparison.'),compareToPrevious:Y.boolean().optional().describe("Compare with the previous measurement on this device. Use equivalent steps and conditions; review warnings and behavior separately."),top:Y.number().min(1).max(40).optional().describe(`Components to list. Default ${Rr}.`),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=n.connectedDevices().find(y=>y.deviceId===r);const o=(s?.tools??[]).find(y=>y.toolId===je);if(!o){return qe("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 qe("This app's @buoy-gg/highlight-updates is too old to measure renders (needs the version with beginMeasurement). Upgrade it, then try again. Meanwhile run_benchmark_batch with captureRenders can still give counts if you have a test route.")}const a=await n.callAction(je,"beginMeasurement",{},r);if(a&&a.ok===false){return qe(`Can't measure renders: ${a.reason??"capture unavailable"}`)}await it(Dr);const i=Date.now();const c=[];if(t.steps?.length){for(const y of t.steps){const p=y.repeat??1;for(let m=0;m<p;m++){if(y.type!==void 0){const v=y.into??y.tap;if(!v){c.push("a `type` step needs `into`");continue}const w=await n.callAction(je,"tapElement",{...Cr(v),text:y.type},r);if(!w?.tapped)c.push(w?.reason??`could not type into "${v}"`);else if(w.matched?.via&&w.matched.via!=="onChangeText"){c.push(`"${v}" is not a text input \u2014 it ran ${w.matched.via}, nothing was typed`)}}else if(y.tap){const v=await n.callAction(je,"tapElement",Cr(y.tap),r);if(!v?.tapped)c.push(v?.reason??`no element matched "${y.tap}"`)}if(y.waitMs)await it(y.waitMs)}}await it(Dr)}else{await it(t.idleMs??Ir)}const u=Date.now()-i;const l=await n.callAction(je,"endMeasurement",{},r);const d=l?.summary;if(!d){return qe("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 k=Or.get(r);Or.set(r,h);const b=t.steps?.length?t.steps.map(y=>(y.type!==void 0?`type "${y.type}"`:`tap "${y.tap}"`)+(y.repeat?` \xD7${y.repeat}`:"")).join(", "):`idle ${(u/1e3).toFixed(1)}s`;const g=[`**measure_renders \u2014 ${b}**`,"",vi(h,t.top??Rr)];if(t.compareToPrevious){g.push("",k?wi(k,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 mi(g.join("\n"))}catch(r){return qe(fi(r))}})}import yi from"fs";import Br from"path";var $i=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".json"]);var ki=new Set(["node_modules",".git",".expo","ios","android","dist","lib","build",".next","coverage","__snapshots__"]);var _i=400;function Si(e){const n=(e??"").trim().toLowerCase();if(n==="always"||n==="never"||n==="auto")return n;return"auto"}var xi=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=yi.watch(e,{recursive:true},(t,r)=>{if(!r)return;const s=String(r);if(s.split(Br.sep).some(o=>ki.has(o)))return;if(!$i.has(Br.extname(s)))return;this.noteEdit(s)});this.watcher.on("error",()=>this.stop())}catch{this.stop()}}noteEdit(e){const n=Date.now();if(n-this.lastEditAt>_i)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`
|
|
214
|
-
|
|
215
|
-
---
|
|
216
|
-
\u26A0\uFE0F **${e.length} source file${e.length===1?"":"s"} changed since anything was last checked on the device** (${n}${t}).
|
|
217
|
-
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.`}};var Lt=new xi;var Ai=`Buoy MCP connects your editor to supported Buoy tools through the configured broker.
|
|
218
|
-
|
|
219
|
-
Start with account and connection setup. Use \`list_devices\` to select an app and inspect
|
|
220
|
-
its available tools. App data and action tools require Buoy Pro. If access fails, explain
|
|
221
|
-
the reported requirement and setup steps. Camera tools use a separate local setup and
|
|
222
|
-
account gate; \`camera_diagnose\` can report setup problems without an app connection.
|
|
223
|
-
|
|
224
|
-
For a runtime bug, \`get_triage\` summarizes available console errors, network activity,
|
|
225
|
-
storage and screen information. Follow up on the relevant section and read source when
|
|
226
|
-
needed. Missing data can reflect missing integration, retention limits or a disconnected
|
|
227
|
-
app. An unresponsive app is not proof of a crash, and post-crash evidence may be unavailable.
|
|
228
|
-
|
|
229
|
-
Choose follow-up tools by the symptom:
|
|
230
|
-
- Persisted values: \`get_storage\` with \`includeValues:true\` for configured storage sources.
|
|
231
|
-
- Requests or API responses: \`get_network_requests\` with \`includeBodies:true\` for captured
|
|
232
|
-
bodies. Capture depends on supported transports, installed hooks and recording timing.
|
|
233
|
-
- Errors: \`get_console\` for retained captured output. A stopped app cannot provide new data.
|
|
234
|
-
- Cache or store state: \`get_react_query\`, \`get_zustand_state\`, \`get_redux_state\` or
|
|
235
|
-
\`get_jotai_state\` for the integrations registered in the app.
|
|
236
|
-
|
|
237
|
-
Use \`get_events\` with \`sources\` to read retained activity from connected event sources.
|
|
238
|
-
It returns compact summaries by default; request \`includeData:true\` when details are needed.
|
|
239
|
-
For request IDs and network actions, use \`get_network_requests\`. Its \`flagged:'any'\` filter
|
|
240
|
-
finds pinned or saved requests. A flag is a reason to inspect a request, not proof of its
|
|
241
|
-
cause or who flagged it. Use \`network_action\` to retain relevant evidence within task scope.
|
|
242
|
-
|
|
243
|
-
For supported UI interactions, \`run_flow\` runs steps such as tap, type, set, reload,
|
|
244
|
-
waitFor and expect. Review step results, failures and available captured output. Use
|
|
245
|
-
\`describe_screen\` to discover exposed elements and \`tap_element\` for individual actions.
|
|
246
|
-
A completed tool call alone does not establish that the user's expected behavior occurred.
|
|
247
|
-
|
|
248
|
-
For render-heavy interactions, use \`measure_renders\` with representative \`steps\`.
|
|
249
|
-
Repeat the same steps after a change with \`compareToPrevious:true\`. Interpret available
|
|
250
|
-
render counts, reasons and wasted-render diagnostics alongside behavior and performance;
|
|
251
|
-
these diagnostics do not prove that a render was unnecessary. For instrumented JavaScript
|
|
252
|
-
tasks, use \`get_js_thread_top\` and \`get_js_thread_origin_detail\`. Their coverage depends
|
|
253
|
-
on the installed hooks. Keep measurement conditions comparable.
|
|
254
|
-
|
|
255
|
-
\`get_images\` inspects instrumented image loads and available cache, timing, size and error
|
|
256
|
-
data. Use \`image_action\` for supported per-image actions and \`set_image_simulation\` for
|
|
257
|
-
integrated image behavior. Simulation does not disconnect the device's network.
|
|
258
|
-
\`get_assets\` inspects the configured manifest, runtime registry and available bundle graph.
|
|
259
|
-
Reported load history and size estimates do not prove complete shipped-asset coverage or
|
|
260
|
-
that an unobserved asset is unused. \`asset_action\` can refresh data and manage baselines.
|
|
261
|
-
|
|
262
|
-
\`reload_app\` requests a JS reload using supported app mechanisms and can wait for
|
|
263
|
-
reconnection. It can try a dev-server fallback for an unresponsive app when that server
|
|
264
|
-
is known and reachable. Recovery is not guaranteed. Reload can discard in-memory evidence;
|
|
265
|
-
collect needed observations first when possible and read state again after reconnecting.
|
|
266
|
-
|
|
267
|
-
\`get_time_machine\` lists snapshots and provider capabilities. \`time_machine_action\`
|
|
268
|
-
captures or restores supported registered state sources. Preview the affected state before
|
|
269
|
-
restoring. Live restore changes supported state in place; reload mode restores supported
|
|
270
|
-
persisted sources and requests a reload. A baseline clears providers that support clearing
|
|
271
|
-
and requests a reload. This does not reset backend state or reproduce a complete reinstall.
|
|
272
|
-
Check per-source applied/skipped outcomes and any reload or route-restoration failures.
|
|
273
|
-
|
|
274
|
-
\`get_clock\` reads the app's clock and whether the Clock tool overrides it. \`clock_action\`
|
|
275
|
-
moves it (set_time, shift), stops it (freeze), speeds it up (set_rate) or resets it.
|
|
276
|
-
Only the app's JS clock changes; the backend, native timers and time zone stay real. Check
|
|
277
|
-
\`get_clock\` before calling a date or expiry wrong, and reset when finished.
|
|
278
|
-
\`get_clock\` also lists the app's sign-in tokens and how long each has left. To test token
|
|
279
|
-
refresh, use \`clock_action\` jump_to_token_expiry (the app refreshes before expiry) or
|
|
280
|
-
fail_next_request (the app refreshes after a 401), have the app send a request, then read
|
|
281
|
-
\`get_clock\` for the refresh check's result.
|
|
282
|
-
|
|
283
|
-
\`get_permissions\` lists the permissions the app can reach, what the OS says, any override and
|
|
284
|
-
the recent permission calls. \`permission_action\` set makes a permission read as not asked,
|
|
285
|
-
granted, limited, denied, blocked or restricted without touching the OS; the real prompt never
|
|
286
|
-
shows while overridden, and reset clears every override. Native code that checks the OS itself
|
|
287
|
-
still sees the real state: \`system_permission\` changes it on an iOS Simulator (simctl) or an
|
|
288
|
-
adb device. Reset overrides when finished.
|
|
289
|
-
|
|
290
|
-
\`lifecycle_action\` puts the app through lifecycle events: background and return, an
|
|
291
|
-
interruption, a memory warning, a deep link, Android back, a color scheme or battery
|
|
292
|
-
change, or a relaunch. These are simulated inside the app and reach its JS listeners only.
|
|
293
|
-
On an iOS simulator, \`real: true\` causes the real OS event instead. \`get_lifecycle\`
|
|
294
|
-
reports what the app did afterwards and whether a relaunch reopened the same screen.
|
|
295
|
-
|
|
296
|
-
\`get_location\` reads where the app thinks it is and whether the Location tool overrides it,
|
|
297
|
-
with its live watches and geofence regions. \`location_action\` pins a place, plays a route,
|
|
298
|
-
crosses a geofence, or turns the GPS signal or location services off. It changes what the
|
|
299
|
-
app's JS location calls return; \`sim_location\` moves the iOS Simulator itself, for native
|
|
300
|
-
map dots and native geofencing. Reset when finished.
|
|
301
|
-
|
|
302
|
-
For iOS Simulator camera input, inspect setup with \`camera_diagnose\`. Use \`camera_source\`
|
|
303
|
-
for supported barcode, file or screen input, \`camera_devices\` for simulators/apps and
|
|
304
|
-
\`camera_inputs\` for local sources. \`camera_launch\` attaches input when launching the app;
|
|
305
|
-
\`camera_zero_setup\` configures attachment for another launcher. \`camera_status\` reports
|
|
306
|
-
available source/decoder status, which does not establish the app's scanner result.
|
|
307
|
-
Use \`camera_stop\` when finished. These tools operate locally without an in-app Buoy
|
|
308
|
-
integration, but require their supported host, simulator and account setup.
|
|
309
|
-
|
|
310
|
-
\`screenshot_component\` locates a supported component by testID/name and attempts a crop.
|
|
311
|
-
It requires the MCP server on the same Mac as the booted iOS Simulator and the component
|
|
312
|
-
inspection setup. Inspect the result before using it as visual evidence.
|
|
313
|
-
|
|
314
|
-
For other supported operations, use \`list_tool_actions\`, \`get_snapshot\` or \`call_action\`.
|
|
315
|
-
Snapshots describe available current state and can be large; request only needed data.
|
|
316
|
-
|
|
317
|
-
After a behavior change, repeat the affected interaction and check the expected result.
|
|
318
|
-
Include restart or persistence checks when relevant to the change. Use appropriate static
|
|
319
|
-
checks for documentation-only work. Report actual checks, observations and remaining limits.
|
|
320
|
-
BUOY_VERIFY reminders track selected edits and tool calls; clearing a reminder is not a
|
|
321
|
-
test result. Stay within the user's authorized task and preserve existing project work.`;var Ti=new Set(["measure_renders","scenario_action","run_flow","run_benchmark_batch","get_triage","tap_element","describe_screen","get_console","get_network_requests","get_events","get_snapshot"]);function Mi(e){const n=new Fo({name:"buoy",version:fe},{capabilities:{tools:{}},instructions:Ai});Lt.start(process.cwd(),Si(process.env.BUOY_VERIFY));const t=n.registerTool.bind(n);n.registerTool=((r,s,o)=>t(r,s,(async(...a)=>{const i=await o(...a);const c=i?.isError===true;if(Ti.has(r)&&!c){Lt.markVerified();return i}const u=Lt.nudge();if(!u)return i;const l=i;if(Array.isArray(l?.content)){return{...l,content:[...l.content,{type:"text",text:u}]}}return i})));si(n,e);hi(n,e);bi(n,e);dn(n,e);yn(n,e);$n(n,e);Uo(n,e);kn(n,e);_n(n,e);Sn(n,e);Tn(n,e);Mn(n,e);Rn(n,e);Cn(n,e);Jo(n,e);Go(n,e);Ko(n,e);na(n,e);ca(n,e);pa(n,e);ga(n,e);jn(n,e);va(n);$a(n,e);Sa(n,e);Ia(n,e);Ca(n,e);Pa(n,e);Va(n,e);return n}var Vc={deviceId:Eo.string().optional().describe('Target device id (from list_devices). Omit to auto-select when exactly one device is connected. Use "All" to broadcast.')};import{spawnSync as Ut}from"child_process";import L from"fs";import Ii from"os";import U from"path";function zt(){return{BUOY_VERIFY:"auto"}}var Pr="https://registry.npmjs.org";var Wt=3e3;function Di(e={}){const n=e.cwd??process.cwd();const t=e.skillSrcDir??U.resolve(__dirname,"../skill");const r=e.log??(a=>process.stdout.write(a+"\n"));const s=Ri(e,r);const o=[];Gt(U.join(n,".mcp.json"),"mcpServers",s,n,o);L.mkdirSync(U.join(n,".cursor"),{recursive:true});Gt(U.join(n,".cursor","mcp.json"),"mcpServers",s,n,o);if(L.existsSync(U.join(n,".vscode"))){Gt(U.join(n,".vscode","mcp.json"),"servers",s,n,o)}ji(t,n,o);Nr(U.join(n,"CLAUDE.md"),n,o);Nr(U.join(n,"AGENTS.md"),n,o);r("Buoy MCP configuration written:");for(const a of o)r(" \u2022 "+a);r("");r("Next steps:");r(" 1. Restart your editor (or reconnect the MCP server) to load `buoy`.");r(" 2. Complete account setup, then open an app with the required Buoy tools and sync integration.");r(" 3. Confirm the device and tools are available. MCP data/action access requires Pro.");if(s.command==="npx"){r("");r(`The editor launches the server with \`npx -y ${le}@latest\`, so it stays`);r(`Registry access may be needed. Re-run \`npx -y ${le}@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 ${s.args[0]?.replace(/dist[/\\]cli\.js$/,"")??""}@latest init --local`)}}function Ri(e,n){if(e.cliPath){return{type:"stdio",command:"node",args:[e.cliPath],env:zt()}}const t=e.mode??"auto";if(t==="npx"){return Jt()}if(t==="local"){return jr(e,n)}const r=Ci();if(r.reachable){return Jt()}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 jr(e,n)}function Jt(){return{type:"stdio",command:"npx",args:["-y",`${le}@latest`],env:zt()}}function jr(e,n){const t=e.installDir??process.env.BUOY_MCP_HOME??U.join(Ii.homedir(),".buoy-mcp");const r=e.registry??Pr;const s=Oi(t,r,n);if(s){return{type:"stdio",command:"node",args:[s],env:zt()}}n("\u26A0 local install failed \u2014 writing the npx entry instead (see the error above).");return Jt()}function Oi(e,n,t){const r=`${le}@${fe==="0.0.0-dev"?"latest":fe}`;L.mkdirSync(e,{recursive:true});const s=process.platform==="win32"?"npm.cmd":"npm";t(`Installing ${r} into ${e} from ${n} \u2026`);const o=Ut(s,["install",r,"--prefix",e,"--registry",n,`--@buoy-gg:registry=${n}`,"--no-audit","--no-fund","--loglevel=error"],{stdio:["ignore","ignore","inherit"],encoding:"utf8"});if(o.status!==0){t(`\u26A0 npm install exited with code ${o.status??"?"}${o.error?` (${o.error.message})`:""}.`);return null}const a=U.join(e,"node_modules",le,"dist","cli.js");if(!L.existsSync(a)){t(`\u26A0 install finished but ${a} is missing.`);return null}return a}function Ci(){const e=Fi();if(!e)return{reachable:false,registry:null};if(/^https?:\/\/registry\.npmjs\.org\/?$/i.test(e)){return{reachable:true,registry:e}}return{reachable:Ei(e),registry:e}}function Fi(){const e=qr("@buoy-gg:registry");if(e)return e;const n=qr("registry");return n??Pr}function qr(e){const n=process.platform==="win32"?"npm.cmd":"npm";const t=Ut(n,["config","get",e],{encoding:"utf8",timeout:Wt});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 Ei(e){const n=Ut(process.execPath,["-e",Bi,e,String(Wt)],{encoding:"utf8",timeout:Wt+2e3});return n.status===0}var Bi=`
|
|
322
|
-
const url = process.argv[1];
|
|
323
|
-
const ms = Number(process.argv[2]) || 3000;
|
|
324
|
-
const c = new AbortController();
|
|
325
|
-
const t = setTimeout(() => c.abort(), ms);
|
|
326
|
-
fetch(url, { method: 'HEAD', signal: c.signal })
|
|
327
|
-
.then(() => { clearTimeout(t); process.exit(0); })
|
|
328
|
-
.catch(() => {
|
|
329
|
-
// A HEAD may be rejected while the host is up; a bare TCP-level failure is
|
|
330
|
-
// what we care about. fetch throwing a TypeError = network unreachable.
|
|
331
|
-
clearTimeout(t);
|
|
332
|
-
process.exit(1);
|
|
333
|
-
});
|
|
334
|
-
`;function Gt(e,n,t,r,s){let o={};if(L.existsSync(e)){try{o=JSON.parse(L.readFileSync(e,"utf8"))}catch{L.copyFileSync(e,e+".bak");s.push(`existing ${pe(e,r)} was invalid JSON \u2014 backed up to ${pe(e,r)}.bak`);o={}}}else{L.mkdirSync(U.dirname(e),{recursive:true})}const a=o[n]&&typeof o[n]==="object"?o[n]:{};const i="buoy"in a;a.buoy=t;o[n]=a;L.writeFileSync(e,JSON.stringify(o,null,2)+"\n");s.push(`${i?"updated":"added"} \`buoy\` in ${pe(e,r)}`)}var ct="# Debugging with Buoy";var Pi=`${ct}
|
|
335
|
-
|
|
336
|
-
Use Buoy to inspect a connected app when runtime evidence helps the task.
|
|
337
|
-
Complete account, tool integration and connection setup first. MCP data and
|
|
338
|
-
action access requires Pro. Follow the user's scope and repository instructions.
|
|
339
|
-
|
|
340
|
-
- \`get_triage\`: summarize available device and tool observations, then choose
|
|
341
|
-
a relevant tool. Missing data is not proof that no problem occurred.
|
|
342
|
-
- \`run_flow\`: run supported tap, type, wait and assertion steps to reproduce
|
|
343
|
-
a failure or check a change. Review the flow before running it.
|
|
344
|
-
- \`get_events\`: inspect retained events from connected tools.
|
|
345
|
-
- \`get_network_requests\`: inspect captured requests and responses. Capture
|
|
346
|
-
depends on installed hooks, transport and when recording began.
|
|
347
|
-
- \`network_conditions\`: take the app offline or add latency to check error
|
|
348
|
-
and retry paths. Development builds only. Restore \`normal\` when finished.
|
|
349
|
-
- \`get_console\`: inspect retained console and error output. A terminated or
|
|
350
|
-
disconnected app may not provide new data.
|
|
351
|
-
- \`get_storage\`: inspect registered storage backends and available keys.
|
|
352
|
-
- \`reload_app\`: reload where supported. Confirm the device remains connected;
|
|
353
|
-
a reload does not guarantee recovery from a crash.
|
|
354
|
-
- \`get_snapshot\`: inspect the available state of a specific tool.
|
|
355
|
-
|
|
356
|
-
After a behavior change, repeat the failing interaction when the environment
|
|
357
|
-
allows it. Use relevant tests and report what was actually checked. For a
|
|
358
|
-
performance change, compare \`measure_renders\` runs with the same steps and
|
|
359
|
-
\`compareToPrevious: true\`; inspect the measurements and their limitations.
|
|
360
|
-
Use \`run_flow\` for supported UI checks. Do not claim a fix was verified when
|
|
361
|
-
only source review or a build was performed.
|
|
362
|
-
|
|
363
|
-
\`BUOY_VERIFY\` controls verification reminders: \`auto\` uses edit-based
|
|
364
|
-
reminders, \`always\` repeats until checked, and \`never\` disables them.
|
|
365
|
-
A reminder is not a test result. Choose checks appropriate to the change;
|
|
366
|
-
prose-only edits do not require running device actions.
|
|
367
|
-
`;function Nr(e,n,t){let r="";if(L.existsSync(e)){try{r=L.readFileSync(e,"utf8")}catch{t.push(`\u26A0 could not read ${pe(e,n)} \u2014 skipped the debugging guide`);return}if(r.includes(ct)){t.push(`${pe(e,n)} already has the "${ct}" block; preserved existing text. Review it against the current bundled guidance before relying on older instructions.`);return}}const s=r===""?"":r.endsWith("\n")?"\n":"\n\n";try{L.writeFileSync(e,r+s+Pi);t.push(`${r?"appended":"created"} "${ct}" block in ${pe(e,n)}`)}catch{t.push(`\u26A0 could not write ${pe(e,n)} \u2014 skipped the debugging guide`)}}function ji(e,n,t){if(!L.existsSync(e)){t.push("\u26A0 no bundled skills found \u2014 skipped");return}const r=L.readdirSync(e,{withFileTypes:true}).filter(s=>s.isDirectory()&&L.existsSync(U.join(e,s.name,"SKILL.md")));if(r.length===0){t.push("\u26A0 no skills with a SKILL.md found \u2014 skipped");return}for(const s of r){const o=U.join(e,s.name);const a=U.join(n,".claude","skills",s.name);Lr(o,a);t.push(`installed the ${s.name} skill \u2192 ${pe(U.join(a,"SKILL.md"),n)}`)}}function Lr(e,n){L.mkdirSync(n,{recursive:true});for(const t of L.readdirSync(e,{withFileTypes:true})){const r=U.join(e,t.name);const s=U.join(n,t.name);if(t.isDirectory())Lr(r,s);else L.copyFileSync(r,s)}}function pe(e,n){const t=U.relative(n,e);return t&&!t.startsWith("..")?t:e}export{dt as BROKER_PORT,Ht as BROKER_URL,Yt as DEFAULT_ACTION_TIMEOUT_MS,Xt as DEFAULT_SNAPSHOT_TIMEOUT_MS,ht as DASHBOARD_NAME,Z as ALL_DEVICES,Fs as SyncClient,fe as VERSION,le as PACKAGE_NAME,un as getUpdateNotice,dn as registerGenericTools,Le as buildAutomationConfig,gt as estimateBatchMs,Ue as rankBatchFromIndex,ze as formatRankingMarkdown,vt as compareReportStats,yn as registerPerfMonitorTools,$n as registerEventsTools,kn as registerReactQueryTools,_n as registerZustandTools,Sn as registerJotaiTools,Tn as registerReduxTools,Mn as registerStorageTools,Rn as registerRoutesTools,Cn as registerConsoleTools,jn as registerScreenshotTools,Mi as createMcpServer,Di as runInit};
|