@buoy-gg/mcp 7.0.43 → 7.0.45
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-GFFMF22U.mjs +364 -0
- package/dist/cli.js +132 -103
- package/dist/cli.mjs +1 -1
- package/dist/index.d.mts +12 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +140 -111
- package/dist/index.mjs +1 -1
- package/package.json +6 -3
- package/dist/chunk-FLZAEJH4.mjs +0 -335
package/dist/chunk-FLZAEJH4.mjs
DELETED
|
@@ -1,335 +0,0 @@
|
|
|
1
|
-
import{DEFAULT_BROKER_PORT as gr}from"@buoy-gg/sync-broker";var Ze=gr;var Dt=`http://localhost:${Ze}`;var Mt=15e3;var vr=2500;var wr=1200;var Rt=2e4;var br=3e4;var Ot=5e3;var yr=15*6e4;var Xe="Dashboard";var J="All";import{readFileSync as Ct,writeFileSync as $r,mkdirSync as kr,renameSync as _r,unlinkSync as Sr}from"fs";import{dirname as xr,join as Ft,resolve as Ar}from"path";import{homedir as Tr}from"os";import{createHash as Ir}from"crypto";import{validateLicense as Dr,isAcceptedValidation as Mr,isTransientLicenseError as Rr,resolveTier as Or,isRecognizedAccount as Cr,isBuoyToken as Fr,verifyFreeToken as Er,resolveAccountAccess as Br,signCache as Et,verifyCacheSignature as qr,LICENSE_LAUNCH_VALIDATION_TTL as Bt,LICENSE_REVALIDATION_INTERVAL as De,LICENSE_TRANSIENT_RETRY_DELAYS as jr,KEYGEN_CONFIG as Pr}from"@buoy-gg/license/headless";var qt=["BUOY_LICENSE_KEY","BUOY_KEY","EXPO_PUBLIC_BUOY_KEY","VITE_BUOY_KEY","REACT_APP_BUOY_KEY"];function jt(e,n=process.env){for(const t of qt)if(n[t]!==void 0)return n[t].trim().toUpperCase()||null;for(const t of[".env.development.local",".env.local",".env"]){let r;try{r=Ct(Ft(e,t),"utf8")}catch{continue}const s=new Map;for(const o of r.split(/\r?\n/)){const a=o.match(/^\s*(?:export\s+)?([A-Z_][A-Z_0-9]*)\s*=\s*(.*)$/);if(!a)continue;const i=a[2].trim();const c=i.match(/^(['"])(.*?)\1\s*(?:#.*)?$/);s.set(a[1],c?c[2]:i.split("#")[0].trim())}for(const o of qt)if(s.has(o))return s.get(o).trim().toUpperCase()||null}return null}var Nr=class{constructor(e,n={}){this.changed=e;this.key=null;this.cache=null;this.timer=null;this.generation=0;this.busy=false;this.nextCheck=0;this.retry=0;this.lastAdmission=false;this.hasAccess=()=>Br({initialized:true,validating:false,key:this.key,tierSource:this.cache?.tier?"key":"none",verifiedAt:this.cache?.cachedAt??null}).status==="admitted";this.projectDir=Ar(n.projectDir??process.env.BUOY_PROJECT_DIR??process.cwd());const t=Ir("sha256").update(this.projectDir).digest("hex").slice(0,20);this.cacheFile=n.cacheFile??Ft(Tr(),".buoy",`account-${t}.json`)}start(){if(this.timer)return;try{const e=JSON.parse(Ct(this.cacheFile,"utf8"));if(e.valid&&qr(e))this.cache=e}catch{}void this.tick();this.timer=setInterval(()=>{void this.tick()},1e3);this.timer.unref()}stop(){++this.generation;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(){const e=jt(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.hasAccess()&&Date.now()-this.cache.lastValidatedAt<Bt&&this.nextCheck===0){this.nextCheck=this.cache.lastValidatedAt+Bt;return}this.busy=true;const n=this.generation;try{if(Fr(e)){const i=Er(e);if(!i){this.cache=null;this.removeCache()}else{const c=Date.now();this.cache=Et({licenseKey:e,licenseId:`token:${i.accountHash}`,valid:true,tier:"free",isPro:false,expiresAt:null,cachedAt:c,lastValidatedAt:c});this.persistCache()}this.nextCheck=Date.now()+De;return}const t=await Dr(e);if(n!==this.generation||jt(this.projectDir)!==e)return;const r=t.data?.relationships?.product?.data?.id;const s=t.meta.code==="EXPIRED"&&(Cr(t.data)||this.cache?.licenseKey===e);if(r&&r!==Pr.productId||!s&&!Mr(t)){this.cache=null;this.removeCache();this.nextCheck=Date.now()+De;return}const o=s?"free":Or(t.data);const a=Date.now();this.cache=Et({licenseKey:e,licenseId:t.data?.id??"",valid:true,tier:o,isPro:o==="pro",expiresAt:s?null:t.data.attributes.expiry,cachedAt:a,lastValidatedAt:a});this.persistCache();this.retry=0;this.nextCheck=a+De}catch(t){if(n!==this.generation)return;const r=Rr(t)?jr[this.retry++]:void 0;this.nextCheck=Date.now()+(r??De)}finally{this.busy=false;this.notify()}}persistCache(){try{kr(xr(this.cacheFile),{recursive:true,mode:448});$r(`${this.cacheFile}.tmp`,JSON.stringify(this.cache),{mode:384});_r(`${this.cacheFile}.tmp`,this.cacheFile)}catch{}}removeCache(){try{Sr(this.cacheFile)}catch{}}};import Lr from"http";import{randomUUID as Ur}from"crypto";import{io as zr}from"socket.io-client";import{createBroker as Jr}from"@buoy-gg/sync-broker";function Wr(e,n){return e==="app"&&(n==="ping"||n==="reloadApp")}function Pt(e){return e>=2}function Vr(e){if(Wr(e.toolId,e.action)){return{timeoutMs:e.fullMs,usedFullBudget:false}}if(!Pt(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 Kr(e){if(e.consecutiveTimeouts>=2)return true;if(e.lastOkAt>0&&e.now-e.lastOkAt>e.unresponsiveAfterMs){return true}return false}var Hr=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.port=e.port??Ze;this.url=e.url??(e.port?`http://localhost:${e.port}`:Dt);this.actionTimeoutMs=e.actionTimeoutMs??Mt;this.log=e.log??(n=>process.stderr.write(`[buoy-mcp] ${n}
|
|
2
|
-
`));this.autoSpawn=e.autoSpawnBroker??true}async start(){const e=await Nt(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 Nr(()=>this.broker?.refreshAccess());this.hostAccount.start();this.broker=Jr({canUseDesktop:this.hostAccount.hasAccess,port:this.port,onError:t=>this.log(`broker error: ${t.code??t.message}`)});await Gr(this.url);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=zr(this.url,{transports:["websocket"],query:{deviceName:Xe},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 i=!!a&&typeof a==="object"&&a.protocol===1&&a.ready===true;this.setAdmission(i);if(i){clearTimeout(o);this.rearmWatches();s()}});t.on("connect",()=>{t.emit("buoy:access:request")});t.on("disconnect",()=>this.setAdmission(false,true));t.once("connect_error",a=>{if(r)return;r=true;clearTimeout(o);n(new Error(`failed to connect to broker at ${this.url}: ${a.message}`))});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 i=false;for(const d of a){if(d.deviceId&&d.tier==="locked")this.lockDevice(String(d.deviceId));else if(d.deviceId&&(d.tier==="free"||d.tier==="pro")){i=this.lockedDevices.delete(String(d.deviceId))||i}}this.devices=a;const c=Date.now();for(const d of a)if(d.deviceId)this.lastSeen.set(d.deviceId,c);this.pruneStaleDevices();if(i)this.rearmWatches()});t.on("devtool-sync",a=>{if(!this.admitted||this.lockedDevices.has(a.persistentDeviceId))return;const i=ee(a.persistentDeviceId,a.toolId);this.snapshots.set(i,a.payload);this.snapshotAt.set(i,Date.now());const c=this.snapshotWaiters.get(i);if(c&&c.length){this.snapshotWaiters.set(i,[]);for(const d of c)d(a.payload)}});t.on("devtool-action-result",a=>{if(!this.admitted)return;const i=this.pendingActions.get(a.requestId);if(!i)return;this.pendingActions.delete(a.requestId);clearTimeout(i.timer);i.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===J){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()-yr;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!==Xe&&e.deviceId).map(e=>{const n=this.capabilities.get(e.deviceId);return{deviceId:e.deviceId,deviceName:e.deviceName,platform:e.platform,isConnected:e.isConnected!==false,isPro:e.isPro===true,tier:e.tier==="free"||e.tier==="pro"?e.tier:e.tier===void 0&&e.isPro===true?"pro":"locked",collision:e.collision===true,tools:n?.tools??[]}})}connectedDevices(){return this.listDevices().filter(e=>e.isConnected)}toolActions(e){return this.listDevices().map(n=>{const t=n.tools.find(r=>r.toolId===e);return t?{deviceId:n.deviceId,deviceName:n.deviceName,actions:t.actions}:null}).filter(n=>n!==null)}resolveDevice(e){this.requireAdmission();if(e){this.requireDeviceAccount(e);return e}const n=this.connectedDevices();const t=n.filter(o=>!this.lockedDevices.has(o.deviceId));if(t.length===0){if(n.length>0){throw new Error(`Devices are connected (${n.map(o=>o.deviceName).join(", ")}), but the broker has not admitted their accounts. Check app account validation and the account announcement after reconnect; this does not prove the user is signed out.`)}throw new Error("No devices are connected to the broker. Open the app with Buoy devtools running.")}if(t.length===1)return t[0].deviceId;const r=t.filter(o=>o.tools.length>0);if(r.length===1)return r[0].deviceId;if(r.length===0){const o=t.map(a=>a.deviceName).join(", ");throw new Error(`Connected devices (${o}) are not exposing any Buoy tools yet. Make sure the app is in the foreground with devtools mounted, then retry.`)}const s=r.map(o=>`${o.deviceName} (${o.deviceId})`).join(", ");throw new Error(`Multiple devices connected \u2014 specify deviceId. Connected: ${s}`)}requireProDevice(e){this.requireAdmission();const n=o=>{if(!o)return"";return o.tier==="locked"?` The broker has not confirmed account access for "${o.deviceName}"; a locked status does not establish whether a key is configured.`:` The connected app "${o.deviceName}" is on the ${o.tier} tier.`};const t=o=>`Buoy Pro is required to use the MCP.${n(o)} Enter a license in the app, or \u2014 if it runs headless (no on-device UI) \u2014 pass \`licenseKey\` to \`<FloatingDevTools />\`. Run \`list_devices\` to check status.`;if(e===J){if(!this.connectedDevices().some(o=>o.isPro))throw new Error(t());return J}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 Pt(this.healthOf(e).consecutiveTimeouts)}timeoutFor(e,n,t){const r=this.healthOf(e);const{timeoutMs:s,usedFullBudget:o}=Vr({consecutiveTimeouts:r.consecutiveTimeouts,lastFullBudgetAt:r.lastFullBudgetAt,now:Date.now(),fullMs:this.actionTimeoutMs,shortMs:vr,recoveryProbeMs:Rt,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=Kr({consecutiveTimeouts:n.consecutiveTimeouts,lastOkAt:n.lastOkAt,now:Date.now(),unresponsiveAfterMs:br});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(ee(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(ee(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(ee(e,"app"));if(typeof t?.devServerOrigin==="string")return t.devServerOrigin;return null}ensureWatching(e,n){const t=ee(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)}}unwatch(e,n){const t=ee(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(ee(n,e))}async getSnapshot(e,n,t={}){const r=this.resolveDevice(n);const s=ee(r,e);this.ensureWatching(e,r);let o=t.timeoutMs??Ot;if(t.timeoutMs===void 0&&this.isUnresponsive(r)){const d=this.healthOf(r);if(Date.now()-d.lastFullBudgetAt>Rt){d.lastFullBudgetAt=Date.now()}else{o=wr}}const a=this.waitForSnapshot(s,o);this.socket?.emit("request-devtool-state",{toolId:e,targetDeviceId:r});const i=await a;this.requireAdmission();this.requireDeviceAccount(r);if(i!==void 0){if(!t.silent)this.noteOk(r);return{deviceId:r,payload:i}}if(!t.silent)this.noteTimeout(r);const c=this.snapshots.get(s);if(c!==void 0){return{deviceId:r,payload:c,stale:this.staleNote(e,r)}}throw new Error(`Timed out waiting for "${e}" state from ${r} (is the tool active?). ${this.unresponsiveNote(r)}`)}staleNote(e,n){const t=this.snapshotAgeMs(e,n);const r=t==null?"an earlier sync":`${Math.round(t/1e3)}s ago`;return`\u26A0\uFE0F Served from the last sync (${r}) \u2014 ${this.unresponsiveNote(n)}`}waitForSnapshot(e,n){return new Promise(t=>{const r=this.snapshotWaiters.get(e)??[];const s=setTimeout(()=>{const a=(this.snapshotWaiters.get(e)??[]).filter(i=>i!==o);this.snapshotWaiters.set(e,a);t(void 0)},n);const o=a=>{clearTimeout(s);t(a)};r.push(o);this.snapshotWaiters.set(e,r)})}async callAction(e,n,t,r,s={}){this.requireAdmission();const o=r===J?J:this.resolveDevice(r);if(!this.socket)throw new Error("SyncClient is not connected");const a=Ur();const i=s.timeoutMs??this.timeoutFor(o,e,n);const c=await new Promise((d,u)=>{const l=setTimeout(()=>{this.pendingActions.delete(a);if(o!==J&&!s.silent)this.noteTimeout(o);u(new Error(`Action "${e}.${n}" got no answer in ${i}ms. `+(o===J?"No device responded.":this.unresponsiveNote(o))))},i);this.pendingActions.set(a,{resolve:d,reject:u,timer:l,target:o});this.socket.emit("devtool-action",{requestId:a,toolId:e,targetDeviceId:o,action:n,params:t??{}})});if(o!==J&&!s.silent)this.noteOk(o);if(!c.ok){throw new Error(c.error||`Action "${e}.${n}" failed on device`)}return c.result}};var ee=(e,n)=>`${e}::${n}`;function Nt(e,n=800){return new Promise(t=>{const r=Lr.get(e,s=>{s.resume();t((s.statusCode??0)>0)});r.setTimeout(n,()=>{r.destroy();t(false)});r.on("error",()=>t(false))})}async function Gr(e,n=20){for(let t=0;t<n;t++){if(await Nt(e,300))return;await Yr(50)}throw new Error(`Spawned broker never became reachable at ${e}`)}var Yr=e=>new Promise(n=>setTimeout(n,e));var ae="7.0.43"?"7.0.43":"0.0.0-dev";var te="@buoy-gg/mcp";import{promises as Lt}from"fs";import Qr from"os";import Zr from"path";var Xr=24*60*60*1e3;var es=1500;var ts=`https://registry.npmjs.org/${te}/latest`;var Ut=Zr.join(Qr.tmpdir(),"buoy-mcp-update-check.json");function ns(e,n){const t=o=>o.split("-")[0].split(".").map(a=>Number(a)||0);const r=t(e);const s=t(n);for(let o=0;o<3;o++){const a=r[o]??0;const i=s[o]??0;if(a>i)return true;if(a<i)return false}return false}async function rs(){try{const e=await Lt.readFile(Ut,"utf8");const n=JSON.parse(e);if(typeof n.checkedAt==="number"&&typeof n.latest==="string"){return n}}catch{}return null}async function ss(e){const n=new AbortController;const t=setTimeout(()=>n.abort(),es);try{const r=await fetch(ts,{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 Lt.writeFile(Ut,JSON.stringify({checkedAt:e,latest:o})).catch(()=>{})}return o}catch{return null}finally{clearTimeout(t)}}async function os(e){const n=await rs();if(n&&e-n.checkedAt<Xr)return n.latest;return ss(e)}async function zt(e=Date.now()){if(ae==="0.0.0-dev")return null;try{const n=await os(e);if(n&&ns(n,ae)){return`A newer buoy-mcp is available (${n}; you're on ${ae}). Update by re-running: npx -y ${te}@latest init \u2014 then restart your editor.`}}catch{}return null}import{z as W}from"zod";function $e(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function et(e){return{isError:true,content:[{type:"text",text:e}]}}function Jt(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 zt();const r=n.listDevices();if(r.length===0){return $e({devices:[],hint:"No devices connected. Open the app with Buoy devtools running, then retry.",...t?{updateAvailable:t}:{}})}const s=r.filter(c=>c.isConnected);const o=s.some(c=>c.isPro);const a=s.some(c=>c.tier!=="locked");const i=s.filter(c=>c.collision);return $e({devices:r,...i.length>0?{warning:`${i.map(c=>`"${c.deviceId}"`).join(", ")}: more than one app is registered under this id, so actions sent to it land on an arbitrary device. Give each device its own externalSync.deviceId (or leave it unset for a per-install default) before mutating anything.`}:{},...o?{}:{hint:a?"The Buoy MCP is a Pro feature \u2014 the connected device is signed in on the free tier, so data/action tools are blocked. Upgrade to Buoy Pro in the app, or pass `licenseKey` to `<FloatingDevTools />` if it runs headless.":"The broker has not confirmed account access for the connected devices, so data/action tools are blocked. A locked status can mean missing configuration, pending/failed validation, or a missing account announcement after reconnect; it does not prove the user is signed out. Check app account status and broker compatibility."},...t?{updateAvailable:t}:{}})});e.registerTool("list_tool_actions",{description:"List the actions a given tool exposes, and which connected devices offer it. Use the action names with call_action.",inputSchema:{toolId:W.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 et(`No connected device exposes tool "${t}". Call list_devices to see available tools.`)}return $e({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:W.string().describe("The tool id to read state from."),deviceId:W.string().optional().describe("Target device id. Omit to auto-select when one device is connected."),timeoutMs:W.number().optional().describe("How long to wait for a fresh snapshot before falling back to the cached one.")}},async({toolId:t,deviceId:r,timeoutMs:s})=>{try{const o=n.requireProDevice(r);const{payload:a}=await n.getSnapshot(t,o,{timeoutMs:s});return $e({toolId:t,deviceId:o,snapshot:a})}catch(o){return et(Wt(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:W.string().describe('The tool id, e.g. "perf-monitor".'),action:W.string().describe('The action name, e.g. "startRecording", "clearAll".'),params:W.record(W.unknown()).optional().describe("JSON params object for the action (shape depends on the action)."),deviceId:W.string().optional().describe('Target device id. Omit to auto-select one device, or "All" to broadcast.'),timeoutMs:W.number().optional().describe("Max time to wait for the device's result.")}},async({toolId:t,action:r,params:s,deviceId:o,timeoutMs:a})=>{try{const i=n.requireProDevice(o);const c=await n.callAction(t,r,s,i,{timeoutMs:a});return $e({toolId:t,action:r,ok:true,result:c??null})}catch(i){return et(Wt(i))}})}function Wt(e){return e instanceof Error?e.message:String(e)}var ge=(e,n,t)=>Math.max(n,Math.min(t,e));var as="__batch_warmup__";var is={nominal:"\u{1F7E2} nominal",fair:"\u{1F7E1} fair",serious:"\u{1F7E0} serious",critical:"\u{1F534} critical",unknown:"\u2014"};var ve={perCaseDurationMs:5e3,settleMs:600,navTimeoutMs:5e3,runsPerCase:3,coolDownMs:2e3,discardWarmupRuns:0};function we(e,n,t){return e??n??t}function Me(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((l,m)=>{const $=(l.name||"").trim()||`case ${m+1}`;return{id:`case-${m}`,name:$,params:l.params??{},route:l.route}});const a=ge(Math.round(we(e.runsPerCase,n.runsPerCase,ve.runsPerCase)),1,10);const i=ge(Math.round(we(e.coolDownMs,n.coolDownMs,ve.coolDownMs)),0,3e4);const c=ge(Math.round(we(e.discardWarmupRuns,n.discardWarmupRuns,ve.discardWarmupRuns)),0,a-1);const d=e.shuffleCases??n.shuffleCases??o.length>3;if(o.length>3&&d===false){t.push("shuffleCases is off with >3 cases \u2014 later cases may be thermally throttled, biasing results. Consider enabling it.")}if(a===1){t.push("runsPerCase=1 \u2014 no median/variance; a single noisy run can mislead. 3+ is recommended.")}const u={targetRoute:r,bounceRoute:s,perCaseDurationMs:ge(Math.round(we(e.perCaseDurationMs,n.perCaseDurationMs,ve.perCaseDurationMs)),1e3,6e4),settleMs:ge(Math.round(we(e.settleMs,n.settleMs,ve.settleMs)),0,1e4),navTimeoutMs:ge(Math.round(we(e.navTimeoutMs,n.navTimeoutMs,ve.navTimeoutMs)),1e3,3e4),cases:o,runsPerCase:a,coolDownMs:i,discardWarmupRuns:c,discardWarmupCase:e.discardWarmupCase??n.discardWarmupCase??true,shuffleCases:d,reloadBetweenCases:e.reloadBetweenCases??n.reloadBetweenCases??false,captureRenders:e.captureRenders??n.captureRenders??true};return{config:u,warnings:t}}function Vt(e){const n=c=>c>=1e3?`${(c/1e3).toFixed(c%1e3?1:0)}s`:`${c}ms`;const t=e.runsPerCase??1;const r=tt(e);const s=r/6e4;const o=s>=1?`~${s.toFixed(1)} min`:`~${Math.round(r/1e3)}s`;const a=[`**${n(e.perCaseDurationMs)} measured per page**`,t>1?`**${t} runs each** (median taken)`:`**1 run each** (no median \u2014 noisier)`,e.reloadBetweenCases?"**full reload between pages** (no state leaks across tests)":"no reload between pages",e.shuffleCases?"shuffled order (cancels thermal bias)":"fixed order",e.captureRenders!==false?"render capture on (per-component why-data)":"render capture off"];const i=e.settleMs+e.perCaseDurationMs+(e.coolDownMs??0)+1800;return`${a.join(", ")}. That's ~${n(i)} wall-clock per page; for ${e.cases.length} page(s) \xD7 ${t} run(s), **${o}** total.`}function tt(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 cs(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 Re(e,n,t,r=[]){const s=e.filter(h=>h.batchId===n);const o=new Map(r.map(h=>[h.index,h.reason]));const a=Array.from(new Set(s.map(h=>h.batchIndex??0))).sort((h,f)=>h-f);const i=h=>{const f=s.filter(g=>(g.batchIndex??0)===h);if(f.length===0)return void 0;return f.find(g=>g.isMedianRun===true)??f.find(g=>g.runIndex===0||g.runIndex===void 0)??f[0]};const c=h=>typeof h==="number"?h:null;const d=a.map(h=>{const f=i(h);const g=s.filter(O=>(O.batchIndex??0)===h).length;const v=f?.name??t?.[h]?.name??`case ${h+1}`;const S=o.get(h)??f?.batchFailureReason;const x=Boolean(S)||!f;const M={batchIndex:h,caseName:v,params:f?.params??{},runs:g,failed:x,failureReason:x?S??"no run recorded":void 0,uiFps:c(f?.uiFpsAvg),jsFps:c(f?.jsFpsAvg),cpu:c(f?.cpuAvg),memMb:c(f?.memMaxMb),jsJank:c(f?.jsJankFrames),uiJank:c(f?.uiJankFrames),deviceMaxRefreshRate:c(f?.deviceMaxRefreshRate),deltaUiFps:null,deltaJsFps:null,...f?.thermalState?{thermalState:f.thermalState}:{},renderCommits:c(f?.renderCommits),renderWasted:f?.renderWasted,topRenderers:f?.topRenderers??[]};return{...M,flags:x?[]:cs(M)}}).filter(h=>h.caseName!==as).map((h,f)=>({...h,batchIndex:f}));const u=d[0];if(u){for(const h of d){if(h===u)continue;if(h.uiFps!=null&&u.uiFps!=null)h.deltaUiFps=ie(h.uiFps-u.uiFps,1);if(h.jsFps!=null&&u.jsFps!=null)h.deltaJsFps=ie(h.jsFps-u.jsFps,1)}}const l=d.filter(h=>!h.failed);const m=(h,f)=>{let g;let v=NaN;for(const S of l){const x=h(S);if(x==null)continue;if(g===void 0||f(x,v)){g=S;v=x}}return g?.caseName};const $=h=>h.jsJank==null&&h.uiJank==null?null:(h.jsJank??0)+(h.uiJank??0);const b={uiFps:m(h=>h.uiFps,(h,f)=>h>f),jsFps:m(h=>h.jsFps,(h,f)=>h>f),lowestCpu:m(h=>h.cpu,(h,f)=>h<f),lowestMem:m(h=>h.memMb,(h,f)=>h<f),fewestJank:m($,(h,f)=>h<f)};const p=l.filter(h=>h.flags.length>0).map(h=>({caseName:h.caseName,flags:h.flags}));const w=l.filter(h=>h.flags.length===0).sort((h,f)=>(f.uiFps??0)-(h.uiFps??0)||(h.cpu??Infinity)-(f.cpu??Infinity)||(h.memMb??Infinity)-(f.memMb??Infinity)).map(h=>h.caseName);return{batchId:n,baselineName:u?.caseName??null,deviceMaxRefreshRate:l.find(h=>h.deviceMaxRefreshRate!=null)?.deviceMaxRefreshRate??null,rows:d,leaders:b,flagged:p,balanced:w}}function Oe(e){const n=(l,m=1)=>l==null?"\u2014":l.toFixed(m);const t=l=>l==null?"":l>0?` (+${l.toFixed(1)})`:` (${l.toFixed(1)})`;const r=[];r.push(`### Benchmark batch \`${e.batchId}\``);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(l=>l.thermalState);const o=s?" Thermal |":"";const a=s?"-------|":"";r.push(`| # | Case | UI FPS | JS FPS | CPU % | Mem MB | JS jank | UI jank |${o} Flags |`);r.push(`|---|------|-------:|-------:|------:|-------:|--------:|--------:|${a}-------|`);for(const l of e.rows){const m=s?` ${is[l.thermalState??"unknown"]??"\u2014"} |`:"";if(l.failed){r.push(`| ${l.batchIndex} | ${l.caseName} | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 | \u2014 |${m} \u274C FAILED (${l.failureReason}) |`);continue}const $=l.flags.length?`\u26A0\uFE0F ${l.flags.join("; ")}`:"\u2713 clean";r.push(`| ${l.batchIndex} | ${l.caseName} | ${n(l.uiFps)}${t(l.deltaUiFps)} | ${n(l.jsFps)}${t(l.deltaJsFps)} | ${n(l.cpu)} | ${n(l.memMb)} | ${n(l.jsJank,0)} | ${n(l.uiJank,0)} |${m} ${$} |`)}const i=e.rows.filter(l=>l.thermalState==="serious"||l.thermalState==="critical");if(i.length){r.push("");r.push(`**\u{1F525} Thermally throttled: ${i.map(l=>l.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 c=e.leaders;const d=[c.uiFps&&`UI FPS \u2192 **${c.uiFps}**`,c.jsFps&&`JS FPS \u2192 **${c.jsFps}**`,c.lowestCpu&&`lowest CPU \u2192 **${c.lowestCpu}**`,c.lowestMem&&`lowest mem \u2192 **${c.lowestMem}**`,c.fewestJank&&`fewest jank \u2192 **${c.fewestJank}**`].filter(Boolean).join(" \xB7 ");if(d)r.push(`**Per-metric best:** ${d}`);r.push(e.balanced.length?`**No configured risk flags:** ${e.balanced.join(", ")}. Check missing metrics and workload requirements before choosing.`:`**No configured risk flags:** no candidates listed. Review failures, available metrics and flags before choosing.`);if(e.flagged.length){r.push(`**\u26A0\uFE0F At-risk:** ${e.flagged.map(l=>`${l.caseName} (${l.flags.join("; ")})`).join(" \xB7 ")}`)}const u=e.rows.filter(l=>!l.failed&&(l.renderCommits!=null||l.topRenderers.length>0)).map(l=>{const m=l.topRenderers.map(p=>`${p.name} \xD7${p.renders} (${p.totalMs}ms${p.cause?`, ${p.cause}`:""})`).join(", ");const $=l.renderCommits!=null?`${l.renderCommits} commits`:"";const b=l.renderWasted!=null?`${l.renderWasted} wasted`:"";return`- **${l.caseName}** \u2014 ${[$,b,m].filter(Boolean).join(": ")}`});if(u.length){r.push("");r.push("**Renders (median run)** \u2014 `wasted` = parent cascades + identity-only prop churn (removable). Cause per component: `propsUnstable` means a parent handed it a fresh function/object with unchanged values \u2014 fix upstream.");r.push(...u)}r.push("");r.push(`_Deltas vs baseline (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 Kt(e,n){const t=(r,s)=>({a:{avg:ie(r.avg,1),p95:ie(r.p95,1)},b:{avg:ie(s.avg,1),p95:ie(s.p95,1)},deltaAvg:ie(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},...ls(e.renders,n.renders)}}function ls(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 ie(e,n){const t=Math.pow(10,n);return Math.round(e*t)/t}import{z as D}from"zod";import{z as us}from"zod";var k=e=>({content:[{type:"text",text:e}]});var y=e=>({isError:true,content:[{type:"text",text:e}]});var I=e=>e instanceof Error?e.message:String(e);var A=us.string().optional().describe("Target device id (auto-selected if one is connected).");function ds(e,n){return typeof e==="number"&&e>0?e:n}function hs(e){return e?`${e}
|
|
3
|
-
|
|
4
|
-
`:""}function Ht(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 ke(e,n){return async t=>{try{const r=e.requireProDevice(t.deviceId);return await n(t,r)}catch(r){return y(I(r))}}}var j="perf-monitor";var _e=1500;var Se=e=>new Promise(n=>setTimeout(n,e));var Gt=e=>({content:[{type:"text",text:JSON.stringify(e,null,2)}]});var ps=D.object({name:D.string().describe("Display name for this variant (becomes the saved run's name)."),params:D.record(D.string()).optional().describe('Query params applied to the route for this case, e.g. { "renderer": "v2", "count": "100" }.'),route:D.string().optional().describe("Optional per-case route override; defaults to targetRoute.")});async function nt(e,n){try{const t=await e.callAction(j,"getAutomationConfig",{},n);if(!t)return{};const{perCaseDurationMs:r,settleMs:s,navTimeoutMs:o,runsPerCase:a,coolDownMs:i,discardWarmupRuns:c,shuffleCases:d,reloadBetweenCases:u,captureRenders:l}=t;return{perCaseDurationMs:r,settleMs:s,navTimeoutMs:o,runsPerCase:a,coolDownMs:i,discardWarmupRuns:c,shuffleCases:d,reloadBetweenCases:u,captureRenders:l}}catch{return{}}}async function G(e,n){const{payload:t}=await e.getSnapshot(j,n,{timeoutMs:4e3});return t}function rt(e){const n=new Set;for(const t of e??[])if(t.batchId)n.add(t.batchId);return n}function Yt(e,n){return(e??[]).filter(t=>t.batchId===n).length}function ms(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 ce(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 fs(e){const n=e.cases.length+(e.discardWarmupCase===true?1:0);return n*(e.runsPerCase??1)}var gs=1e4;function vs(e){return!!e&&e!=="idle"&&e!=="done"&&e!=="cancelled"}async function Qt(e,n,t,r=gs){const s=Date.now();while(Date.now()-s<r){const o=await G(e,n).catch(()=>null);if(o&&!vs(o.live?.automation?.phase))return true;await Se(_e)}t(`automation still busy after ${Math.round(r/1e3)}s`);return false}async function ws(e,n,t){const{preBatchIds:r,expectedRuns:s,maxWaitMs:o,log:a}=t;const i=Date.now();let c="";let d=false;let u=0;while(Date.now()-i<o){let $;try{$=await G(e,n)}catch{await Se(_e);continue}const b=$.index??[];const p=$.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??ce(b,w.batchId)}}if(p!=="idle")d=true;if(p!==c){c=p;a(`automation phase: ${p}`)}const h=[...rt(b)].find(f=>!r.has(f));if(h){const f=Yt(b,h);if(s>0&&f>=s){await Qt(e,n,a);a(`batch ${h} complete (${f}/${s} runs saved)`);return{batchId:h,failures:ce(b,h)}}if(p==="idle"&&d&&f>0){if(++u>=3){a(`batch ${h} settled (${f} runs, automation idle)`);return{batchId:h,failures:ce(b,h)}}}else{u=0}}await Se(_e)}const l=await G(e,n).catch(()=>null);const m=l?[...rt(l.index)].find($=>!r.has($)):void 0;if(m&&l)return{batchId:m,failures:ce(l.index,m),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 Zt(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:D.string().describe('The screen to benchmark, e.g. "/perf-test". Reads case params to pick a variant.'),cases:D.array(ps).min(1).describe("The variants to compare. Case #0 is the baseline for deltas."),bounceRoute:D.string().optional().describe('Screen to bounce to between runs so the test screen fully remounts. Defaults to "/" (or a stub if target is "/").'),runsPerCase:D.number().optional().describe("Runs per case; the median becomes the canonical result. Default 3 (1\u201310)."),perCaseDurationMs:D.number().optional().describe("How long to record each run. Default 5000."),settleMs:D.number().optional().describe("Idle gap after navigation before recording. Default 600."),coolDownMs:D.number().optional().describe("Idle between runs/cases for thermal recovery. Default 2000."),navTimeoutMs:D.number().optional().describe("Max wait for navigation per run. Default 5000."),discardWarmupRuns:D.number().optional().describe("Discard first N runs of each case before taking the median. Default 0."),shuffleCases:D.boolean().optional().describe("Interleave and shuffle case order to reduce order-related bias. Default on for >3 cases."),reloadBetweenCases:D.boolean().optional().describe("Fully reload JS between cases (needs <AutomationResumer/> mounted). Default false."),captureRenders:D.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:D.string().optional().describe("Target device id. Omit to auto-select when one device is connected."),maxWaitMs:D.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 nt(n,s);const{config:a,warnings:i}=Me(t,o);const c=tt(a);const d=t.maxWaitMs??c*3+6e4;const u=fs(a);if(!await Qt(n,s,r)){return y("Another benchmark batch is still running on this device. Wait for it to finish, or cancel it (call_action perf-monitor cancelAutomation), then retry.")}await n.callAction(j,"acknowledgeAutomation",{},s).catch(()=>{});await n.callAction(j,"setEnabled",{enabled:true},s).catch(()=>{});await n.callAction(j,"refreshIndex",{},s).catch(()=>{});const l=await G(n,s);const m=rt(l.index);r(`starting batch: ${a.cases.length} cases \xD7 ${a.runsPerCase} runs (~${Math.round(c/1e3)}s estimated) on ${s}`);await n.callAction(j,"startAutomation",{config:a},s);const $=await ws(n,s,{preBatchIds:m,expectedRuns:u,maxWaitMs:d,log:r});if($.cancelled){await n.callAction(j,"acknowledgeAutomation",{},s).catch(()=>{});return y(`Batch ${$.batchId} was cancelled before completing.`)}await n.callAction(j,"refreshIndex",{},s).catch(()=>{});const b=await G(n,s);const p=Re(b.index??[],$.batchId,a.cases,$.failures);await n.callAction(j,"acknowledgeAutomation",{},s).catch(()=>{});await n.callAction(j,"setEnabled",{enabled:false},s).catch(()=>{});const w=Oe(p);const h={batchId:$.batchId,leaders:p.leaders,balanced:p.balanced,flagged:p.flagged,rows:p.rows,failures:$.failures,warnings:i,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(h,null,2)}
|
|
9
|
-
\`\`\``)}catch(s){return y(I(s))}});e.registerTool("get_automation_status",{description:"Get the perf-monitor automation batch status (current phase + last completed batch) without waiting.",inputSchema:{deviceId:D.string().optional().describe("Target device id (auto-selected if one is connected).")}},async({deviceId:t})=>{try{const r=n.requireProDevice(t);const s=await G(n,r);return Gt({deviceId:r,automation:s.live?.automation??{phase:"idle"},automationCompleted:s.live?.automationCompleted??null})}catch(r){return y(I(r))}});e.registerTool("wait_for_automation",{description:"Block until the in-flight perf-monitor batch finishes, then return its ranked comparison. Use this if a batch was started another way (e.g. on the device).",inputSchema:{deviceId:A,maxWaitMs:D.number().optional().describe("Max time to wait. Default 600000 (10 min).")}},async({deviceId:t,maxWaitMs:r})=>{const s=a=>process.stderr.write(`[buoy-mcp] ${a}
|
|
10
|
-
`);const o=r??6e5;try{const a=n.requireProDevice(t);const i=Date.now();let c=false;let d=0;let u=-1;let l=null;while(Date.now()-i<o){let b;try{b=await G(n,a)}catch{await Se(_e);continue}const p=b.live?.automationCompleted;if(p?.phase==="cancelled")return y(`Batch ${p.batchId} was cancelled.`);if(p?.phase==="done"){l={batchId:p.batchId,failures:p.failures??ce(b.index,p.batchId)};break}const w=b.live?.automation?.phase??"idle";if(w!=="idle")c=true;const h=ms(b.index);if(w==="idle"&&h){const f=Yt(b.index,h);if(f===u){if(c&&++d>=3){l={batchId:h,failures:ce(b.index,h)};break}if(!c&&Date.now()-i>4e3){l={batchId:h,failures:ce(b.index,h)};break}}else{d=0;u=f}}else{d=0}await Se(_e)}if(!l)return y("No automation batch completed within the wait window.");await n.callAction(j,"refreshIndex",{},a).catch(()=>{});const m=await G(n,a);const $=Re(m.index??[],l.batchId,void 0,l.failures);await n.callAction(j,"acknowledgeAutomation",{},a).catch(()=>{});return k(`${Oe($)}
|
|
11
|
-
|
|
12
|
-
\`\`\`json
|
|
13
|
-
${JSON.stringify($,null,2)}
|
|
14
|
-
\`\`\``)}catch(a){return y(I(a))}});e.registerTool("get_batch_report",{description:"Re-rank a previously-run benchmark batch by its batchId (from the saved recordings index).",inputSchema:{batchId:D.string().describe("The batch id to report on."),deviceId:A}},async({batchId:t,deviceId:r})=>{try{const s=n.requireProDevice(r);await n.callAction(j,"refreshIndex",{},s).catch(()=>{});const o=await G(n,s);const a=(o.index??[]).filter(c=>c.batchId===t);if(a.length===0)return y(`No saved runs found for batch "${t}".`);const i=Re(o.index??[],t);return k(`${Oe(i)}
|
|
15
|
-
|
|
16
|
-
\`\`\`json
|
|
17
|
-
${JSON.stringify(i,null,2)}
|
|
18
|
-
\`\`\``)}catch(s){return y(I(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:D.string().describe("First (baseline) report id."),reportIdB:D.string().describe("Second report id to compare against the baseline."),deviceId:A}},async({reportIdA:t,reportIdB:r,deviceId:s})=>{try{const o=n.requireProDevice(s);const[a,i]=await Promise.all([n.callAction(j,"loadReport",{id:t},o),n.callAction(j,"loadReport",{id:r},o)]);if(!a)return y(`Report "${t}" not found.`);if(!i)return y(`Report "${r}" not found.`);return Gt(Kt({name:a.metadata.name,stats:a.stats,renders:a.renders},{name:i.metadata.name,stats:i.stats,renders:i.renders}))}catch(o){return y(I(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:D.number().optional().describe("How many pages/variants you plan to test, for a total-time estimate. Default 1."),deviceId:A}},async({pages:t,deviceId:r})=>{try{const s=n.requireProDevice(r);const o=await nt(n,s);const a=Math.max(1,Math.round(t??1));const{config:i}=Me({targetRoute:"/_preview",cases:Array.from({length:a},(d,u)=>({name:`page ${u+1}`}))},o);const c=Object.keys(o).length>0?"this device's saved settings":"default profile (none saved)";return k(`**Benchmark settings (${c}):** ${Vt(i)}
|
|
19
|
-
|
|
20
|
-
\`\`\`json
|
|
21
|
-
${JSON.stringify(o,null,2)}
|
|
22
|
-
\`\`\``)}catch(s){return y(I(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:D.number().optional().describe("Recording length per page (ms)."),settleMs:D.number().optional().describe("Idle after navigation before recording (ms)."),coolDownMs:D.number().optional().describe("Idle between runs/cases (ms)."),navTimeoutMs:D.number().optional().describe("Max wait for navigation per run (ms)."),runsPerCase:D.number().optional().describe("Runs per page; median is the canonical result (1\u201310)."),discardWarmupRuns:D.number().optional().describe("Discard first N runs of each page before the median."),shuffleCases:D.boolean().optional().describe("Interleave and shuffle case order to reduce order-related bias."),reloadBetweenCases:D.boolean().optional().describe("Fully reload JS between pages (needs <AutomationResumer/> mounted)."),captureRenders:D.boolean().optional().describe("Capture per-component render counts/durations during each run."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=await n.callAction(j,"getAutomationConfig",{},r)??{};const o=["perCaseDurationMs","settleMs","coolDownMs","navTimeoutMs","runsPerCase","discardWarmupRuns","shuffleCases","reloadBetweenCases","captureRenders"];const a={};for(const l of o){const m=t[l];if(m!==void 0)a[l]=m}if(Object.keys(a).length===0){return y("No settings provided to save. Pass at least one field (e.g. perCaseDurationMs).")}const i={...s,...a};const c=await n.callAction(j,"setAutomationConfig",{config:i},r);const d=await nt(n,r);const{config:u}=Me({targetRoute:"/_preview",cases:[{name:"page 1"}]},d);return k(`Saved. **New benchmark settings:** ${Vt(u)}
|
|
23
|
-
|
|
24
|
-
\`\`\`json
|
|
25
|
-
${JSON.stringify(c??d,null,2)}
|
|
26
|
-
\`\`\``)}catch(r){return y(I(r))}})}import{z as le}from"zod";var bs="events";var ys={storage:["storage-async","storage-mmkv"],"react-query":["react-query","react-query-query","react-query-mutation"]};function $s(e){if(!e||e.length===0)return void 0;return[...new Set(e.flatMap(n=>ys[n]??[n]))]}function Xt(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:le.number().optional().describe("Most-recent N events to include. Default 25."),sources:le.array(le.string()).optional().describe('Only these sources. Coarse names accepted: "network", "redux", "react-query", "storage", "route", "render", "zustand", "jotai". Omit for all.'),status:le.enum(["all","errors","success","pending"]).optional().describe("Filter by status. Default all."),includeData:le.boolean().optional().describe("Include each event's full raw payload (HEAVY \u2014 network bodies, state trees). Default false (compact)."),format:le.enum(["markdown","json","text","mermaid"]).optional().describe("Output format. Default markdown."),preset:le.enum(["llm","bugReport","json","errors","minimal","mermaid"]).optional().describe("Start from a named Copy-Settings preset (then your other args override it)."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s={};const o=$s(t.sources);if(o)s.filterSources=o;if(t.status)s.filterMode=t.status;if(t.includeData!==void 0)s.includeEventData=t.includeData;if(t.format)s.format=t.format==="text"?"plaintext":t.format;const a=await n.callAction(bs,"exportEvents",{preset:t.preset,settings:s,limit:t.limit??25},r);if(!a||typeof a.output!=="string"){return y("No events result from the device. The events tool may be inactive, or the app needs a newer Buoy (get_events requires the exportEvents action).")}const i=a.includedData?"":" \u2014 compact view; pass includeData:true, a specific source, or a bigger limit for full payloads";const c=`
|
|
27
|
-
|
|
28
|
-
_Showing ${a.returned} of ${a.totalAvailable} captured event(s)${i}._`;return k((a.output||"(no events captured)")+c)}catch(r){return y(I(r))}})}import{z as xe}from"zod";var ks="query";var _s="react-query";async function st(e,n,t,r){try{return await e.callAction(ks,n,t,r)}catch(s){const o=I(s);if(!/unknown tool/i.test(o))throw s;return await e.callAction(_s,n,t,r)}}var Ss={fresh:"\u{1F7E2}",stale:"\u{1F7E1}",fetching:"\u{1F504}",error:"\u{1F534}",inactive:"\u26AA\uFE0F",paused:"\u23F8\uFE0F",disabled:"\u{1F6AB}"};function xs(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 en(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:xe.boolean().optional().describe("Include each query's full cached data payload (HEAVY). Default false."),staleOnly:xe.boolean().optional().describe("Only stale queries. Default false."),limit:xe.number().optional().describe("Most-recently-updated N queries. Default 25."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=await st(n,"listQueries",{includeData:t.includeData??false,staleOnly:t.staleOnly??false,limit:t.limit??25},r);if(!s||!Array.isArray(s.queries)){return y("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((d,u)=>{const l=Ss[d.status]??"\u2022";const m=`${u+1}. ${l} ${d.status} \xB7 \`${d.queryHash}\` \xB7 ${d.observers} obs \xB7 ${xs(d.updatedAt)}`;const $=d.error?` \u2014 \u26A0\uFE0F ${d.error}`:"";const b=s.includedData?`
|
|
29
|
-
data: ${JSON.stringify(d.data)}`:"";return m+$+b});const a=s.queries.filter(d=>d.isStale).length;const i=`**React Query cache \u2014 ${s.total} queries (showing ${s.returned}, ${a} stale):**`;const c=s.includedData?"":"\n\n_Compact view. Pass includeData:true for cached payloads, staleOnly:true to narrow. Act on one with react_query_action using the `hash` in backticks._";return k(`${i}
|
|
30
|
-
|
|
31
|
-
${o.join("\n")}${c}`)}catch(r){return y(I(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:xe.enum(["invalidate","refetch","reset","remove","clear"]).describe("invalidate/refetch/reset/remove a single query (needs queryHash); clear empties the whole query cache."),queryHash:xe.string().optional().describe("The target query's hash (from get_react_query, shown in backticks). Required for all actions except clear."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);if(t.action==="clear"){await st(n,"clearQueryCache",{},r);return k("Requested clearing of the connected React Query cache. Read it again to confirm.")}if(!t.queryHash){return y(`'${t.action}' needs a queryHash. Call get_react_query first and use a row's hash (in backticks).`)}await st(n,t.action,{queryHash:t.queryHash},r);return k(`Requested ${t.action} on query \`${t.queryHash}\`.`)}catch(r){return y(I(r))}})}import{z as ue}from"zod";var ot="zustand";function tn(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:ue.boolean().optional().describe("Include each store's full current state object (HEAVY). Default false (keys only)."),limit:ue.number().optional().describe("First N stores. Default all."),deviceId:A}},ke(n,async(t,r)=>{const s=await n.callAction(ot,"listStores",{includeValues:t.includeValues??false,limit:t.limit},r);if(!s||!Array.isArray(s.stores)){return y(Ht({toolId:ot,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((i,c)=>{const d=i.isPersisted?` \xB7 persisted${i.persistName?` (${i.persistName})`:""}`:"";const u=s.includedValues?`
|
|
32
|
-
${JSON.stringify(i.currentState)}`:` \xB7 keys: ${(i.keys??[]).join(", ")||"\u2014"}`;return`${c+1}. **${i.name}** \xB7 ${i.changes} changes${d}${u}`});const a=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")}${a}`)}));e.registerTool("zustand_action",{description:"Set the state of a Zustand store (time-travel / reset / tweak during debugging). Targets a store by name (from get_zustand_state). By default replaces the whole state; pass replace:false to merge a partial.",inputSchema:{store:ue.string().describe("Store name to target (from get_zustand_state)."),state:ue.record(ue.string(),ue.unknown()).describe("The new state object."),replace:ue.boolean().optional().describe("Replace the whole state (default true) or merge a partial (false)."),deviceId:A}},ke(n,async(t,r)=>{await n.callAction(ot,"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 Ce}from"zod";var at="jotai";function nn(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:Ce.boolean().optional().describe("Include each atom's current value (HEAVY). Default false."),limit:Ce.number().optional().describe("First N atoms. Default all."),deviceId:A}},ke(n,async(t,r)=>{const s=await n.callAction(at,"listAtoms",{includeValues:t.includeValues??false,limit:t.limit},r);if(!s||!Array.isArray(s.atoms)){return y(Ht({toolId:at,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((i,c)=>{const d=i.writable?"writable":"read-only";const u=s.includedValues?`
|
|
35
|
-
${JSON.stringify(i.currentValue)}`:"";return`${c+1}. **${i.label}** \xB7 ${i.changes} changes \xB7 ${d}${u}`});const a=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")}${a}`)}));e.registerTool("jotai_action",{description:"Set the value of a writable Jotai atom (by label, from get_jotai_state). Read-only/derived atoms cannot be set (you'll get a clear error). Use for tweaking state during debugging.",inputSchema:{atom:Ce.string().describe("Atom label to set (from get_jotai_state; must be writable)."),value:Ce.unknown().describe("The new value (any JSON \u2014 number, string, object, etc.)."),deviceId:A}},ke(n,async(t,r)=>{await n.callAction(at,"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 it}from"zod";var rn="redux";function sn(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 As="\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 on(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:it.boolean().optional().describe("Include the full current state tree (HEAVY). Default false (slice names only)."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=await n.callAction(rn,"getState",{includeValues:t.includeValues??false},r);if(!s){return y("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 y(sn(s.reason));const o=s.slices.length?s.slices.join(", "):"(none)";const a=s.capture==="top-level-only"?As:"";if(t.includeValues){return k(`**Redux store \u2014 slices: ${o}**
|
|
38
|
-
|
|
39
|
-
\`\`\`json
|
|
40
|
-
${JSON.stringify(s.state,null,2)}
|
|
41
|
-
\`\`\`${a}`)}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})._${a}`)}catch(r){return y(I(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:it.string().describe('The action type, e.g. "counter/increment" or "auth/logout".'),payload:it.unknown().optional().describe("Optional action payload (any JSON)."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s={type:t.type};if(t.payload!==void 0)s.payload=t.payload;const o=await n.callAction(rn,"dispatch",{action:s},r);if(!o||!o.dispatched)return y(sn(o?.reason));return k(`Dispatched \`${t.type}\`${t.payload!==void 0?` with payload ${JSON.stringify(t.payload)}`:""}.`)}catch(r){return y(I(r))}})}import{z as be}from"zod";var ne="storage";function ct(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 an(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:be.string().optional().describe("Only keys containing this substring (case-insensitive)."),includeValues:be.boolean().optional().describe("Include each key's value (truncated). Default false (keys only)."),limit:be.number().optional().describe("Max keys per backend section. Default 100."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=t.pattern?.toLowerCase();const o=typeof t.limit==="number"&&t.limit>0?t.limit:100;const a=b=>!s||b.toLowerCase().includes(s);const i=[];const c=await n.callAction(ne,"async.getAllKeys",{},r);if(!Array.isArray(c)){return y("No storage result from the device. The storage tool may be inactive.")}const d=c.filter(a).slice(0,o);if(d.length>0){let b;if(t.includeValues){const p=await n.callAction(ne,"async.multiGet",{keys:d},r);const w=new Map((p??[]).map(([h,f])=>[h,f]));b=d.map(h=>`- \`${h}\` = ${ct(w.get(h)??null)}`)}else{b=d.map(p=>`- \`${p}\``)}i.push(`**AsyncStorage (${d.length}/${c.length} keys):**
|
|
44
|
-
${b.join("\n")}`)}const u=await n.callAction(ne,"mmkv.snapshot",{},r).catch(()=>null);for(const b of u??[]){const p=b.entries.filter(f=>a(f.key)).slice(0,o);if(p.length===0)continue;const w=p.map(f=>t.includeValues?`- \`${f.key}\` (${f.valueType}) = ${ct(f.value)}`:`- \`${f.key}\``);const h=[b.encrypted&&"encrypted",b.readOnly&&"read-only"].filter(Boolean).join(", ");i.push(`**MMKV \`${b.id}\`${h?` (${h})`:""} (${p.length}/${b.entries.length} keys):**
|
|
45
|
-
${w.join("\n")}`)}const l=await n.callAction(ne,"secure.keys",{},r).catch(()=>null);const m=(l??[]).filter(b=>a(b.key)).slice(0,o);if(m.length>0){const b=await Promise.all(m.map(async p=>{if(p.requireAuthentication)return`- \`${p.key}\` \u{1F512} (biometric-protected \u2014 not read)`;if(!t.includeValues)return`- \`${p.key}\``;const w=await n.callAction(ne,"secure.get",{key:p.key},r).catch(()=>null);return`- \`${p.key}\` = ${ct(w)}`}));i.push(`**SecureStore (${m.length} registered keys):**
|
|
46
|
-
${b.join("\n")}`)}if(i.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(`${i.join("\n\n")}${$}`)}catch(r){return y(I(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:be.enum(["set","remove","clear"]).describe("set/remove a key, or clear supported app AsyncStorage keys."),key:be.string().optional().describe("The key (required for set and remove)."),value:be.string().optional().describe("The string value to store (required for set; JSON-encode objects)."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);if(t.action==="clear"){await n.callAction(ne,"clearAppStorage",{},r);return k("Requested clearing of supported app AsyncStorage keys. Read storage again to confirm.")}if(!t.key){return y(`'${t.action}' needs a key.`)}if(t.action==="remove"){await n.callAction(ne,"async.removeItem",{key:t.key},r);return k(`Requested removal of storage key "${t.key}".`)}if(t.value===void 0){return y("'set' needs a value (a string).")}await n.callAction(ne,"async.setItem",{key:t.key,value:t.value},r);return k(`Requested update of storage key "${t.key}".`)}catch(r){return y(I(r))}})}import{z as lt}from"zod";var cn="route-events";function ln(e,n=[]){for(const t of e??[]){if(t.path)n.push(t.path);if(t.children?.length)ln(t.children,n)}return n}function un(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:lt.boolean().optional().describe("Also list available configured route paths (can be long). Default false."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:s}=await n.getSnapshot(cn,r);const o=Array.isArray(s)?{events:s}:s??{};const a=Array.isArray(o.stack)?o.stack:[];const i=a.find(l=>l.isFocused)??a[a.length-1];const c=i?.pathname??"(unknown)";const d=[`**Current route:** \`${c}\``];if(a.length){const l=a.map((m,$)=>`${$+1}. \`${m.pathname??m.name??"?"}\`${m.isFocused?" \u2190 focused":""}`);d.push(`
|
|
47
|
-
**Navigation stack** (top last):
|
|
48
|
-
${l.join("\n")}`)}const u=ln(o.sitemap?.routes);if(t.includeSitemap){const l=u.slice(0,200);d.push(`
|
|
49
|
-
**Sitemap (${u.length} routes${l.length<u.length?`, showing ${l.length}`:""}):**
|
|
50
|
-
${l.map(m=>`- \`${m}\``).join("\n")}`)}else{d.push(`
|
|
51
|
-
**Sitemap:** ${u.length} routes _(pass includeSitemap:true to list them)_`)}d.push("\n_Navigate with navigate({ path })._");return k(d.join("\n"))}catch(r){return y(I(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:lt.string().describe("The concrete path to navigate to, e.g. '/pokemon/25'."),replace:lt.boolean().optional().describe("Replace the current screen instead of pushing (use when resetting, e.g. to '/')."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);await n.callAction(cn,"navigate",{path:t.path,replace:t.replace===true},r);return k(`Navigated to \`${t.path}\`${t.replace?" (replaced current screen)":""}.`)}catch(r){return y(I(r))}})}import{z as ut}from"zod";var Ts="console";var dn={verbose:0,info:1,warning:2,error:3};var Is={verbose:"\xB7",info:"info",warning:"warn",error:"ERR"};function Ds(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 hn(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:ut.enum(["verbose","info","warning","error"]).optional().describe("Minimum level to include (severity threshold). e.g. 'warning' = warnings + errors. Default all."),limit:ut.number().optional().describe("Most-recent N entries. Default 50."),pattern:ut.string().optional().describe("Only entries whose message contains this substring (case-insensitive)."),deviceId:A}},ke(n,async(t,r)=>{const{payload:s,stale:o}=await n.getSnapshot(Ts,r);const a=hs(o);const i=Array.isArray(s)?{entries:s}:s??{};const c=Array.isArray(i.entries)?i.entries:[];const d=t.level?dn[t.level]:0;const u=t.pattern?.toLowerCase();const l=c.filter(f=>dn[f.level]>=d&&(!u||(f.message??"").toLowerCase().includes(u)));const m=[...l].sort((f,g)=>f.id-g.id);const $=ds(t.limit,50);const b=m.slice(-$);if(b.length===0){return k(`${a}No console entries${t.level?` at level \u2265 ${t.level}`:""}${u?` matching "${t.pattern}"`:""} (${c.length} total captured).`)}const p=b.map(f=>`${Ds(f.timestamp)} [${Is[f.level]??f.level}] ${f.message}`);const w=t.level?`, level \u2265 ${t.level}`:"";const h=`**Console \u2014 ${c.length} entries (showing ${b.length}${w}):**`;return k(`${a}${h}
|
|
52
|
-
|
|
53
|
-
\`\`\`
|
|
54
|
-
${p.join("\n")}
|
|
55
|
-
\`\`\`
|
|
56
|
-
|
|
57
|
-
_Tail of recent logs. Use get_snapshot for available console entry details._`)}))}import{z as dt}from"zod";import{execFile as Ms}from"child_process";import{promisify as Rs}from"util";import{promises as Fe}from"fs";import pn from"os";import mn from"path";import{randomUUID as fn}from"crypto";var gn=Rs(Ms);var Ee=(e,n,t)=>Math.min(Math.max(e,n),t);function Os(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 Cs(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 Fs(){if(process.platform!=="darwin"){return{ok:false,error:"Screenshotting a component requires macOS with Xcode's iOS Simulator (uses `xcrun simctl`)."}}const e=mn.join(pn.tmpdir(),`buoy-mcp-sim-${fn()}.png`);try{await gn("xcrun",["simctl","io","booted","screenshot","--type=png",e],{timeout:15e3})}catch(n){return{ok:false,error:Os(n)}}try{const n=await Fe.readFile(e);const t=Cs(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 Es(e,n,t){const r=Ee(Math.round(t.x),0,Math.max(0,n.width-1));const s=Ee(Math.round(t.y),0,Math.max(0,n.height-1));const o=Ee(Math.round(t.width),1,n.width-r);const a=Ee(Math.round(t.height),1,n.height-s);const i=mn.join(pn.tmpdir(),`buoy-mcp-crop-${fn()}.png`);try{await gn("sips",["-c",String(a),String(o),"--cropOffset",String(s),String(r),e,"--out",i],{timeout:1e4});const c=await Fe.readFile(i);return{ok:true,buffer:c,width:o,height:a}}catch(c){const d=c;return{ok:false,error:`Crop failed: ${d?.stderr||d?.message||c}`}}finally{await Fe.unlink(i).catch(()=>{});await Fe.unlink(e).catch(()=>{})}}function Bs(e,n,t){if(t!=null){const o=e.find(a=>a.nativeTag===t);if(o)return o}const r=(n??"").trim().toLowerCase();if(!r)return void 0;let s;for(const o of e){const a=[o.testID,o.label,o.text,o.name].filter(Boolean).map(d=>d.toLowerCase());let i=0;for(const d of a){if(d===r)i=Math.max(i,100);else if(d.startsWith(r))i=Math.max(i,50);else if(d.includes(r))i=Math.max(i,25)}const c=o.tap;if(c&&c.x>=0&&c.x<=1&&c.y>=0&&c.y<=1)i+=20;else if(c)i-=40;if(i<=0)continue;if(!s||i>s.score)s={el:o,score:i}}return s?.el}function qs(e,n){return{x:e.x*n.width,y:e.y*n.height,width:e.width*n.width,height:e.height*n.height}}var ht="highlight-updates";var js=12;var Ps=6;var Be=e=>({isError:true,content:[{type:"text",text:e}]});var Ns=e=>e instanceof Error?e.message:String(e);function Ls(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 Us(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 vn(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:dt.string().optional().describe('Fuzzy match against testID, nativeID, accessibilityLabel, component name, or view type \u2014 e.g. "submit-button".'),nativeTag:dt.number().optional().describe("An exact nativeTag (from a previous call's candidates) to skip fuzzy matching."),scrollIntoView:dt.boolean().optional().describe("Attempt to scroll an off-screen component into view before capture. Default true; inspect the result."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);await n.callAction(ht,"setSilentTracking",{enabled:true},r).catch(()=>{});const s=await n.callAction(ht,"locateComponent",{query:t.query,nativeTag:t.nativeTag,scrollIntoView:t.scrollIntoView??true,margin:js},r);let o=s;if(!o.matched&&(o.reason==="no-renders"||o.reason==="no-match")){const p=await n.callAction(ht,"describeScreen",{},r).catch(()=>null);const w=p?.elements?Bs(p.elements,t.query,t.nativeTag):void 0;if(w?.frame&&p?.screen){o={matched:true,live:true,rect:qs(w.frame,p.screen),screen:p.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 Be(Ls(o,t.query)+Us(o.candidates))}const a=await Fs();if(!a.ok||!a.srcPath||!a.width||!a.height){return Be(a.error??"Screenshot capture failed.")}const i=a.width/o.screen.width;const c=o.rect;const d=Ps;const u=await Es(a.srcPath,{width:a.width,height:a.height},{x:(c.x-d)*i,y:(c.y-d)*i,width:(c.width+d*2)*i,height:(c.height+d*2)*i});if(!u.ok||!u.buffer){return Be(u.error??"Crop failed.")}const l=o.componentName||"component";const m=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 b=`Captured "${l}"${m} \u2014 ${u.width}\xD7${u.height}px.${$}`;return{content:[{type:"image",data:u.buffer.toString("base64"),mimeType:"image/png"},{type:"text",text:b}]}}catch(r){return Be(Ns(r))}})}import{McpServer as zs}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as Js}from"zod";import{z as T}from"zod";var P="network";var wn=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 Ws(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 Vs(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 Ks(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 Hs(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 bn(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 Gs(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 yn=8;async function $n(e,n,t,r=yn){const s=n.filter(c=>c.id&&(c.requestBodyOmitted===true&&c.requestData===void 0||c.responseBodyOmitted===true&&c.responseData===void 0));const o=new Map;if(s.length===0)return{bodies:o,skipped:0};const a=s.slice(0,r);const i=await Promise.allSettled(a.map(c=>e.callAction(P,"getEventBody",{id:c.id},t)));i.forEach((c,d)=>{const u=a[d].id;const l=c.status==="fulfilled"?c.value:null;o.set(u,l?{...l}:{unresolved:true})});return{bodies:o,skipped:s.length-a.length}}async function Ys(e,n){let t=null;try{t=await e.callAction(P,"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 kn(e){return e>0?`
|
|
61
|
-
|
|
62
|
-
_${e} more withheld ${e===1?"body was":"bodies were"} not fetched (cap ${yn} per listing, they are large). Get one in full with its id._`:""}function _n(e,n){const t=e.id?n.get(e.id):void 0;const r=(s,o,a)=>{const i=s??o;if(i!==void 0&&i!==null)return Gs(i);if(!a)return"(none)";return t?.unresolved?"(withheld \u2014 the device did not answer getEventBody)":"(none)"};return`
|
|
63
|
-
\u2514\u2500 request: ${r(e.requestData,t?.requestData,e.requestBodyOmitted)}
|
|
64
|
-
\u2514\u2500 response: ${r(e.responseData,t?.responseData,e.responseBodyOmitted)}`}function Sn(e,n,t){const r=n.path||n.url;const s=[`${n.duration!==void 0?`${Math.round(n.duration)}ms`:"\u2014"}`,Hs(n.responseSize),n.host??"",n.requestClient??""].filter(Boolean);const o=n.operationName?` (${n.operationName})`:"";return`${e}. \`${n.id}\` ${Vs(n)} ${Ks(n)} ${n.method} ${r}${o}${t?` ${t}`:""}
|
|
65
|
-
\u2514\u2500 ${s.join(" \xB7 ")}`}function Qs(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:T.enum(["get","set"]).describe("Read the effective profile or select one."),profile:T.enum(["normal","offline","slow","verySlow"]).optional().describe("Required for set."),deviceId:A}},async t=>{try{if(t.action==="set"&&!t.profile)return y("Set requires a profile.");const r=n.resolveDevice(t.deviceId);const s=await n.callAction(P,t.action==="get"?"getNetworkConditions":"setNetworkConditions",t.action==="set"?{profile:t.profile}:void 0,r);if(!s||typeof s!=="object"||!("profile"in s))return y("The device did not report its effective network conditions.");return k(JSON.stringify(s))}catch(r){return y(I(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:T.number().optional().describe("Most-recent N requests. Default 25."),pattern:T.string().optional().describe("Only requests whose URL contains this substring (case-insensitive)."),status:T.enum(["all","errors","success","pending"]).optional().describe("Filter by outcome. Default all."),flagged:T.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:T.boolean().optional().describe("Include truncated request/response bodies. Default false (compact)."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:s}=await n.getSnapshot(P,r);const{events:o,saved:a}=Ws(s);const i=typeof t.limit==="number"&&t.limit>0?t.limit:25;const c=t.pattern?.toLowerCase();const d=new Set;const u=new Set;for(const p of a){if(p.pinned)d.add(p.event?.id);if(p.saved)u.add(p.event?.id);if(p.pinned)d.add(p.liveId);if(p.saved)u.add(p.liveId)}if(t.flagged){const p=a.filter(g=>t.flagged==="pinned"?g.pinned:t.flagged==="saved"?g.saved:g.pinned||g.saved);const w=p.filter(g=>g.event&&bn(g.event,t.status)).filter(g=>!c||(g.event.url??"").toLowerCase().includes(c)).slice(0,i);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 h=t.includeBodies?await $n(n,w.map(g=>g.event),r):{bodies:new Map,skipped:0};const f=w.map((g,v)=>{const S=[g.pinned?"\u{1F4CC} pinned":"",g.saved?"\u{1F516} saved":""].filter(Boolean).join(" ");const x=g.event.id?.startsWith("saved:")?" \xB7 from an earlier app run":"";const M=g.bodyTruncated?" \xB7 body truncated":"";let O=Sn(v+1,g.event,S);O+=`
|
|
68
|
-
\u2514\u2500 key \`${g.key}\`${x}${M}`;if(t.includeBodies)O+=_n(g.event,h.bodies);return O}).join("\n");return k(`**Kept requests on ${r}** \u2014 ${w.length} of ${p.length}
|
|
69
|
-
|
|
70
|
-
${f}
|
|
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._${kn(h.skipped)}`)}const l=o.filter(p=>bn(p,t.status)).filter(p=>!c||(p.url??"").toLowerCase().includes(c)).slice(0,i);if(l.length===0){const p=o.length===0?await Ys(n,r):"No request matched the filter.";return k(`No requests on ${r}. ${p}`)}const m=t.includeBodies?await $n(n,l,r):{bodies:new Map,skipped:0};const $=l.map((p,w)=>{const h=[d.has(p.id)?"\u{1F4CC}":"",u.has(p.id)?"\u{1F516}":""].filter(Boolean).join("");let f=Sn(w+1,p,h);if(t.includeBodies)f+=_n(p,m.bodies);return f}).join("\n");const b=a.length>0?` \xB7 ${a.length} kept (flagged:'any' to list)`:"";return k(`**Network requests on ${r}** \u2014 ${l.length} of ${o.length}${b}
|
|
73
|
-
|
|
74
|
-
${$}
|
|
75
|
-
|
|
76
|
-
_\u{1F4CC} pinned \xB7 \u{1F516} saved. Act on one with its id, e.g. network_action({action:"pin", id:"${l[0].id}"})._${kn(m.skipped)}`)}catch(r){return y(I(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:T.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:T.string().optional().describe("Request id for pin/unpin/save/unsave \u2014 from get_network_requests."),key:T.string().optional().describe("Kept-record key for `remove` \u2014 from get_network_requests({flagged:'any'})."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=["pin","unpin","save","unsave"].includes(t.action);if(s&&!t.id){return y(`"${t.action}" needs an \`id\`. List requests with get_network_requests to get one.`)}if(t.action==="remove"&&!t.key){return y('"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(P,"setPinned",{id:t.id,pinned:t.action==="pin"},r);if(o===null)return y(`No request "${t.id}" on ${r}. It may have been cleared or aged out \u2014 re-list with get_network_requests.`);const a=typeof o==="object"&&o!==null&&o.reason==="pin-cap";if(a)return y(`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(P,"setSaved",{id:t.id,saved:t.action==="save"},r);if(o===null)return y(`No request "${t.id}" on ${r}. It may have been cleared or aged out \u2014 re-list with get_network_requests.`);const a=typeof o==="object"&&o!==null&&o.reason==="saved-cap";if(a)return y(`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(P,"removeSavedRecord",{key:t.key},r);return k(`Removed kept record \`${t.key}\` on ${r}.`);case"clearPinned":await n.callAction(P,"clearPinnedRequests",{},r);return k(`Unpinned all requests on ${r} (saved ones kept).`);case"clearSaved":await n.callAction(P,"clearSavedRequests",{},r);return k(`Cleared saved requests on ${r} (pinned ones kept).`);case"clearRequests":await n.callAction(P,"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 y(I(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:T.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:T.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:T.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:T.array(T.string()).optional().describe("For `add`: restrict to these HTTP methods. Omit for any."),kind:T.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:T.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:T.union([T.string(),T.record(T.unknown()),T.array(T.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:T.record(T.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:T.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:T.record(T.string()).optional().describe("For kind 'respond': response headers to send."),failKind:T.enum(["network","timeout"]).optional().describe("For kind 'fail': 'network' (default) or 'timeout'."),delayMs:T.number().optional().describe("Latency before the outcome, in ms. Works with every kind."),times:T.number().optional().describe("Auto-disable the rule after N matches. Use 1 for 'make the next call fail' so it can't linger."),alternate:T.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:T.string().optional().describe("Label shown in the developer's UI."),enabled:T.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:T.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:T.string().optional().describe("For `debug`: a concrete URL to test the rules against, so the report says which rule would match it and why."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);switch(t.action){case"add":{if(!t.urlPattern&&!t.fromRequestId){return y("`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(P,"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 y(o?.error??`Could not add the rule on ${r}.`)}const a=o.rule?.urlPattern??t.urlPattern;const i=o.rule?.enabled===false?`
|
|
77
|
-
|
|
78
|
-
It is switched OFF \u2014 arm it with network_override({action:"enable", id:"${o.rule?.id}"}).`:"";return k(`Override added on ${r} \u2014 \`${o.rule?.id}\` matching \`${a}\`.${i}
|
|
79
|
-
|
|
80
|
-
Trigger the request now (navigate / tap_element), then check it with get_network_requests or describe_screen. Remove it with network_override({action:"remove", id:"${o.rule?.id}"}) when you're done.`)}case"remove":{if(!t.id){return y('`remove` needs an `id`. List them with network_override({action:"list"}).')}await n.callAction(P,"deleteOverrideRule",{id:t.id},r);return k(`Removed override \`${t.id}\` on ${r}.`)}case"clear":await n.callAction(P,"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(P,"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(P,"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(P,"listOverrideRules",{},r);const o=s?.rules??[];if(t.id){const i=o.find(c=>c.id===t.id);if(!i){return y(`No override rule \`${t.id}\` on ${r}. List them with network_override({action:"list"}).`)}return k(`**Override rule \`${i.id}\`** on ${r}${wn(s)}
|
|
81
|
-
|
|
82
|
-
\`\`\`json
|
|
83
|
-
${JSON.stringify(i,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 a=o.map((i,c)=>{const d=i.kind==="respond"?`\u2192 ${i.status??200}${i.statusText?` ${i.statusText}`:""}`:i.kind==="fail"?`\u2192 ${i.failKind==="timeout"?"timeout":"network error"}`:"\u2192 real response";const u=[i.methods?.length?i.methods.join("/"):"any method",d,i.kind==="respond"&&i.body?`body ${i.body.length}B`:"",i.headers&&Object.keys(i.headers).length?`${Object.keys(i.headers).length} header(s)`:"",i.delayMs?`${i.delayMs}ms delay`:"",i.alternate?"every other request":"",typeof i.times==="number"?`${i.times}\xD7 then off`:"",`${i.hits} hit${i.hits===1?"":"s"}`,i.seen!=null&&i.seen!==i.hits?`${i.seen} matched`:"",i.enabled?"":"DISABLED"].filter(Boolean);return`${c+1}. \`${i.id}\`${i.name?` ${i.name}`:""}
|
|
87
|
-
\u2514\u2500 \`${i.urlPattern}\` \xB7 ${u.join(" \xB7 ")}`});return k(`**Override rules on ${r}**${wn(s)}
|
|
88
|
-
|
|
89
|
-
${a.join("\n")}
|
|
90
|
-
|
|
91
|
-
Full detail incl. body: network_override({action:"list", id:"${o[0]?.id}"}).`)}case"debug":{const s=await n.callAction(P,"debugOverrides",{url:t.url},r);if(!s){return y(`${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 y(I(r))}})}import{z as re}from"zod";var qe="sentry";var de=e=>({content:[{type:"text",text:e}]});var je=e=>({isError:true,content:[{type:"text",text:e}]});var Pe=e=>e instanceof Error?e.message:String(e);function xn(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 An(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 pt(e,n){if(n==="bytes")return An(e);if(e>=1e6)return`${(e/1e6).toFixed(1)}M`;if(e>=1e3)return`${(e/1e3).toFixed(1)}k`;return String(e)}var Zs={errors:5e3,spans:5e6,replays:50,logBytes:5*1024**3,attachmentBytes:1*1024**3};var Xs={errors:"count",spans:"count",replays:"count",logBytes:"bytes",attachmentBytes:"bytes"};function Ne(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 eo(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:re.string().optional().describe("Only envelopes containing this item type, e.g. 'event' for errors or 'transaction' for traces."),limit:re.number().optional().describe("Most-recent N envelopes. Default 25."),deviceId:re.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(qe,r);const a=o?`${o}
|
|
98
|
-
|
|
99
|
-
`:"";const i=s??{};const c=Array.isArray(i.envelopes)?i.envelopes:[];const d=t.type?c.filter(b=>b.items.some(p=>p.type===t.type)):c;const u=typeof t.limit==="number"&&t.limit>0?t.limit:25;const l=d.slice(-u);if(l.length===0){return de(`${a}No Sentry envelopes${t.type?` containing a '${t.type}' item`:""} (${c.length} captured this session).${Ne(i.status)}`)}const m=l.map(b=>{const p=b.items.map(g=>g.type).join("+");const w=b.items.reduce((g,v)=>g+(v.spanCount??0),0);const h=w>0?` \xB7 ${w} span${w===1?"":"s"}`:"";const f=`${b.id}. ${xn(b.timestamp)} [${p}] ${An(b.totalBytes)}${h}`;return`${f}
|
|
100
|
-
\u2514\u2500 ${b.items[0]?.summary??"envelope"}`});const $=`**Sentry \u2014 ${c.length} envelope${c.length===1?"":"s"} sent (showing ${l.length}${t.type?`, type '${t.type}'`:""}):**`;return de(`${a}${$}${Ne(i.status)}
|
|
101
|
-
|
|
102
|
-
${m.join("\n")}
|
|
103
|
-
|
|
104
|
-
_Full payloads (exception, breadcrumbs, contexts) via get_snapshot('sentry'). Billing units via get_sentry_cost._`)}catch(r){return je(Pe(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:re.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(qe,r);const a=o?`${o}
|
|
105
|
-
|
|
106
|
-
`:"";const i=s??{};const c=i.usage;if(!c?.session){return de(`${a}No usage is available in this capture.${Ne(i.status)}`)}const d=c.session;const u=c.projectedMonthly;const l=Object.keys(d);const m=l.map(w=>{const h=Xs[w];const f=pt(d[w],h);if(!u)return`- ${w}: ${f} this session`;const g=u[w];const v=Zs[w];const S=v>0?Math.round(g/v*100):null;const x=S===null?" (no configured reference quota)":` \u2014 ${S}% of the configured reference quota of ${pt(v,h)}`;return`- ${w}: ${f} this session \u2192 ~${pt(g,h)}/mo${x}`});const $=c.windowMs?` over ${Math.round(c.windowMs/1e3)}s`:"";const b=c.topContributors?.length?`
|
|
107
|
-
|
|
108
|
-
**What produced it:**
|
|
109
|
-
${c.topContributors.map(w=>`- ${w.label} \u2014 ${w.units} ${w.category}`).join("\n")}`:"";const p=u?"\n\n_The monthly figure extrapolates one session on one device \u2014 it catches a config that is orders of magnitude off, it is not a forecast._":"\n\n_Session too short to project a month from._";return de(`${a}**Sentry usage estimate \u2014 ${i.envelopes?.length??0} envelopes${$}:**
|
|
110
|
-
|
|
111
|
-
${m.join("\n")}${b}${p}`)}catch(r){return je(Pe(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:re.number().optional().describe("Most-recent N drop records. Default 30."),deviceId:re.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(qe,r);const a=o?`${o}
|
|
112
|
-
|
|
113
|
-
`:"";const i=s??{};const c=i.drops?.summary??[];const d=i.drops?.recent??[];if(c.length===0){return de(`${a}No drops are reported in the available capture.${Ne(i.status)}
|
|
114
|
-
|
|
115
|
-
_If an event is missing from sentry.io, check capture coverage, transport errors, the DSN/project, inbound filters and quota. Local capture does not confirm delivery._`)}const u=typeof t.limit==="number"&&t.limit>0?t.limit:30;const l=d.slice(-u);const m=c.map(b=>`- ${b.reason}: ${b.units} unit${b.units===1?"":"s"} across ${b.records} record${b.records===1?"":"s"}`);const $=l.map(b=>`${xn(b.timestamp)} [${b.reason}] ${b.category}${b.quantity>1?` \xD7${b.quantity}`:""} \u2014 ${b.detail} (${b.source})`);return de(`${a}**Sentry drops \u2014 by reason:**
|
|
116
|
-
|
|
117
|
-
${m.join("\n")}
|
|
118
|
-
|
|
119
|
-
**Recent (${l.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 je(Pe(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:re.enum(["clear"]).describe("The action to perform."),deviceId:re.string().optional().describe("Target device id (auto-selected if one is connected).")}},async t=>{try{const r=n.requireProDevice(t.deviceId);await n.callAction(qe,"clearEnvelopes",{},r);return de("Cleared the Sentry inspector \u2014 envelopes and drop records. Drive your flow, then read get_sentry_envelopes or get_sentry_cost.")}catch(r){return je(Pe(r))}})}import{z as Y}from"zod";var Tn="time-machine";function In(e){return e<1024?`${e} B`:`${(e/1024).toFixed(1)} KB`}function Dn(e){const n=Object.entries(e.results).map(([r,s])=>{const o=s.skipped.slice(0,3).map(i=>`
|
|
126
|
-
\xB7 ${i.id}: ${i.reason}`).join("");const a=s.warnings.slice(0,3).map(i=>`
|
|
127
|
-
\u26A0 ${i}`).join("");return` ${s.ok?"\u2713":"\u2715"} ${r} \u2014 applied ${s.applied}${s.skipped.length?`, skipped ${s.skipped.length}`:""}${o}${a}`});const t=e.route;if(t){n.push(t.status==="navigated"?` \u2713 route \u2014 navigated to ${t.href}`:t.status==="deferred"?` \u21BB route \u2014 ${t.href} will be opened after the reload`:` \u2715 route \u2014 ${t.error??t.status}`)}return`Restored "${e.snapshotName}" (${e.mode}${e.willReload?", app reloading":""}):
|
|
128
|
-
${n.join("\n")}`}function to(e,n){e.registerTool("get_time_machine",{description:"List the app's Time Machine state snapshots (restore points) and which state sources (storage/redux/zustand/jotai/react-query) can currently be captured/restored. Each snapshot also records the route it was captured on (shown as `route`), which a restore can navigate back to. Use time_machine_action to capture a snapshot before driving a flow, then restore supported sources to repeat the flow. Uncaptured and backend state can still differ.",inputSchema:{deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const{payload:s}=await n.getSnapshot(Tn,r);const o=s??{};const a=o.snapshots??[];const i=o.providers??[];const c=i.map(l=>{const m=l.canCapture?l.canRestore?"capture+restore":"capture only":"unavailable";return`- ${l.label} (${l.id}): ${m}${l.detail?` \u2014 ${l.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 d=a.map(l=>{const m=Object.values(l.sources).reduce((p,w)=>p+w.warnings.length,0);const $=l.baseline?"baseline: clear supported providers and request reload":`${In(l.sizeBytes)} \xB7 ${Object.keys(l.sources).join(", ")}`;const b=l.route?` \xB7 route ${l.route.href}`:"";return`- \`${l.id}\` **${l.name}** \u2014 ${new Date(l.createdAt).toISOString()} \xB7 ${$}${b}${m?` \xB7 \u26A0 ${m}`:""}`});const u=[`**Time Machine \u2014 ${a.length} snapshot(s):**`,d.length?d.join("\n"):"_none yet \u2014 capture one with time_machine_action_",`**Sources:**
|
|
129
|
-
${c.join("\n")||"_no providers registered_"}`];if(o.lastOutcome)u.push(`**Last restore:**
|
|
130
|
-
${Dn(o.lastOutcome)}`);return k(u.join("\n\n"))}catch(r){return y(I(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:Y.enum(["capture","capture_baseline","preview","restore","delete","rename"]).describe("What to do."),id:Y.string().optional().describe("Snapshot id (required for restore/delete/rename; from get_time_machine)."),name:Y.string().optional().describe("Snapshot name (for capture and rename)."),mode:Y.enum(["live","reload"]).optional().describe("Restore mode. Default 'live'."),excludeKeys:Y.array(Y.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:Y.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:Y.array(Y.string()).optional().describe("Capture/restore only these source ids (default all)."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=(o,a)=>n.callAction(Tn,o,a,r);switch(t.action){case"capture":{const o=await s("capture",{name:t.name??"",sourceIds:t.sourceIds});const a=o.snapshot;const i=Object.entries(a.sources).flatMap(([c,d])=>d.warnings.map(u=>`
|
|
131
|
-
\u26A0 ${c}: ${u}`)).join("");return k(`Captured \`${a.id}\` "${a.name}" \u2014 ${In(a.sizeBytes)} \xB7 ${Object.keys(a.sources).join(", ")}${i}`)}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 y("preview requires `id` (from get_time_machine).");const o=await s("preview",{id:t.id});const a=[];let i=0;for(const d of o.sources){const u={};for(const $ of d.items){u[$.verdict]=(u[$.verdict]??0)+1}const l=(u.added??0)+(u.removed??0)+(u.changed??0)+(u["too-large"]??0);i+=l;const m=Object.entries(u).filter(([$])=>$!=="unchanged").map(([$,b])=>`${b} ${$}`);a.push(`- **${d.label}**: ${m.length?m.join(", "):"no changes"}${d.error?` \u2014 \u26A0 ${d.error}`:""}`);for(const $ of d.items.filter(b=>b.verdict!=="unchanged").slice(0,8)){a.push(` ${$.verdict==="added"?"+":$.verdict==="removed"?"\u2212":$.verdict==="wont-apply"?"\u2298":"\u2248"} ${$.label}${$.reason?` (${$.reason})`:""}`)}for(const $ of d.notes)a.push(` \xB7 ${$}`)}const c=i===0?"**Restore would change NOTHING** (states identical or nothing applicable).":`**Restore would apply ${i} change(s):**`;return k(`${c}
|
|
132
|
-
${a.join("\n")}`)}case"restore":{if(!t.id)return y("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(Dn(o))}case"delete":{if(!t.id)return y("delete requires `id`.");await s("delete",{id:t.id});return k(`Deleted snapshot \`${t.id}\`.`)}case"rename":{if(!t.id||!t.name)return y("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 y(I(r))}})}import{z as N}from"zod";var Mn="clock";function he(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 Rn(e){const n=[e.active?`**App clock: ${e.virtualIso}** (${e.mode}${e.rate!==1?`, ${e.rate}\xD7`:""}), ${he(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: ${he(e.lastJump.byMs)}${e.lastJump.firedTimers?`, ran ${e.lastJump.firedTimers} due timer(s)`:""}`)}n.push(...no(e));n.push(`Settings: persist=${e.settings.persist} showChip=${e.settings.showChip} fireTimersOnJump=${e.settings.fireTimersOnJump}`);return n.join("\n")}function no(e){const n=e.tokens;if(!n)return[];if(!n.available)return["Sign-in tokens: unavailable (the app has no @buoy-gg/network)."];if(n.tokens.length===0)return["Sign-in tokens: none seen yet (they appear once the app sends a signed-in request)."];const t=["Sign-in tokens (read from captured requests; raw tokens are never shown):"];for(const s of n.tokens){const o=s.expiresAt!==void 0?s.expiresAt-e.virtualNow:void 0;const a=s.serverExpiresAt!==void 0?s.serverExpiresAt-e.realNow:void 0;const i=s.neverExpires?"never expires":o===void 0?"expiry unknown":o>0?`expires in ${he(o).slice(1)} on the app's clock`:`expired ${he(-o).slice(1)} ago on the app's clock`;const c=a!==void 0&&o!==void 0&&Math.abs(a-o)>2e3?a>0?`; the server accepts it for ${he(a).slice(1)} more`:"; the server no longer accepts it":"";const d=[s.hint??s.formatLabel,s.expirySource?`expiry from ${s.expirySource}`:null,s.issuedBy?`issued by ${s.issuedBy}`:null,s.claims.sub?`sub ${s.claims.sub}`:null,`${s.uses} request(s)`,s.refreshes?`${s.refreshes} refresh(es)`:null,s.expiredSends?`SENT ${s.expiredSends}\xD7 AFTER EXPIRY`:null,s.rejected?`rejected ${s.rejected}\xD7`:null,s.looping?`REFRESH LOOP (${s.recentRefreshes} new tokens in 20s)`:null].filter(Boolean);t.push(`- [${s.id}] ${s.label} \u2192 ${s.host}: ${i}${c} (${d.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 ${he(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 (${he(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 ro(e,n){e.registerTool("get_clock",{description:"Read the app's clock as the Clock tool (@buoy-gg/clock) sees it: the time the app reads now, whether it is overridden (running, frozen or sped up), how far it is from real time, and the pending app timers a jump ahead could run. Also lists the app's sign-in tokens seen in its traffic (JWT, PASETO, opaque tokens with an expiry from the login response, session cookies): time left on the app's clock and the server's, who issued them, refreshes, sends after expiry, refresh loops, and the result of a running refresh check. Check this before calling a date, countdown, expiry or sign-out a bug.",inputSchema:{deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=await n.callAction(Mn,"getState",{},r);return k(Rn(s))}catch(r){return y(I(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:N.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:N.union([N.string(),N.number()]).optional().describe("set_time (required) / freeze (optional): target time."),by:N.union([N.string(),N.number()]).optional().describe("shift (required): signed duration like '+1d', '-2h30m', '90s', or ms."),freeze:N.boolean().optional().describe("set_time: stop the clock at `time`. Default false."),fireTimers:N.boolean().optional().describe("shift: run app timers that come due inside a forward jump. Default on."),rate:N.number().optional().describe("set_rate (required): speed multiplier, 0.1-86400; 1 is normal."),persist:N.boolean().optional().describe("settings: keep the override across reloads."),showChip:N.boolean().optional().describe("settings: show the floating clock chip while overridden."),fireTimersOnJump:N.boolean().optional().describe("settings: default for shift's fireTimers."),token:N.string().optional().describe("jump_to_token_expiry / fail_next_request: token id from get_clock. Default: the most recently used token."),leadMs:N.number().optional().describe("jump_to_token_expiry: land this many ms before expiry. Default 10000."),status:N.number().optional().describe("fail_next_request: 401 (default) or 403."),times:N.number().optional().describe("fail_next_request: how many requests to fail, 1-10. Default 1."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=(a,i={})=>n.callAction(Mn,a,i,r);let o;switch(t.action){case"set_time":if(t.time===void 0)return y("set_time requires `time`.");o=await s("setTime",{time:t.time,freeze:t.freeze??false});break;case"shift":if(t.by===void 0)return y("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 y("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(Rn(o))}catch(r){return y(I(r))}})}import{z as _}from"zod";var On="scenarios";var pe=e=>({content:[{type:"text",text:e}]});var V=e=>({isError:true,content:[{type:"text",text:e}]});var Cn=e=>e instanceof Error?e.message:String(e);function so(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 Le(e){const n=e.vars?.length?`
|
|
133
|
-
variables: ${e.vars.map(so).join("; ")}`:"";const t=e.stepLines?.length?`
|
|
134
|
-
${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?`
|
|
135
|
-
expected: ${e.expectedOutcome}`:"";return`- \`${e.id}\` **${e.name}** \u2014 ${r}${n}${s}${t}`}function Fn(e,n,t){if(!n.length)return`**${e} (0):**
|
|
136
|
-
_none_`;if(!t.length){return`**${e} (${n.length}):**
|
|
137
|
-
${n.map(Le).join("\n")}`}const r=[`**${e} (${n.length}):**`];for(const o of t){const a=n.filter(i=>(i.folder??"").toLowerCase()===o.toLowerCase());if(!a.length)continue;r.push(`_${o} (${a.length})_
|
|
138
|
-
${a.map(Le).join("\n")}`)}const s=n.filter(o=>!o.folder);if(s.length){r.push(`_Ungrouped (${s.length})_
|
|
139
|
-
${s.map(Le).join("\n")}`)}return r.join("\n")}function oo(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:
|
|
140
|
-
${e.effects.map(t=>` \xB7 ${t.label} [${t.kind}]`).join("\n")}`].filter(Boolean).join("\n")}function ao(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(On,r);const o=s??{};const a=o.code??[];const i=o.device??[];const c=o.drafts??[];const d=o.folders??[];const u=[];u.push(o.active?`\u26A0\uFE0F **SIMULATED \u2014 a scenario is active.** The app is showing bent state right now.
|
|
141
|
-
${oo(o.active)}`:"**No scenario active** \u2014 the app is showing real data.");if(d.length){u.push(`**Folders:** ${d.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.`)}u.push(Fn("Shipped with this app",a,d));u.push(Fn("Saved on this device",i,d));if(c.length){u.push(`**Drafts awaiting review on the device (${c.length}):** these are INERT and cannot run until a human accepts them on the device.
|
|
142
|
-
${c.map(Le).join("\n")}`)}return pe(u.join("\n\n"))}catch(r){return V(Cn(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,a)=>n.callAction(On,o,a,r);switch(t.action){case"preview":{if(!t.id)return V("preview requires `id` (from get_scenarios).");const o=await s("preview",{id:t.id,params:t.params??{}});const a=[`**Dry run \u2014 \`${t.id}\`** (nothing has been changed)`,`variables: ${Object.entries(o.values).map(([i,c])=>`${i}=${String(c)}`).join(", ")||"none"}`,`**Would do:**
|
|
143
|
-
${o.willDo.map(i=>` \xB7 ${i.label} [${i.durability}]`).join("\n")}`];if(o.expectedOutcome)a.push(`**Expected outcome:** ${o.expectedOutcome}`);if(o.conflict){a.push(`\u26A0\uFE0F **Conflict:** "${o.conflict.activeName}" is active and touches the same target(s): ${o.conflict.overlaps.join(", ")}. Running will SWAP \u2014 it deactivates first.`)}if(o.warnings?.length)a.push(`**Warnings:**
|
|
144
|
-
${o.warnings.map(i=>` \xB7 ${i}`).join("\n")}`);a.push(o.ok?"Pre-flight checks passed. Review the intended effects before running.":`\u274C **Cannot run:**
|
|
145
|
-
${o.errors.map(i=>` \xB7 ${i}`).join("\n")}`);return pe(a.join("\n\n"))}case"run":{if(!t.id)return V("run requires `id` (from get_scenarios).");const o=await s("run",{id:t.id,params:t.params??{}});if(o.preflightErrors?.length){return V(`Pre-flight refused to run \`${t.id}\` \u2014 nothing was changed:
|
|
146
|
-
${o.preflightErrors.map(i=>` \xB7 ${i}`).join("\n")}`)}const a=(o.steps??[]).map(i=>{const c=i.skipped?"\u2013":i.ok?"\u2713":"\u2717";const d=i.error?`
|
|
147
|
-
${i.error}`:"";return` ${c} ${i.label} (${i.ms}ms)${d}`}).join("\n");if(!o.ok){return V(`Run FAILED \u2014 it stopped at the failing step and nothing after it ran. The steps before it DID apply:
|
|
148
|
-
${a}
|
|
149
|
-
|
|
150
|
-
The device is now in a partial state. Deactivate to reverse what landed, or fix the step and run again.`)}return pe([`\u2705 **Scenario active \u2014 ${o.name??t.id}**`,a,`**Reported effects:**
|
|
151
|
-
${(o.effects??[]).map(i=>` \xB7 ${i.label} [${i.kind}]`).join("\n")}`,"The device shows a SIMULATED banner while this is active. Deactivate when done, and account for these effects when interpreting observations."].join("\n\n"))}case"deactivate":{const o=await s("deactivate",{});const a=o.report;const i=[`Removed ${a.removedRules} override rule(s)`,a.stoppedImpersonation?"Ended impersonation":null,a.undoStepsRan?`Ran ${a.undoStepsRan} undo step(s)`:null].filter(Boolean);const c=a.unrestoredStorageKeys.length?`
|
|
152
|
-
|
|
153
|
-
\u26A0\uFE0F **NOT restored:** ${a.unrestoredStorageKeys.join(", ")} \u2014 a storage write has no automatic inverse. The app still holds these values.`:"";const d=a.errors.length?`
|
|
154
|
-
|
|
155
|
-
Errors: ${a.errors.join("; ")}`:"";return pe(`**Deactivated.**
|
|
156
|
-
${i.map(u=>` \xB7 ${u}`).join("\n")}${c}${d}`)}case"save":{if(!t.scenario)return V("save requires `scenario`.");const o=await s("save",{scenario:t.scenario});if(!o.ok){return V(`Save rejected:
|
|
157
|
-
${(o.errors??[o.error??"unknown error"]).map(a=>` \xB7 ${a}`).join("\n")}`)}return pe(`Saved \`${o.id}\` **as a draft**.
|
|
158
|
-
|
|
159
|
-
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 V("setFolder requires `id` (from get_scenarios).");const o=await s("setFolder",{id:t.id,folder:t.folder});return pe(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 V("delete requires `id`.");await s("delete",{id:t.id});return pe(`Deleted \`${t.id}\` from the device library.`)}}}catch(r){return V(Cn(r))}})}import{z as Q}from"zod";import{execFile as io}from"child_process";import{promisify as co}from"util";import{existsSync as En,readFileSync as lo}from"fs";import mt from"os";import ye from"path";var uo=co(io);function ho(){const e=process.env.BUOY_SIMCAM_DIR;const n=[...e?[ye.join(e,"buoycam")]:[],"/Applications/Buoy.app/Contents/Resources/simcam/buoycam",ye.join(mt.homedir(),"Applications/Buoy.app/Contents/Resources/simcam/buoycam")];let t=__dirname;for(let r=0;r<8;r++){n.push(ye.join(t,"apps/desktop/resources/simcam/buoycam"));const s=ye.dirname(t);if(s===t)break;t=s}return n}var Ue=null;function po(){if(Ue)return Ue;Ue=ho().find(e=>En(e))??null;return Ue}async function K(e){const n=po();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 uo(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 mo(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 fo(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 go(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 vo(){const e=process.env.BUOY_ENTITLEMENT_FILE;if(e)return[e];return[ye.join(mt.homedir(),"Library/Application Support/Buoy/entitlement.json"),ye.join(mt.homedir(),"Library/Application Support/buoy-desktop/entitlement.json")]}function Bn(){for(const e of vo()){try{if(!En(e))continue;const n=JSON.parse(lo(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 wo(e){return`\`${e}\` is a Buoy Pro feature.
|
|
160
|
-
|
|
161
|
-
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.
|
|
162
|
-
|
|
163
|
-
_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 L=e=>({content:[{type:"text",text:e}]});var me=e=>Bn().isPro?null:Z(wo(e));var Z=e=>({isError:true,content:[{type:"text",text:e}]});function bo(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:Q.enum(["barcode","image","video","camera","screen","pattern"]).describe("What the camera should show."),value:Q.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:Q.enum(["qr","pdf417","aztec","code128"]).optional().describe("Barcode symbology; defaults to qr.")}},async n=>{const t=me("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 K(r);if(!s.ok){return Z(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 L(`The simulator camera is now showing ${o}, at ${s.data?.fps??0} fps.
|
|
164
|
-
|
|
165
|
-
_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=me("camera_status");if(n)return n;const t=await K(["status"]);if(!t.ok||!t.data){return Z(t.error??"could not read the simulator camera status")}const{publishing:r,fps:s,codes:o}=t.data;if(!r){return L("The simulator camera is not publishing anything.\n\n_Set a source with `camera_source` first._")}return L([`Publishing at ${s} fps.`,o.length?`Currently decoding: ${o.map(a=>`\`${a}\``).join(", ")}`:"No barcode in the current frame.","","_A code shown here is what the app receives. If the app is not reacting to it, the problem is in the app, not the camera \u2014 `camera_diagnose` will say whether the app is even reading the feed._"].join("\n"))});e.registerTool("camera_launch",{description:"Relaunch a simulator app with the camera attached. A camera can only be attached when a process starts, so an app that is already running cannot be given one \u2014 this terminates and relaunches it.",inputSchema:{bundleId:Q.string().describe("The app's bundle identifier."),udid:Q.string().optional().describe("Simulator udid, if more than one is booted.")}},async n=>{const t=me("camera_launch");if(t)return t;const r=["launch",n.bundleId];if(n.udid)r.push("--udid",n.udid);const s=await K(r);if(!s.ok){return Z(s.error??s.data?.error??"could not launch the app")}return L(`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:Q.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 K(t);if(!r.data?.checks){return Z(r.error??"could not run the simulator camera diagnosis")}const s=Bn();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 L(mo(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=me("camera_stop");if(n)return n;const t=await K(["stop"]);if(!t.ok){return Z(t.error??t.data?.error??"could not stop the camera")}return L("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:Q.string().optional().describe("Which simulator's apps to list. Only needed when several are booted.")}},async n=>{const t=me("camera_devices");if(t)return t;const r=await K(["devices"]);if(!r.ok||!r.data){return Z(r.error??"could not list booted simulators")}const s=r.data.devices??[];let o=null;if(s.length===1||n.udid){const a=await K(["apps",...n.udid?["--udid",n.udid]:[]]);o=a.ok?a.data?.apps??[]:null}return L(fo(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=me("camera_inputs");if(n)return n;const[t,r]=await Promise.all([K(["cameras"]),K(["windows"])]);if(!t.ok&&!r.ok){return Z(t.error??r.error??"could not list the Mac's cameras or windows")}return L(go(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:Q.enum(["on","off","status"]).describe("Turn it on, off, or report the current state."),udid:Q.string().optional().describe("Which simulator. Only needed when several are booted.")}},async n=>{const t=me("camera_zero_setup");if(t)return t;const r=await K(["zero-setup",n.action,...n.udid?["--udid",n.udid]:[]]);if(!r.ok){return Z(r.error??r.data?.error??"could not change zero-setup mode")}const s=r.data??{};if(n.action==="status"){if(!s.enabled)return L("Zero-setup mode is **off**.");return L(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 L("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 L("Zero-setup mode is **off**.")})}import{z as U}from"zod";var qn="highlight-updates";var ft=e=>({content:[{type:"text",text:e}]});var ze=e=>({isError:true,content:[{type:"text",text:e}]});var jn=e=>e instanceof Error?e.message:String(e);function yo(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 gt=0;var Pn=3;var $o="\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 ko(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:U.boolean().optional().describe("Only return tappable (onPress) elements. Default false (include labels/text for context)."),includeBuoy:U.boolean().optional().describe("Also list Buoy's own overlay \u2014 the dial, tool sheets, Ask Buoy's chat. Default false: the screen described is the app's. Exact testIDs inside Buoy (buoy-\u2026) can still be tapped without this."),deviceId:A}},async t=>{try{const r=n.requireProDevice(t.deviceId);const s=await n.callAction(qn,"describeScreen",{includeBuoy:t.includeBuoy},r);const o=s?.elements??[];const a=t.interactiveOnly?o.filter(d=>d.interactive):o;if(a.length===0){return ft("No elements found on screen. If the app just navigated, wait a moment and retry; make sure highlight-updates is enabled in the app.")}const i=s.hiddenBuoy?` Buoy's own overlay (${s.hiddenBuoy} element${s.hiddenBuoy===1?"":"s"}) is left out \u2014 pass includeBuoy:true to see it.`:"";const c=`Screen ${s.screen.width}\xD7${s.screen.height} \u2014 ${a.length} element${a.length===1?"":"s"} (\u2022 = tappable). Tap with tap_element({ testID | query | nativeTag }).${i}`;return ft(`${c}
|
|
166
|
-
|
|
167
|
-
${a.map(yo).join("\n")}`)}catch(r){return ze(jn(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:U.number().optional().describe("Exact nativeTag from describe_screen (most precise)."),testID:U.string().optional().describe("Exact testID of the element."),query:U.string().optional().describe('Fuzzy match against testID / label / visible text / component name \u2014 e.g. "Sign in".'),value:U.union([U.number(),U.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:U.string().optional().describe("For a text input: the string to set via onChangeText."),longPress:U.boolean().optional().describe("Invoke the element's onLongPress instead of onPress. Fails with a clear reason if the element has no onLongPress handler."),scrollIntoView:U.boolean().optional().describe("Attempt to scroll an off-screen target into view. Default true; inspect the action result."),includeBuoy:U.boolean().optional().describe("Let a fuzzy `query` match Buoy's own overlay. Default false \u2014 an exact nativeTag/testID always may."),deviceId:A}},async t=>{try{if(t.nativeTag==null&&!t.testID&&!t.query){return ze("Provide one of: nativeTag, testID, or query (from describe_screen).")}const r=n.requireProDevice(t.deviceId);const s=await n.callAction(qn,"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);gt+=1;const o=gt>=Pn&>%Pn===0?$o:"";if(s?.tapped&&s.matched){const i=s.matched;const c=i.text??i.label??i.name;const d=i.testID?` [testID=${i.testID}]`:i.nativeTag!=null?` #${i.nativeTag}`:"";const u=s.scrolled?" (scrolled into view)":"";const l=i.via==="onValueChange"?`Set "${c}"${d} \u2192 ${JSON.stringify(i.value)}`:i.via==="onChangeText"?`Typed ${JSON.stringify(i.value)} into "${c}"${d}`:i.via==="onLongPress"?`Long-pressed "${c}"${d}`:`Tapped "${c}"${d}`;const m=s.effect;const $=!m?"":m.commits>0?` ${m.commits} re-render${m.commits===1?"":"s"} followed.`:` No re-render followed within ${m.observedMs}ms \u2014 the handler ran but the app did not react. The element may sit on a screen beneath the current one, or be inert; do not treat this as done.`;const b=s.alsoMatched?.length?`
|
|
168
|
-
Also matched equally well (the choice was a coin toss \u2014 re-tap by #nativeTag if this was wrong):
|
|
169
|
-
`+s.alsoMatched.map(p=>`- ${p.name}${p.text?` "${p.text}"`:""}${p.testID?` [testID=${p.testID}]`:""}${p.nativeTag!=null?` #${p.nativeTag}`:""}`).join("\n"):"";return ft(`${l}${u}.${$}${b}${o}`)}let a=s?.reason??"Tap failed.";if(s?.candidates?.length){a+="\n\nTappable candidates:\n"+s.candidates.map(i=>`- ${i.name}${i.text?` "${i.text}"`:""}${i.testID?` [testID=${i.testID}]`:""}${i.nativeTag!=null?` #${i.nativeTag}`:""}`).join("\n")}return ze(a)}catch(r){return ze(jn(r))}})}import{z as vt}from"zod";var wt="js-top";var _o="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function So(e){const n=Math.max(1,...e);return e.map(t=>_o[Math.min(7,Math.floor(t/n*7.999))]).join("")}function xo(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 Ao(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): \`${So(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 To(e,n){e.registerTool("get_js_thread_top",{description:"Sample instrumented JavaScript task origins and return available timing, busy percentage and freeze attribution. Coverage depends on installed hooks; unattributed work can remain. Requires @buoy-gg/js-top and Buoy Pro. The call waits for the sample: arrange the interaction during that window using an available concurrent driver or a person, rather than starting it after this call returns. clearFirst resets tracked statistics before sampling. Use get_js_thread_origin_detail for a returned row key and measure_renders for component render diagnostics.",inputSchema:{deviceId:A,durationMs:vt.number().optional().describe("How long to sample before reading the table. Default 3000; clamped to 250\u201330000."),clearFirst:vt.boolean().optional().describe("Reset tracked statistics before sampling. Hook coverage and attribution limits still apply.")}},async({deviceId:t,durationMs:r,clearFirst:s})=>{try{const o=n.requireProDevice(t);const a=Math.min(Math.max(r??3e3,250),3e4);const i=await n.callAction(wt,"sample",{durationMs:a,clearFirst:s===true},o);if(!i)return y("Device returned no snapshot \u2014 is @buoy-gg/js-top installed in the app?");const c=xo(i,a);const d={busyPct:Math.round(i.busyPct*10)/10,freezeSummary:i.freezeSummary,tiers:i.tiers,rows:i.rows.slice(0,15).map(u=>({key:u.key,api:u.api,windowMs:Math.round(u.windowMs*10)/10,pctOfBusy:Math.round(u.pctOfBusy*10)/10,calls:u.calls,avgMs:Math.round(u.avgMs*100)/100,maxMs:Math.round(u.maxMs*10)/10,totalMs:Math.round(u.totalMs),freezes:u.freezes,worstFreezeMs:u.worstFreezeMs}))};return k(`${c}
|
|
170
|
-
|
|
171
|
-
\`\`\`json
|
|
172
|
-
${JSON.stringify(d)}
|
|
173
|
-
\`\`\``)}catch(o){return y(I(o))}});e.registerTool("get_js_thread_origin_detail",{description:'Inspect one js-top task origin in depth: schedules vs runs, avg/max/total exclusive ms, a 5s activity sparkline, freeze attribution, and the captured scheduling site (caller function + stack frames). Pass a row `key` from get_js_thread_top\'s JSON (e.g. "interval|pollFeed" or "unattributed" for the system row).',inputSchema:{deviceId:A,key:vt.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(wt,"getOriginDetail",{key:r},s);if(!o){return y(`Origin "${r}" is not tracked (cleared, evicted, or never existed). Re-run get_js_thread_top for current keys.`)}const a=Ao(o);return k(`${a}
|
|
174
|
-
|
|
175
|
-
\`\`\`json
|
|
176
|
-
${JSON.stringify(o)}
|
|
177
|
-
\`\`\``)}catch(s){return y(I(s))}});e.registerTool("clear_js_thread_stats",{description:"Reset the js-top task table, freeze history, and busy history on the device (fresh measurement window).",inputSchema:{deviceId:A}},async({deviceId:t})=>{try{const r=n.requireProDevice(t);await n.callAction(wt,"clear",{},r);return k("Cleared js-top stats.")}catch(r){return y(I(r))}})}import{z as H}from"zod";var X="images";function Nn(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 Io(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 Ln(e){if(e.cache)return e.cache;if(e.progressSeen)return"network";return"?"}function Un(e){return`${(e/(1024*1024)).toFixed(1)}MB`}function Do(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${Un(r.estDecodedBytes)} decoded`+(r.estWastedBytes>0?` \xB7 **${Un(r.estWastedBytes)} wasted on oversized sources**`:""));const s=e.insights;if(s){const a=[];if(s.duplicates.length>0)a.push(`${s.duplicates.length} duplicate URL(s): ${s.duplicates.slice(0,3).map(i=>`${Nn(i.uri)}\xD7${i.count}`).join(", ")}`);if(s.retryStorms.length>0)a.push(`${s.retryStorms.length} retry storm(s): ${s.retryStorms.slice(0,3).map(i=>`#${i.id}(${i.loadCount} loads)`).join(", ")}`);if(s.queueSaturated)a.push("iOS image queue saturated (>4 concurrent loads)");if(s.missingAlt>0)a.push(`${s.missingAlt} image(s) missing alt/accessibilityLabel`);if(s.layoutShifters.length>0)a.push(`${s.layoutShifters.length} layout-shifting image(s): ${s.layoutShifters.slice(0,3).map(i=>`#${i.id}`).join(", ")} \u2014 reserve explicit dimensions`);if(a.length>0){t.push("");t.push(`**Insights:** ${a.join(" \xB7 ")}`)}}const o=e.captureStatus;if(o.rnDecoratorTooLate){t.push("");t.push('\u26A0 RN <Image> capture missed the module-load race \u2014 add `import "@buoy-gg/images/register"` as the FIRST import of the app entry file.')}if(e.globalModes.network!=="normal"||e.globalModes.blank){t.push("");t.push(`\u26A0 Simulation active: network=${e.globalModes.network}${e.globalModes.blank?", blank images ON":""} (set_image_simulation to reset).`)}t.push("");t.push("| id | image | lib | status | cache | ms | decoded px | shown dp | verdict | sim |");t.push("|---|---|---|---|---|---|---|---|---|---|");for(const a of e.records){const i=a.intrinsic?`${a.intrinsic.width}\xD7${a.intrinsic.height}`:"\u2013";const c=a.layout?`${a.layout.width}\xD7${a.layout.height}`:"\u2013";const d=a.status==="error"?`**error**${a.errorCode?` (${a.errorCode})`:""}`:a.status;t.push(`| ${a.id} | ${Nn(a.uri)} | ${a.lib} | ${d}${a.mounted?"":" (unmounted)"} | ${Ln(a)} | ${a.ms??"\u2013"} | ${i} | ${c} | ${Io(a)} | ${a.overrideLabel??"\u2013"} |`)}t.push("");t.push("_Act on a row with `image_action` using its `id` (hard_reload / retry / force_error / force_loading / force_blank / swap_url / flash / restore / evict_disk)._");return t.join("\n")}var Mo={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 Ro(e,n){e.registerTool("get_images",{description:"Inspect image loads reported through the Buoy image integration, including available cache origin, load timing, size estimates, errors and simulation overrides. Coverage depends on instrumented components and platform support. Requires @buoy-gg/images on the device.",inputSchema:{deviceId:A,limit:H.number().optional().describe("Max records to return (newest first). Default 30, max 200."),status:H.enum(["pending","loading","loaded","error"]).optional().describe("Only records in this state (e.g. 'error' for the failure log).")}},async({deviceId:t,limit:r,status:s})=>{try{const o=n.requireProDevice(t);const a=Math.min(Math.max(r??30,1),200);const i=await n.callAction(X,"list",{limit:a,status:s},o);if(!i)return y("Device returned nothing \u2014 is @buoy-gg/images installed in the app?");const c=Do(i,a);const d={stats:i.stats,insights:i.insights,captureStatus:i.captureStatus,globalModes:i.globalModes,records:i.records.map(u=>({id:u.id,uri:u.uri,lib:u.lib,status:u.status,mounted:u.mounted,cache:u.cache,ms:u.ms,intrinsic:u.intrinsic,layout:u.layout,oversizeFactor:u.oversizeFactor,wastedKB:u.wastedKB,error:u.error,errorCode:u.errorCode,overrideLabel:u.overrideLabel,loadCount:u.loadCount,hasAltText:u.hasAltText,layoutShifts:u.layoutShifts}))};return k(`${c}
|
|
178
|
-
|
|
179
|
-
\`\`\`json
|
|
180
|
-
${JSON.stringify(d)}
|
|
181
|
-
\`\`\``)}catch(o){return y(I(o))}});e.registerTool("image_action",{description:"Request an action for a registered image ID: hard_reload, retry, evict_disk, flash, prove_savings or a supported simulation override. swap_url requires url; restore removes the override. Support depends on the component and platform. prove_savings attempts a WebP conversion at displayed size and reports available byte comparisons and a device-local URI; inspect visual quality and originalBytesSource before using the result. Other actions return an acknowledgement and, when available, a later record snapshot; that snapshot may precede load completion. A device-local URI is not necessarily accessible from the editor host.",inputSchema:{deviceId:A,id:H.number().describe("Record id from get_images."),action:H.enum(["hard_reload","retry","evict_disk","flash","prove_savings","force_error","force_loading","force_blank","swap_url","restore"]).describe("What to do."),url:H.string().optional().describe("Replacement URL (swap_url only).")}},async({deviceId:t,id:r,action:s,url:o})=>{try{const a=n.requireProDevice(t);if(s==="prove_savings"){const m=await n.callAction(X,"proveSavings",{id:r},a);if(!m)return y("Device returned nothing for proveSavings.");if(!m.ok)return y(m.message);const $=[`**prove_savings** on #${r}: ${m.message}`];if(m.originalBytes!=null)$.push(`Original: ${Math.round(m.originalBytes/1024)}KB (${m.originalBytesSource})`);if(m.optimizedBytes!=null)$.push(`Optimized: ${Math.round(m.optimizedBytes/1024)}KB \u2014 ${m.optimizedDims?.width}\xD7${m.optimizedDims?.height} WebP`);if(m.savedBytes!=null)$.push(`**Saved: ${Math.round(m.savedBytes/1024)}KB (${m.savedPct}%)**`);if(m.optimizedUri)$.push(`Preview in place: image_action {id:${r}, action:"swap_url", url:"${m.optimizedUri}"}`);return k($.join("\n"))}const i=Mo[s];if(!i)return y(`Unknown action: ${s}`);if(s==="swap_url"&&!o)return y("swap_url requires the `url` param.");const c=await n.callAction(X,i.action,{id:r,...i.params?.(o)??{}},a);const d=s==="flash"?0:1500;if(d>0)await new Promise(m=>setTimeout(m,d));const u=await n.callAction(X,"getDetail",{id:r},a).catch(()=>null);const l=[`**${s}** on #${r}: ${c?.message??(c?.ok===false?"failed":"done")}`];if(u){l.push("");l.push(`Now: status=${u.status}${u.errorCode?` (${u.errorCode})`:""} \xB7 cache=${Ln(u)} \xB7 ms=${u.ms??"\u2013"} \xB7 loads=${u.loadCount}${u.overrideLabel?` \xB7 sim="${u.overrideLabel}"`:""}${u.mounted?"":" \xB7 UNMOUNTED"}`);if(u.error)l.push(`Error: ${u.error}`)}return k(l.join("\n"))}catch(a){return y(I(a))}});e.registerTool("set_image_simulation",{description:"Configure supported instrumented image loads: offline simulates network-load failures while bundled assets can still load; cold requests cache bypass; normal resets the network mode. Reload or remount existing images as needed. blankImages removes sources from integrated images; massAction targets registered mounted images. Can also clear the registry or supported Expo caches. These modes do not change device connectivity.",inputSchema:{deviceId:A,network:H.enum(["normal","offline","cold"]).optional().describe("Network simulation mode."),blankImages:H.boolean().optional().describe("Render integrated images without a source."),massAction:H.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:H.boolean().optional().describe("Clear the captured image log."),clearExpoCaches:H.boolean().optional().describe("Clear expo-image memory + disk caches.")}},async({deviceId:t,network:r,blankImages:s,massAction:o,clearRegistry:a,clearExpoCaches:i})=>{try{const c=n.requireProDevice(t);const d=[];if(o){const u=await n.callAction(X,"massAction",{kind:o},c);d.push(u?.message??`mass ${o} applied`)}if(r){await n.callAction(X,"setNetworkMode",{mode:r},c);d.push(`network=${r}`)}if(s!=null){await n.callAction(X,"setBlankImages",{enabled:s},c);d.push(`blankImages=${s}`)}if(a){await n.callAction(X,"clearRecords",{},c);d.push("registry cleared")}if(i){const u=await n.callAction(X,"clearExpoCaches",{},c);d.push(u?.message??"expo caches cleared")}if(d.length===0)return y("Pass at least one of: network, blankImages, massAction, clearRegistry, clearExpoCaches.");return k(`Applied: ${d.join(" \xB7 ")}`)}catch(c){return y(I(c))}})}import{z as Ae}from"zod";function Oo(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 fe="assets";function se(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 zn(e){if(e.sizeBytes==null)return"\u2013";return e.sizeSource==="measured"?se(e.sizeBytes):`~${se(e.sizeBytes)}`}function Jn(e){if(!e.length)return"\u2013";return e.map(n=>`@${n}x`).join(" ")}function Co(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 Fo(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(([,u])=>u.count>0).map(([u,l])=>`${l.count} ${u}${l.bytes>0?` (${se(l.bytes)})`:""}`);t.push(`${r.loaded} loaded \xB7 ${r.neverLoaded} never loaded \xB7 `+(r.totalBytes>0?`${se(r.totalBytes)} measured (${r.measuredCount}/${r.total})`:"sizes not measured")+` \xB7 ${o.join(" \xB7 ")}`);if(s.fontFamilies.length>0){t.push(`Loaded font families: ${s.fontFamilies.join(", ")}`)}const a=Oo(s);if(a)t.push(a);if(s.measuring)t.push("\u26A0 Size measurement in progress \u2014 byte totals are partial; re-run get_assets shortly.");const i=e.insights;const c=[];if(i.neverLoaded.length)c.push(`${i.neverLoaded.length} never loaded`);if(i.duplicates.length){const u=i.duplicates.reduce((l,m)=>l+(m.wastedBytes??0),0);c.push(`${i.duplicates.length} duplicate group(s)${u>0?` (${se(u)} wasted)`:""}`)}if(i.overDecode.length)c.push(`${i.overDecode.length} decode larger than 2\xD7 the screen`);if(i.webpCandidates.length)c.push(`${i.webpCandidates.length} WebP candidate(s)`);if(i.heavyGifs.length)c.push(`${i.heavyGifs.length} heavy GIF(s)`);if(i.heavyFonts.length)c.push(`${i.heavyFonts.length} heavy font(s)`);if(i.scaleGaps.length)c.push(`${i.scaleGaps.length} scale gap(s)`);if(i.scaleAnomalies.length)c.push(`${i.scaleAnomalies.length} scale anomaly(ies)`);if(c.length){t.push("");t.push(`**Findings:** ${c.join(" \xB7 ")}`)}const d=e.diff;if(d){const u=d.netBytes==null?"net unknown":Math.abs(d.netBytes)<1024?"\xB10 net":`${d.netBytes>=0?"+":"\u2212"}${se(Math.abs(d.netBytes))} net`;t.push("");t.push(`**Since baseline** (${new Date(d.baselineSavedAt).toISOString()}): ${d.added.length} added \xB7 ${d.removed.length} removed \xB7 ${d.grown.length} grew \xB7 ${u}`+(d.removed.length?` \u2014 removed: ${d.removed.slice(0,5).map(l=>`${l.name}.${l.type}`).join(", ")}${d.removed.length>5?"\u2026":""}`:""))}t.push("");t.push("| id | asset | kind | dims | scales | size | flags |");t.push("|---|---|---|---|---|---|---|");for(const u of e.records){const l=u.width!=null&&u.height!=null?`${Math.round(u.width)}\xD7${Math.round(u.height)}`:"\u2013";t.push(`| ${u.id} | ${u.name}.${u.type} | ${u.kind} | ${l} | ${Jn(u.scales)} | ${zn(u)} | ${Co(u,i)} |`)}t.push("");t.push("_Sizes marked ~ are decoded-memory estimates (unmeasurable in this environment). Use `asset_action` for rescan / measure_sizes / detail / baseline ops._");return t.join("\n")}function Eo(e,n){e.registerTool("get_assets",{description:"Inspect assets reported by the configured manifest, runtime registry and available Metro bundle graph. Includes available dimensions, scale coverage, byte sizes, observed load history, audit findings and saved-baseline differences. Size measurement and coverage depend on setup; not observed loading does not mean unused. Use get_images for instrumented runtime image loads. Requires @buoy-gg/assets on the device.",inputSchema:{deviceId:A,limit:Ae.number().optional().describe("Max records to return (largest first). Default 40, max 500."),kind:Ae.enum(["image","font","video","audio","data","other"]).optional().describe("Only assets of this kind."),unusedOnly:Ae.boolean().optional().describe("Only assets shipped in the bundle but never loaded at runtime.")}},async({deviceId:t,limit:r,kind:s,unusedOnly:o})=>{try{const a=n.requireProDevice(t);const i=Math.min(Math.max(r??40,1),500);const c=await n.callAction(fe,"list",{limit:o?500:i,kind:s,loadedOnly:false},a);if(!c)return y("Device returned nothing \u2014 is @buoy-gg/assets installed in the app?");if(o){c.records=c.records.filter(l=>!l.loaded).slice(0,i)}const d=Fo(c,i);const u={stats:c.stats,scanStatus:c.scanStatus,insights:c.insights,diff:c.diff,records:c.records.map(l=>({id:l.id,name:l.name,type:l.type,kind:l.kind,hash:l.hash,width:l.width,height:l.height,scales:l.scales,loaded:l.loaded,sizeBytes:l.sizeBytes,sizeSource:l.sizeSource}))};return k(`${d}
|
|
182
|
-
|
|
183
|
-
\`\`\`json
|
|
184
|
-
${JSON.stringify(u)}
|
|
185
|
-
\`\`\``)}catch(a){return y(I(a))}});e.registerTool("asset_action",{description:"Drive the assets tool: rescan (re-walk the registry + merge the Metro bundle graph + refresh fonts + measure sizes \u2014 run this first if the inventory looks stale or empty), measure_sizes (re-measure byte sizes only), detail (full metadata for one asset by id: source dir, per-scale sizes, resolved URI, per-file graph paths), save_baseline (persist the current inventory for before/after comparison \u2014 save, make your change, then get_assets shows added/removed/grown/net bytes), clear_baseline, clear_records (wipe + rescan rebuilds).",inputSchema:{deviceId:A,action:Ae.enum(["rescan","measure_sizes","detail","save_baseline","clear_baseline","clear_records"]).describe("What to do."),id:Ae.number().optional().describe("Asset id from get_assets (detail only).")}},async({deviceId:t,action:r,id:s})=>{try{const o=n.requireProDevice(t);switch(r){case"rescan":{const a=await n.callAction(fe,"rescan",{},o);const i=a?.scanStatus;if(!i)return y("Device returned nothing for rescan.");return k(`Rescan done: ${i.registryCount} registered at runtime`+(i.graphCount!=null?` \xB7 ${i.graphCount} in the bundle graph`:" \xB7 no bundle graph")+(i.graphError?` (graph: ${i.graphError})`:"")+` \xB7 ${i.fontFamilies.length} font families`+(i.measuring?" \xB7 size measurement running \u2014 get_assets in a moment":""))}case"measure_sizes":{const a=await n.callAction(fe,"measureSizes",{},o);return k(`Measured ${a?.measured??0} of ${a?.total??0} assets.`)}case"detail":{if(s==null)return y("detail requires the `id` param (from get_assets).");const a=await n.callAction(fe,"getDetail",{id:s},o);if(!a)return y(`Asset ${s} not found \u2014 re-run get_assets for current ids.`);const i=[`## ${a.name}.${a.type} (#${a.id})`,"",`- Kind: ${a.kind} \xB7 ${a.loaded?"loaded at runtime":"in bundle, NEVER loaded"} (${a.origin})`];if(a.width!=null)i.push(`- Dimensions: ${a.width}\xD7${a.height} logical \xB7 scales ${Jn(a.scales)}`);if(a.sizesByScale){for(const[c,d]of Object.entries(a.sizesByScale)){i.push(`- Size @${c}x: ${se(d)}`)}}if(a.sizeBytes!=null)i.push(`- Total: ${zn(a)}`);if(a.estDecodedBytes)i.push(`- Decoded memory: ~${se(a.estDecodedBytes)} (RGBA)`);if(a.hash)i.push(`- Hash: ${a.hash}`);if(a.fileSystemLocation)i.push(`- Source dir: ${a.fileSystemLocation}`);if(a.files?.length)i.push(`- Files: ${a.files.join(", ")}`);if(a.uri)i.push(`- Resolved URI: ${a.uri}`);return k(i.join("\n"))}case"save_baseline":{const a=await n.callAction(fe,"saveBaseline",{},o);return k(`Baseline saved (${a?.assets??0} assets). Make your change, then get_assets reports added/removed/grown/net bytes against it.`)}case"clear_baseline":{await n.callAction(fe,"clearBaseline",{},o);return k("Baseline cleared.")}case"clear_records":{const a=await n.callAction(fe,"clearRecords",{},o);return k(a?.message??"Inventory cleared.")}}}catch(o){return y(I(o))}})}import{z as Je}from"zod";import{WebSocket as Bo}from"ws";var qo=3e3;function jo(e){return`${e.replace(/^http/,"ws").replace(/\/+$/,"")}/message`}function Po(e){return new Promise(n=>{let t=false;const r=i=>{if(t)return;t=true;n(i)};let s;try{s=new Bo(jo(e))}catch(i){r({ok:false,error:i.message});return}const o=setTimeout(()=>{try{s.close()}catch{}r({ok:false,error:`dev server at ${e} did not accept a connection`})},qo);let a=false;s.on("open",()=>{try{s.send(JSON.stringify({version:2,method:"reload"}));a=true;clearTimeout(o);setTimeout(()=>{try{s.close()}catch{}r({ok:true})},250)}catch(i){clearTimeout(o);r({ok:false,error:i.message})}});s.on("error",i=>{clearTimeout(o);if(a)return;r({ok:false,error:i.message})})})}var bt="app";var Wn="reloadApp";var No=3e4;var Lo=1200;var Vn=1500;var Uo=400;var Kn=e=>new Promise(n=>setTimeout(n,e));async function Hn(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 zo(e,n){if(n===J)return;const t=e.toolActions(bt).find(r=>r.deviceId===n);if(!t?.actions.includes(Wn)){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 Jo(e,n,t,r){const s=Date.now();await Kn(Lo);while(Date.now()-s<t){const o=await Hn(e,n,Vn);if(o!==null&&o!==r)return Date.now()-s;await Kn(Uo)}return null}function Wo(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:Je.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:Je.boolean().optional().describe("Wait for the app to come back before returning. Default true \u2014 turn off for fire-and-forget."),timeoutMs:Je.number().optional().describe("How long to wait for the app to reconnect, in ms. Default 30000."),deviceId:Je.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);zo(n,r);const s=t.wait===false?null:await Hn(n,r,Vn);let o=null;let a=false;const i=async u=>{const l=n.devServerOrigin(r);if(!l){if(u)throw u;throw new Error("The app is not answering and no dev-server origin is known (it was never learned from a successful ping). Reload the app by hand.")}const m=await Po(l);if(!m.ok){throw new Error(`The app is not answering (it looks crashed) and the dev server at ${l} could not be reached either: ${m.error}. Reload the app by hand.`)}a=true};if(n.isUnresponsive(r)&&n.devServerOrigin(r)){await i()}else{try{o=await n.callAction(bt,Wn,{strategy:t.strategy??"auto"},r)}catch(u){await i(u)}}const c=a?` via the dev server (the app was unresponsive \u2014 its own reload could not be reached)`:o?.strategy?` via ${o.strategy}`:"";if(t.wait===false){return k(`Reload requested${c}. The app is restarting \u2014 its in-memory state is gone; re-read anything you cached.`)}const d=await Jo(n,r,t.timeoutMs??No,s);if(d==null){return y(`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 ${(d/1e3).toFixed(1)}s. All in-memory state was reset, so re-read any state you cached before this.`)}catch(r){return y(I(r))}})}import{z as Vo}from"zod";var Ko=e=>({content:[{type:"text",text:e}]});var Ho=e=>({isError:true,content:[{type:"text",text:e}]});var Gn=e=>e instanceof Error?e.message:String(e);var Go=5e3;var Yo=20;var Qo=400;var Zo=1600;var Xo=160;var We=(e,n=Xo)=>e.length>n?`${e.slice(0,n)}\u2026`:e;function ea(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 ta(e,n,t){const r=[];try{const s=await e.callAction("storage","mmkv.snapshot",{},n,t);for(const o of s??[]){const a=o.entries?.length??0;if(a>0)r.push(`MMKV "${o.id}": ${a} key${a===1?"":"s"}`)}}catch{}try{const s=await e.callAction("storage","secure.keys",{},n,t);if(s?.length)r.push(`SecureStore: ${s.length} key${s.length===1?"":"s"}`)}catch{}return r.length?`
|
|
186
|
-
${r.join(" \xB7 ")} \u2014 read with get_storage`:""}async function Ve(e,n){try{const t=await n();return t?`${e}
|
|
187
|
-
${t}`:null}catch(t){const r=Gn(t);if(/not responding|timed out|got no answer/i.test(r)){return`${e}
|
|
188
|
-
(no answer \u2014 see the note above)`}return`${e}
|
|
189
|
-
(unavailable: ${We(r,120)})`}}function na(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:Vo.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(p=>p.deviceId===r);const o=new Set((s?.tools??[]).map(p=>p.toolId));const a=`**${s?.deviceName??r}** (${s?.platform??"?"}, id \`${r}\`) \u2014 tools: ${[...o].join(", ")||"none"}`;const i={timeoutMs:Go};const[c,d,u,l]=await Promise.all([Ve("**Console \u2014 recent errors/warnings:**",async()=>{if(!o.has("console"))return null;const{payload:p}=await n.getSnapshot("console",r,i);const w=p;const h=Array.isArray(w)?w:w?.entries??[];const f=h.filter(v=>v.level==="error"||v.level==="warning");const g=f.slice(-8);if(g.length===0){return`(none \u2014 ${h.length} entries captured)`}return g.map(v=>`${ea(v.timestamp)} [${v.level==="error"?"ERR":"warn"}] ${We((v.message??"").split("\n").map(S=>S.trim()).filter(Boolean).slice(0,3).join(" \u23CE "),220)}`).join("\n")}),Ve("**Network \u2014 recent requests:**",async()=>{if(!o.has("network"))return null;const{payload:p}=await n.getSnapshot("network",r,i);const w=Array.isArray(p)?p:p?.events??[];if(w.length===0)return"(no requests captured yet)";const h=w.slice(-8);return h.map(f=>{const g=f.error||(f.status??0)>=400?"\u274C":"\u2705";const v=f.path??f.url??"?";const S=f.error??f.status??"pending";return`${g} ${f.method??"GET"} ${We(String(v),80)} \u2192 ${S}${f.duration?` (${Math.round(f.duration)}ms)`:""}`}).join("\n")}),Ve("**Storage \u2014 persisted values:**",async()=>{if(!o.has("storage"))return null;const p=await n.callAction("storage","async.getAllKeys",{},r,i);if(!Array.isArray(p)||p.length===0){return"(no app keys)"}const w=p.slice(0,Yo);let h=[];try{h=await n.callAction("storage","async.multiGet",{keys:w},r,i)??[]}catch{return`${w.map(M=>`\`${M}\``).join(", ")}
|
|
190
|
-
_Values: get_storage includeValues:true_`}const f=new Map(h);let g=Zo;const v=w.map(M=>{const O=f.get(M);if(O==null)return`- \`${M}\` = (null)`;if(O.length>Qo){return`- \`${M}\` = (${(O.length/1024).toFixed(1)} KB \u2014 read with get_storage)`}if(g<=0)return`- \`${M}\` = (not shown \u2014 triage budget spent; read with get_storage)`;g-=O.length;return`- \`${M}\` = ${O}`});const S=p.length-w.length;const x=await ta(n,r,i);return`${v.join("\n")}${S>0?`
|
|
191
|
-
\u2026+${S} more keys`:""}${x}`}),Ve("**Screen \u2014 what's visible now:**",async()=>{if(!o.has("highlight-updates"))return null;const p=await n.callAction("highlight-updates","describeScreen",{},r,i);const w=(p?.elements??[]).filter(h=>h.interactive);if(w.length===0)return"(nothing interactive on screen)";return w.slice(0,20).map(h=>`\u2022 ${h.name}${h.text||h.label?` "${We(h.text??h.label??"",60)}"`:""}${h.testID?` [testID=${h.testID}]`:""}`).join("\n")})]);const m=n.isUnresponsive(r);const $=m?`
|
|
192
|
-
|
|
193
|
-
\u{1F6D1} ${n.unresponsiveNote(r)}`:"";const b=[c,d,u,l].filter(Boolean).join("\n\n");return Ko(`${a}${$}
|
|
194
|
-
|
|
195
|
-
${b}
|
|
196
|
-
|
|
197
|
-
_Drill in with get_console, get_network_requests (includeBodies:true for response bodies), get_storage (includeValues:true), describe_screen._`)}catch(r){return Ho(Gn(r))}})}import{z as F}from"zod";var yt="highlight-updates";var Yn="app";var ra=e=>({content:[{type:"text",text:e}]});var sa=e=>({isError:true,content:[{type:"text",text:e}]});var $t=e=>e instanceof Error?e.message:String(e);var Ke=e=>new Promise(n=>setTimeout(n,e));var Qn=250;var oa=5e3;var Zn=2e3;var aa=1200;var ia=1500;var kt=12e4;function He(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 ca(e){const n=e.text??e.label;return`${e.interactive?"\u2022 ":" "}${e.name}${n?` "${n}"`:""}${e.testID?` [testID=${e.testID}]`:""}`}var la=F.object({tap:F.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),longPress:F.boolean().optional().describe("Make `tap` a long-press instead."),type:F.string().optional().describe("Text to type (needs `into`)."),into:F.string().optional().describe("Target text input for `type`: testID or fuzzy text."),set:F.union([F.number(),F.boolean()]).optional().describe("Set a toggle (true/false) or slider (number) \u2014 pair with `tap` as the target."),reload:F.boolean().optional().describe("Reload the JS bundle before this step's action."),waitMs:F.number().min(0).max(3e4).optional().describe("Fixed pause after the action, in ms (max 30000)."),waitFor:F.string().optional().describe("Wait until an element matching this appears (default 5s)."),waitGone:F.string().optional().describe("Wait until no element matches this (default 5s)."),expect:F.string().optional().describe("Assert an element matching this IS on screen (waits up to 2s for it); fails the flow if not."),expectGone:F.string().optional().describe("Assert nothing matches this (waits up to 2s for it to go); fails the flow if something does."),timeoutMs:F.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 ua(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:F.array(la).min(1).describe("Steps to run, in order."),include:F.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:F.boolean().optional().describe("Keep going after a failed step instead of stopping. Default false."),deviceId:A}},async t=>{const r=Date.now();try{const s=n.requireProDevice(t.deviceId);const o=t.include??"all";const a=async()=>{const g=await n.callAction(yt,"describeScreen",{},s);return g?.elements??[]};const i=async()=>{try{const g=await n.callAction(Yn,"ping",{},s,{timeoutMs:ia,silent:true});return typeof g?.startedAt==="number"?g.startedAt:null}catch{return null}};const c=async(g,v)=>{const S=Date.now();while(Date.now()-S<v){const x=await i();if(x!==null&&x!==g)return Date.now()-S;await Ke(Qn)}return null};const d=new Set;const u=new Set;const l=new Set((n.connectedDevices().find(g=>g.deviceId===s)?.tools??[]).map(g=>g.toolId));if(o==="all"){if(l.has("console")){const{payload:g}=await n.getSnapshot("console",s).catch(()=>({payload:null}));const v=g?.entries??[];for(const S of v)d.add(S.id)}if(l.has("network")){const{payload:g}=await n.getSnapshot("network",s).catch(()=>({payload:null}));const v=Array.isArray(g)?g:g?.events??[];for(const S of v)u.add(S.id)}}const m=async(g,v)=>{const S=Date.now();for(;;){if(Date.now()-S>=v||Date.now()-r>kt){return{ok:false,ms:Date.now()-S}}let x=[];try{x=await a()}catch{}if(g(x))return{ok:true,ms:Date.now()-S};await Ke(Qn)}};const $=[];let b=null;let p=0;for(let g=0;g<t.steps.length;g++){const v=t.steps[g];const S=`${g+1}`;const x=v.timeoutMs??oa;if(Date.now()-r>kt){$.push(`${S} \u2717 flow exceeded ${kt/1e3}s \u2014 stopped here`);b=g;break}const M=[];const O=[];const fr=v.reload||v.tap||v.type!==void 0||v.waitMs||v.waitFor||v.waitGone||v.expect||v.expectGone;if(!fr){$.push(`${g+1} \u2717 step does nothing \u2014 give it a tap/type/wait/expect${v.set!==void 0?" (`set` needs `tap` naming the control)":""}`);b=b??g;if(!t.continueOnFailure)break;continue}try{if(v.reload){const R=await i();await n.callAction(Yn,"reloadApp",{strategy:"auto"},s);await Ke(aa);const C=await c(R,Math.max(x,2e4));if(C==null){M.push("app did not come back after reload")}else{O.push(`reloaded (${C}ms)`);await m(q=>q.length>0,1e4)}}if(v.type!==void 0){const R=v.into??v.tap;if(!R){M.push("`type` needs `into` (which input to type into)")}else{const C=await n.callAction(yt,"tapElement",{...Xn(R),text:v.type},s);if(!C?.tapped){M.push(C?.reason??`could not type into "${R}"`)}else if(C.matched?.via&&C.matched.via!=="onChangeText"){M.push(`"${R}" is not a text input \u2014 it ran ${C.matched.via} instead, and the text was not entered`)}else{O.push(`typed ${JSON.stringify(v.type)} into "${R}"`)}}}else if(v.tap){const R={...Xn(v.tap)};if(v.longPress)R.longPress=true;if(v.set!==void 0)R.value=v.set;const C=await n.callAction(yt,"tapElement",R,s);if(!C?.tapped){M.push(C?.reason??`no element matched "${v.tap}"`)}else{const q=C.matched;const Qe=q?.text??q?.label??q?.name??v.tap;if(v.set!==void 0&&q?.via&&q.via!=="onValueChange"){M.push(`"${Qe}" is not a toggle/slider \u2014 it ran ${q.via} instead, so it was not set to ${JSON.stringify(v.set)}`)}else{O.push(v.set!==void 0?`set "${Qe}" \u2192 ${JSON.stringify(q?.value??v.set)}`:`${v.longPress?"long-pressed":"tapped"} "${Qe}"`)}}}if(!M.length&&v.waitMs){await Ke(v.waitMs);O.push(`waited ${v.waitMs}ms`)}if(!M.length&&v.waitFor){const R=await m(C=>C.some(q=>He(q,v.waitFor)),x);if(R.ok)O.push(`"${v.waitFor}" appeared (${R.ms}ms)`);else M.push(`"${v.waitFor}" never appeared within ${x}ms`)}if(!M.length&&v.waitGone){const R=await m(C=>!C.some(q=>He(q,v.waitGone)),x);if(R.ok)O.push(`"${v.waitGone}" gone (${R.ms}ms)`);else M.push(`"${v.waitGone}" was still there after ${x}ms`)}if(!M.length&&v.expect){const R=await m(C=>C.some(q=>He(q,v.expect)),v.timeoutMs??Zn);if(R.ok)O.push(`"${v.expect}" is on screen`);else M.push(`expected "${v.expect}" on screen \u2014 not found`)}if(!M.length&&v.expectGone){const R=await m(C=>!C.some(q=>He(q,v.expectGone)),v.timeoutMs??Zn);if(R.ok)O.push(`"${v.expectGone}" is gone`);else M.push(`expected "${v.expectGone}" to be gone \u2014 still on screen`)}}catch(R){M.push($t(R))}if(M.length){$.push(`${S} \u2717 ${er(v)} \u2014 ${M.join("; ")}`);b=b??g;if(!t.continueOnFailure)break}else{p++;$.push(`${S} \u2713 ${O.join(", ")||er(v)}`)}}const w=((Date.now()-r)/1e3).toFixed(1);const h=b===null?`**Flow: ${p}/${t.steps.length} steps OK (${w}s)**`:`**Flow FAILED at step ${b+1} \u2014 ${p}/${t.steps.length} steps OK (${w}s)**`;const f=[h,$.join("\n")];if(o!=="none"){try{const g=await a();const v=g.filter(S=>S.interactive).slice(0,30);f.push(`**Screen now (${v.length} interactive of ${g.length}):**
|
|
198
|
-
${v.map(ca).join("\n")}`)}catch(g){f.push(`**Screen now:** unavailable \u2014 ${tr($t(g))}`)}}if(o==="all"){if(l.has("network")){const{payload:g}=await n.getSnapshot("network",s).catch(()=>({payload:null}));const v=Array.isArray(g)?g:g?.events??[];const S=v.filter(x=>!u.has(x.id)).slice(-15);if(S.length){f.push(`**Network during this flow (${S.length}):**
|
|
199
|
-
`+S.map(x=>`${x.error||(x.status??0)>=400?"\u274C":"\u2705"} ${x.method??"GET"} ${x.path??x.url??"?"} \u2192 ${x.error??x.status??"pending"}`).join("\n"))}}if(l.has("console")){const{payload:g}=await n.getSnapshot("console",s).catch(()=>({payload:null}));const v=g?.entries??[];const S=v.filter(x=>!d.has(x.id)&&(x.level==="error"||x.level==="warning")).slice(-10);if(S.length){f.push(`**Console during this flow (${S.length}):**
|
|
200
|
-
`+S.map(x=>`[${x.level==="error"?"ERR":"warn"}] ${tr(da(x.message??""),220)}`).join("\n"))}}}return ra(f.join("\n\n"))}catch(s){return sa($t(s))}})}function Xn(e){return/\s/.test(e)?{query:e}:{testID:e,query:e}}function er(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 tr=(e,n=160)=>e.length>n?`${e.slice(0,n)}\u2026`:e;var da=(e,n=3)=>e.split("\n").map(t=>t.trim()).filter(Boolean).slice(0,n).join(" \u23CE ");import{z}from"zod";var Te="highlight-updates";var ha=e=>({content:[{type:"text",text:e}]});var Ie=e=>({isError:true,content:[{type:"text",text:e}]});var pa=e=>e instanceof Error?e.message:String(e);var Ge=e=>new Promise(n=>setTimeout(n,e));var nr=3e3;var rr=400;var sr=12;var or=new Map;var ma=z.object({tap:z.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),type:z.string().optional().describe("Text to type (needs `into`)."),into:z.string().optional().describe("Target text input for `type`: testID or fuzzy text."),waitMs:z.number().min(0).max(1e4).optional().describe("Pause after the action, in ms."),repeat:z.number().min(1).max(20).optional().describe("Do this step N times (default 1). Useful for 'tap it five times'.")}).describe("One interaction to measure. Keep it to the thing you're asking about.");function ar(e){return/\s/.test(e)?{query:e}:{testID:e,query:e}}function ir(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 cr={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 fa(e,n){const t=e.summary;const r=t.wastedRenders??0;const s=t.totalRenders>0?Math.round(r/t.totalRenders*100):0;const o=[];const a=t.totalRenderMs??0;o.push(`**${t.totalRenders} component renders across ${t.totalCommits} commits in ${(e.windowMs/1e3).toFixed(1)}s**`+(a>0?` \xB7 ${a.toFixed(1)}ms of render work`:"")+` \xB7 ${r} wasted (${s}%)`);const i=Object.entries(t.causes??{}).filter(([,l])=>(l??0)>0).sort((l,m)=>(m[1]??0)-(l[1]??0)).map(([l,m])=>`${l} ${m}`).join(" \xB7 ");if(i)o.push(`causes: ${i}`);o.push("");o.push("| component | self ms | renders | cause | dragged along by | changed props |");o.push("|---|---:|---:|---|---|---|");const c=[...t.topComponents].sort((l,m)=>(m.totalMs??0)-(l.totalMs??0)||m.renders-l.renders).slice(0,n);for(const l of c){o.push(`| ${l.name} | ${(l.totalMs??0).toFixed(1)} | ${l.renders} | ${ir(l.causes)} | ${l.parentName??"\u2014"} | ${(l.changedProps??[]).join(", ")||"\u2014"} |`)}if(t.topComponents.length>n){o.push(`_\u2026+${t.topComponents.length-n} more components_`)}const d=new Set(c.map(l=>ir(l.causes)));const u=[...d].filter(l=>cr[l]).map(l=>`\`${l}\` = ${cr[l]}`);if(u.length){o.push("");o.push(u.join(" \xB7 "))}o.push("");o.push("`wasted` classifies parent cascades and identity-only prop changes. Investigate whether these renders are needed before changing them. Rows are sorted by **self ms**. Compare timing and render counts for the measured workload, and check behavior before deciding whether memoization helps.");return o.join("\n")}function ga(e,n){const t=(u,l)=>{const m=l-u;return`${u} \u2192 ${l} (${m>0?"+":""}${m})`};const r=e.summary;const s=n.summary;const o=[`**vs "${e.label}"**`];o.push(`- total renders: ${t(r.totalRenders,s.totalRenders)}`);o.push(`- wasted: ${t(r.wastedRenders??0,s.wastedRenders??0)}`);const a=new Map(r.topComponents.map(u=>[u.name,u.renders]));const i=[];for(const u of s.topComponents.slice(0,20)){const l=a.get(u.name)??0;if(l!==u.renders)i.push(`${u.name} ${t(l,u.renders)}`);a.delete(u.name)}for(const[u,l]of a){if(l>0)i.push(`${u} ${t(l,0)}`)}if(i.length)o.push(`- per component: ${i.slice(0,10).join(" \xB7 ")}`);const c=s.totalRenders<r.totalRenders;const d=s.totalRenders>r.totalRenders;o.push(d?"\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 va(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:z.array(ma).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:z.number().min(500).max(2e4).optional().describe(`Idle sample length when no steps are given. Default ${nr}.`),label:z.string().optional().describe('Name this measurement, e.g. "before fix". Shown in the next comparison.'),compareToPrevious:z.boolean().optional().describe("Compare with the previous measurement on this device. Use equivalent steps and conditions; review warnings and behavior separately."),top:z.number().min(1).max(40).optional().describe(`Components to list. Default ${sr}.`),deviceId:A}},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===Te);if(!o){return Ie("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 Ie("This app's @buoy-gg/highlight-updates is too old to measure renders (needs the version with beginMeasurement). Upgrade it, then try again. Meanwhile run_benchmark_batch with captureRenders can still give counts if you have a test route.")}const a=await n.callAction(Te,"beginMeasurement",{},r);if(a&&a.ok===false){return Ie(`Can't measure renders: ${a.reason??"capture unavailable"}`)}await Ge(rr);const i=Date.now();const c=[];if(t.steps?.length){for(const w of t.steps){const h=w.repeat??1;for(let f=0;f<h;f++){if(w.type!==void 0){const g=w.into??w.tap;if(!g){c.push("a `type` step needs `into`");continue}const v=await n.callAction(Te,"tapElement",{...ar(g),text:w.type},r);if(!v?.tapped)c.push(v?.reason??`could not type into "${g}"`);else if(v.matched?.via&&v.matched.via!=="onChangeText"){c.push(`"${g}" is not a text input \u2014 it ran ${v.matched.via}, nothing was typed`)}}else if(w.tap){const g=await n.callAction(Te,"tapElement",ar(w.tap),r);if(!g?.tapped)c.push(g?.reason??`no element matched "${w.tap}"`)}if(w.waitMs)await Ge(w.waitMs)}}await Ge(rr)}else{await Ge(t.idleMs??nr)}const d=Date.now()-i;const u=await n.callAction(Te,"endMeasurement",{},r);const l=u?.summary;if(!l){return Ie("The capture window closed without returning anything. If the app reloaded mid-measurement, try again.")}const m={label:t.label??(t.steps?.length?"interaction":"idle"),windowMs:d,summary:l};const $=or.get(r);or.set(r,m);const b=t.steps?.length?t.steps.map(w=>(w.type!==void 0?`type "${w.type}"`:`tap "${w.tap}"`)+(w.repeat?` \xD7${w.repeat}`:"")).join(", "):`idle ${(d/1e3).toFixed(1)}s`;const p=[`**measure_renders \u2014 ${b}**`,"",fa(m,t.top??sr)];if(t.compareToPrevious){p.push("",$?ga($,m):"_No previous measurement on this device to compare against._")}if(c.length)p.push("",`\u26A0\uFE0F ${c.join("; ")}`);if(l.totalRenders===0){p.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){p.push("","_Compare another run using the same steps and `compareToPrevious:true`; check behavior and interaction warnings as well._")}return ha(p.join("\n"))}catch(r){return Ie(pa(r))}})}import wa from"fs";import lr from"path";var ba=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".json"]);var ya=new Set(["node_modules",".git",".expo","ios","android","dist","lib","build",".next","coverage","__snapshots__"]);var $a=400;function ka(e){const n=(e??"").trim().toLowerCase();if(n==="always"||n==="never"||n==="auto")return n;return"auto"}var _a=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=wa.watch(e,{recursive:true},(t,r)=>{if(!r)return;const s=String(r);if(s.split(lr.sep).some(o=>ya.has(o)))return;if(!ba.has(lr.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>$a)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`
|
|
201
|
-
|
|
202
|
-
---
|
|
203
|
-
\u26A0\uFE0F **${e.length} source file${e.length===1?"":"s"} changed since anything was last checked on the device** (${n}${t}).
|
|
204
|
-
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 _t=new _a;var Sa=`Buoy MCP connects your editor to supported Buoy tools through the configured broker.
|
|
205
|
-
|
|
206
|
-
Start with account and connection setup. Use \`list_devices\` to select an app and inspect
|
|
207
|
-
its available tools. App data and action tools require Buoy Pro. If access fails, explain
|
|
208
|
-
the reported requirement and setup steps. Camera tools use a separate local setup and
|
|
209
|
-
account gate; \`camera_diagnose\` can report setup problems without an app connection.
|
|
210
|
-
|
|
211
|
-
For a runtime bug, \`get_triage\` summarizes available console errors, network activity,
|
|
212
|
-
storage and screen information. Follow up on the relevant section and read source when
|
|
213
|
-
needed. Missing data can reflect missing integration, retention limits or a disconnected
|
|
214
|
-
app. An unresponsive app is not proof of a crash, and post-crash evidence may be unavailable.
|
|
215
|
-
|
|
216
|
-
Choose follow-up tools by the symptom:
|
|
217
|
-
- Persisted values: \`get_storage\` with \`includeValues:true\` for configured storage sources.
|
|
218
|
-
- Requests or API responses: \`get_network_requests\` with \`includeBodies:true\` for captured
|
|
219
|
-
bodies. Capture depends on supported transports, installed hooks and recording timing.
|
|
220
|
-
- Errors: \`get_console\` for retained captured output. A stopped app cannot provide new data.
|
|
221
|
-
- Cache or store state: \`get_react_query\`, \`get_zustand_state\`, \`get_redux_state\` or
|
|
222
|
-
\`get_jotai_state\` for the integrations registered in the app.
|
|
223
|
-
|
|
224
|
-
Use \`get_events\` with \`sources\` to read retained activity from connected event sources.
|
|
225
|
-
It returns compact summaries by default; request \`includeData:true\` when details are needed.
|
|
226
|
-
For request IDs and network actions, use \`get_network_requests\`. Its \`flagged:'any'\` filter
|
|
227
|
-
finds pinned or saved requests. A flag is a reason to inspect a request, not proof of its
|
|
228
|
-
cause or who flagged it. Use \`network_action\` to retain relevant evidence within task scope.
|
|
229
|
-
|
|
230
|
-
For supported UI interactions, \`run_flow\` runs steps such as tap, type, set, reload,
|
|
231
|
-
waitFor and expect. Review step results, failures and available captured output. Use
|
|
232
|
-
\`describe_screen\` to discover exposed elements and \`tap_element\` for individual actions.
|
|
233
|
-
A completed tool call alone does not establish that the user's expected behavior occurred.
|
|
234
|
-
|
|
235
|
-
For render-heavy interactions, use \`measure_renders\` with representative \`steps\`.
|
|
236
|
-
Repeat the same steps after a change with \`compareToPrevious:true\`. Interpret available
|
|
237
|
-
render counts, reasons and wasted-render diagnostics alongside behavior and performance;
|
|
238
|
-
these diagnostics do not prove that a render was unnecessary. For instrumented JavaScript
|
|
239
|
-
tasks, use \`get_js_thread_top\` and \`get_js_thread_origin_detail\`. Their coverage depends
|
|
240
|
-
on the installed hooks. Keep measurement conditions comparable.
|
|
241
|
-
|
|
242
|
-
\`get_images\` inspects instrumented image loads and available cache, timing, size and error
|
|
243
|
-
data. Use \`image_action\` for supported per-image actions and \`set_image_simulation\` for
|
|
244
|
-
integrated image behavior. Simulation does not disconnect the device's network.
|
|
245
|
-
\`get_assets\` inspects the configured manifest, runtime registry and available bundle graph.
|
|
246
|
-
Reported load history and size estimates do not prove complete shipped-asset coverage or
|
|
247
|
-
that an unobserved asset is unused. \`asset_action\` can refresh data and manage baselines.
|
|
248
|
-
|
|
249
|
-
\`reload_app\` requests a JS reload using supported app mechanisms and can wait for
|
|
250
|
-
reconnection. It can try a dev-server fallback for an unresponsive app when that server
|
|
251
|
-
is known and reachable. Recovery is not guaranteed. Reload can discard in-memory evidence;
|
|
252
|
-
collect needed observations first when possible and read state again after reconnecting.
|
|
253
|
-
|
|
254
|
-
\`get_time_machine\` lists snapshots and provider capabilities. \`time_machine_action\`
|
|
255
|
-
captures or restores supported registered state sources. Preview the affected state before
|
|
256
|
-
restoring. Live restore changes supported state in place; reload mode restores supported
|
|
257
|
-
persisted sources and requests a reload. A baseline clears providers that support clearing
|
|
258
|
-
and requests a reload. This does not reset backend state or reproduce a complete reinstall.
|
|
259
|
-
Check per-source applied/skipped outcomes and any reload or route-restoration failures.
|
|
260
|
-
|
|
261
|
-
\`get_clock\` reads the app's clock and whether the Clock tool overrides it. \`clock_action\`
|
|
262
|
-
moves it (set_time, shift), stops it (freeze), speeds it up (set_rate) or resets it.
|
|
263
|
-
Only the app's JS clock changes; the backend, native timers and time zone stay real. Check
|
|
264
|
-
\`get_clock\` before calling a date or expiry wrong, and reset when finished.
|
|
265
|
-
\`get_clock\` also lists the app's sign-in tokens and how long each has left. To test token
|
|
266
|
-
refresh, use \`clock_action\` jump_to_token_expiry (the app refreshes before expiry) or
|
|
267
|
-
fail_next_request (the app refreshes after a 401), have the app send a request, then read
|
|
268
|
-
\`get_clock\` for the refresh check's result.
|
|
269
|
-
|
|
270
|
-
For iOS Simulator camera input, inspect setup with \`camera_diagnose\`. Use \`camera_source\`
|
|
271
|
-
for supported barcode, file or screen input, \`camera_devices\` for simulators/apps and
|
|
272
|
-
\`camera_inputs\` for local sources. \`camera_launch\` attaches input when launching the app;
|
|
273
|
-
\`camera_zero_setup\` configures attachment for another launcher. \`camera_status\` reports
|
|
274
|
-
available source/decoder status, which does not establish the app's scanner result.
|
|
275
|
-
Use \`camera_stop\` when finished. These tools operate locally without an in-app Buoy
|
|
276
|
-
integration, but require their supported host, simulator and account setup.
|
|
277
|
-
|
|
278
|
-
\`screenshot_component\` locates a supported component by testID/name and attempts a crop.
|
|
279
|
-
It requires the MCP server on the same Mac as the booted iOS Simulator and the component
|
|
280
|
-
inspection setup. Inspect the result before using it as visual evidence.
|
|
281
|
-
|
|
282
|
-
For other supported operations, use \`list_tool_actions\`, \`get_snapshot\` or \`call_action\`.
|
|
283
|
-
Snapshots describe available current state and can be large; request only needed data.
|
|
284
|
-
|
|
285
|
-
After a behavior change, repeat the affected interaction and check the expected result.
|
|
286
|
-
Include restart or persistence checks when relevant to the change. Use appropriate static
|
|
287
|
-
checks for documentation-only work. Report actual checks, observations and remaining limits.
|
|
288
|
-
BUOY_VERIFY reminders track selected edits and tool calls; clearing a reminder is not a
|
|
289
|
-
test result. Stay within the user's authorized task and preserve existing project work.`;var xa=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 Aa(e){const n=new zs({name:"buoy",version:ae},{capabilities:{tools:{}},instructions:Sa});_t.start(process.cwd(),ka(process.env.BUOY_VERIFY));const t=n.registerTool.bind(n);n.registerTool=((r,s,o)=>t(r,s,(async(...a)=>{const i=await o(...a);const c=i?.isError===true;if(xa.has(r)&&!c){_t.markVerified();return i}const d=_t.nudge();if(!d)return i;const u=i;if(Array.isArray(u?.content)){return{...u,content:[...u.content,{type:"text",text:d}]}}return i})));na(n,e);ua(n,e);va(n,e);Jt(n,e);Zt(n,e);Xt(n,e);Qs(n,e);en(n,e);tn(n,e);nn(n,e);on(n,e);an(n,e);un(n,e);hn(n,e);eo(n,e);to(n,e);ro(n,e);ao(n,e);vn(n,e);bo(n);ko(n,e);To(n,e);Ro(n,e);Eo(n,e);Wo(n,e);return n}var ji={deviceId:Js.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 St}from"child_process";import E from"fs";import Ta from"os";import B from"path";function xt(){return{BUOY_VERIFY:"auto"}}var ur="https://registry.npmjs.org";var At=3e3;function Ia(e={}){const n=e.cwd??process.cwd();const t=e.skillSrcDir??B.resolve(__dirname,"../skill");const r=e.log??(a=>process.stdout.write(a+"\n"));const s=Da(e,r);const o=[];It(B.join(n,".mcp.json"),"mcpServers",s,n,o);E.mkdirSync(B.join(n,".cursor"),{recursive:true});It(B.join(n,".cursor","mcp.json"),"mcpServers",s,n,o);if(E.existsSync(B.join(n,".vscode"))){It(B.join(n,".vscode","mcp.json"),"servers",s,n,o)}Ba(t,n,o);pr(B.join(n,"CLAUDE.md"),n,o);pr(B.join(n,"AGENTS.md"),n,o);r("Buoy MCP configuration written:");for(const a of o)r(" \u2022 "+a);r("");r("Next steps:");r(" 1. Restart your editor (or reconnect the MCP server) to load `buoy`.");r(" 2. Complete account setup, then open an app with the required Buoy tools and sync integration.");r(" 3. Confirm the device and tools are available. MCP data/action access requires Pro.");if(s.command==="npx"){r("");r(`The editor launches the server with \`npx -y ${te}@latest\`, so it stays`);r(`Registry access may be needed. Re-run \`npx -y ${te}@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 Da(e,n){if(e.cliPath){return{type:"stdio",command:"node",args:[e.cliPath],env:xt()}}const t=e.mode??"auto";if(t==="npx"){return Tt()}if(t==="local"){return dr(e,n)}const r=Ra();if(r.reachable){return Tt()}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 dr(e,n)}function Tt(){return{type:"stdio",command:"npx",args:["-y",`${te}@latest`],env:xt()}}function dr(e,n){const t=e.installDir??process.env.BUOY_MCP_HOME??B.join(Ta.homedir(),".buoy-mcp");const r=e.registry??ur;const s=Ma(t,r,n);if(s){return{type:"stdio",command:"node",args:[s],env:xt()}}n("\u26A0 local install failed \u2014 writing the npx entry instead (see the error above).");return Tt()}function Ma(e,n,t){const r=`${te}@${ae==="0.0.0-dev"?"latest":ae}`;E.mkdirSync(e,{recursive:true});const s=process.platform==="win32"?"npm.cmd":"npm";t(`Installing ${r} into ${e} from ${n} \u2026`);const o=St(s,["install",r,"--prefix",e,"--registry",n,`--@buoy-gg:registry=${n}`,"--no-audit","--no-fund","--loglevel=error"],{stdio:["ignore","ignore","inherit"],encoding:"utf8"});if(o.status!==0){t(`\u26A0 npm install exited with code ${o.status??"?"}${o.error?` (${o.error.message})`:""}.`);return null}const a=B.join(e,"node_modules",te,"dist","cli.js");if(!E.existsSync(a)){t(`\u26A0 install finished but ${a} is missing.`);return null}return a}function Ra(){const e=Oa();if(!e)return{reachable:false,registry:null};if(/^https?:\/\/registry\.npmjs\.org\/?$/i.test(e)){return{reachable:true,registry:e}}return{reachable:Ca(e),registry:e}}function Oa(){const e=hr("@buoy-gg:registry");if(e)return e;const n=hr("registry");return n??ur}function hr(e){const n=process.platform==="win32"?"npm.cmd":"npm";const t=St(n,["config","get",e],{encoding:"utf8",timeout:At});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 Ca(e){const n=St(process.execPath,["-e",Fa,e,String(At)],{encoding:"utf8",timeout:At+2e3});return n.status===0}var Fa=`
|
|
290
|
-
const url = process.argv[1];
|
|
291
|
-
const ms = Number(process.argv[2]) || 3000;
|
|
292
|
-
const c = new AbortController();
|
|
293
|
-
const t = setTimeout(() => c.abort(), ms);
|
|
294
|
-
fetch(url, { method: 'HEAD', signal: c.signal })
|
|
295
|
-
.then(() => { clearTimeout(t); process.exit(0); })
|
|
296
|
-
.catch(() => {
|
|
297
|
-
// A HEAD may be rejected while the host is up; a bare TCP-level failure is
|
|
298
|
-
// what we care about. fetch throwing a TypeError = network unreachable.
|
|
299
|
-
clearTimeout(t);
|
|
300
|
-
process.exit(1);
|
|
301
|
-
});
|
|
302
|
-
`;function It(e,n,t,r,s){let o={};if(E.existsSync(e)){try{o=JSON.parse(E.readFileSync(e,"utf8"))}catch{E.copyFileSync(e,e+".bak");s.push(`existing ${oe(e,r)} was invalid JSON \u2014 backed up to ${oe(e,r)}.bak`);o={}}}else{E.mkdirSync(B.dirname(e),{recursive:true})}const a=o[n]&&typeof o[n]==="object"?o[n]:{};const i="buoy"in a;a.buoy=t;o[n]=a;E.writeFileSync(e,JSON.stringify(o,null,2)+"\n");s.push(`${i?"updated":"added"} \`buoy\` in ${oe(e,r)}`)}var Ye="# Debugging with Buoy";var Ea=`${Ye}
|
|
303
|
-
|
|
304
|
-
Use Buoy to inspect a connected app when runtime evidence helps the task.
|
|
305
|
-
Complete account, tool integration and connection setup first. MCP data and
|
|
306
|
-
action access requires Pro. Follow the user's scope and repository instructions.
|
|
307
|
-
|
|
308
|
-
- \`get_triage\`: summarize available device and tool observations, then choose
|
|
309
|
-
a relevant tool. Missing data is not proof that no problem occurred.
|
|
310
|
-
- \`run_flow\`: run supported tap, type, wait and assertion steps to reproduce
|
|
311
|
-
a failure or check a change. Review the flow before running it.
|
|
312
|
-
- \`get_events\`: inspect retained events from connected tools.
|
|
313
|
-
- \`get_network_requests\`: inspect captured requests and responses. Capture
|
|
314
|
-
depends on installed hooks, transport and when recording began.
|
|
315
|
-
- \`network_conditions\`: take the app offline or add latency to check error
|
|
316
|
-
and retry paths. Development builds only. Restore \`normal\` when finished.
|
|
317
|
-
- \`get_console\`: inspect retained console and error output. A terminated or
|
|
318
|
-
disconnected app may not provide new data.
|
|
319
|
-
- \`get_storage\`: inspect registered storage backends and available keys.
|
|
320
|
-
- \`reload_app\`: reload where supported. Confirm the device remains connected;
|
|
321
|
-
a reload does not guarantee recovery from a crash.
|
|
322
|
-
- \`get_snapshot\`: inspect the available state of a specific tool.
|
|
323
|
-
|
|
324
|
-
After a behavior change, repeat the failing interaction when the environment
|
|
325
|
-
allows it. Use relevant tests and report what was actually checked. For a
|
|
326
|
-
performance change, compare \`measure_renders\` runs with the same steps and
|
|
327
|
-
\`compareToPrevious: true\`; inspect the measurements and their limitations.
|
|
328
|
-
Use \`run_flow\` for supported UI checks. Do not claim a fix was verified when
|
|
329
|
-
only source review or a build was performed.
|
|
330
|
-
|
|
331
|
-
\`BUOY_VERIFY\` controls verification reminders: \`auto\` uses edit-based
|
|
332
|
-
reminders, \`always\` repeats until checked, and \`never\` disables them.
|
|
333
|
-
A reminder is not a test result. Choose checks appropriate to the change;
|
|
334
|
-
prose-only edits do not require running device actions.
|
|
335
|
-
`;function pr(e,n,t){let r="";if(E.existsSync(e)){try{r=E.readFileSync(e,"utf8")}catch{t.push(`\u26A0 could not read ${oe(e,n)} \u2014 skipped the debugging guide`);return}if(r.includes(Ye)){t.push(`${oe(e,n)} already has the "${Ye}" 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{E.writeFileSync(e,r+s+Ea);t.push(`${r?"appended":"created"} "${Ye}" block in ${oe(e,n)}`)}catch{t.push(`\u26A0 could not write ${oe(e,n)} \u2014 skipped the debugging guide`)}}function Ba(e,n,t){if(!E.existsSync(e)){t.push("\u26A0 no bundled skills found \u2014 skipped");return}const r=E.readdirSync(e,{withFileTypes:true}).filter(s=>s.isDirectory()&&E.existsSync(B.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=B.join(e,s.name);const a=B.join(n,".claude","skills",s.name);mr(o,a);t.push(`installed the ${s.name} skill \u2192 ${oe(B.join(a,"SKILL.md"),n)}`)}}function mr(e,n){E.mkdirSync(n,{recursive:true});for(const t of E.readdirSync(e,{withFileTypes:true})){const r=B.join(e,t.name);const s=B.join(n,t.name);if(t.isDirectory())mr(r,s);else E.copyFileSync(r,s)}}function oe(e,n){const t=B.relative(n,e);return t&&!t.startsWith("..")?t:e}export{Ze as BROKER_PORT,Dt as BROKER_URL,Mt as DEFAULT_ACTION_TIMEOUT_MS,Ot as DEFAULT_SNAPSHOT_TIMEOUT_MS,Xe as DASHBOARD_NAME,J as ALL_DEVICES,Hr as SyncClient,ae as VERSION,te as PACKAGE_NAME,zt as getUpdateNotice,Jt as registerGenericTools,Me as buildAutomationConfig,tt as estimateBatchMs,Re as rankBatchFromIndex,Oe as formatRankingMarkdown,Kt as compareReportStats,Zt as registerPerfMonitorTools,Xt as registerEventsTools,en as registerReactQueryTools,tn as registerZustandTools,nn as registerJotaiTools,on as registerReduxTools,an as registerStorageTools,un as registerRoutesTools,hn as registerConsoleTools,vn as registerScreenshotTools,Aa as createMcpServer,Ia as runInit};
|