@buoy-gg/mcp 7.0.47 → 7.0.49

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