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