@buoy-gg/mcp 7.0.42 → 7.0.44
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-YQ3KGD5Y.mjs +364 -0
- package/dist/cli.js +132 -103
- package/dist/cli.mjs +1 -1
- package/dist/index.js +131 -102
- package/dist/index.mjs +1 -1
- package/package.json +6 -3
- package/dist/chunk-OOYI5S34.mjs +0 -335
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
import{DEFAULT_BROKER_PORT as Fn}from"@buoy-gg/sync-broker";var at=Fn;var Nt=`http://localhost:${at}`;var Lt=15e3;var qn=2500;var jn=1200;var Ut=2e4;var Bn=3e4;var zt=5e3;var Pn=15*6e4;var it="Dashboard";var G="All";import{readFileSync as Jt,writeFileSync as Nn,mkdirSync as Ln,renameSync as Un,unlinkSync as zn}from"fs";import{dirname as Jn,join as Wt,resolve as Wn}from"path";import{homedir as Vn}from"os";import{createHash as Gn}from"crypto";import{validateLicense as Kn,isAcceptedValidation as Hn,isTransientLicenseError as Yn,resolveTier as Qn,isRecognizedAccount as Xn,isBuoyToken as Zn,verifyFreeToken as eo,resolveAccountAccess as to,signCache as Vt,verifyCacheSignature as ro,LICENSE_LAUNCH_VALIDATION_TTL as Gt,LICENSE_REVALIDATION_INTERVAL as qe,LICENSE_TRANSIENT_RETRY_DELAYS as no,KEYGEN_CONFIG as oo}from"@buoy-gg/license/headless";var Kt=["BUOY_LICENSE_KEY","BUOY_KEY","EXPO_PUBLIC_BUOY_KEY","VITE_BUOY_KEY","REACT_APP_BUOY_KEY"];function Ht(e,r=process.env){for(const t of Kt)if(r[t]!==void 0)return r[t].trim().toUpperCase()||null;for(const t of[".env.development.local",".env.local",".env"]){let n;try{n=Jt(Wt(e,t),"utf8")}catch{continue}const o=new Map;for(const s of n.split(/\r?\n/)){const a=s.match(/^\s*(?:export\s+)?([A-Z_][A-Z_0-9]*)\s*=\s*(.*)$/);if(!a)continue;const i=a[2].trim();const c=i.match(/^(['"])(.*?)\1\s*(?:#.*)?$/);o.set(a[1],c?c[2]:i.split("#")[0].trim())}for(const s of Kt)if(o.has(s))return o.get(s).trim().toUpperCase()||null}return null}var so=class{constructor(e,r={}){this.changed=e;this.key=null;this.cache=null;this.timer=null;this.generation=0;this.busy=false;this.nextCheck=0;this.retry=0;this.lastAdmission=false;this.hasAccess=()=>to({initialized:true,validating:false,key:this.key,tierSource:this.cache?.tier?"key":"none",verifiedAt:this.cache?.cachedAt??null}).status==="admitted";this.projectDir=Wn(r.projectDir??process.env.BUOY_PROJECT_DIR??process.cwd());const t=Gn("sha256").update(this.projectDir).digest("hex").slice(0,20);this.cacheFile=r.cacheFile??Wt(Vn(),".buoy",`account-${t}.json`)}start(){if(this.timer)return;try{const e=JSON.parse(Jt(this.cacheFile,"utf8"));if(e.valid&&ro(e))this.cache=e}catch{}void this.tick();this.timer=setInterval(()=>{void this.tick()},1e3);this.timer.unref()}stop(){++this.generation;if(this.timer)clearInterval(this.timer);this.timer=null;this.key=null;this.cache=null;this.notify()}notify(){const e=this.hasAccess();if(e===this.lastAdmission)return;this.lastAdmission=e;this.changed()}async tick(){const e=Ht(this.projectDir);if(e!==this.key){++this.generation;this.key=e;if(this.cache?.licenseKey!==e)this.cache=null;this.nextCheck=0;this.retry=0;if(!e)this.removeCache()}this.notify();if(!e||this.busy||Date.now()<this.nextCheck)return;if(this.cache&&this.hasAccess()&&Date.now()-this.cache.lastValidatedAt<Gt&&this.nextCheck===0){this.nextCheck=this.cache.lastValidatedAt+Gt;return}this.busy=true;const r=this.generation;try{if(Zn(e)){const i=eo(e);if(!i){this.cache=null;this.removeCache()}else{const c=Date.now();this.cache=Vt({licenseKey:e,licenseId:`token:${i.accountHash}`,valid:true,tier:"free",isPro:false,expiresAt:null,cachedAt:c,lastValidatedAt:c});this.persistCache()}this.nextCheck=Date.now()+qe;return}const t=await Kn(e);if(r!==this.generation||Ht(this.projectDir)!==e)return;const n=t.data?.relationships?.product?.data?.id;const o=t.meta.code==="EXPIRED"&&(Xn(t.data)||this.cache?.licenseKey===e);if(n&&n!==oo.productId||!o&&!Hn(t)){this.cache=null;this.removeCache();this.nextCheck=Date.now()+qe;return}const s=o?"free":Qn(t.data);const a=Date.now();this.cache=Vt({licenseKey:e,licenseId:t.data?.id??"",valid:true,tier:s,isPro:s==="pro",expiresAt:o?null:t.data.attributes.expiry,cachedAt:a,lastValidatedAt:a});this.persistCache();this.retry=0;this.nextCheck=a+qe}catch(t){if(r!==this.generation)return;const n=Yn(t)?no[this.retry++]:void 0;this.nextCheck=Date.now()+(n??qe)}finally{this.busy=false;this.notify()}}persistCache(){try{Ln(Jn(this.cacheFile),{recursive:true,mode:448});Nn(`${this.cacheFile}.tmp`,JSON.stringify(this.cache),{mode:384});Un(`${this.cacheFile}.tmp`,this.cacheFile)}catch{}}removeCache(){try{zn(this.cacheFile)}catch{}}};import ao from"http";import{randomUUID as io}from"crypto";import{io as co}from"socket.io-client";import{createBroker as lo,brokerTokenPath as ct,readBrokerToken as uo,writeBrokerToken as ho,DASHBOARD_TOKEN_REQUIRED as po}from"@buoy-gg/sync-broker";function mo(e,r){return e==="app"&&(r==="ping"||r==="reloadApp")}function Yt(e){return e>=2}function fo(e){if(mo(e.toolId,e.action)){return{timeoutMs:e.fullMs,usedFullBudget:false}}if(!Yt(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 go(e){if(e.consecutiveTimeouts>=2)return true;if(e.lastOkAt>0&&e.now-e.lastOkAt>e.unresponsiveAfterMs){return true}return false}var vo=class{constructor(e={}){this.socket=null;this.admitted=false;this.lockedDevices=new Set;this.hostAccount=null;this.broker=null;this.capabilities=new Map;this.devices=[];this.snapshots=new Map;this.watching=new Map;this.pendingActions=new Map;this.snapshotWaiters=new Map;this.snapshotAt=new Map;this.health=new Map;this.devServerOrigins=new Map;this.originProbed=new Set;this.lastSeen=new Map;this.port=e.port??at;this.url=e.url??(e.port?`http://localhost:${e.port}`:Nt);this.actionTimeoutMs=e.actionTimeoutMs??Lt;this.log=e.log??(r=>process.stderr.write(`[buoy-mcp] ${r}
|
|
2
|
+
`));this.autoSpawn=e.autoSpawnBroker??true}async start(){const e=await Qt(this.url);let r="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 so(()=>this.broker?.refreshAccess());this.hostAccount.start();this.broker=lo({canUseDesktop:this.hostAccount.hasAccess,port:this.port,onError:t=>this.log(`broker error: ${t.code??t.message}`)});await wo(this.url);try{ho(this.broker.dashboardToken,ct(this.port))}catch(t){this.log(`could not write the broker token file: ${t.message}`)}r="spawned"}else{this.log(`found a running broker at ${this.url} \u2014 connecting as a dashboard`)}await this.connectSocket();return r}connectSocket(){return new Promise((e,r)=>{const t=co(this.url,{transports:["websocket"],query:{deviceName:it},auth:i=>{const c=this.broker?.dashboardToken??uo(ct(this.port));i(c?{dashboardToken:c}:{})},reconnection:true,reconnectionDelay:500,timeout:4e3});this.socket=t;let n=false;const o=()=>{if(n)return;n=true;this.log("connected to broker");e()};const s=setTimeout(()=>{if(n)return;n=true;r(new Error("Broker account is locked or the broker needs an update. Sign in to Buoy Desktop or run npx buoy login for standalone MCP."))},5e3);t.on("buoy:access",i=>{const c=!!i&&typeof i==="object"&&i.protocol===1&&i.ready===true;this.setAdmission(c);if(c){clearTimeout(s);this.rearmWatches();o()}});t.on("connect",()=>{t.emit("buoy:access:request")});t.on("disconnect",()=>this.setAdmission(false,true));const a=i=>i.message===po;t.once("connect_error",i=>{if(n)return;n=true;clearTimeout(s);r(new Error(a(i)?`The broker at ${this.url} refused this MCP as a dashboard: the token in ${ct(this.port)} is missing or stale. Update Buoy Desktop, or restart it so it writes the file.`:`failed to connect to broker at ${this.url}: ${i.message}`))});t.on("connect_error",i=>{if(!a(i)||t.active)return;setTimeout(()=>{if(this.socket===t&&!t.connected)t.connect()},1e3).unref?.()});t.on("devtool-capabilities",i=>{if(!this.admitted||this.lockedDevices.has(i.persistentDeviceId))return;this.capabilities.set(i.persistentDeviceId,i);void this.learnDevServerOrigin(i.persistentDeviceId)});t.on("all-devices-update",i=>{if(!this.admitted)return;if(!Array.isArray(i))return;let c=false;for(const l of i){if(l.deviceId&&l.tier==="locked")this.lockDevice(String(l.deviceId));else if(l.deviceId&&(l.tier==="free"||l.tier==="pro")){c=this.lockedDevices.delete(String(l.deviceId))||c}}this.devices=i;const d=Date.now();for(const l of i)if(l.deviceId)this.lastSeen.set(l.deviceId,d);this.pruneStaleDevices();if(c)this.rearmWatches()});t.on("devtool-sync",i=>{if(!this.admitted||this.lockedDevices.has(i.persistentDeviceId))return;const c=ne(i.persistentDeviceId,i.toolId);this.snapshots.set(c,i.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(i.payload)}});t.on("devtool-action-result",i=>{if(!this.admitted)return;const c=this.pendingActions.get(i.requestId);if(!c)return;this.pendingActions.delete(i.requestId);clearTimeout(c.timer);c.resolve(i)})})}requireAdmission(){if(!this.admitted)throw new Error("A verified Buoy account and an updated broker are required. Sign in to Buoy Desktop, or run npx buoy login for standalone MCP.")}setAdmission(e,r=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(!r)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 n of t)n(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 r=`${e}::`;for(const t of this.snapshots.keys())if(t.startsWith(r)){this.snapshots.delete(t);this.snapshotAt.delete(t)}for(const[t,n]of this.snapshotWaiters)if(t.startsWith(r)){this.snapshotWaiters.delete(t);for(const o of n)o(void 0)}for(const[t,n]of this.pendingActions)if(n.target===e||n.target===G){clearTimeout(n.timer);this.pendingActions.delete(t);n.reject(new Error("Device account access ended while the action was pending."))}}pruneStaleDevices(){const e=Date.now()-Pn;for(const[r,t]of this.lastSeen){if(t>e)continue;if(this.devices.some(o=>o.deviceId===r))continue;this.lastSeen.delete(r);this.capabilities.delete(r);this.health.delete(r);this.devServerOrigins.delete(r);this.originProbed.delete(r);const n=`${r}::`;for(const o of[...this.snapshots.keys()]){if(o.startsWith(n)){this.snapshots.delete(o);this.snapshotAt.delete(o)}}for(const o of[...this.watching.keys()]){if(o.startsWith(n))this.watching.delete(o)}}}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 r of e)r(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!==it&&e.deviceId).map(e=>{const r=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:r?.tools??[]}})}connectedDevices(){return this.listDevices().filter(e=>e.isConnected)}toolActions(e){return this.listDevices().map(r=>{const t=r.tools.find(n=>n.toolId===e);return t?{deviceId:r.deviceId,deviceName:r.deviceName,actions:t.actions}:null}).filter(r=>r!==null)}resolveDevice(e){this.requireAdmission();if(e){this.requireDeviceAccount(e);return e}const r=this.connectedDevices();const t=r.filter(s=>!this.lockedDevices.has(s.deviceId));if(t.length===0){if(r.length>0){throw new Error(`Devices are connected (${r.map(s=>s.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 n=t.filter(s=>s.tools.length>0);if(n.length===1)return n[0].deviceId;if(n.length===0){const s=t.map(a=>a.deviceName).join(", ");throw new Error(`Connected devices (${s}) are not exposing any Buoy tools yet. Make sure the app is in the foreground with devtools mounted, then retry.`)}const o=n.map(s=>`${s.deviceName} (${s.deviceId})`).join(", ");throw new Error(`Multiple devices connected \u2014 specify deviceId. Connected: ${o}`)}requireProDevice(e){this.requireAdmission();const r=s=>{if(!s)return"";return s.tier==="locked"?` The broker has not confirmed account access for "${s.deviceName}"; a locked status does not establish whether a key is configured.`:` The connected app "${s.deviceName}" is on the ${s.tier} tier.`};const t=s=>`Buoy Pro is required to use the MCP.${r(s)} Enter a license in the app, or \u2014 if it runs headless (no on-device UI) \u2014 pass \`licenseKey\` to \`<FloatingDevTools />\`. Run \`list_devices\` to check status.`;if(e===G){if(!this.connectedDevices().some(s=>s.isPro))throw new Error(t());return G}const n=this.resolveDevice(e);const o=this.connectedDevices().find(s=>s.deviceId===n);if(!o?.isPro)throw new Error(t(o));return n}healthOf(e){let r=this.health.get(e);if(!r){r={consecutiveTimeouts:0,lastOkAt:0,lastFullBudgetAt:0};this.health.set(e,r)}return r}noteOk(e){const r=this.healthOf(e);r.consecutiveTimeouts=0;r.lastOkAt=Date.now()}noteTimeout(e){this.healthOf(e).consecutiveTimeouts+=1}isUnresponsive(e){return Yt(this.healthOf(e).consecutiveTimeouts)}timeoutFor(e,r,t){const n=this.healthOf(e);const{timeoutMs:o,usedFullBudget:s}=fo({consecutiveTimeouts:n.consecutiveTimeouts,lastFullBudgetAt:n.lastFullBudgetAt,now:Date.now(),fullMs:this.actionTimeoutMs,shortMs:qn,recoveryProbeMs:Ut,toolId:r,action:t});if(s)n.lastFullBudgetAt=Date.now();return o}unresponsiveNote(e){const r=this.healthOf(e);const t=r.lastOkAt?Math.round((Date.now()-r.lastOkAt)/1e3):null;const n=go({consecutiveTimeouts:r.consecutiveTimeouts,lastOkAt:r.lastOkAt,now:Date.now(),unresponsiveAfterMs:Bn});const o=[`The app on "${e}" is not responding (${r.consecutiveTimeouts} call${r.consecutiveTimeouts===1?"":"s"} unanswered${t!=null?`, last answered ${t}s ago`:""}).`,n?"It is most likely CRASHED \u2014 a fatal render error unmounts the React tree, and the dev tools live in that tree, so nothing on-device can answer until the app is reloaded.":"It may be busy, mid-reload, or crashing."];const s=this.lastFatalFor(e);if(s)o.push(`Last captured error: ${s}`);o.push(s?"Read the crash state with get_console / get_storage (served from the last sync), then reload_app to recover.":"Try get_console (served from the last sync) for the app's last words, then reload_app to recover.");return o.join(" ")}lastFatalFor(e){const r=this.snapshots.get(ne(e,"console"));const t=r?.entries;if(!Array.isArray(t))return null;for(let n=t.length-1;n>=0;n--){const o=t[n];if(o?.fatal||o?.level==="error"){const s=(o.message??"").split("\n")[0];if(s)return s.length>300?`${s.slice(0,300)}\u2026`:s}}return null}snapshotAgeMs(e,r){this.requireAdmission();const t=this.snapshotAt.get(ne(r,e));return t?Date.now()-t:null}noteDevServerOrigin(e,r){if(typeof r==="string"&&/^https?:\/\//.test(r)){this.devServerOrigins.set(e,r)}}async learnDevServerOrigin(e){if(this.devServerOrigins.has(e)||this.originProbed.has(e))return;this.originProbed.add(e);const r=this.capabilities.get(e)?.tools?.some(t=>t.toolId==="app");if(!r)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 r=this.devServerOrigins.get(e);if(r)return r;const t=this.snapshots.get(ne(e,"app"));if(typeof t?.devServerOrigin==="string")return t.devServerOrigin;return null}ensureWatching(e,r){const t=ne(r,e);if(this.watching.has(t))return;this.watching.set(t,{toolId:e,targetDeviceId:r});this.sendWatch(e,r)}sendWatch(e,r){if(!this.admitted||!this.socket?.connected||this.lockedDevices.has(r))return;this.socket?.emit("devtool-watch",{toolId:e,targetDeviceId:r,watching:true,stream:false})}rearmWatches(){for(const{toolId:e,targetDeviceId:r}of this.watching.values()){this.sendWatch(e,r)}}unwatch(e,r){const t=ne(r,e);if(!this.watching.delete(t))return;if(this.admitted&&this.socket?.connected)this.socket.emit("devtool-watch",{toolId:e,targetDeviceId:r,watching:false})}cachedSnapshot(e,r){this.requireAdmission();this.requireDeviceAccount(r);return this.snapshots.get(ne(r,e))}async getSnapshot(e,r,t={}){const n=this.resolveDevice(r);const o=ne(n,e);this.ensureWatching(e,n);let s=t.timeoutMs??zt;if(t.timeoutMs===void 0&&this.isUnresponsive(n)){const d=this.healthOf(n);if(Date.now()-d.lastFullBudgetAt>Ut){d.lastFullBudgetAt=Date.now()}else{s=jn}}const a=this.waitForSnapshot(o,s);this.socket?.emit("request-devtool-state",{toolId:e,targetDeviceId:n});const i=await a;this.requireAdmission();this.requireDeviceAccount(n);if(i!==void 0){if(!t.silent)this.noteOk(n);return{deviceId:n,payload:i}}if(!t.silent)this.noteTimeout(n);const c=this.snapshots.get(o);if(c!==void 0){return{deviceId:n,payload:c,stale:this.staleNote(e,n)}}throw new Error(`Timed out waiting for "${e}" state from ${n} (is the tool active?). ${this.unresponsiveNote(n)}`)}staleNote(e,r){const t=this.snapshotAgeMs(e,r);const n=t==null?"an earlier sync":`${Math.round(t/1e3)}s ago`;return`\u26A0\uFE0F Served from the last sync (${n}) \u2014 ${this.unresponsiveNote(r)}`}waitForSnapshot(e,r){return new Promise(t=>{const n=this.snapshotWaiters.get(e)??[];const o=setTimeout(()=>{const a=(this.snapshotWaiters.get(e)??[]).filter(i=>i!==s);this.snapshotWaiters.set(e,a);t(void 0)},r);const s=a=>{clearTimeout(o);t(a)};n.push(s);this.snapshotWaiters.set(e,n)})}async callAction(e,r,t,n,o={}){this.requireAdmission();const s=n===G?G:this.resolveDevice(n);if(!this.socket)throw new Error("SyncClient is not connected");const a=io();const i=o.timeoutMs??this.timeoutFor(s,e,r);const c=await new Promise((d,l)=>{const u=setTimeout(()=>{this.pendingActions.delete(a);if(s!==G&&!o.silent)this.noteTimeout(s);l(new Error(`Action "${e}.${r}" got no answer in ${i}ms. `+(s===G?"No device responded.":this.unresponsiveNote(s))))},i);this.pendingActions.set(a,{resolve:d,reject:l,timer:u,target:s});this.socket.emit("devtool-action",{requestId:a,toolId:e,targetDeviceId:s,action:r,params:t??{}})});if(s!==G&&!o.silent)this.noteOk(s);if(!c.ok){throw new Error(c.error||`Action "${e}.${r}" failed on device`)}return c.result}};var ne=(e,r)=>`${e}::${r}`;function Qt(e,r=800){return new Promise(t=>{const n=ao.get(e,o=>{o.resume();t((o.statusCode??0)>0)});n.setTimeout(r,()=>{n.destroy();t(false)});n.on("error",()=>t(false))})}async function wo(e,r=20){for(let t=0;t<r;t++){if(await Qt(e,300))return;await bo(50)}throw new Error(`Spawned broker never became reachable at ${e}`)}var bo=e=>new Promise(r=>setTimeout(r,e));var le="7.0.44"?"7.0.44":"0.0.0-dev";var oe="@buoy-gg/mcp";import{promises as Xt}from"fs";import yo from"os";import $o from"path";var ko=24*60*60*1e3;var _o=1500;var So=`https://registry.npmjs.org/${oe}/latest`;var Zt=$o.join(yo.tmpdir(),"buoy-mcp-update-check.json");function Ao(e,r){const t=s=>s.split("-")[0].split(".").map(a=>Number(a)||0);const n=t(e);const o=t(r);for(let s=0;s<3;s++){const a=n[s]??0;const i=o[s]??0;if(a>i)return true;if(a<i)return false}return false}async function xo(){try{const e=await Xt.readFile(Zt,"utf8");const r=JSON.parse(e);if(typeof r.checkedAt==="number"&&typeof r.latest==="string"){return r}}catch{}return null}async function To(e){const r=new AbortController;const t=setTimeout(()=>r.abort(),_o);try{const n=await fetch(So,{signal:r.signal});if(!n.ok)return null;const o=await n.json();const s=typeof o.version==="string"?o.version:null;if(s){await Xt.writeFile(Zt,JSON.stringify({checkedAt:e,latest:s})).catch(()=>{})}return s}catch{return null}finally{clearTimeout(t)}}async function Io(e){const r=await xo();if(r&&e-r.checkedAt<ko)return r.latest;return To(e)}async function er(e=Date.now()){if(le==="0.0.0-dev")return null;try{const r=await Io(e);if(r&&Ao(r,le)){return`A newer buoy-mcp is available (${r}; you're on ${le}). Update by re-running: npx -y ${oe}@latest init \u2014 then restart your editor.`}}catch{}return null}import{z as K}from"zod";function Te(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function lt(e){return{isError:true,content:[{type:"text",text:e}]}}function tr(e,r){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 er();const n=r.listDevices();if(n.length===0){return Te({devices:[],hint:"No devices connected. Open the app with Buoy devtools running, then retry.",...t?{updateAvailable:t}:{}})}const o=n.filter(c=>c.isConnected);const s=o.some(c=>c.isPro);const a=o.some(c=>c.tier!=="locked");const i=o.filter(c=>c.collision);return Te({devices:n,...i.length>0?{warning:`${i.map(c=>`"${c.deviceId}"`).join(", ")}: more than one app is registered under this id, so actions sent to it land on an arbitrary device. Give each device its own externalSync.deviceId (or leave it unset for a per-install default) before mutating anything.`}:{},...s?{}:{hint:a?"The Buoy MCP is a Pro feature \u2014 the connected device is signed in on the free tier, so data/action tools are blocked. Upgrade to Buoy Pro in the app, or pass `licenseKey` to `<FloatingDevTools />` if it runs headless.":"The broker has not confirmed account access for the connected devices, so data/action tools are blocked. A locked status can mean missing configuration, pending/failed validation, or a missing account announcement after reconnect; it does not prove the user is signed out. Check app account status and broker compatibility."},...t?{updateAvailable:t}:{}})});e.registerTool("list_tool_actions",{description:"List the actions a given tool exposes, and which connected devices offer it. Use the action names with call_action.",inputSchema:{toolId:K.string().describe('The tool id, e.g. "perf-monitor", "network", "react-query".')}},async({toolId:t})=>{const n=r.toolActions(t);if(n.length===0){return lt(`No connected device exposes tool "${t}". Call list_devices to see available tools.`)}return Te({toolId:t,offerings:n})});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:K.string().describe("The tool id to read state from."),deviceId:K.string().optional().describe("Target device id. Omit to auto-select when one device is connected."),timeoutMs:K.number().optional().describe("How long to wait for a fresh snapshot before falling back to the cached one.")}},async({toolId:t,deviceId:n,timeoutMs:o})=>{try{const s=r.requireProDevice(n);const{payload:a}=await r.getSnapshot(t,s,{timeoutMs:o});return Te({toolId:t,deviceId:s,snapshot:a})}catch(s){return lt(rr(s))}});e.registerTool("call_action",{description:"Invoke any action a tool exposes (see list_tool_actions) and return its result. This is the generic escape hatch that works for every Buoy tool.",inputSchema:{toolId:K.string().describe('The tool id, e.g. "perf-monitor".'),action:K.string().describe('The action name, e.g. "startRecording", "clearAll".'),params:K.record(K.unknown()).optional().describe("JSON params object for the action (shape depends on the action)."),deviceId:K.string().optional().describe('Target device id. Omit to auto-select one device, or "All" to broadcast.'),timeoutMs:K.number().optional().describe("Max time to wait for the device's result.")}},async({toolId:t,action:n,params:o,deviceId:s,timeoutMs:a})=>{try{const i=r.requireProDevice(s);const c=await r.callAction(t,n,o,i,{timeoutMs:a});return Te({toolId:t,action:n,ok:true,result:c??null})}catch(i){return lt(rr(i))}})}function rr(e){return e instanceof Error?e.message:String(e)}var ye=(e,r,t)=>Math.max(r,Math.min(t,e));var Do="__batch_warmup__";var Ro={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 ke(e,r,t){return e??r??t}function je(e,r={}){const t=[];const n=(e.targetRoute||"").trim();if(!n)throw new Error("targetRoute is required (the screen to benchmark).");let o=(e.bounceRoute||"").trim();if(!o)o=n==="/"?"/_buoy_bounce":"/";if(o===n){throw new Error(`bounceRoute ("${o}") must differ from targetRoute \u2014 it's the screen we bounce to so the test screen fully remounts each run.`)}if(!Array.isArray(e.cases)||e.cases.length===0){throw new Error("At least one case is required.")}const s=e.cases.map((u,f)=>{const k=(u.name||"").trim()||`case ${f+1}`;return{id:`case-${f}`,name:k,params:u.params??{},route:u.route}});const a=ye(Math.round(ke(e.runsPerCase,r.runsPerCase,$e.runsPerCase)),1,10);const i=ye(Math.round(ke(e.coolDownMs,r.coolDownMs,$e.coolDownMs)),0,3e4);const c=ye(Math.round(ke(e.discardWarmupRuns,r.discardWarmupRuns,$e.discardWarmupRuns)),0,a-1);const d=e.shuffleCases??r.shuffleCases??s.length>3;if(s.length>3&&d===false){t.push("shuffleCases is off with >3 cases \u2014 later cases may be thermally throttled, biasing results. Consider enabling it.")}if(a===1){t.push("runsPerCase=1 \u2014 no median/variance; a single noisy run can mislead. 3+ is recommended.")}const l={targetRoute:n,bounceRoute:o,perCaseDurationMs:ye(Math.round(ke(e.perCaseDurationMs,r.perCaseDurationMs,$e.perCaseDurationMs)),1e3,6e4),settleMs:ye(Math.round(ke(e.settleMs,r.settleMs,$e.settleMs)),0,1e4),navTimeoutMs:ye(Math.round(ke(e.navTimeoutMs,r.navTimeoutMs,$e.navTimeoutMs)),1e3,3e4),cases:s,runsPerCase:a,coolDownMs:i,discardWarmupRuns:c,discardWarmupCase:e.discardWarmupCase??r.discardWarmupCase??true,shuffleCases:d,reloadBetweenCases:e.reloadBetweenCases??r.reloadBetweenCases??false,captureRenders:e.captureRenders??r.captureRenders??true};return{config:l,warnings:t}}function nr(e){const r=c=>c>=1e3?`${(c/1e3).toFixed(c%1e3?1:0)}s`:`${c}ms`;const t=e.runsPerCase??1;const n=ut(e);const o=n/6e4;const s=o>=1?`~${o.toFixed(1)} min`:`~${Math.round(n/1e3)}s`;const a=[`**${r(e.perCaseDurationMs)} measured per page**`,t>1?`**${t} runs each** (median taken)`:`**1 run each** (no median \u2014 noisier)`,e.reloadBetweenCases?"**full reload between pages** (no state leaks across tests)":"no reload between pages",e.shuffleCases?"shuffled order (cancels thermal bias)":"fixed order",e.captureRenders!==false?"render capture on (per-component why-data)":"render capture off"];const i=e.settleMs+e.perCaseDurationMs+(e.coolDownMs??0)+1800;return`${a.join(", ")}. That's ~${r(i)} wall-clock per page; for ${e.cases.length} page(s) \xD7 ${t} run(s), **${s}** total.`}function ut(e){const r=1800;const t=e.settleMs+e.perCaseDurationMs+e.coolDownMs+r;let n=e.cases.length*(e.runsPerCase??1)*t;if(e.reloadBetweenCases)n+=e.cases.length*3e3;return n}function Oo(e){const r=[];const t=e.deviceMaxRefreshRate;if(e.uiFps!=null&&t&&e.uiFps<t*.95){r.push("UI thread drops frames")}else if(e.uiJank!=null&&e.uiJank>=2){r.push("UI jank spikes")}if(e.cpu!=null&&e.cpu>=90)r.push("CPU near cap");if(e.jsJank!=null&&e.jsJank>=5)r.push("JS thread stalls");return r}function Be(e,r,t,n=[]){const o=e.filter(h=>h.batchId===r);const s=new Map(n.map(h=>[h.index,h.reason]));const a=Array.from(new Set(o.map(h=>h.batchIndex??0))).sort((h,g)=>h-g);const i=h=>{const g=o.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=a.map(h=>{const g=i(h);const v=o.filter(C=>(C.batchIndex??0)===h).length;const w=g?.name??t?.[h]?.name??`case ${h+1}`;const x=s.get(h)??g?.batchFailureReason;const T=Boolean(x)||!g;const O={batchIndex:h,caseName:w,params:g?.params??{},runs:v,failed:T,failureReason:T?x??"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??[]};return{...O,flags:T?[]:Oo(O)}}).filter(h=>h.caseName!==Do).map((h,g)=>({...h,batchIndex:g}));const l=d[0];if(l){for(const h of d){if(h===l)continue;if(h.uiFps!=null&&l.uiFps!=null)h.deltaUiFps=ue(h.uiFps-l.uiFps,1);if(h.jsFps!=null&&l.jsFps!=null)h.deltaJsFps=ue(h.jsFps-l.jsFps,1)}}const u=d.filter(h=>!h.failed);const f=(h,g)=>{let v;let w=NaN;for(const x of u){const T=h(x);if(T==null)continue;if(v===void 0||g(T,w)){v=x;w=T}}return v?.caseName};const k=h=>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)};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??0)-(h.uiFps??0)||(h.cpu??Infinity)-(g.cpu??Infinity)||(h.memMb??Infinity)-(g.memMb??Infinity)).map(h=>h.caseName);return{batchId:r,baselineName:l?.caseName??null,deviceMaxRefreshRate:u.find(h=>h.deviceMaxRefreshRate!=null)?.deviceMaxRefreshRate??null,rows:d,leaders:y,flagged:p,balanced:b}}function Pe(e){const r=(u,f=1)=>u==null?"\u2014":u.toFixed(f);const t=u=>u==null?"":u>0?` (+${u.toFixed(1)})`:` (${u.toFixed(1)})`;const n=[];n.push(`### Benchmark batch \`${e.batchId}\``);n.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.`);n.push("");const o=e.rows.some(u=>u.thermalState);const s=o?" Thermal |":"";const a=o?"-------|":"";n.push(`| # | Case | UI FPS | JS FPS | CPU % | Mem MB | JS jank | UI jank |${s} Flags |`);n.push(`|---|------|-------:|-------:|------:|-------:|--------:|--------:|${a}-------|`);for(const u of e.rows){const f=o?` ${Ro[u.thermalState??"unknown"]??"\u2014"} |`:"";if(u.failed){n.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";n.push(`| ${u.batchIndex} | ${u.caseName} | ${r(u.uiFps)}${t(u.deltaUiFps)} | ${r(u.jsFps)}${t(u.deltaJsFps)} | ${r(u.cpu)} | ${r(u.memMb)} | ${r(u.jsJank,0)} | ${r(u.uiJank,0)} |${f} ${k} |`)}const i=e.rows.filter(u=>u.thermalState==="serious"||u.thermalState==="critical");if(i.length){n.push("");n.push(`**\u{1F525} Thermally throttled: ${i.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.`)}n.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)n.push(`**Per-metric best:** ${d}`);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.`);if(e.flagged.length){n.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){n.push("");n.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.");n.push(...l)}n.push("");n.push(`_Deltas vs baseline (case #0). Don't pick on one metric \u2014 explain the trade-off (e.g. "A is cheapest but drops UI frames \u2192 jank risk; B costs more CPU but caps nothing")._`);return n.join("\n")}function or(e,r){const t=(n,o)=>({a:{avg:ue(n.avg,1),p95:ue(n.p95,1)},b:{avg:ue(o.avg,1),p95:ue(o.p95,1)},deltaAvg:ue(o.avg-n.avg,1)});return{a:e.name,b:r.name,uiFps:t(e.stats.uiFps,r.stats.uiFps),jsFps:t(e.stats.jsFps,r.stats.jsFps),cpuUsage:t(e.stats.cpuUsage,r.stats.cpuUsage),memoryUsage:t(e.stats.memoryUsage,r.stats.memoryUsage),jsJankFrames:{a:e.stats.jsJankFrames,b:r.stats.jsJankFrames,delta:r.stats.jsJankFrames-e.stats.jsJankFrames},uiJankFrames:{a:e.stats.uiJankFrames,b:r.stats.uiJankFrames,delta:r.stats.uiJankFrames-e.stats.uiJankFrames},...Mo(e.renders,r.renders)}}function Mo(e,r){if(!e&&!r)return null;const t=n=>n??0;return{renders:{total:{a:t(e?.totalRenders),b:t(r?.totalRenders),delta:t(r?.totalRenders)-t(e?.totalRenders)},commits:{a:t(e?.totalCommits),b:t(r?.totalCommits),delta:t(r?.totalCommits)-t(e?.totalCommits)},wasted:{a:t(e?.wastedRenders),b:t(r?.wastedRenders),delta:t(r?.wastedRenders)-t(e?.wastedRenders)},causes:{a:e?.causes??{},b:r?.causes??{}}}}}function ue(e,r){const t=Math.pow(10,r);return Math.round(e*t)/t}import{z as R}from"zod";import{z as Co}from"zod";var $=e=>({content:[{type:"text",text:e}]});var m=e=>({isError:true,content:[{type:"text",text:e}]});var A=e=>e instanceof Error?e.message:String(e);var S=Co.string().optional().describe("Target device id (auto-selected if one is connected).");function Eo(e,r){return typeof e==="number"&&e>0?e:r}function Fo(e){return e?`${e}
|
|
3
|
+
|
|
4
|
+
`:""}function sr(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 Ie(e,r){return async t=>{try{const n=e.requireProDevice(t.deviceId);return await r(t,n)}catch(n){return m(A(n))}}}var N="perf-monitor";var De=1500;var Re=e=>new Promise(r=>setTimeout(r,e));var ar=e=>({content:[{type:"text",text:JSON.stringify(e,null,2)}]});var qo=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 dt(e,r){try{const t=await e.callAction(N,"getAutomationConfig",{},r);if(!t)return{};const{perCaseDurationMs:n,settleMs:o,navTimeoutMs:s,runsPerCase:a,coolDownMs:i,discardWarmupRuns:c,shuffleCases:d,reloadBetweenCases:l,captureRenders:u}=t;return{perCaseDurationMs:n,settleMs:o,navTimeoutMs:s,runsPerCase:a,coolDownMs:i,discardWarmupRuns:c,shuffleCases:d,reloadBetweenCases:l,captureRenders:u}}catch{return{}}}async function X(e,r){const{payload:t}=await e.getSnapshot(N,r,{timeoutMs:4e3});return t}function ht(e){const r=new Set;for(const t of e??[])if(t.batchId)r.add(t.batchId);return r}function ir(e,r){return(e??[]).filter(t=>t.batchId===r).length}function jo(e){let r=null;for(const t of e??[]){if(t.batchId&&(!r||t.createdAt>r.at))r={id:t.batchId,at:t.createdAt}}return r?.id??null}function de(e,r){const t=new Map;for(const n of e??[]){if(n.batchId===r&&n.batchFailureReason&&!t.has(n.batchIndex??0)){t.set(n.batchIndex??0,n.batchFailureReason)}}return[...t.entries()].map(([n,o])=>({index:n,reason:o}))}function Bo(e){const r=e.cases.length+(e.discardWarmupCase===true?1:0);return r*(e.runsPerCase??1)}var Po=1e4;function No(e){return!!e&&e!=="idle"&&e!=="done"&&e!=="cancelled"}async function cr(e,r,t,n=Po){const o=Date.now();while(Date.now()-o<n){const s=await X(e,r).catch(()=>null);if(s&&!No(s.live?.automation?.phase))return true;await Re(De)}t(`automation still busy after ${Math.round(n/1e3)}s`);return false}async function Lo(e,r,t){const{preBatchIds:n,expectedRuns:o,maxWaitMs:s,log:a}=t;const i=Date.now();let c="";let d=false;let l=0;while(Date.now()-i<s){let k;try{k=await X(e,r)}catch{await Re(De);continue}const y=k.index??[];const p=k.live?.automation?.phase??"idle";const b=k.live?.automationCompleted;if(b?.phase==="cancelled"&&!n.has(b.batchId)){return{batchId:b.batchId,failures:[],cancelled:true}}if(b?.phase==="done"&&!n.has(b.batchId)){return{batchId:b.batchId,failures:b.failures??de(y,b.batchId)}}if(p!=="idle")d=true;if(p!==c){c=p;a(`automation phase: ${p}`)}const h=[...ht(y)].find(g=>!n.has(g));if(h){const g=ir(y,h);if(o>0&&g>=o){await cr(e,r,a);a(`batch ${h} complete (${g}/${o} runs saved)`);return{batchId:h,failures:de(y,h)}}if(p==="idle"&&d&&g>0){if(++l>=3){a(`batch ${h} settled (${g} runs, automation idle)`);return{batchId:h,failures:de(y,h)}}}else{l=0}}await Re(De)}const u=await X(e,r).catch(()=>null);const f=u?[...ht(u.index)].find(k=>!n.has(k)):void 0;if(f&&u)return{batchId:f,failures:de(u.index,f),timedOut:true};throw new Error(`Batch did not start within ${Math.round(s/1e3)}s (last phase: ${c||"idle"}). Check get_automation_status \u2014 the device may not have navigated.`)}function lr(e,r){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(qo).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 n=o=>process.stderr.write(`[buoy-mcp] ${o}
|
|
5
|
+
`);try{const o=r.requireProDevice(t.deviceId);const s=await dt(r,o);const{config:a,warnings:i}=je(t,s);const c=ut(a);const d=t.maxWaitMs??c*3+6e4;const l=Bo(a);if(!await cr(r,o,n)){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 r.callAction(N,"acknowledgeAutomation",{},o).catch(()=>{});await r.callAction(N,"setEnabled",{enabled:true},o).catch(()=>{});await r.callAction(N,"refreshIndex",{},o).catch(()=>{});const u=await X(r,o);const f=ht(u.index);n(`starting batch: ${a.cases.length} cases \xD7 ${a.runsPerCase} runs (~${Math.round(c/1e3)}s estimated) on ${o}`);await r.callAction(N,"startAutomation",{config:a},o);const k=await Lo(r,o,{preBatchIds:f,expectedRuns:l,maxWaitMs:d,log:n});if(k.cancelled){await r.callAction(N,"acknowledgeAutomation",{},o).catch(()=>{});return m(`Batch ${k.batchId} was cancelled before completing.`)}await r.callAction(N,"refreshIndex",{},o).catch(()=>{});const y=await X(r,o);const p=Be(y.index??[],k.batchId,a.cases,k.failures);await r.callAction(N,"acknowledgeAutomation",{},o).catch(()=>{});await r.callAction(N,"setEnabled",{enabled:false},o).catch(()=>{});const b=Pe(p);const h={batchId:k.batchId,leaders:p.leaders,balanced:p.balanced,flagged:p.flagged,rows:p.rows,failures:k.failures,warnings:i,estimateMs:c,...k.timedOut?{note:"Wait cap hit \u2014 results may be partial (some runs may still be saving)."}:{}};return $(`${b}
|
|
6
|
+
|
|
7
|
+
\`\`\`json
|
|
8
|
+
${JSON.stringify(h,null,2)}
|
|
9
|
+
\`\`\``)}catch(o){return m(A(o))}});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 n=r.requireProDevice(t);const o=await X(r,n);return ar({deviceId:n,automation:o.live?.automation??{phase:"idle"},automationCompleted:o.live?.automationCompleted??null})}catch(n){return m(A(n))}});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:n})=>{const o=a=>process.stderr.write(`[buoy-mcp] ${a}
|
|
10
|
+
`);const s=n??6e5;try{const a=r.requireProDevice(t);const i=Date.now();let c=false;let d=0;let l=-1;let u=null;while(Date.now()-i<s){let y;try{y=await X(r,a)}catch{await Re(De);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??de(y.index,p.batchId)};break}const b=y.live?.automation?.phase??"idle";if(b!=="idle")c=true;const h=jo(y.index);if(b==="idle"&&h){const g=ir(y.index,h);if(g===l){if(c&&++d>=3){u={batchId:h,failures:de(y.index,h)};break}if(!c&&Date.now()-i>4e3){u={batchId:h,failures:de(y.index,h)};break}}else{d=0;l=g}}else{d=0}await Re(De)}if(!u)return m("No automation batch completed within the wait window.");await r.callAction(N,"refreshIndex",{},a).catch(()=>{});const f=await X(r,a);const k=Be(f.index??[],u.batchId,void 0,u.failures);await r.callAction(N,"acknowledgeAutomation",{},a).catch(()=>{});return $(`${Pe(k)}
|
|
11
|
+
|
|
12
|
+
\`\`\`json
|
|
13
|
+
${JSON.stringify(k,null,2)}
|
|
14
|
+
\`\`\``)}catch(a){return m(A(a))}});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:n})=>{try{const o=r.requireProDevice(n);await r.callAction(N,"refreshIndex",{},o).catch(()=>{});const s=await X(r,o);const a=(s.index??[]).filter(c=>c.batchId===t);if(a.length===0)return m(`No saved runs found for batch "${t}".`);const i=Be(s.index??[],t);return $(`${Pe(i)}
|
|
15
|
+
|
|
16
|
+
\`\`\`json
|
|
17
|
+
${JSON.stringify(i,null,2)}
|
|
18
|
+
\`\`\``)}catch(o){return m(A(o))}});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:n,deviceId:o})=>{try{const s=r.requireProDevice(o);const[a,i]=await Promise.all([r.callAction(N,"loadReport",{id:t},s),r.callAction(N,"loadReport",{id:n},s)]);if(!a)return m(`Report "${t}" not found.`);if(!i)return m(`Report "${n}" not found.`);return ar(or({name:a.metadata.name,stats:a.stats,renders:a.renders},{name:i.metadata.name,stats:i.stats,renders:i.renders}))}catch(s){return m(A(s))}});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:n})=>{try{const o=r.requireProDevice(n);const s=await dt(r,o);const a=Math.max(1,Math.round(t??1));const{config:i}=je({targetRoute:"/_preview",cases:Array.from({length:a},(d,l)=>({name:`page ${l+1}`}))},s);const c=Object.keys(s).length>0?"this device's saved settings":"default profile (none saved)";return $(`**Benchmark settings (${c}):** ${nr(i)}
|
|
19
|
+
|
|
20
|
+
\`\`\`json
|
|
21
|
+
${JSON.stringify(s,null,2)}
|
|
22
|
+
\`\`\``)}catch(o){return m(A(o))}});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 n=r.requireProDevice(t.deviceId);const o=await r.callAction(N,"getAutomationConfig",{},n)??{};const s=["perCaseDurationMs","settleMs","coolDownMs","navTimeoutMs","runsPerCase","discardWarmupRuns","shuffleCases","reloadBetweenCases","captureRenders"];const a={};for(const u of s){const f=t[u];if(f!==void 0)a[u]=f}if(Object.keys(a).length===0){return m("No settings provided to save. Pass at least one field (e.g. perCaseDurationMs).")}const i={...o,...a};const c=await r.callAction(N,"setAutomationConfig",{config:i},n);const d=await dt(r,n);const{config:l}=je({targetRoute:"/_preview",cases:[{name:"page 1"}]},d);return $(`Saved. **New benchmark settings:** ${nr(l)}
|
|
23
|
+
|
|
24
|
+
\`\`\`json
|
|
25
|
+
${JSON.stringify(c??d,null,2)}
|
|
26
|
+
\`\`\``)}catch(n){return m(A(n))}})}import{z as he}from"zod";var Uo="events";var zo={storage:["storage-async","storage-mmkv"],"react-query":["react-query","react-query-query","react-query-mutation"]};function Jo(e){if(!e||e.length===0)return void 0;return[...new Set(e.flatMap(r=>zo[r]??[r]))]}function ur(e,r){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:he.number().optional().describe("Most-recent N events to include. Default 25."),sources:he.array(he.string()).optional().describe('Only these sources. Coarse names accepted: "network", "redux", "react-query", "storage", "route", "render", "zustand", "jotai". Omit for all.'),status:he.enum(["all","errors","success","pending"]).optional().describe("Filter by status. Default all."),includeData:he.boolean().optional().describe("Include each event's full raw payload (HEAVY \u2014 network bodies, state trees). Default false (compact)."),format:he.enum(["markdown","json","text","mermaid"]).optional().describe("Output format. Default markdown."),preset:he.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 n=r.requireProDevice(t.deviceId);const o={};const s=Jo(t.sources);if(s)o.filterSources=s;if(t.status)o.filterMode=t.status;if(t.includeData!==void 0)o.includeEventData=t.includeData;if(t.format)o.format=t.format==="text"?"plaintext":t.format;const a=await r.callAction(Uo,"exportEvents",{preset:t.preset,settings:o,limit:t.limit??25},n);if(!a||typeof a.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 i=a.includedData?"":" \u2014 compact view; pass includeData:true, a specific source, or a bigger limit for full payloads";const c=`
|
|
27
|
+
|
|
28
|
+
_Showing ${a.returned} of ${a.totalAvailable} captured event(s)${i}._`;return $((a.output||"(no events captured)")+c)}catch(n){return m(A(n))}})}import{z as Oe}from"zod";var Wo="query";var Vo="react-query";async function pt(e,r,t,n){try{return await e.callAction(Wo,r,t,n)}catch(o){const s=A(o);if(!/unknown tool/i.test(s))throw o;return await e.callAction(Vo,r,t,n)}}var Go={fresh:"\u{1F7E2}",stale:"\u{1F7E1}",fetching:"\u{1F504}",error:"\u{1F534}",inactive:"\u26AA\uFE0F",paused:"\u23F8\uFE0F",disabled:"\u{1F6AB}"};function Ko(e){if(!e)return"\u2014";const r=Math.round((Date.now()-e)/1e3);if(r<60)return`${r}s ago`;if(r<3600)return`${Math.round(r/60)}m ago`;if(r<86400)return`${Math.round(r/3600)}h ago`;return`${Math.round(r/86400)}d ago`}function dr(e,r){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:Oe.boolean().optional().describe("Include each query's full cached data payload (HEAVY). Default false."),staleOnly:Oe.boolean().optional().describe("Only stale queries. Default false."),limit:Oe.number().optional().describe("Most-recently-updated N queries. Default 25."),deviceId:S}},async t=>{try{const n=r.requireProDevice(t.deviceId);const o=await pt(r,"listQueries",{includeData:t.includeData??false,staleOnly:t.staleOnly??false,limit:t.limit??25},n);if(!o||!Array.isArray(o.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(o.queries.length===0){return $(`React Query cache is empty (0 of ${o.total} queries${t.staleOnly?" match staleOnly":""}).`)}const s=o.queries.map((d,l)=>{const u=Go[d.status]??"\u2022";const f=`${l+1}. ${u} ${d.status} \xB7 \`${d.queryHash}\` \xB7 ${d.observers} obs \xB7 ${Ko(d.updatedAt)}`;const k=d.error?` \u2014 \u26A0\uFE0F ${d.error}`:"";const y=o.includedData?`
|
|
29
|
+
data: ${JSON.stringify(d.data)}`:"";return f+k+y});const a=o.queries.filter(d=>d.isStale).length;const i=`**React Query cache \u2014 ${o.total} queries (showing ${o.returned}, ${a} stale):**`;const c=o.includedData?"":"\n\n_Compact view. Pass includeData:true for cached payloads, staleOnly:true to narrow. Act on one with react_query_action using the `hash` in backticks._";return $(`${i}
|
|
30
|
+
|
|
31
|
+
${s.join("\n")}${c}`)}catch(n){return m(A(n))}});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:Oe.enum(["invalidate","refetch","reset","remove","clear"]).describe("invalidate/refetch/reset/remove a single query (needs queryHash); clear empties the whole query cache."),queryHash:Oe.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 n=r.requireProDevice(t.deviceId);if(t.action==="clear"){await pt(r,"clearQueryCache",{},n);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 pt(r,t.action,{queryHash:t.queryHash},n);return $(`Requested ${t.action} on query \`${t.queryHash}\`.`)}catch(n){return m(A(n))}})}import{z as pe}from"zod";var mt="zustand";function hr(e,r){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:pe.boolean().optional().describe("Include each store's full current state object (HEAVY). Default false (keys only)."),limit:pe.number().optional().describe("First N stores. Default all."),deviceId:S}},Ie(r,async(t,n)=>{const o=await r.callAction(mt,"listStores",{includeValues:t.includeValues??false,limit:t.limit},n);if(!o||!Array.isArray(o.stores)){return m(sr({toolId:mt,mcpTool:"get_zustand_state",action:"listStores"}))}if(o.stores.length===0){return $("No Zustand stores are registered (call watchStores to register them).")}const s=o.stores.map((i,c)=>{const d=i.isPersisted?` \xB7 persisted${i.persistName?` (${i.persistName})`:""}`:"";const l=o.includedValues?`
|
|
32
|
+
${JSON.stringify(i.currentState)}`:` \xB7 keys: ${(i.keys??[]).join(", ")||"\u2014"}`;return`${c+1}. **${i.name}** \xB7 ${i.changes} changes${d}${l}`});const a=o.includedValues?"":"\n\n_Compact view (keys only). Pass includeValues:true for full state. Mutate with zustand_action({store, state})._";return $(`**Zustand stores \u2014 ${o.total} (showing ${o.returned}):**
|
|
33
|
+
|
|
34
|
+
${s.join("\n")}${a}`)}));e.registerTool("zustand_action",{description:"Set the state of a Zustand store (time-travel / reset / tweak during debugging). Targets a store by name (from get_zustand_state). By default replaces the whole state; pass replace:false to merge a partial.",inputSchema:{store:pe.string().describe("Store name to target (from get_zustand_state)."),state:pe.record(pe.string(),pe.unknown()).describe("The new state object."),replace:pe.boolean().optional().describe("Replace the whole state (default true) or merge a partial (false)."),deviceId:S}},Ie(r,async(t,n)=>{await r.callAction(mt,"setState",{storeName:t.store,state:t.state,replace:t.replace??true},n);return $(`Requested state update on Zustand store "${t.store}" (${t.replace===false?"merged":"replaced"}).`)}))}import{z as Ne}from"zod";var ft="jotai";function pr(e,r){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:Ne.boolean().optional().describe("Include each atom's current value (HEAVY). Default false."),limit:Ne.number().optional().describe("First N atoms. Default all."),deviceId:S}},Ie(r,async(t,n)=>{const o=await r.callAction(ft,"listAtoms",{includeValues:t.includeValues??false,limit:t.limit},n);if(!o||!Array.isArray(o.atoms)){return m(sr({toolId:ft,mcpTool:"get_jotai_state",action:"listAtoms"}))}if(o.atoms.length===0){return $("No Jotai atoms are being watched (call watchAtoms to register them).")}const s=o.atoms.map((i,c)=>{const d=i.writable?"writable":"read-only";const l=o.includedValues?`
|
|
35
|
+
${JSON.stringify(i.currentValue)}`:"";return`${c+1}. **${i.label}** \xB7 ${i.changes} changes \xB7 ${d}${l}`});const a=o.includedValues?"":"\n\n_Compact view. Pass includeValues:true for current values. Set a writable atom with jotai_action({atom, value})._";return $(`**Jotai atoms \u2014 ${o.total} (showing ${o.returned}):**
|
|
36
|
+
|
|
37
|
+
${s.join("\n")}${a}`)}));e.registerTool("jotai_action",{description:"Set the value of a writable Jotai atom (by label, from get_jotai_state). Read-only/derived atoms cannot be set (you'll get a clear error). Use for tweaking state during debugging.",inputSchema:{atom:Ne.string().describe("Atom label to set (from get_jotai_state; must be writable)."),value:Ne.unknown().describe("The new value (any JSON \u2014 number, string, object, etc.)."),deviceId:S}},Ie(r,async(t,n)=>{await r.callAction(ft,"setAtom",{label:t.atom,value:t.value},n);return $(`Requested update of Jotai atom "${t.atom}" to ${JSON.stringify(t.value)}.`)}))}import{z as gt}from"zod";var mr="redux";function fr(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 Ho="\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 gr(e,r){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:gt.boolean().optional().describe("Include the full current state tree (HEAVY). Default false (slice names only)."),deviceId:S}},async t=>{try{const n=r.requireProDevice(t.deviceId);const o=await r.callAction(mr,"getState",{includeValues:t.includeValues??false},n);if(!o){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(!o.available)return m(fr(o.reason));const s=o.slices.length?o.slices.join(", "):"(none)";const a=o.capture==="top-level-only"?Ho:"";if(t.includeValues){return $(`**Redux store \u2014 slices: ${s}**
|
|
38
|
+
|
|
39
|
+
\`\`\`json
|
|
40
|
+
${JSON.stringify(o.state,null,2)}
|
|
41
|
+
\`\`\`${a}`)}return $(`**Redux store \u2014 slices: ${s}**
|
|
42
|
+
|
|
43
|
+
_Compact view. Pass includeValues:true for the full state tree. Dispatch with redux_dispatch({type, payload})._${a}`)}catch(n){return m(A(n))}});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:gt.string().describe('The action type, e.g. "counter/increment" or "auth/logout".'),payload:gt.unknown().optional().describe("Optional action payload (any JSON)."),deviceId:S}},async t=>{try{const n=r.requireProDevice(t.deviceId);const o={type:t.type};if(t.payload!==void 0)o.payload=t.payload;const s=await r.callAction(mr,"dispatch",{action:o},n);if(!s||!s.dispatched)return m(fr(s?.reason));return $(`Dispatched \`${t.type}\`${t.payload!==void 0?` with payload ${JSON.stringify(t.payload)}`:""}.`)}catch(n){return m(A(n))}})}import{z as _e}from"zod";var se="storage";function vt(e,r=200){if(e===null||e===void 0)return"(null)";const t=typeof e==="string"?e:JSON.stringify(e);return t.length>r?`${t.slice(0,r)}\u2026(+${t.length-r} chars)`:t}function vr(e,r){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:_e.string().optional().describe("Only keys containing this substring (case-insensitive)."),includeValues:_e.boolean().optional().describe("Include each key's value (truncated). Default false (keys only)."),limit:_e.number().optional().describe("Max keys per backend section. Default 100."),deviceId:S}},async t=>{try{const n=r.requireProDevice(t.deviceId);const o=t.pattern?.toLowerCase();const s=typeof t.limit==="number"&&t.limit>0?t.limit:100;const a=y=>!o||y.toLowerCase().includes(o);const i=[];const c=await r.callAction(se,"async.getAllKeys",{},n);if(!Array.isArray(c)){return m("No storage result from the device. The storage tool may be inactive.")}const d=c.filter(a).slice(0,s);if(d.length>0){let y;if(t.includeValues){const p=await r.callAction(se,"async.multiGet",{keys:d},n);const b=new Map((p??[]).map(([h,g])=>[h,g]));y=d.map(h=>`- \`${h}\` = ${vt(b.get(h)??null)}`)}else{y=d.map(p=>`- \`${p}\``)}i.push(`**AsyncStorage (${d.length}/${c.length} keys):**
|
|
44
|
+
${y.join("\n")}`)}const l=await r.callAction(se,"mmkv.snapshot",{},n).catch(()=>null);for(const y of l??[]){const p=y.entries.filter(g=>a(g.key)).slice(0,s);if(p.length===0)continue;const b=p.map(g=>t.includeValues?`- \`${g.key}\` (${g.valueType}) = ${vt(g.value)}`:`- \`${g.key}\``);const h=[y.encrypted&&"encrypted",y.readOnly&&"read-only"].filter(Boolean).join(", ");i.push(`**MMKV \`${y.id}\`${h?` (${h})`:""} (${p.length}/${y.entries.length} keys):**
|
|
45
|
+
${b.join("\n")}`)}const u=await r.callAction(se,"secure.keys",{},n).catch(()=>null);const f=(u??[]).filter(y=>a(y.key)).slice(0,s);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 r.callAction(se,"secure.get",{key:p.key},n).catch(()=>null);return`- \`${p.key}\` = ${vt(b)}`}));i.push(`**SecureStore (${f.length} registered keys):**
|
|
46
|
+
${y.join("\n")}`)}if(i.length===0){return $(`No storage keys${o?` matching "${t.pattern}"`:""} in any backend.`)}const k=t.includeValues?"":"\n\n_Keys only. Pass includeValues:true for values, or a pattern to filter. Modify AsyncStorage with storage_action._";return $(`${i.join("\n\n")}${k}`)}catch(n){return m(A(n))}});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:_e.enum(["set","remove","clear"]).describe("set/remove a key, or clear supported app AsyncStorage keys."),key:_e.string().optional().describe("The key (required for set and remove)."),value:_e.string().optional().describe("The string value to store (required for set; JSON-encode objects)."),deviceId:S}},async t=>{try{const n=r.requireProDevice(t.deviceId);if(t.action==="clear"){await r.callAction(se,"clearAppStorage",{},n);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 r.callAction(se,"async.removeItem",{key:t.key},n);return $(`Requested removal of storage key "${t.key}".`)}if(t.value===void 0){return m("'set' needs a value (a string).")}await r.callAction(se,"async.setItem",{key:t.key,value:t.value},n);return $(`Requested update of storage key "${t.key}".`)}catch(n){return m(A(n))}})}import{z as wt}from"zod";var wr="route-events";function br(e,r=[]){for(const t of e??[]){if(t.path)r.push(t.path);if(t.children?.length)br(t.children,r)}return r}function yr(e,r){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:wt.boolean().optional().describe("Also list available configured route paths (can be long). Default false."),deviceId:S}},async t=>{try{const n=r.requireProDevice(t.deviceId);const{payload:o}=await r.getSnapshot(wr,n);const s=Array.isArray(o)?{events:o}:o??{};const a=Array.isArray(s.stack)?s.stack:[];const i=a.find(u=>u.isFocused)??a[a.length-1];const c=i?.pathname??"(unknown)";const d=[`**Current route:** \`${c}\``];if(a.length){const u=a.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=br(s.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(n){return m(A(n))}});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:wt.string().describe("The concrete path to navigate to, e.g. '/pokemon/25'."),replace:wt.boolean().optional().describe("Replace the current screen instead of pushing (use when resetting, e.g. to '/')."),deviceId:S}},async t=>{try{const n=r.requireProDevice(t.deviceId);await r.callAction(wr,"navigate",{path:t.path,replace:t.replace===true},n);return $(`Navigated to \`${t.path}\`${t.replace?" (replaced current screen)":""}.`)}catch(n){return m(A(n))}})}import{z as bt}from"zod";var Yo="console";var $r={verbose:0,info:1,warning:2,error:3};var Qo={verbose:"\xB7",info:"info",warning:"warn",error:"ERR"};function Xo(e){const r=new Date(e);const t=(n,o=2)=>String(n).padStart(o,"0");return`${t(r.getHours())}:${t(r.getMinutes())}:${t(r.getSeconds())}.${t(r.getMilliseconds(),3)}`}function kr(e,r){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:bt.enum(["verbose","info","warning","error"]).optional().describe("Minimum level to include (severity threshold). e.g. 'warning' = warnings + errors. Default all."),limit:bt.number().optional().describe("Most-recent N entries. Default 50."),pattern:bt.string().optional().describe("Only entries whose message contains this substring (case-insensitive)."),deviceId:S}},Ie(r,async(t,n)=>{const{payload:o,stale:s}=await r.getSnapshot(Yo,n);const a=Fo(s);const i=Array.isArray(o)?{entries:o}:o??{};const c=Array.isArray(i.entries)?i.entries:[];const d=t.level?$r[t.level]:0;const l=t.pattern?.toLowerCase();const u=c.filter(g=>$r[g.level]>=d&&(!l||(g.message??"").toLowerCase().includes(l)));const f=[...u].sort((g,v)=>g.id-v.id);const k=Eo(t.limit,50);const y=f.slice(-k);if(y.length===0){return $(`${a}No console entries${t.level?` at level \u2265 ${t.level}`:""}${l?` matching "${t.pattern}"`:""} (${c.length} total captured).`)}const p=y.map(g=>`${Xo(g.timestamp)} [${Qo[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 $(`${a}${h}
|
|
52
|
+
|
|
53
|
+
\`\`\`
|
|
54
|
+
${p.join("\n")}
|
|
55
|
+
\`\`\`
|
|
56
|
+
|
|
57
|
+
_Tail of recent logs. Use get_snapshot for available console entry details._`)}))}import{z as yt}from"zod";import{execFile as Zo}from"child_process";import{promisify as es}from"util";import{promises as Le}from"fs";import _r from"os";import Sr from"path";import{randomUUID as Ar}from"crypto";var xr=es(Zo);var Ue=(e,r,t)=>Math.min(Math.max(e,r),t);function ts(e){const r=e;if(r?.code==="ENOENT"){return"Xcode command-line tools (xcrun) not found. Install Xcode to capture the iOS Simulator."}const t=String(r?.stderr||r?.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 rs(e){const r=[137,80,78,71,13,10,26,10];if(e.length<24||!r.every((t,n)=>e[n]===t))return null;return{width:e.readUInt32BE(16),height:e.readUInt32BE(20)}}async function ns(){if(process.platform!=="darwin"){return{ok:false,error:"Screenshotting a component requires macOS with Xcode's iOS Simulator (uses `xcrun simctl`)."}}const e=Sr.join(_r.tmpdir(),`buoy-mcp-sim-${Ar()}.png`);try{await xr("xcrun",["simctl","io","booted","screenshot","--type=png",e],{timeout:15e3})}catch(r){return{ok:false,error:ts(r)}}try{const r=await Le.readFile(e);const t=rs(r);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(r){return{ok:false,error:`Failed to read screenshot: ${r.message}`}}}async function os(e,r,t){const n=Ue(Math.round(t.x),0,Math.max(0,r.width-1));const o=Ue(Math.round(t.y),0,Math.max(0,r.height-1));const s=Ue(Math.round(t.width),1,r.width-n);const a=Ue(Math.round(t.height),1,r.height-o);const i=Sr.join(_r.tmpdir(),`buoy-mcp-crop-${Ar()}.png`);try{await xr("sips",["-c",String(a),String(s),"--cropOffset",String(o),String(n),e,"--out",i],{timeout:1e4});const c=await Le.readFile(i);return{ok:true,buffer:c,width:s,height:a}}catch(c){const d=c;return{ok:false,error:`Crop failed: ${d?.stderr||d?.message||c}`}}finally{await Le.unlink(i).catch(()=>{});await Le.unlink(e).catch(()=>{})}}function ss(e,r,t){if(t!=null){const s=e.find(a=>a.nativeTag===t);if(s)return s}const n=(r??"").trim().toLowerCase();if(!n)return void 0;let o;for(const s of e){const a=[s.testID,s.label,s.text,s.name].filter(Boolean).map(d=>d.toLowerCase());let i=0;for(const d of a){if(d===n)i=Math.max(i,100);else if(d.startsWith(n))i=Math.max(i,50);else if(d.includes(n))i=Math.max(i,25)}const c=s.tap;if(c&&c.x>=0&&c.x<=1&&c.y>=0&&c.y<=1)i+=20;else if(c)i-=40;if(i<=0)continue;if(!o||i>o.score)o={el:s,score:i}}return o?.el}function as(e,r){return{x:e.x*r.width,y:e.y*r.height,width:e.width*r.width,height:e.height*r.height}}var $t="highlight-updates";var is=12;var cs=6;var ze=e=>({isError:true,content:[{type:"text",text:e}]});var ls=e=>e instanceof Error?e.message:String(e);function us(e,r){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 r?`Nothing matched "${r}".`:"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 ds(e){if(!e||e.length===0)return"";const r=e.map(t=>{const n=t.testID||t.nativeID;return`- ${t.componentName||t.viewType}${n?` (${n})`:""} \u2014 nativeTag ${t.nativeTag}, rendered \xD7${t.renderCount}`});return`
|
|
58
|
+
|
|
59
|
+
Closest matches (retry with a more precise query, or pass nativeTag directly):
|
|
60
|
+
${r.join("\n")}`}function Tr(e,r){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:yt.string().optional().describe('Fuzzy match against testID, nativeID, accessibilityLabel, component name, or view type \u2014 e.g. "submit-button".'),nativeTag:yt.number().optional().describe("An exact nativeTag (from a previous call's candidates) to skip fuzzy matching."),scrollIntoView:yt.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 n=r.requireProDevice(t.deviceId);await r.callAction($t,"setSilentTracking",{enabled:true},n).catch(()=>{});const o=await r.callAction($t,"locateComponent",{query:t.query,nativeTag:t.nativeTag,scrollIntoView:t.scrollIntoView??true,margin:is},n);let s=o;if(!s.matched&&(s.reason==="no-renders"||s.reason==="no-match")){const p=await r.callAction($t,"describeScreen",{},n).catch(()=>null);const b=p?.elements?ss(p.elements,t.query,t.nativeTag):void 0;if(b?.frame&&p?.screen){s={matched:true,live:true,rect:as(b.frame,p.screen),screen:p.screen,nativeTag:b.nativeTag??void 0,componentName:b.name,testID:b.testID}}else if(s.reason==="no-renders"){s={matched:false,reason:"no-match",candidates:s.candidates}}}if(!s.matched||!s.rect||!s.screen){return ze(us(s,t.query)+ds(s.candidates))}const a=await ns();if(!a.ok||!a.srcPath||!a.width||!a.height){return ze(a.error??"Screenshot capture failed.")}const i=a.width/s.screen.width;const c=s.rect;const d=cs;const l=await os(a.srcPath,{width:a.width,height:a.height},{x:(c.x-d)*i,y:(c.y-d)*i,width:(c.width+d*2)*i,height:(c.height+d*2)*i});if(!l.ok||!l.buffer){return ze(l.error??"Crop failed.")}const u=s.componentName||"component";const f=s.testID?` (testID: "${s.testID}")`:"";const k=s.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(n){return ze(ls(n))}})}import{McpServer as hs}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as ps}from"zod";import{z as I}from"zod";var L="network";var Ir=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 ms(e){if(Array.isArray(e))return{events:e,saved:[]};if(e&&typeof e==="object"){const r=e;return{events:Array.isArray(r.events)?r.events:[],saved:Array.isArray(r.saved)?r.saved:[]}}return{events:[],saved:[]}}function fs(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 gs(e){if(e.status!==void 0&&e.status>0)return String(e.status);if(e.error){const r=e.error.replace(/^HTTP\s+\d+:\s*/i,"").trim();if(!r||r==="undefined"||r==="no error"){return"ERR"}return`ERR ${e.error}`}if(e.status===void 0)return"pending";return String(e.status)}function vs(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 Dr(e,r){if(!r||r==="all")return true;const t=!!e.error||e.status!==void 0&&e.status>=400;if(r==="errors")return t;if(r==="pending")return e.status===void 0&&!e.error;if(r==="success")return!t&&e.status!==void 0;return true}function ws(e,r=600){if(e===null||e===void 0)return"(none)";const t=typeof e==="string"?e:JSON.stringify(e);return t.length>r?`${t.slice(0,r)}\u2026(+${t.length-r} chars)`:t}var Rr=8;async function Or(e,r,t,n=Rr){const o=r.filter(c=>c.id&&(c.requestBodyOmitted===true&&c.requestData===void 0||c.responseBodyOmitted===true&&c.responseData===void 0));const s=new Map;if(o.length===0)return{bodies:s,skipped:0};const a=o.slice(0,n);const i=await Promise.allSettled(a.map(c=>e.callAction(L,"getEventBody",{id:c.id},t)));i.forEach((c,d)=>{const l=a[d].id;const u=c.status==="fulfilled"?c.value:null;s.set(l,u?{...u}:{unresolved:true})});return{bodies:s,skipped:o.length-a.length}}async function bs(e,r){let t=null;try{t=await e.callAction(L,"getCaptureStatus",{},r)}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 Mr(e){return e>0?`
|
|
61
|
+
|
|
62
|
+
_${e} more withheld ${e===1?"body was":"bodies were"} not fetched (cap ${Rr} per listing, they are large). Get one in full with its id._`:""}function Cr(e,r){const t=e.id?r.get(e.id):void 0;const n=(o,s,a)=>{const i=o??s;if(i!==void 0&&i!==null)return ws(i);if(!a)return"(none)";return t?.unresolved?"(withheld \u2014 the device did not answer getEventBody)":"(none)"};return`
|
|
63
|
+
\u2514\u2500 request: ${n(e.requestData,t?.requestData,e.requestBodyOmitted)}
|
|
64
|
+
\u2514\u2500 response: ${n(e.responseData,t?.responseData,e.responseBodyOmitted)}`}function Er(e,r,t){const n=r.path||r.url;const o=[`${r.duration!==void 0?`${Math.round(r.duration)}ms`:"\u2014"}`,vs(r.responseSize),r.host??"",r.requestClient??""].filter(Boolean);const s=r.operationName?` (${r.operationName})`:"";return`${e}. \`${r.id}\` ${fs(r)} ${gs(r)} ${r.method} ${n}${s}${t?` ${t}`:""}
|
|
65
|
+
\u2514\u2500 ${o.join(" \xB7 ")}`}function ys(e,r){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 n=r.resolveDevice(t.deviceId);const o=await r.callAction(L,t.action==="get"?"getNetworkConditions":"setNetworkConditions",t.action==="set"?{profile:t.profile}:void 0,n);if(!o||typeof o!=="object"||!("profile"in o))return m("The device did not report its effective network conditions.");return $(JSON.stringify(o))}catch(n){return m(A(n))}});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 n=r.requireProDevice(t.deviceId);const{payload:o}=await r.getSnapshot(L,n);const{events:s,saved:a}=ms(o);const i=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 a){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=a.filter(v=>t.flagged==="pinned"?v.pinned:t.flagged==="saved"?v.saved:v.pinned||v.saved);const b=p.filter(v=>v.event&&Dr(v.event,t.status)).filter(v=>!c||(v.event.url??"").toLowerCase().includes(c)).slice(0,i);if(b.length===0){return $(`No ${t.flagged==="any"?"pinned or saved":t.flagged} requests on ${n}.
|
|
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 Or(r,b.map(v=>v.event),n):{bodies:new Map,skipped:0};const g=b.map((v,w)=>{const x=[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 O=v.bodyTruncated?" \xB7 body truncated":"";let C=Er(w+1,v.event,x);C+=`
|
|
68
|
+
\u2514\u2500 key \`${v.key}\`${T}${O}`;if(t.includeBodies)C+=Cr(v.event,h.bodies);return C}).join("\n");return $(`**Kept requests on ${n}** \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._${Mr(h.skipped)}`)}const u=s.filter(p=>Dr(p,t.status)).filter(p=>!c||(p.url??"").toLowerCase().includes(c)).slice(0,i);if(u.length===0){const p=s.length===0?await bs(r,n):"No request matched the filter.";return $(`No requests on ${n}. ${p}`)}const f=t.includeBodies?await Or(r,u,n):{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=Er(b+1,p,h);if(t.includeBodies)g+=Cr(p,f.bodies);return g}).join("\n");const y=a.length>0?` \xB7 ${a.length} kept (flagged:'any' to list)`:"";return $(`**Network requests on ${n}** \u2014 ${u.length} of ${s.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}"})._${Mr(f.skipped)}`)}catch(n){return m(A(n))}});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 n=r.requireProDevice(t.deviceId);const o=["pin","unpin","save","unsave"].includes(t.action);if(o&&!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 s=await r.callAction(L,"setPinned",{id:t.id,pinned:t.action==="pin"},n);if(s===null)return m(`No request "${t.id}" on ${n}. It may have been cleared or aged out \u2014 re-list with get_network_requests.`);const a=typeof s==="object"&&s!==null&&s.reason==="pin-cap";if(a)return m(`Pin limit reached on ${n}. Unpin something first (network_action({action:"clearPinned"}) drops them all).`);return $(`${t.action==="pin"?"\u{1F4CC} Pinned":"Unpinned"} \`${t.id}\` on ${n}.`)}case"save":case"unsave":{const s=await r.callAction(L,"setSaved",{id:t.id,saved:t.action==="save"},n);if(s===null)return m(`No request "${t.id}" on ${n}. It may have been cleared or aged out \u2014 re-list with get_network_requests.`);const a=typeof s==="object"&&s!==null&&s.reason==="saved-cap";if(a)return m(`Saved-request limit reached on ${n}. Remove one first, or network_action({action:"clearSaved"}).`);return $(`${t.action==="save"?"\u{1F516} Saved":"Unsaved"} \`${t.id}\` on ${n}.`)}case"remove":await r.callAction(L,"removeSavedRecord",{key:t.key},n);return $(`Removed kept record \`${t.key}\` on ${n}.`);case"clearPinned":await r.callAction(L,"clearPinnedRequests",{},n);return $(`Unpinned all requests on ${n} (saved ones kept).`);case"clearSaved":await r.callAction(L,"clearSavedRequests",{},n);return $(`Cleared saved requests on ${n} (pinned ones kept).`);case"clearRequests":await r.callAction(L,"clearEvents",{},n);return $(`Clear request sent to ${n}. Re-list to confirm the live capture list; this action does not clear retained records.`)}}catch(n){return m(A(n))}});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 n=r.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 o=await r.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}},n);const s=o;if(!s?.ok){return m(s?.error??`Could not add the rule on ${n}.`)}const a=s.rule?.urlPattern??t.urlPattern;const i=s.rule?.enabled===false?`
|
|
77
|
+
|
|
78
|
+
It is switched OFF \u2014 arm it with network_override({action:"enable", id:"${s.rule?.id}"}).`:"";return $(`Override added on ${n} \u2014 \`${s.rule?.id}\` matching \`${a}\`.${i}
|
|
79
|
+
|
|
80
|
+
Trigger the request now (navigate / tap_element), then check it with get_network_requests or describe_screen. Remove it with network_override({action:"remove", id:"${s.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 r.callAction(L,"deleteOverrideRule",{id:t.id},n);return $(`Removed override \`${t.id}\` on ${n}.`)}case"clear":await r.callAction(L,"clearOverrideRules",{},n);return $(`Removed all override rules on ${n}. Other interception or simulation settings may still apply.`);case"enable":case"disable":{const o=t.action==="enable";if(t.id){await r.callAction(L,"setOverrideRuleEnabled",{id:t.id,enabled:o},n);return $(`Rule \`${t.id}\` was requested ${o?"ON":"OFF"} on ${n}. The other rules and the master switch are unchanged.`)}await r.callAction(L,"setOverridesEnabled",{enabled:o},n);return $(o?`Overrides enabled in settings for ${n}.`:`Overrides switched OFF for ${n}. Rules are kept \u2014 re-enable with network_override({action:"enable"}).`)}case"list":{const o=await r.callAction(L,"listOverrideRules",{},n);const s=o?.rules??[];if(t.id){const i=s.find(c=>c.id===t.id);if(!i){return m(`No override rule \`${t.id}\` on ${n}. List them with network_override({action:"list"}).`)}return $(`**Override rule \`${i.id}\`** on ${n}${Ir(o)}
|
|
81
|
+
|
|
82
|
+
\`\`\`json
|
|
83
|
+
${JSON.stringify(i,null,2)}
|
|
84
|
+
\`\`\``)}if(s.length===0){return $(`No override rules on ${n}.
|
|
85
|
+
|
|
86
|
+
Add one with network_override({action:"add", urlPattern:"https://api.example.com/test*", status:500}) to force an error state.`)}const a=s.map((i,c)=>{const d=i.kind==="respond"?`\u2192 ${i.status??200}${i.statusText?` ${i.statusText}`:""}`:i.kind==="fail"?`\u2192 ${i.failKind==="timeout"?"timeout":"network error"}`:"\u2192 real response";const l=[i.methods?.length?i.methods.join("/"):"any method",d,i.kind==="respond"&&i.body?`body ${i.body.length}B`:"",i.headers&&Object.keys(i.headers).length?`${Object.keys(i.headers).length} header(s)`:"",i.delayMs?`${i.delayMs}ms delay`:"",i.alternate?"every other request":"",typeof i.times==="number"?`${i.times}\xD7 then off`:"",`${i.hits} hit${i.hits===1?"":"s"}`,i.seen!=null&&i.seen!==i.hits?`${i.seen} matched`:"",i.enabled?"":"DISABLED"].filter(Boolean);return`${c+1}. \`${i.id}\`${i.name?` ${i.name}`:""}
|
|
87
|
+
\u2514\u2500 \`${i.urlPattern}\` \xB7 ${l.join(" \xB7 ")}`});return $(`**Override rules on ${n}**${Ir(o)}
|
|
88
|
+
|
|
89
|
+
${a.join("\n")}
|
|
90
|
+
|
|
91
|
+
Full detail incl. body: network_override({action:"list", id:"${s[0]?.id}"}).`)}case"debug":{const o=await r.callAction(L,"debugOverrides",{url:t.url},n);if(!o){return m(`${n} did not answer the diagnostics call \u2014 the network tool may not be mounted.`)}return $(`**Override diagnostics on ${n}**${t.url?` for \`${t.url}\``:""}
|
|
92
|
+
|
|
93
|
+
\`\`\`json
|
|
94
|
+
${JSON.stringify(o,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(n){return m(A(n))}})}import{z as ae}from"zod";var Je="sentry";var me=e=>({content:[{type:"text",text:e}]});var We=e=>({isError:true,content:[{type:"text",text:e}]});var Ve=e=>e instanceof Error?e.message:String(e);function Fr(e){const r=new Date(e);const t=n=>String(n).padStart(2,"0");return`${t(r.getHours())}:${t(r.getMinutes())}:${t(r.getSeconds())}`}function qr(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 kt(e,r){if(r==="bytes")return qr(e);if(e>=1e6)return`${(e/1e6).toFixed(1)}M`;if(e>=1e3)return`${(e/1e3).toFixed(1)}k`;return String(e)}var $s={errors:5e3,spans:5e6,replays:50,logBytes:5*1024**3,attachmentBytes:1*1024**3};var ks={errors:"count",spans:"count",replays:"count",logBytes:"bytes",attachmentBytes:"bytes"};function Ge(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 _s(e,r){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:ae.string().optional().describe("Only envelopes containing this item type, e.g. 'event' for errors or 'transaction' for traces."),limit:ae.number().optional().describe("Most-recent N envelopes. Default 25."),deviceId:ae.string().optional().describe("Target device id (auto-selected if one is connected).")}},async t=>{try{const n=r.requireProDevice(t.deviceId);const{payload:o,stale:s}=await r.getSnapshot(Je,n);const a=s?`${s}
|
|
98
|
+
|
|
99
|
+
`:"";const i=o??{};const c=Array.isArray(i.envelopes)?i.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 me(`${a}No Sentry envelopes${t.type?` containing a '${t.type}' item`:""} (${c.length} captured this session).${Ge(i.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}. ${Fr(y.timestamp)} [${p}] ${qr(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 me(`${a}${k}${Ge(i.status)}
|
|
101
|
+
|
|
102
|
+
${f.join("\n")}
|
|
103
|
+
|
|
104
|
+
_Full payloads (exception, breadcrumbs, contexts) via get_snapshot('sentry'). Billing units via get_sentry_cost._`)}catch(n){return We(Ve(n))}});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:ae.string().optional().describe("Target device id (auto-selected if one is connected).")}},async t=>{try{const n=r.requireProDevice(t.deviceId);const{payload:o,stale:s}=await r.getSnapshot(Je,n);const a=s?`${s}
|
|
105
|
+
|
|
106
|
+
`:"";const i=o??{};const c=i.usage;if(!c?.session){return me(`${a}No usage is available in this capture.${Ge(i.status)}`)}const d=c.session;const l=c.projectedMonthly;const u=Object.keys(d);const f=u.map(b=>{const h=ks[b];const g=kt(d[b],h);if(!l)return`- ${b}: ${g} this session`;const v=l[b];const w=$s[b];const x=w>0?Math.round(v/w*100):null;const T=x===null?" (no configured reference quota)":` \u2014 ${x}% of the configured reference quota of ${kt(w,h)}`;return`- ${b}: ${g} this session \u2192 ~${kt(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 me(`${a}**Sentry usage estimate \u2014 ${i.envelopes?.length??0} envelopes${k}:**
|
|
110
|
+
|
|
111
|
+
${f.join("\n")}${y}${p}`)}catch(n){return We(Ve(n))}});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:ae.number().optional().describe("Most-recent N drop records. Default 30."),deviceId:ae.string().optional().describe("Target device id (auto-selected if one is connected).")}},async t=>{try{const n=r.requireProDevice(t.deviceId);const{payload:o,stale:s}=await r.getSnapshot(Je,n);const a=s?`${s}
|
|
112
|
+
|
|
113
|
+
`:"";const i=o??{};const c=i.drops?.summary??[];const d=i.drops?.recent??[];if(c.length===0){return me(`${a}No drops are reported in the available capture.${Ge(i.status)}
|
|
114
|
+
|
|
115
|
+
_If an event is missing from sentry.io, check capture coverage, transport errors, the DSN/project, inbound filters and quota. Local capture does not confirm delivery._`)}const l=typeof t.limit==="number"&&t.limit>0?t.limit:30;const 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=>`${Fr(y.timestamp)} [${y.reason}] ${y.category}${y.quantity>1?` \xD7${y.quantity}`:""} \u2014 ${y.detail} (${y.source})`);return me(`${a}**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(n){return We(Ve(n))}});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:ae.enum(["clear"]).describe("The action to perform."),deviceId:ae.string().optional().describe("Target device id (auto-selected if one is connected).")}},async t=>{try{const n=r.requireProDevice(t.deviceId);await r.callAction(Je,"clearEnvelopes",{},n);return me("Cleared the Sentry inspector \u2014 envelopes and drop records. Drive your flow, then read get_sentry_envelopes or get_sentry_cost.")}catch(n){return We(Ve(n))}})}import{z as Z}from"zod";var jr="time-machine";function Br(e){return e<1024?`${e} B`:`${(e/1024).toFixed(1)} KB`}function Pr(e){const r=Object.entries(e.results).map(([n,o])=>{const s=o.skipped.slice(0,3).map(i=>`
|
|
126
|
+
\xB7 ${i.id}: ${i.reason}`).join("");const a=o.warnings.slice(0,3).map(i=>`
|
|
127
|
+
\u26A0 ${i}`).join("");return` ${o.ok?"\u2713":"\u2715"} ${n} \u2014 applied ${o.applied}${o.skipped.length?`, skipped ${o.skipped.length}`:""}${s}${a}`});const t=e.route;if(t){r.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
|
+
${r.join("\n")}`}function Ss(e,r){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 n=r.requireProDevice(t.deviceId);const{payload:o}=await r.getSnapshot(jr,n);const s=o??{};const a=s.snapshots??[];const i=s.providers??[];const c=i.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(s.route){c.push(s.route.available?`- Route (route): capture+restore \u2014 recorded with every snapshot; pass restoreRoute:true to return to it${s.route.current?` (now ${s.route.current})`:""}`:"- Route (route): unavailable \u2014 no Expo Router on this device, snapshots record no route")}const d=a.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":`${Br(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 ${a.length} snapshot(s):**`,d.length?d.join("\n"):"_none yet \u2014 capture one with time_machine_action_",`**Sources:**
|
|
129
|
+
${c.join("\n")||"_no providers registered_"}`];if(s.lastOutcome)l.push(`**Last restore:**
|
|
130
|
+
${Pr(s.lastOutcome)}`);return $(l.join("\n\n"))}catch(n){return m(A(n))}});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:Z.enum(["capture","capture_baseline","preview","restore","delete","rename"]).describe("What to do."),id:Z.string().optional().describe("Snapshot id (required for restore/delete/rename; from get_time_machine)."),name:Z.string().optional().describe("Snapshot name (for capture and rename)."),mode:Z.enum(["live","reload"]).optional().describe("Restore mode. Default 'live'."),excludeKeys:Z.array(Z.string()).optional().describe('Restore only: item keys to LEAVE UNTOUCHED, as "sourceId::itemKey" (itemKey = the key shown by the preview action, e.g. "query::[\\"pokemon\\"]" or "storage::async:@cart").'),restoreRoute:Z.boolean().optional().describe("Restore only: also navigate back to the route the snapshot was captured on (shown as `route` by get_time_machine). With mode 'reload' the navigation happens automatically on the next boot. Default false \u2014 state is restored but the app stays on the current screen."),sourceIds:Z.array(Z.string()).optional().describe("Capture/restore only these source ids (default all)."),deviceId:S}},async t=>{try{const n=r.requireProDevice(t.deviceId);const o=(s,a)=>r.callAction(jr,s,a,n);switch(t.action){case"capture":{const s=await o("capture",{name:t.name??"",sourceIds:t.sourceIds});const a=s.snapshot;const i=Object.entries(a.sources).flatMap(([c,d])=>d.warnings.map(l=>`
|
|
131
|
+
\u26A0 ${c}: ${l}`)).join("");return $(`Captured \`${a.id}\` "${a.name}" \u2014 ${Br(a.sizeBytes)} \xB7 ${Object.keys(a.sources).join(", ")}${i}`)}case"capture_baseline":{const s=await o("captureBaseline",{});return $(`Captured baseline \`${s.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 s=await o("preview",{id:t.id});const a=[];let i=0;for(const d of s.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);i+=u;const f=Object.entries(l).filter(([k])=>k!=="unchanged").map(([k,y])=>`${y} ${k}`);a.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)){a.push(` ${k.verdict==="added"?"+":k.verdict==="removed"?"\u2212":k.verdict==="wont-apply"?"\u2298":"\u2248"} ${k.label}${k.reason?` (${k.reason})`:""}`)}for(const k of d.notes)a.push(` \xB7 ${k}`)}const c=i===0?"**Restore would change NOTHING** (states identical or nothing applicable).":`**Restore would apply ${i} change(s):**`;return $(`${c}
|
|
132
|
+
${a.join("\n")}`)}case"restore":{if(!t.id)return m("restore requires `id` (from get_time_machine).");const s=await o("restore",{id:t.id,mode:t.mode??"live",excludeKeys:t.excludeKeys,restoreRoute:t.restoreRoute});return $(Pr(s))}case"delete":{if(!t.id)return m("delete requires `id`.");await o("delete",{id:t.id});return $(`Deleted snapshot \`${t.id}\`.`)}case"rename":{if(!t.id||!t.name)return m("rename requires `id` and `name`.");await o("rename",{id:t.id,name:t.name});return $(`Renamed \`${t.id}\` to "${t.name}".`)}}}catch(n){return m(A(n))}})}import{z as U}from"zod";var Nr="clock";function fe(e){const r=e<0?"-":"+";let t=Math.abs(Math.round(e/1e3));if(t===0)return"0s";const n=[];for(const[o,s]of[["d",86400],["h",3600],["m",60],["s",1]]){if(t>=s){n.push(`${Math.floor(t/s)}${o}`);t%=s}if(n.length===2)break}return r+n.join(" ")}function Lr(e){const r=[e.active?`**App clock: ${e.virtualIso}** (${e.mode}${e.rate!==1?`, ${e.rate}\xD7`:""}), ${fe(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){r.push(`Last change: ${fe(e.lastJump.byMs)}${e.lastJump.firedTimers?`, ran ${e.lastJump.firedTimers} due timer(s)`:""}`)}r.push(...As(e));r.push(`Settings: persist=${e.settings.persist} showChip=${e.settings.showChip} fireTimersOnJump=${e.settings.fireTimersOnJump}`);return r.join("\n")}function As(e){const r=e.tokens;if(!r)return[];if(!r.available)return["Sign-in tokens: unavailable (the app has no @buoy-gg/network)."];if(r.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 o of r.tokens){const s=o.expiresAt!==void 0?o.expiresAt-e.virtualNow:void 0;const a=o.serverExpiresAt!==void 0?o.serverExpiresAt-e.realNow:void 0;const i=o.neverExpires?"never expires":s===void 0?"expiry unknown":s>0?`expires in ${fe(s).slice(1)} on the app's clock`:`expired ${fe(-s).slice(1)} ago on the app's clock`;const c=a!==void 0&&s!==void 0&&Math.abs(a-s)>2e3?a>0?`; the server accepts it for ${fe(a).slice(1)} more`:"; the server no longer accepts it":"";const d=[o.hint??o.formatLabel,o.expirySource?`expiry from ${o.expirySource}`:null,o.issuedBy?`issued by ${o.issuedBy}`:null,o.claims.sub?`sub ${o.claims.sub}`:null,`${o.uses} request(s)`,o.refreshes?`${o.refreshes} refresh(es)`:null,o.expiredSends?`SENT ${o.expiredSends}\xD7 AFTER EXPIRY`:null,o.rejected?`rejected ${o.rejected}\xD7`:null,o.looping?`REFRESH LOOP (${o.recentRefreshes} new tokens in 20s)`:null].filter(Boolean);t.push(`- [${o.id}] ${o.label} \u2192 ${o.host}: ${i}${c} (${d.join(", ")})`)}const n=r.check;if(n){const o=n.status==="refreshed"?`refreshed${n.kind==="401"&&n.forcedAt?" after the forced 401":""}${n.newIssuedBy?` via ${n.newIssuedBy}`:""}${n.newLifetimeMs?`; new token lasts ${fe(n.newLifetimeMs).slice(1)}`:""}`:n.status==="loop"?`REFRESH LOOP: ${n.newTokens} new tokens since the check started`:n.kind==="401"&&n.forcedAt===void 0?"waiting: the next request to that API will get a 401 (the app must send one)":`waiting for a new token (${fe(e.realNow-n.startedAt).slice(1)} so far)`;const s=n.staleAfterFailure?`; the app re-sent the old token ${n.staleAfterFailure}\xD7 after the 401`:"";t.push(`Refresh check (${n.kind==="401"?"forced 401":"jump to expiry"}): ${o}${s}`)}return t}function xs(e,r){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 n=r.requireProDevice(t.deviceId);const o=await r.callAction(Nr,"getState",{},n);return $(Lr(o))}catch(n){return m(A(n))}});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 n=r.requireProDevice(t.deviceId);const o=(a,i={})=>r.callAction(Nr,a,i,n);let s;switch(t.action){case"set_time":if(t.time===void 0)return m("set_time requires `time`.");s=await o("setTime",{time:t.time,freeze:t.freeze??false});break;case"shift":if(t.by===void 0)return m("shift requires `by`, e.g. '+1d'.");s=await o("shift",{by:t.by,...t.fireTimers!==void 0?{fireTimers:t.fireTimers}:{}});break;case"freeze":s=await o("freeze",t.time!==void 0?{time:t.time}:{});break;case"resume":s=await o("resume");break;case"set_rate":if(t.rate===void 0)return m("set_rate requires `rate`.");s=await o("setRate",{rate:t.rate});break;case"reset":s=await o("reset");break;case"settings":s=await o("updateSettings",{...t.persist!==void 0?{persist:t.persist}:{},...t.showChip!==void 0?{showChip:t.showChip}:{},...t.fireTimersOnJump!==void 0?{fireTimersOnJump:t.fireTimersOnJump}:{}});break;case"jump_to_token_expiry":s=await o("jumpToTokenExpiry",{...t.token?{token:t.token}:{},...t.leadMs!==void 0?{leadMs:t.leadMs}:{}});break;case"fail_next_request":s=await o("failNextRequest",{...t.token?{token:t.token}:{},...t.status!==void 0?{status:t.status}:{},...t.times!==void 0?{times:t.times}:{}});break;case"stop_token_check":s=await o("stopTokenCheck");break}return $(Lr(s))}catch(n){return m(A(n))}})}import{execFile as Ts}from"child_process";import{promisify as Is}from"util";import{z}from"zod";var _t="permissions";var Ds=Is(Ts);var Ur=["location","locationBackground","camera","microphone","notifications","photos","contacts","calendar","reminders","tracking","motion","bluetooth"];function zr(e,r=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 o of e.permissions){const s=[o.override?`override **${o.override}**`:"not overridden",`system ${o.real??"unknown"}`,o.calls?`asked ${o.calls}\xD7`:"not asked yet",o.sources.length?`via ${o.sources.join(", ")}`:null,`can be: ${o.states.join(", ")}`].filter(Boolean);t.push(`- ${o.id} (${o.label}): ${s.join("; ")}`);if(o.warning)t.push(` \u26A0 ${o.warning}`)}const n=e.settings;t.push(`Settings: requestAnswer=${n.requestAnswer} notifyApp=${n.notifyApp} interceptSettings=${n.interceptSettings} enforce=${n.enforce} persist=${n.persist} showChip=${n.showChip}`);if(e.log.length){t.push("Recent calls (newest first):");for(const o of e.log.slice(0,r)){const s=new Date(o.at).toISOString().slice(11,19);const a=o.error??o.returned??"no answer";t.push(`- ${s} ${o.source}.${o.method} \u2192 ${a}${o.overridden?" (override)":""}${o.real&&o.real!==o.returned?`, system ${o.real}`:""}${o.answer?`, answered ${o.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 Rs={location:"location",locationBackground:"location-always",camera:"camera",microphone:"microphone",photos:"photos",contacts:"contacts",calendar:"calendar",reminders:"reminders",motion:"motion"};var Jr={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 Se(e,r){const{stdout:t}=await Ds(e,r,{timeout:2e4});return t}async function Os(e,r){if(r)return r;const t=JSON.parse(await Se("xcrun",["simctl","list","devices","booted","-j"]));const n=Object.values(t.devices).flat();const o=n.filter(s=>s.name===e.host.deviceName);if(o.length===1)return o[0].udid;if(!e.host.deviceName&&n.length===1)return n[0].udid;throw new Error(o.length===0?`No booted simulator is named "${e.host.deviceName??"?"}". Pass \`udid\`.`:`${o.length} booted simulators are named "${e.host.deviceName}". Pass \`udid\`.`)}async function Ms(e){if(e)return e;const r=await Se("adb",["devices"]);const t=r.split("\n").slice(1).map(n=>n.trim().split(/\s+/)).filter(n=>n[1]==="device").map(n=>n[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 Cs(e,r,t,n){const o=e.host.bundleId;if(!o)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":Rs[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 Os(e,n.udid);await Se("xcrun",["simctl","privacy",d,r,c,o]);return`simctl privacy ${r} ${c} for ${o} on ${d}.${r==="grant"?"":" iOS ends the app's process when a permission is revoked or reset; relaunch it."}`}const s=await Ms(n.serial);const a=t==="all"?Object.values(Jr).flat():Jr[t];if(!a)throw new Error(`No Android permission is known for ${t}.`);const i=[];for(const c of a){const d=`android.permission.${c}`;try{if(r==="grant")await Se("adb",["-s",s,"shell","pm","grant",o,d]);else{await Se("adb",["-s",s,"shell","pm","revoke",o,d]);if(r==="reset"){await Se("adb",["-s",s,"shell","pm","clear-permission-flags",o,d,"user-set","user-fixed"])}}i.push(c)}catch{}}if(i.length===0)throw new Error(`None of ${a.join(", ")} could be changed. Is it declared in the app's manifest?`);return`adb ${r} ${i.join(", ")} for ${o} on ${s}.${r==="grant"?"":" Android restarts the app's process when a permission is revoked."}`}function Es(e,r){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 n=r.requireProDevice(t.deviceId);const o=await r.callAction(_t,"getState",{},n);return $(zr(o,t.logLimit??12))}catch(n){return m(A(n))}});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): ${Ur.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 n=r.requireProDevice(t.deviceId);const o=(a,i={})=>r.callAction(_t,a,i,n);let s;switch(t.action){case"set":if(!t.permission||!t.state)return m("set requires `permission` and `state`.");s=await o("setOverride",{permission:t.permission,state:t.state});break;case"clear":if(!t.permission)return m("clear requires `permission`.");s=await o("clearOverride",{permission:t.permission});break;case"reset":s=await o("resetAll");break;case"answer":if(!t.answer)return m("answer requires `answer`: ask, allow, limited or deny.");s=await o("updateSettings",{requestAnswer:t.answer});break;case"settings":s=await o("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`.");s=await o("requestReal",{permission:t.permission});break;case"return_from_settings":s=await o("simulateReturnFromSettings");break;case"clear_log":s=await o("clearLog");break}return $(zr(s))}catch(n){return m(A(n))}});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(`${Ur.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 n=r.requireProDevice(t.deviceId);const o=await r.callAction(_t,"getState",{},n);const s=await Cs(o,t.action,t.permission,{udid:t.udid,serial:t.serial});return $(s)}catch(n){return m(A(n))}})}import{execFile as Fs}from"child_process";import{promisify as qs}from"util";import{z as F}from"zod";var Wr="lifecycle";var js=qs(Fs);function Me(e){if(e==null)return"can't count";return e===0?"none":String(e)}function Ke(e){const r=[];if(e.away){const n=Math.round((Date.now()-e.away.startedAt)/1e3);r.push(`**Simulated: ${e.away.kind==="background"?"in the background":"interrupted (inactive)"}** for ${n}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{r.push(`App state: active (real OS state: ${e.realAppState}).`)}if(e.power){r.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)r.push(`Simulated color scheme: ${e.scheme.scheme} (${e.scheme.mode}).`);r.push(`App listeners: app state ${Me(e.listeners.appState)}, memory warning ${Me(e.listeners.memoryWarning)}, deep link ${Me(e.listeners.deepLink)}`+(e.platform==="android"?`, window focus ${Me(e.listeners.focus)}`:"")+(e.batteryLibraries.length?`, battery ${Me(e.listeners.battery)} (${e.batteryLibraries.join(", ")})`:", battery: no battery library installed")+".");if(e.report){const n=e.report;r.push(`
|
|
133
|
+
**Report: ${n.label}**${n.collectingUntil!=null?" (still collecting)":""}`);if(n.unavailable)r.push(n.unavailable);if(n.finding)r.push(`Finding: ${n.finding}`);if(n.note)r.push(`Note: ${n.note}`);const o=Object.entries(n.counts).map(([s,a])=>`${a} ${s}`).join(", ");if(!n.unavailable)r.push(`Counts: ${o||"nothing happened"}`);for(const s of n.events.slice(0,25)){r.push(`- +${(s.at/1e3).toFixed(1)}s ${s.whileAway?"[away] ":""}${s.source}: ${s.title}${s.subtitle?` (${s.subtitle})`:""}${s.status==="error"?" ERROR":""}`)}}if(e.relaunch){const n=e.relaunch;r.push(n.restored==null&&n.after==null?`
|
|
134
|
+
Relaunch: checking where the app landed (was on ${n.before??"unknown"}).`:`
|
|
135
|
+
Relaunch: ${n.restored?`restored ${n.after}`:`landed on ${n.after??"unknown"}, was on ${n.before??"unknown"}`}${n.tookMs!=null?` (${(n.tookMs/1e3).toFixed(1)}s)`:""}.`)}if(typeof e.handled==="boolean")r.push(`Back press handled by the app: ${e.handled}.`);if(e.log.length)r.push(`
|
|
136
|
+
Recent: ${e.log.slice(0,5).map(n=>n.text).join(" \xB7 ")}`);const t=e.recipes.filter(n=>!n.unavailable).map(n=>n.id);r.push(`Recipes: ${t.join(", ")}`);return r.join("\n")}async function ge(e){const{stdout:r}=await js("xcrun",["simctl",...e],{timeout:2e4});return r}async function Bs(e,r){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(r)return r;const t=JSON.parse(await ge(["list","devices","booted","-j"]));const n=Object.values(t.devices).flat().filter(o=>o.name===e.host.deviceName);if(n.length===1)return n[0].udid;throw new Error(n.length===0?`No booted simulator is named "${e.host.deviceName??"?"}". Pass \`udid\`.`:`${n.length} booted simulators are named "${e.host.deviceName}". Pass \`udid\`.`)}function Vr(e){if(!e.host.bundleId)throw new Error("The app did not report its bundle id (needs expo-application).");return e.host.bundleId}var Ps=e=>new Promise(r=>setTimeout(r,e));function Ns(e,r){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 n=r.requireProDevice(t.deviceId);const o=await r.callAction(Wr,"getState",{},n);return $(Ke(o))}catch(n){return m(A(n))}});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:F.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:F.union([F.string(),F.number()]).optional().describe("background / interrupt: return by itself after this long ('5s', '5m', ms). Omit to stay until return."),skipWait:F.boolean().optional().describe("background / interrupt: move the app clock forward by `duration` and return at once. Needs @buoy-gg/clock."),url:F.string().optional().describe("open_url (required): the link, with its scheme."),scheme:F.enum(["light","dark","system"]).optional().describe("color_scheme (required). 'system' ends the simulated scheme."),mode:F.enum(["js","native"]).optional().describe("color_scheme: 'js' emits the change to JS listeners (default); 'native' overrides the app's native appearance too."),level:F.number().optional().describe("battery: 0 to 1 (or a percentage above 1)."),lowPowerMode:F.boolean().optional().describe("battery: low power mode on or off."),state:F.enum(["unplugged","charging","full","unknown"]).optional().describe("battery: charging state."),id:F.string().optional().describe("recipe (required): a recipe id from get_lifecycle, e.g. 'away-31m'."),showChip:F.boolean().optional().describe("settings: show the floating status chip while simulating."),reportWindow:F.union([F.string(),F.number()]).optional().describe("settings: how long reports keep collecting after the app returns ('5s')."),real:F.boolean().optional().describe("iOS simulator only: cause the real OS event through xcrun simctl (background, return, relaunch, color_scheme, open_url)."),udid:F.string().optional().describe("real: the simulator udid, when its name is ambiguous."),deviceId:S}},async t=>{try{const n=r.requireProDevice(t.deviceId);const o=(a,i={})=>r.callAction(Wr,a,i,n);if(t.real){const a=await o("getState");const i=await Bs(a,t.udid);let c;switch(t.action){case"background":await ge(["launch",i,"com.apple.Preferences"]);c="Sent to the background for real (Settings opened on top). Use return with real: true.";break;case"return":await ge(["launch",i,Vr(a)]);c="Brought back to the foreground for real.";break;case"relaunch":{const l=Vr(a);await o("prepareRelaunch");await ge(["terminate",i,l]);await ge(["launch",i,l]);c="Killed the process and launched it again (a real cold start). Read get_lifecycle in a few seconds for where it landed; a dev build reloads its bundle first.";break}case"color_scheme":if(!t.scheme)return 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 ge(["ui",i,"appearance",t.scheme]);c=`Simulator appearance set to ${t.scheme} (affects every app on this simulator).`;break;case"open_url":if(!t.url)return m("open_url requires `url`.");await ge(["openurl",i,t.url]);c='Opened through the OS. A custom scheme may first show an "Open in" prompt on the simulator.';break;default:return m(`${t.action} has no real (host-side) version. iOS has no command-line memory warning; leave \`real\` off to simulate it.`)}await Ps(1200);const d=t.action==="relaunch"||t.action==="background"?a:await o("getState");return $(`${c}
|
|
137
|
+
|
|
138
|
+
${Ke(d)}`)}let s;switch(t.action){case"background":s=await o("background",{duration:t.duration,skipWait:t.skipWait});break;case"interrupt":s=await o("interrupt",{duration:t.duration,skipWait:t.skipWait});break;case"return":s=await o("returnToApp");break;case"memory_warning":s=await o("memoryWarning");break;case"open_url":if(!t.url)return m("open_url requires `url`.");s=await o("openUrl",{url:t.url});break;case"press_back":s=await o("pressBack");break;case"color_scheme":if(!t.scheme)return m("color_scheme requires `scheme`.");s=await o("setColorScheme",{scheme:t.scheme,mode:t.mode??"js"});break;case"battery":s=await o("setPower",{...t.level!==void 0?{level:t.level}:{},...t.lowPowerMode!==void 0?{lowPowerMode:t.lowPowerMode}:{},...t.state?{state:t.state}:{}});break;case"reset_battery":s=await o("resetPower");break;case"relaunch":s=await o("relaunch");return $(`Relaunching: the app's JS restarts now. Read get_lifecycle in a few seconds for where it landed.
|
|
139
|
+
|
|
140
|
+
${Ke(s)}`);case"recipe":if(!t.id)return m("recipe requires `id`; get_lifecycle lists them.");s=await o("runRecipe",{id:t.id});break;case"clear_report":s=await o("clearReport");break;case"reset":s=await o("reset");break;case"settings":s=await o("updateSettings",{...t.showChip!==void 0?{showChip:t.showChip}:{},...t.reportWindow!==void 0?{reportWindow:t.reportWindow}:{}});break}return $(Ke(s))}catch(n){return m(A(n))}})}import{execFile as Ls}from"child_process";import{promisify as Us}from"util";import{z as D}from"zod";var Gr=Us(Ls);var Kr="location";function Ae(e){if(e==null||!Number.isFinite(e))return"?";return e<1e3?`${Math.round(e)} m`:`${(e/1e3).toFixed(e<1e4?1:0)} km`}function St(e){return`${e.latitude.toFixed(5)}, ${e.longitude.toFixed(5)}`}function Hr(e){const r=e.override;const t=[];if(!e.active){t.push("**Location: real** (no override; the app gets the device's own location)")}else{const s=e.current.fix;const a=s?St(s):`no fix (${e.current.reason})`;if(r.mode==="route"&&r.route&&e.progress){t.push(`**Location: route "${r.route.name??r.route.id??"custom"}"** ${r.playing?"moving":e.progress.finished?"arrived":"paused"} at ${(r.route.speed*3.6).toFixed(1)} km/h, ${Ae(e.progress.along)} of ${Ae(e.progress.length)}${r.route.loop?" (loops)":""} \u2192 ${a}`)}else if(r.mode==="fixed"){t.push(`**Location: pinned** ${r.place.label?`"${r.place.label}" `:""}\u2192 ${a}`)}else{t.push(`**Location: real position**, with overrides below`)}if(s){t.push(`Reported: \xB1${Ae(s.accuracy)}${s.heading!=null?`, heading ${Math.round(s.heading)}\xB0`:""}${s.speed!=null?`, ${s.speed.toFixed(1)} m/s`:""}${r.jitter?`, drifting up to ${Ae(r.jitter)}`:""}`)}if(!r.signal)t.push("GPS signal: OFF (updates stop, requests fail)");if(!r.services)t.push("Location services: OFF (the app is told they are disabled)")}if(e.permission){const s=e.permission;t.push(s.status==="granted"?`Permission: granted (${s.background?"always":"while in use"}, ${s.precision==="reduced"?"approximate":"precise"})`:`Permission: ${s.status.toUpperCase()} (the app's location requests fail)`)}if(e.current.precision==="reduced")t.push("Precise location is OFF in the permission: positions snap to ~3 km.");t.push(`Libraries overridden: ${e.libraries.length?e.libraries.join(", "):"none found in this app"}`);const n=e.watches.filter(s=>s.kind==="position");t.push(`Live watches: ${n.length?n.map(s=>`${s.library}#${s.id} (${s.updates} updates)`).join(", "):"none"}`);for(const s of e.tasks){if(s.kind==="geofencing"){t.push(`Geofencing task "${s.name}" (${s.intercepted?"simulated":"native"}, ${s.runs} runs):`);for(const a of s.regions){t.push(`- ${a.identifier}${a.label?` (${a.label})`:""}: ${a.state}, radius ${Ae(a.radius)}${a.distance!=null?`, ${Ae(a.distance)} from center`:""} (${St(a)})`)}}else{t.push(`Background location task "${s.name}" (${s.intercepted?"simulated":"native"}, ${s.runs} runs)`)}}const o=e.log.slice(-10);if(o.length){t.push("Recent:");for(const s of o)t.push(`- [${s.kind}] ${s.text}${s.detail?` (${s.detail})`:""}`)}if(e.places.length)t.push(`App places: ${e.places.map(s=>s.label??St(s)).join(", ")}`);if(e.routes.length)t.push(`App routes: ${e.routes.map(s=>s.id??s.name).join(", ")}`);t.push(`Presets: ${e.presets.map(s=>s.id).join(", ")}`);return t.join("\n")}async function zs(){const{stdout:e}=await Gr("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const r=JSON.parse(e);return Object.values(r.devices).flat().filter(t=>t.state==="Booted").map(({udid:t,name:n})=>({udid:t,name:n}))}async function Js(e){if(process.platform!=="darwin")throw new Error("sim_location needs macOS with Xcode's iOS Simulator.");const r=await zs();if(e){if(!r.some(t=>t.udid===e))throw new Error(`Simulator ${e} is not booted.`);return e}if(r.length===1)return r[0].udid;if(r.length===0)throw new Error("No iOS Simulator is booted.");throw new Error(`${r.length} simulators are booted; pass \`udid\`: ${r.map(t=>`${t.name} (${t.udid})`).join(", ")}`)}function Ws(e,r){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 n=r.requireProDevice(t.deviceId);const o=await r.callAction(Kr,"getState",{},n);return $(Hr(o))}catch(n){return m(A(n))}});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 n=r.requireProDevice(t.deviceId);const o=(i,c={})=>r.callAction(Kr,i,c,n);const s=(...i)=>{const c={};for(const d of i)if(t[d]!==void 0)c[d]=t[d];return c};let a;switch(t.action){case"set_location":a=await o("setLocation",s("latitude","longitude","label","query","place"));break;case"start_route":a=await o("startRoute",s("points","route","to","speed","heading","loop"));break;case"pause_route":a=await o("pauseRoute");break;case"resume_route":a=await o("resumeRoute");break;case"stop_route":a=await o("stopRoute");break;case"seek_route":a=await o("seekRoute",s("meters","fraction"));break;case"set_speed":if(t.speed===void 0)return m("set_speed requires `speed` in m/s.");a=await o("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.`);a=await o(t.action==="enter_region"?"enterRegion":"exitRegion",s("identifier","task"));break;case"conditions":if(!t.conditions)return m("conditions requires `conditions`: good, weak, no-signal or off.");a=await o("setConditions",{conditions:t.conditions});break;case"signal":if(t.on===void 0)return m("signal requires `on`.");a=await o("setSignal",{on:t.on});break;case"services":if(t.on===void 0)return m("services requires `on`.");a=await o("setServices",{on:t.on});break;case"tune":a=await o("tune",s("accuracy","jitter","heading","interval"));break;case"use_real":a=await o("useRealLocation");break;case"reset":a=await o("reset");break;case"settings":a=await o("updateSettings",s("persist","showChip"));break;case"clear_log":a=await o("clearLog");break}return $(Hr(a))}catch(n){return m(A(n))}});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 n=await Js(t.udid);const o=(...s)=>Gr("xcrun",["simctl","location",n,...s],{timeout:15e3});switch(t.action){case"set":if(t.latitude===void 0||t.longitude===void 0)return m("set requires `latitude` and `longitude`.");await o("set",`${t.latitude},${t.longitude}`);return $(`Simulator ${n} location set to ${t.latitude}, ${t.longitude}.`);case"route":{const s=t.points??[];if(s.length<2)return m("route requires two or more `points`.");const a=[`--speed=${t.speed??20}`,`--interval=${t.interval??1}`];await o("start",...a,...s.map(i=>`${i.latitude},${i.longitude}`));return $(`Simulator ${n} is moving through ${s.length} points at ${t.speed??20} m/s.`)}case"clear":await o("clear");return $(`Simulator ${n} location cleared.`)}}catch(n){return m(A(n))}})}import{z as _}from"zod";var Yr="scenarios";var ve=e=>({content:[{type:"text",text:e}]});var H=e=>({isError:true,content:[{type:"text",text:e}]});var Qr=e=>e instanceof Error?e.message:String(e);function Vs(e){const r=e.options?.length?` one of ${e.options.join("|")}`:"";const t=e.default!==void 0?` (default ${String(e.default)})`:"";return`${e.key}: ${e.type}${r}${t}`}function He(e){const r=e.vars?.length?`
|
|
141
|
+
variables: ${e.vars.map(Vs).join("; ")}`:"";const t=e.stepLines?.length?`
|
|
142
|
+
${e.stepLines.map(s=>` \xB7 ${s.label} [${s.durability}]`).join("\n")}`:"";const n=[`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 o=e.expectedOutcome?`
|
|
143
|
+
expected: ${e.expectedOutcome}`:"";return`- \`${e.id}\` **${e.name}** \u2014 ${n}${r}${o}${t}`}function Xr(e,r,t){if(!r.length)return`**${e} (0):**
|
|
144
|
+
_none_`;if(!t.length){return`**${e} (${r.length}):**
|
|
145
|
+
${r.map(He).join("\n")}`}const n=[`**${e} (${r.length}):**`];for(const s of t){const a=r.filter(i=>(i.folder??"").toLowerCase()===s.toLowerCase());if(!a.length)continue;n.push(`_${s} (${a.length})_
|
|
146
|
+
${a.map(He).join("\n")}`)}const o=r.filter(s=>!s.folder);if(o.length){n.push(`_Ungrouped (${o.length})_
|
|
147
|
+
${o.map(He).join("\n")}`)}return n.join("\n")}function Gs(e){const r=Object.entries(e.varValues).map(([t,n])=>`${t}=${String(n)}`).join(", ");return[`**${e.name}** (\`${e.scenarioId}\` v${e.version}) \u2014 active since ${new Date(e.runAt).toISOString()}`,r?`variables: ${r}`:null,`effects:
|
|
148
|
+
${e.effects.map(t=>` \xB7 ${t.label} [${t.kind}]`).join("\n")}`].filter(Boolean).join("\n")}function Ks(e,r){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 n=r.requireProDevice(t.deviceId);const{payload:o}=await r.getSnapshot(Yr,n);const s=o??{};const a=s.code??[];const i=s.device??[];const c=s.drafts??[];const d=s.folders??[];const l=[];l.push(s.active?`\u26A0\uFE0F **SIMULATED \u2014 a scenario is active.** The app is showing bent state right now.
|
|
149
|
+
${Gs(s.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(Xr("Shipped with this app",a,d));l.push(Xr("Saved on this device",i,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(He).join("\n")}`)}return ve(l.join("\n\n"))}catch(n){return H(Qr(n))}});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 n=r.requireProDevice(t.deviceId);const o=(s,a)=>r.callAction(Yr,s,a,n);switch(t.action){case"preview":{if(!t.id)return H("preview requires `id` (from get_scenarios).");const s=await o("preview",{id:t.id,params:t.params??{}});const a=[`**Dry run \u2014 \`${t.id}\`** (nothing has been changed)`,`variables: ${Object.entries(s.values).map(([i,c])=>`${i}=${String(c)}`).join(", ")||"none"}`,`**Would do:**
|
|
151
|
+
${s.willDo.map(i=>` \xB7 ${i.label} [${i.durability}]`).join("\n")}`];if(s.expectedOutcome)a.push(`**Expected outcome:** ${s.expectedOutcome}`);if(s.conflict){a.push(`\u26A0\uFE0F **Conflict:** "${s.conflict.activeName}" is active and touches the same target(s): ${s.conflict.overlaps.join(", ")}. Running will SWAP \u2014 it deactivates first.`)}if(s.warnings?.length)a.push(`**Warnings:**
|
|
152
|
+
${s.warnings.map(i=>` \xB7 ${i}`).join("\n")}`);a.push(s.ok?"Pre-flight checks passed. Review the intended effects before running.":`\u274C **Cannot run:**
|
|
153
|
+
${s.errors.map(i=>` \xB7 ${i}`).join("\n")}`);return ve(a.join("\n\n"))}case"run":{if(!t.id)return H("run requires `id` (from get_scenarios).");const s=await o("run",{id:t.id,params:t.params??{}});if(s.preflightErrors?.length){return H(`Pre-flight refused to run \`${t.id}\` \u2014 nothing was changed:
|
|
154
|
+
${s.preflightErrors.map(i=>` \xB7 ${i}`).join("\n")}`)}const a=(s.steps??[]).map(i=>{const c=i.skipped?"\u2013":i.ok?"\u2713":"\u2717";const d=i.error?`
|
|
155
|
+
${i.error}`:"";return` ${c} ${i.label} (${i.ms}ms)${d}`}).join("\n");if(!s.ok){return H(`Run FAILED \u2014 it stopped at the failing step and nothing after it ran. The steps before it DID apply:
|
|
156
|
+
${a}
|
|
157
|
+
|
|
158
|
+
The device is now in a partial state. Deactivate to reverse what landed, or fix the step and run again.`)}return ve([`\u2705 **Scenario active \u2014 ${s.name??t.id}**`,a,`**Reported effects:**
|
|
159
|
+
${(s.effects??[]).map(i=>` \xB7 ${i.label} [${i.kind}]`).join("\n")}`,"The device shows a SIMULATED banner while this is active. Deactivate when done, and account for these effects when interpreting observations."].join("\n\n"))}case"deactivate":{const s=await o("deactivate",{});const a=s.report;const i=[`Removed ${a.removedRules} override rule(s)`,a.stoppedImpersonation?"Ended impersonation":null,a.undoStepsRan?`Ran ${a.undoStepsRan} undo step(s)`:null].filter(Boolean);const c=a.unrestoredState??[];const d=(a.unrestoredStorageKeys.length?`
|
|
160
|
+
|
|
161
|
+
\u26A0\uFE0F **NOT restored:** ${a.unrestoredStorageKeys.join(", ")} \u2014 a storage write has no automatic inverse. The app still holds these values.`:"")+(c.length?`
|
|
162
|
+
|
|
163
|
+
\u26A0\uFE0F **Stores NOT restored:** ${c.join(", ")} \u2014 a state write has no automatic inverse. These stores still hold what the scenario wrote.`:"");const l=a.errors.length?`
|
|
164
|
+
|
|
165
|
+
Errors: ${a.errors.join("; ")}`:"";return ve(`**Deactivated.**
|
|
166
|
+
${i.map(u=>` \xB7 ${u}`).join("\n")}${d}${l}`)}case"save":{if(!t.scenario)return H("save requires `scenario`.");const s=await o("save",{scenario:t.scenario});if(!s.ok){return H(`Save rejected:
|
|
167
|
+
${(s.errors??[s.error??"unknown error"]).map(a=>` \xB7 ${a}`).join("\n")}`)}return ve(`Saved \`${s.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 H("setFolder requires `id` (from get_scenarios).");const s=await o("setFolder",{id:t.id,folder:t.folder});return ve(s.folder?`Filed \`${s.id}\` under **${s.folder}**.`:`Removed \`${s.id}\` from its folder \u2014 it now shows under Ungrouped.`)}case"delete":{if(!t.id)return H("delete requires `id`.");await o("delete",{id:t.id});return ve(`Deleted \`${t.id}\` from the device library.`)}}}catch(n){return H(Qr(n))}})}import{z as ee}from"zod";import{execFile as Hs}from"child_process";import{promisify as Ys}from"util";import{existsSync as Zr,readFileSync as Qs}from"fs";import At from"os";import xe from"path";var Xs=Ys(Hs);function Zs(){const e=process.env.BUOY_SIMCAM_DIR;const r=[...e?[xe.join(e,"buoycam")]:[],"/Applications/Buoy.app/Contents/Resources/simcam/buoycam",xe.join(At.homedir(),"Applications/Buoy.app/Contents/Resources/simcam/buoycam")];let t=__dirname;for(let n=0;n<8;n++){r.push(xe.join(t,"apps/desktop/resources/simcam/buoycam"));const o=xe.dirname(t);if(o===t)break;t=o}return r}var Ye=null;function ea(){if(Ye)return Ye;Ye=Zs().find(e=>Zr(e))??null;return Ye}async function Y(e){const r=ea();if(!r){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 Xs(r,[...e,"--json"],{timeout:3e4});return{ok:true,data:JSON.parse(t)}}catch(t){const n=t.stdout??"";try{return{ok:false,data:JSON.parse(n)}}catch{return{ok:false,error:t.message||"the simulator camera CLI failed"}}}}function ta(e){const r=e.filter(s=>s.level==="fail");const t=e.filter(s=>s.level==="warn");if(r.length===0&&t.length===0){return"The simulator camera is healthy \u2014 every check passed."}const n=[];for(const s of[...r,...t]){n.push(`- **${s.name}** (${s.level}): ${s.detail}`);if(s.fix)n.push(` ${s.fix}`)}const o=r.length>0?`${r.length} problem${r.length===1?"":"s"} found.`:`No hard failures, but ${t.length} thing${t.length===1?"":"s"} worth knowing.`;return[o,"",...n].join("\n")}function ra(e,r){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(n=>`- **${n.name}** (${n.runtime}) \u2014 \`${n.udid}\``)];if(e.length>1&&r===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(r===null){t.push("","_Could not read the installed apps._");return t.join("\n")}if(r.length===0){t.push("","No apps installed on it.");return t.join("\n")}t.push("",`${r.length} installed app${r.length===1?"":"s"}:`,...r.map(n=>`- ${n.name} \u2014 \`${n.bundleId}\``),"","_Pass one of these bundle ids to `camera_launch` to relaunch it with the camera attached._");return t.join("\n")}function na(e,r){const t=[];t.push(e.length?'**Mac cameras** (for `kind: "camera"`):':"**Mac cameras**: none found.");if(e.length){t.push(...e.map(n=>`- ${n.name} \u2014 \`${n.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(r.length?'**Capturable windows** (for `kind: "screen"`, `value: "window:<id>"`):':"**Capturable windows**: none found.");if(r.length){t.push(...r.map(n=>`- ${n.app}${n.title?` \u2014 ${n.title}`:""} \u2014 \`window:${n.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 oa(){const e=process.env.BUOY_ENTITLEMENT_FILE;if(e)return[e];return[xe.join(At.homedir(),"Library/Application Support/Buoy/entitlement.json"),xe.join(At.homedir(),"Library/Application Support/buoy-desktop/entitlement.json")]}function en(){for(const e of oa()){try{if(!Zr(e))continue;const r=JSON.parse(Qs(e,"utf8"));return{tier:r.tier==="pro"||r.tier==="free"?r.tier:"locked",isPro:r.isPro===true&&r.hasDesktopAccess===true&&typeof r.validUntil==="number"&&Number.isFinite(r.validUntil)&&Date.now()<r.validUntil&&typeof r.proValidUntil==="number"&&Number.isFinite(r.proValidUntil)&&Date.now()<r.proValidUntil}}catch{}}return{tier:"locked",isPro:false}}function sa(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 J=e=>({content:[{type:"text",text:e}]});var we=e=>en().isPro?null:te(sa(e));var te=e=>({isError:true,content:[{type:"text",text:e}]});function aa(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:ee.enum(["barcode","image","video","camera","screen","pattern"]).describe("What the camera should show."),value:ee.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:ee.enum(["qr","pdf417","aztec","code128"]).optional().describe("Barcode symbology; defaults to qr.")}},async r=>{const t=we("camera_source");if(t)return t;const n=["source",r.kind];if(r.value)n.push(r.value);if(r.format)n.push("--format",r.format);const o=await Y(n);if(!o.ok){return te(o.error??o.data?.error??"could not set the camera source")}const s=r.kind==="barcode"?`a ${r.format??"qr"} code reading "${r.value}"`:r.kind==="screen"?`this Mac's screen (${r.value??"behind the simulator window"})`:r.value??r.kind;return J(`The simulator camera is now showing ${s}, at ${o.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 r=we("camera_status");if(r)return r;const t=await Y(["status"]);if(!t.ok||!t.data){return te(t.error??"could not read the simulator camera status")}const{publishing:n,fps:o,codes:s}=t.data;if(!n){return J("The simulator camera is not publishing anything.\n\n_Set a source with `camera_source` first._")}return J([`Publishing at ${o} fps.`,s.length?`Currently decoding: ${s.map(a=>`\`${a}\``).join(", ")}`:"No barcode in the current frame.","","_A code shown here is what the app receives. If the app is not reacting to it, the problem is in the app, not the camera \u2014 `camera_diagnose` will say whether the app is even reading the feed._"].join("\n"))});e.registerTool("camera_launch",{description:"Relaunch a simulator app with the camera attached. A camera can only be attached when a process starts, so an app that is already running cannot be given one \u2014 this terminates and relaunches it.",inputSchema:{bundleId:ee.string().describe("The app's bundle identifier."),udid:ee.string().optional().describe("Simulator udid, if more than one is booted.")}},async r=>{const t=we("camera_launch");if(t)return t;const n=["launch",r.bundleId];if(r.udid)n.push("--udid",r.udid);const o=await Y(n);if(!o.ok){return te(o.error??o.data?.error??"could not launch the app")}return J(`Relaunched \`${r.bundleId}\` with the camera attached${o.data?.pid?` (pid ${o.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:ee.string().optional().describe("Check a specific app \u2014 whether the library is actually loaded in it.")}},async r=>{const t=["diagnose"];if(r.bundleId)t.push(r.bundleId);const n=await Y(t);if(!n.data?.checks){return te(n.error??"could not run the simulator camera diagnosis")}const o=en();const s=o.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 J(ta(n.data.checks)+s)});e.registerTool("camera_stop",{description:"Turn the simulator camera off and stop publishing frames. The camera stays on until stopped \u2014 across app relaunches and after a test finishes \u2014 so call this when done, or the next thing that opens a camera will still see the last source.",inputSchema:{}},async()=>{const r=we("camera_stop");if(r)return r;const t=await Y(["stop"]);if(!t.ok){return te(t.error??t.data?.error??"could not stop the camera")}return J("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:ee.string().optional().describe("Which simulator's apps to list. Only needed when several are booted.")}},async r=>{const t=we("camera_devices");if(t)return t;const n=await Y(["devices"]);if(!n.ok||!n.data){return te(n.error??"could not list booted simulators")}const o=n.data.devices??[];let s=null;if(o.length===1||r.udid){const a=await Y(["apps",...r.udid?["--udid",r.udid]:[]]);s=a.ok?a.data?.apps??[]:null}return J(ra(o,s))});e.registerTool("camera_inputs",{description:"List what this Mac can point the simulator camera at: its webcams (the uniqueId for `camera_source` with kind `camera`) and the windows the screen source can film (the id for `window:<id>`). Call this before choosing a `camera` or windowed `screen` source \u2014 those ids cannot be guessed.",inputSchema:{}},async()=>{const r=we("camera_inputs");if(r)return r;const[t,n]=await Promise.all([Y(["cameras"]),Y(["windows"])]);if(!t.ok&&!n.ok){return te(t.error??n.error??"could not list the Mac's cameras or windows")}return J(na(t.data?.cameras??[],n.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:ee.enum(["on","off","status"]).describe("Turn it on, off, or report the current state."),udid:ee.string().optional().describe("Which simulator. Only needed when several are booted.")}},async r=>{const t=we("camera_zero_setup");if(t)return t;const n=await Y(["zero-setup",r.action,...r.udid?["--udid",r.udid]:[]]);if(!n.ok){return te(n.error??n.data?.error??"could not change zero-setup mode")}const o=n.data??{};if(r.action==="status"){if(!o.enabled)return J("Zero-setup mode is **off**.");return J(o.foreign?`Zero-setup is on, but **another tool owns it** (\`${o.path}\`). Quit that tool before turning Buoy's on.`:"Zero-setup mode is **on** \u2014 anything this simulator launches gets the camera.")}if(r.action==="on"){return J("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 J("Zero-setup mode is **off**.")})}import{z as W}from"zod";var tn="highlight-updates";var xt=e=>({content:[{type:"text",text:e}]});var Qe=e=>({isError:true,content:[{type:"text",text:e}]});var rn=e=>e instanceof Error?e.message:String(e);function ia(e){let r=e.interactive?"\u2022 ":" ";r+=e.name;const t=e.text??e.label;if(t)r+=` "${t}"`;if(e.role)r+=` <${e.role}>`;if(e.control)r+=` {${e.control}${e.value!==void 0?`=${JSON.stringify(e.value)}`:""}}`;if(e.longPressable)r+=" {long-press}";if(e.testID)r+=` [testID=${e.testID}]`;if(e.tap)r+=` (tap: ${e.tap.x},${e.tap.y})`;if(e.nativeTag!=null)r+=` #${e.nativeTag}`;return r}var Tt=0;var nn=3;var ca="\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 la(e,r){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:W.boolean().optional().describe("Only return tappable (onPress) elements. Default false (include labels/text for context)."),includeBuoy:W.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 n=r.requireProDevice(t.deviceId);const o=await r.callAction(tn,"describeScreen",{includeBuoy:t.includeBuoy},n);const s=o?.elements??[];const a=t.interactiveOnly?s.filter(d=>d.interactive):s;if(a.length===0){return xt("No elements found on screen. If the app just navigated, wait a moment and retry; make sure highlight-updates is enabled in the app.")}const i=o.hiddenBuoy?` Buoy's own overlay (${o.hiddenBuoy} element${o.hiddenBuoy===1?"":"s"}) is left out \u2014 pass includeBuoy:true to see it.`:"";const c=`Screen ${o.screen.width}\xD7${o.screen.height} \u2014 ${a.length} element${a.length===1?"":"s"} (\u2022 = tappable). Tap with tap_element({ testID | query | nativeTag }).${i}`;return xt(`${c}
|
|
176
|
+
|
|
177
|
+
${a.map(ia).join("\n")}`)}catch(n){return Qe(rn(n))}});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:W.number().optional().describe("Exact nativeTag from describe_screen (most precise)."),testID:W.string().optional().describe("Exact testID of the element."),query:W.string().optional().describe('Fuzzy match against testID / label / visible text / component name \u2014 e.g. "Sign in".'),value:W.union([W.number(),W.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:W.string().optional().describe("For a text input: the string to set via onChangeText."),longPress:W.boolean().optional().describe("Invoke the element's onLongPress instead of onPress. Fails with a clear reason if the element has no onLongPress handler."),scrollIntoView:W.boolean().optional().describe("Attempt to scroll an off-screen target into view. Default true; inspect the action result."),includeBuoy:W.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 Qe("Provide one of: nativeTag, testID, or query (from describe_screen).")}const n=r.requireProDevice(t.deviceId);const o=await r.callAction(tn,"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},n);Tt+=1;const s=Tt>=nn&&Tt%nn===0?ca:"";if(o?.tapped&&o.matched){const i=o.matched;const c=i.text??i.label??i.name;const d=i.testID?` [testID=${i.testID}]`:i.nativeTag!=null?` #${i.nativeTag}`:"";const l=o.scrolled?" (scrolled into view)":"";const u=i.via==="onValueChange"?`Set "${c}"${d} \u2192 ${JSON.stringify(i.value)}`:i.via==="onChangeText"?`Typed ${JSON.stringify(i.value)} into "${c}"${d}`:i.via==="onLongPress"?`Long-pressed "${c}"${d}`:`Tapped "${c}"${d}`;const f=o.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=o.alsoMatched?.length?`
|
|
178
|
+
Also matched equally well (the choice was a coin toss \u2014 re-tap by #nativeTag if this was wrong):
|
|
179
|
+
`+o.alsoMatched.map(p=>`- ${p.name}${p.text?` "${p.text}"`:""}${p.testID?` [testID=${p.testID}]`:""}${p.nativeTag!=null?` #${p.nativeTag}`:""}`).join("\n"):"";return xt(`${u}${l}.${k}${y}${s}`)}let a=o?.reason??"Tap failed.";if(o?.candidates?.length){a+="\n\nTappable candidates:\n"+o.candidates.map(i=>`- ${i.name}${i.text?` "${i.text}"`:""}${i.testID?` [testID=${i.testID}]`:""}${i.nativeTag!=null?` #${i.nativeTag}`:""}`).join("\n")}return Qe(a)}catch(n){return Qe(rn(n))}})}import{z as It}from"zod";var Dt="js-top";var ua="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function da(e){const r=Math.max(1,...e);return e.map(t=>ua[Math.min(7,Math.floor(t/r*7.999))]).join("")}function ha(e,r){const t=[];t.push(`## JS thread top (${(r/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((n,o)=>{const s=n.freezes>0?`\u26A0 ${n.freezes} (worst ${n.worstFreezeMs}ms)`:"\u2013";t.push(`| ${o+1} | ${n.label} | ${n.api} | ${n.windowMs.toFixed(1)} | ${n.pctOfBusy.toFixed(1)} | ${n.calls} | ${n.avgMs.toFixed(2)} | ${n.maxMs.toFixed(1)} | ${s} |`)});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 pa(e){const r=[];r.push(`## Origin detail \u2014 ${e.label}`);r.push("");r.push(`API: \`${e.api}\` \xB7 key: \`${e.key}\``);r.push("");r.push(`Activity last 5s (250ms buckets): \`${da(e.buckets)}\` \u2014 ${e.windowMs.toFixed(1)}ms in window, ${e.pctOfBusy.toFixed(1)}% of busy time.`);r.push("");r.push("| runs | scheduled | avg/run | max/run | total | last run | freezes (60s) | worst freeze |");r.push("|---|---|---|---|---|---|---|---|");r.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){r.push("");r.push(`Scheduled from: **${e.caller?`${e.caller}()`:"unknown caller"}**${e.file?` \u2014 ${e.file}${e.line!=null?`:${e.line}`:""}`:""}`);if(e.frames?.length){r.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"){r.push("");r.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 r.join("\n")}function ma(e,r){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:It.number().optional().describe("How long to sample before reading the table. Default 3000; clamped to 250\u201330000."),clearFirst:It.boolean().optional().describe("Reset tracked statistics before sampling. Hook coverage and attribution limits still apply.")}},async({deviceId:t,durationMs:n,clearFirst:o})=>{try{const s=r.requireProDevice(t);const a=Math.min(Math.max(n??3e3,250),3e4);const i=await r.callAction(Dt,"sample",{durationMs:a,clearFirst:o===true},s);if(!i)return m("Device returned no snapshot \u2014 is @buoy-gg/js-top installed in the app?");const c=ha(i,a);const d={busyPct:Math.round(i.busyPct*10)/10,freezeSummary:i.freezeSummary,tiers:i.tiers,rows:i.rows.slice(0,15).map(l=>({key:l.key,api:l.api,windowMs:Math.round(l.windowMs*10)/10,pctOfBusy:Math.round(l.pctOfBusy*10)/10,calls:l.calls,avgMs:Math.round(l.avgMs*100)/100,maxMs:Math.round(l.maxMs*10)/10,totalMs:Math.round(l.totalMs),freezes:l.freezes,worstFreezeMs:l.worstFreezeMs}))};return $(`${c}
|
|
180
|
+
|
|
181
|
+
\`\`\`json
|
|
182
|
+
${JSON.stringify(d)}
|
|
183
|
+
\`\`\``)}catch(s){return m(A(s))}});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:It.string().describe("Origin key from get_js_thread_top's JSON rows.")}},async({deviceId:t,key:n})=>{try{const o=r.requireProDevice(t);const s=await r.callAction(Dt,"getOriginDetail",{key:n},o);if(!s){return m(`Origin "${n}" is not tracked (cleared, evicted, or never existed). Re-run get_js_thread_top for current keys.`)}const a=pa(s);return $(`${a}
|
|
184
|
+
|
|
185
|
+
\`\`\`json
|
|
186
|
+
${JSON.stringify(s)}
|
|
187
|
+
\`\`\``)}catch(o){return m(A(o))}});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 n=r.requireProDevice(t);await r.callAction(Dt,"clear",{},n);return $("Cleared js-top stats.")}catch(n){return m(A(n))}})}import{z as Q}from"zod";var re="images";function on(e){if(!e)return"(no source)";const r=e.match(/[?&]unstable_path=([^&?]+)/);const t=r?decodeURIComponent(r[1]):e;const n=t.split("?")[0]??t;const o=n.split("/").filter(Boolean);return o[o.length-1]??t}function fa(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 sn(e){if(e.cache)return e.cache;if(e.progressSeen)return"network";return"?"}function an(e){return`${(e/(1024*1024)).toFixed(1)}MB`}function ga(e,r){const t=[];const n=e.stats;t.push(`## Images registry (${e.total} records, showing ${Math.min(r,e.records.length)})`);t.push("");t.push(`${n.loaded} loaded \xB7 ${n.errors} failed \xB7 ${n.loading} in flight \xB7 \u2248${an(n.estDecodedBytes)} decoded`+(n.estWastedBytes>0?` \xB7 **${an(n.estWastedBytes)} wasted on oversized sources**`:""));const o=e.insights;if(o){const a=[];if(o.duplicates.length>0)a.push(`${o.duplicates.length} duplicate URL(s): ${o.duplicates.slice(0,3).map(i=>`${on(i.uri)}\xD7${i.count}`).join(", ")}`);if(o.retryStorms.length>0)a.push(`${o.retryStorms.length} retry storm(s): ${o.retryStorms.slice(0,3).map(i=>`#${i.id}(${i.loadCount} loads)`).join(", ")}`);if(o.queueSaturated)a.push("iOS image queue saturated (>4 concurrent loads)");if(o.missingAlt>0)a.push(`${o.missingAlt} image(s) missing alt/accessibilityLabel`);if(o.layoutShifters.length>0)a.push(`${o.layoutShifters.length} layout-shifting image(s): ${o.layoutShifters.slice(0,3).map(i=>`#${i.id}`).join(", ")} \u2014 reserve explicit dimensions`);if(a.length>0){t.push("");t.push(`**Insights:** ${a.join(" \xB7 ")}`)}}const s=e.captureStatus;if(s.rnDecoratorTooLate){t.push("");t.push('\u26A0 RN <Image> capture missed the module-load race \u2014 add `import "@buoy-gg/images/register"` as the FIRST import of the app entry file.')}if(e.globalModes.network!=="normal"||e.globalModes.blank){t.push("");t.push(`\u26A0 Simulation active: network=${e.globalModes.network}${e.globalModes.blank?", blank images ON":""} (set_image_simulation to reset).`)}t.push("");t.push("| id | image | lib | status | cache | ms | decoded px | shown dp | verdict | sim |");t.push("|---|---|---|---|---|---|---|---|---|---|");for(const a of e.records){const i=a.intrinsic?`${a.intrinsic.width}\xD7${a.intrinsic.height}`:"\u2013";const c=a.layout?`${a.layout.width}\xD7${a.layout.height}`:"\u2013";const d=a.status==="error"?`**error**${a.errorCode?` (${a.errorCode})`:""}`:a.status;t.push(`| ${a.id} | ${on(a.uri)} | ${a.lib} | ${d}${a.mounted?"":" (unmounted)"} | ${sn(a)} | ${a.ms??"\u2013"} | ${i} | ${c} | ${fa(a)} | ${a.overrideLabel??"\u2013"} |`)}t.push("");t.push("_Act on a row with `image_action` using its `id` (hard_reload / retry / force_error / force_loading / force_blank / swap_url / flash / restore / evict_disk)._");return t.join("\n")}var va={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 wa(e,r){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:Q.number().optional().describe("Max records to return (newest first). Default 30, max 200."),status:Q.enum(["pending","loading","loaded","error"]).optional().describe("Only records in this state (e.g. 'error' for the failure log).")}},async({deviceId:t,limit:n,status:o})=>{try{const s=r.requireProDevice(t);const a=Math.min(Math.max(n??30,1),200);const i=await r.callAction(re,"list",{limit:a,status:o},s);if(!i)return m("Device returned nothing \u2014 is @buoy-gg/images installed in the app?");const c=ga(i,a);const d={stats:i.stats,insights:i.insights,captureStatus:i.captureStatus,globalModes:i.globalModes,records:i.records.map(l=>({id:l.id,uri:l.uri,lib:l.lib,status:l.status,mounted:l.mounted,cache:l.cache,ms:l.ms,intrinsic:l.intrinsic,layout:l.layout,oversizeFactor:l.oversizeFactor,wastedKB:l.wastedKB,error:l.error,errorCode:l.errorCode,overrideLabel:l.overrideLabel,loadCount:l.loadCount,hasAltText:l.hasAltText,layoutShifts:l.layoutShifts}))};return $(`${c}
|
|
188
|
+
|
|
189
|
+
\`\`\`json
|
|
190
|
+
${JSON.stringify(d)}
|
|
191
|
+
\`\`\``)}catch(s){return m(A(s))}});e.registerTool("image_action",{description:"Request an action for a registered image ID: hard_reload, retry, evict_disk, flash, prove_savings or a supported simulation override. swap_url requires url; restore removes the override. Support depends on the component and platform. prove_savings attempts a WebP conversion at displayed size and reports available byte comparisons and a device-local URI; inspect visual quality and originalBytesSource before using the result. Other actions return an acknowledgement and, when available, a later record snapshot; that snapshot may precede load completion. A device-local URI is not necessarily accessible from the editor host.",inputSchema:{deviceId:S,id:Q.number().describe("Record id from get_images."),action:Q.enum(["hard_reload","retry","evict_disk","flash","prove_savings","force_error","force_loading","force_blank","swap_url","restore"]).describe("What to do."),url:Q.string().optional().describe("Replacement URL (swap_url only).")}},async({deviceId:t,id:n,action:o,url:s})=>{try{const a=r.requireProDevice(t);if(o==="prove_savings"){const f=await r.callAction(re,"proveSavings",{id:n},a);if(!f)return m("Device returned nothing for proveSavings.");if(!f.ok)return m(f.message);const k=[`**prove_savings** on #${n}: ${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:${n}, action:"swap_url", url:"${f.optimizedUri}"}`);return $(k.join("\n"))}const i=va[o];if(!i)return m(`Unknown action: ${o}`);if(o==="swap_url"&&!s)return m("swap_url requires the `url` param.");const c=await r.callAction(re,i.action,{id:n,...i.params?.(s)??{}},a);const d=o==="flash"?0:1500;if(d>0)await new Promise(f=>setTimeout(f,d));const l=await r.callAction(re,"getDetail",{id:n},a).catch(()=>null);const u=[`**${o}** on #${n}: ${c?.message??(c?.ok===false?"failed":"done")}`];if(l){u.push("");u.push(`Now: status=${l.status}${l.errorCode?` (${l.errorCode})`:""} \xB7 cache=${sn(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(a){return m(A(a))}});e.registerTool("set_image_simulation",{description:"Configure supported instrumented image loads: offline simulates network-load failures while bundled assets can still load; cold requests cache bypass; normal resets the network mode. Reload or remount existing images as needed. blankImages removes sources from integrated images; massAction targets registered mounted images. Can also clear the registry or supported Expo caches. These modes do not change device connectivity.",inputSchema:{deviceId:S,network:Q.enum(["normal","offline","cold"]).optional().describe("Network simulation mode."),blankImages:Q.boolean().optional().describe("Render integrated images without a source."),massAction:Q.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:Q.boolean().optional().describe("Clear the captured image log."),clearExpoCaches:Q.boolean().optional().describe("Clear expo-image memory + disk caches.")}},async({deviceId:t,network:n,blankImages:o,massAction:s,clearRegistry:a,clearExpoCaches:i})=>{try{const c=r.requireProDevice(t);const d=[];if(s){const l=await r.callAction(re,"massAction",{kind:s},c);d.push(l?.message??`mass ${s} applied`)}if(n){await r.callAction(re,"setNetworkMode",{mode:n},c);d.push(`network=${n}`)}if(o!=null){await r.callAction(re,"setBlankImages",{enabled:o},c);d.push(`blankImages=${o}`)}if(a){await r.callAction(re,"clearRecords",{},c);d.push("registry cleared")}if(i){const l=await r.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(A(c))}})}import{z as Ce}from"zod";function ba(e){if(e.graphSupported&&e.graphCount!=null)return null;const r=(e.graphError??"").trim();const t=e.dev===true||!!r;if(t){return r?`\u26A0 Metro bundle graph unavailable (${r}) \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 be="assets";function ie(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 cn(e){if(e.sizeBytes==null)return"\u2013";return e.sizeSource==="measured"?ie(e.sizeBytes):`~${ie(e.sizeBytes)}`}function ln(e){if(!e.length)return"\u2013";return e.map(r=>`@${r}x`).join(" ")}function ya(e,r){const t=[];if(!e.loaded)t.push("UNUSED");if(r.overDecode.includes(e.id))t.push("OVERSIZE");if(r.duplicates.some(n=>n.ids.includes(e.id)))t.push("DUP");if(r.heavyGifs.includes(e.id)||r.heavyFonts.includes(e.id))t.push("HEAVY");if(r.scaleAnomalies.includes(e.id))t.push("BAD-SCALE");else if(r.scaleGaps.includes(e.id))t.push("LOW-RES");if(r.webpCandidates.includes(e.id))t.push("WEBP");return t.length?t.join(" "):"\u2013"}function $a(e,r){const t=[];const n=e.stats;const o=e.scanStatus;t.push(`## Asset inventory (${e.total} assets, showing ${Math.min(r,e.records.length)}, largest first)`);t.push("");const s=Object.entries(n.byKind).filter(([,l])=>l.count>0).map(([l,u])=>`${u.count} ${l}${u.bytes>0?` (${ie(u.bytes)})`:""}`);t.push(`${n.loaded} loaded \xB7 ${n.neverLoaded} never loaded \xB7 `+(n.totalBytes>0?`${ie(n.totalBytes)} measured (${n.measuredCount}/${n.total})`:"sizes not measured")+` \xB7 ${s.join(" \xB7 ")}`);if(o.fontFamilies.length>0){t.push(`Loaded font families: ${o.fontFamilies.join(", ")}`)}const a=ba(o);if(a)t.push(a);if(o.measuring)t.push("\u26A0 Size measurement in progress \u2014 byte totals are partial; re-run get_assets shortly.");const i=e.insights;const c=[];if(i.neverLoaded.length)c.push(`${i.neverLoaded.length} never loaded`);if(i.duplicates.length){const l=i.duplicates.reduce((u,f)=>u+(f.wastedBytes??0),0);c.push(`${i.duplicates.length} duplicate group(s)${l>0?` (${ie(l)} wasted)`:""}`)}if(i.overDecode.length)c.push(`${i.overDecode.length} decode larger than 2\xD7 the screen`);if(i.webpCandidates.length)c.push(`${i.webpCandidates.length} WebP candidate(s)`);if(i.heavyGifs.length)c.push(`${i.heavyGifs.length} heavy GIF(s)`);if(i.heavyFonts.length)c.push(`${i.heavyFonts.length} heavy font(s)`);if(i.scaleGaps.length)c.push(`${i.scaleGaps.length} scale gap(s)`);if(i.scaleAnomalies.length)c.push(`${i.scaleAnomalies.length} scale anomaly(ies)`);if(c.length){t.push("");t.push(`**Findings:** ${c.join(" \xB7 ")}`)}const d=e.diff;if(d){const l=d.netBytes==null?"net unknown":Math.abs(d.netBytes)<1024?"\xB10 net":`${d.netBytes>=0?"+":"\u2212"}${ie(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} | ${ln(l.scales)} | ${cn(l)} | ${ya(l,i)} |`)}t.push("");t.push("_Sizes marked ~ are decoded-memory estimates (unmeasurable in this environment). Use `asset_action` for rescan / measure_sizes / detail / baseline ops._");return t.join("\n")}function ka(e,r){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:Ce.number().optional().describe("Max records to return (largest first). Default 40, max 500."),kind:Ce.enum(["image","font","video","audio","data","other"]).optional().describe("Only assets of this kind."),unusedOnly:Ce.boolean().optional().describe("Only assets shipped in the bundle but never loaded at runtime.")}},async({deviceId:t,limit:n,kind:o,unusedOnly:s})=>{try{const a=r.requireProDevice(t);const i=Math.min(Math.max(n??40,1),500);const c=await r.callAction(be,"list",{limit:s?500:i,kind:o,loadedOnly:false},a);if(!c)return m("Device returned nothing \u2014 is @buoy-gg/assets installed in the app?");if(s){c.records=c.records.filter(u=>!u.loaded).slice(0,i)}const d=$a(c,i);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(a){return m(A(a))}});e.registerTool("asset_action",{description:"Drive the assets tool: rescan (re-walk the registry + merge the Metro bundle graph + refresh fonts + measure sizes \u2014 run this first if the inventory looks stale or empty), measure_sizes (re-measure byte sizes only), detail (full metadata for one asset by id: source dir, per-scale sizes, resolved URI, per-file graph paths), save_baseline (persist the current inventory for before/after comparison \u2014 save, make your change, then get_assets shows added/removed/grown/net bytes), clear_baseline, clear_records (wipe + rescan rebuilds).",inputSchema:{deviceId:S,action:Ce.enum(["rescan","measure_sizes","detail","save_baseline","clear_baseline","clear_records"]).describe("What to do."),id:Ce.number().optional().describe("Asset id from get_assets (detail only).")}},async({deviceId:t,action:n,id:o})=>{try{const s=r.requireProDevice(t);switch(n){case"rescan":{const a=await r.callAction(be,"rescan",{},s);const i=a?.scanStatus;if(!i)return m("Device returned nothing for rescan.");return $(`Rescan done: ${i.registryCount} registered at runtime`+(i.graphCount!=null?` \xB7 ${i.graphCount} in the bundle graph`:" \xB7 no bundle graph")+(i.graphError?` (graph: ${i.graphError})`:"")+` \xB7 ${i.fontFamilies.length} font families`+(i.measuring?" \xB7 size measurement running \u2014 get_assets in a moment":""))}case"measure_sizes":{const a=await r.callAction(be,"measureSizes",{},s);return $(`Measured ${a?.measured??0} of ${a?.total??0} assets.`)}case"detail":{if(o==null)return m("detail requires the `id` param (from get_assets).");const a=await r.callAction(be,"getDetail",{id:o},s);if(!a)return m(`Asset ${o} not found \u2014 re-run get_assets for current ids.`);const i=[`## ${a.name}.${a.type} (#${a.id})`,"",`- Kind: ${a.kind} \xB7 ${a.loaded?"loaded at runtime":"in bundle, NEVER loaded"} (${a.origin})`];if(a.width!=null)i.push(`- Dimensions: ${a.width}\xD7${a.height} logical \xB7 scales ${ln(a.scales)}`);if(a.sizesByScale){for(const[c,d]of Object.entries(a.sizesByScale)){i.push(`- Size @${c}x: ${ie(d)}`)}}if(a.sizeBytes!=null)i.push(`- Total: ${cn(a)}`);if(a.estDecodedBytes)i.push(`- Decoded memory: ~${ie(a.estDecodedBytes)} (RGBA)`);if(a.hash)i.push(`- Hash: ${a.hash}`);if(a.fileSystemLocation)i.push(`- Source dir: ${a.fileSystemLocation}`);if(a.files?.length)i.push(`- Files: ${a.files.join(", ")}`);if(a.uri)i.push(`- Resolved URI: ${a.uri}`);return $(i.join("\n"))}case"save_baseline":{const a=await r.callAction(be,"saveBaseline",{},s);return $(`Baseline saved (${a?.assets??0} assets). Make your change, then get_assets reports added/removed/grown/net bytes against it.`)}case"clear_baseline":{await r.callAction(be,"clearBaseline",{},s);return $("Baseline cleared.")}case"clear_records":{const a=await r.callAction(be,"clearRecords",{},s);return $(a?.message??"Inventory cleared.")}}}catch(s){return m(A(s))}})}import{z as Xe}from"zod";import{WebSocket as _a}from"ws";var Sa=3e3;function Aa(e){return`${e.replace(/^http/,"ws").replace(/\/+$/,"")}/message`}function xa(e){return new Promise(r=>{let t=false;const n=i=>{if(t)return;t=true;r(i)};let o;try{o=new _a(Aa(e))}catch(i){n({ok:false,error:i.message});return}const s=setTimeout(()=>{try{o.close()}catch{}n({ok:false,error:`dev server at ${e} did not accept a connection`})},Sa);let a=false;o.on("open",()=>{try{o.send(JSON.stringify({version:2,method:"reload"}));a=true;clearTimeout(s);setTimeout(()=>{try{o.close()}catch{}n({ok:true})},250)}catch(i){clearTimeout(s);n({ok:false,error:i.message})}});o.on("error",i=>{clearTimeout(s);if(a)return;n({ok:false,error:i.message})})})}var Rt="app";var un="reloadApp";var Ta=3e4;var Ia=1200;var dn=1500;var Da=400;var hn=e=>new Promise(r=>setTimeout(r,e));async function pn(e,r,t){try{const n=await e.callAction(Rt,"ping",{},r,{timeoutMs:t,silent:true});e.noteDevServerOrigin(r,n?.devServerOrigin);return typeof n?.startedAt==="number"?n.startedAt:null}catch{return null}}function Ra(e,r){if(r===G)return;const t=e.toolActions(Rt).find(n=>n.deviceId===r);if(!t?.actions.includes(un)){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 Oa(e,r,t,n){const o=Date.now();await hn(Ia);while(Date.now()-o<t){const s=await pn(e,r,dn);if(s!==null&&s!==n)return Date.now()-o;await hn(Da)}return null}function Ma(e,r){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:Xe.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:Xe.boolean().optional().describe("Wait for the app to come back before returning. Default true \u2014 turn off for fire-and-forget."),timeoutMs:Xe.number().optional().describe("How long to wait for the app to reconnect, in ms. Default 30000."),deviceId:Xe.string().optional().describe('Target device id (auto-selected if one is connected). Use "All" to reload every connected app.')}},async t=>{try{const n=r.requireProDevice(t.deviceId);Ra(r,n);const o=t.wait===false?null:await pn(r,n,dn);let s=null;let a=false;const i=async l=>{const u=r.devServerOrigin(n);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 xa(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.`)}a=true};if(r.isUnresponsive(n)&&r.devServerOrigin(n)){await i()}else{try{s=await r.callAction(Rt,un,{strategy:t.strategy??"auto"},n)}catch(l){await i(l)}}const c=a?` via the dev server (the app was unresponsive \u2014 its own reload could not be reached)`:s?.strategy?` via ${s.strategy}`:"";if(t.wait===false){return $(`Reload requested${c}. The app is restarting \u2014 its in-memory state is gone; re-read anything you cached.`)}const d=await Oa(r,n,t.timeoutMs??Ta,o);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(n){return m(A(n))}})}import{z as Ca}from"zod";var Ea=e=>({content:[{type:"text",text:e}]});var Fa=e=>({isError:true,content:[{type:"text",text:e}]});var mn=e=>e instanceof Error?e.message:String(e);var qa=5e3;var ja=20;var Ba=400;var Pa=1600;var Na=160;var Ze=(e,r=Na)=>e.length>r?`${e.slice(0,r)}\u2026`:e;function La(e){if(!e)return"--:--:--";const r=new Date(e);const t=n=>String(n).padStart(2,"0");return`${t(r.getHours())}:${t(r.getMinutes())}:${t(r.getSeconds())}`}async function Ua(e,r,t){const n=[];try{const o=await e.callAction("storage","mmkv.snapshot",{},r,t);for(const s of o??[]){const a=s.entries?.length??0;if(a>0)n.push(`MMKV "${s.id}": ${a} key${a===1?"":"s"}`)}}catch{}try{const o=await e.callAction("storage","secure.keys",{},r,t);if(o?.length)n.push(`SecureStore: ${o.length} key${o.length===1?"":"s"}`)}catch{}return n.length?`
|
|
196
|
+
${n.join(" \xB7 ")} \u2014 read with get_storage`:""}async function et(e,r){try{const t=await r();return t?`${e}
|
|
197
|
+
${t}`:null}catch(t){const n=mn(t);if(/not responding|timed out|got no answer/i.test(n)){return`${e}
|
|
198
|
+
(no answer \u2014 see the note above)`}return`${e}
|
|
199
|
+
(unavailable: ${Ze(n,120)})`}}function za(e,r){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:Ca.string().optional().describe("Target device id (auto-selected if one is connected).")}},async t=>{try{const n=r.requireProDevice(t.deviceId);const o=r.connectedDevices().find(p=>p.deviceId===n);const s=new Set((o?.tools??[]).map(p=>p.toolId));const a=`**${o?.deviceName??n}** (${o?.platform??"?"}, id \`${n}\`) \u2014 tools: ${[...s].join(", ")||"none"}`;const i={timeoutMs:qa};const[c,d,l,u]=await Promise.all([et("**Console \u2014 recent errors/warnings:**",async()=>{if(!s.has("console"))return null;const{payload:p}=await r.getSnapshot("console",n,i);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=>`${La(w.timestamp)} [${w.level==="error"?"ERR":"warn"}] ${Ze((w.message??"").split("\n").map(x=>x.trim()).filter(Boolean).slice(0,3).join(" \u23CE "),220)}`).join("\n")}),et("**Network \u2014 recent requests:**",async()=>{if(!s.has("network"))return null;const{payload:p}=await r.getSnapshot("network",n,i);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 x=g.error??g.status??"pending";return`${v} ${g.method??"GET"} ${Ze(String(w),80)} \u2192 ${x}${g.duration?` (${Math.round(g.duration)}ms)`:""}`}).join("\n")}),et("**Storage \u2014 persisted values:**",async()=>{if(!s.has("storage"))return null;const p=await r.callAction("storage","async.getAllKeys",{},n,i);if(!Array.isArray(p)||p.length===0){return"(no app keys)"}const b=p.slice(0,ja);let h=[];try{h=await r.callAction("storage","async.multiGet",{keys:b},n,i)??[]}catch{return`${b.map(O=>`\`${O}\``).join(", ")}
|
|
200
|
+
_Values: get_storage includeValues:true_`}const g=new Map(h);let v=Pa;const w=b.map(O=>{const C=g.get(O);if(C==null)return`- \`${O}\` = (null)`;if(C.length>Ba){return`- \`${O}\` = (${(C.length/1024).toFixed(1)} KB \u2014 read with get_storage)`}if(v<=0)return`- \`${O}\` = (not shown \u2014 triage budget spent; read with get_storage)`;v-=C.length;return`- \`${O}\` = ${C}`});const x=p.length-b.length;const T=await Ua(r,n,i);return`${w.join("\n")}${x>0?`
|
|
201
|
+
\u2026+${x} more keys`:""}${T}`}),et("**Screen \u2014 what's visible now:**",async()=>{if(!s.has("highlight-updates"))return null;const p=await r.callAction("highlight-updates","describeScreen",{},n,i);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?` "${Ze(h.text??h.label??"",60)}"`:""}${h.testID?` [testID=${h.testID}]`:""}`).join("\n")})]);const f=r.isUnresponsive(n);const k=f?`
|
|
202
|
+
|
|
203
|
+
\u{1F6D1} ${r.unresponsiveNote(n)}`:"";const y=[c,d,l,u].filter(Boolean).join("\n\n");return Ea(`${a}${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(n){return Fa(mn(n))}})}import{z as q}from"zod";var Ot="highlight-updates";var fn="app";var Ja=e=>({content:[{type:"text",text:e}]});var Wa=e=>({isError:true,content:[{type:"text",text:e}]});var Mt=e=>e instanceof Error?e.message:String(e);var tt=e=>new Promise(r=>setTimeout(r,e));var gn=250;var Va=5e3;var vn=2e3;var Ga=1200;var Ka=1500;var Ct=12e4;function rt(e,r){if(e.testID&&e.testID===r)return true;const t=r.toLowerCase();return[e.testID,e.text,e.label,e.name].filter(Boolean).some(n=>String(n).toLowerCase().includes(t))}function Ha(e){const r=e.text??e.label;return`${e.interactive?"\u2022 ":" "}${e.name}${r?` "${r}"`:""}${e.testID?` [testID=${e.testID}]`:""}`}var Ya=q.object({tap:q.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),longPress:q.boolean().optional().describe("Make `tap` a long-press instead."),type:q.string().optional().describe("Text to type (needs `into`)."),into:q.string().optional().describe("Target text input for `type`: testID or fuzzy text."),set:q.union([q.number(),q.boolean()]).optional().describe("Set a toggle (true/false) or slider (number) \u2014 pair with `tap` as the target."),reload:q.boolean().optional().describe("Reload the JS bundle before this step's action."),waitMs:q.number().min(0).max(3e4).optional().describe("Fixed pause after the action, in ms (max 30000)."),waitFor:q.string().optional().describe("Wait until an element matching this appears (default 5s)."),waitGone:q.string().optional().describe("Wait until no element matches this (default 5s)."),expect:q.string().optional().describe("Assert an element matching this IS on screen (waits up to 2s for it); fails the flow if not."),expectGone:q.string().optional().describe("Assert nothing matches this (waits up to 2s for it to go); fails the flow if something does."),timeoutMs:q.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 Qa(e,r){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:q.array(Ya).min(1).describe("Steps to run, in order."),include:q.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:q.boolean().optional().describe("Keep going after a failed step instead of stopping. Default false."),deviceId:S}},async t=>{const n=Date.now();try{const o=r.requireProDevice(t.deviceId);const s=t.include??"all";const a=async()=>{const v=await r.callAction(Ot,"describeScreen",{},o);return v?.elements??[]};const i=async()=>{try{const v=await r.callAction(fn,"ping",{},o,{timeoutMs:Ka,silent:true});return typeof v?.startedAt==="number"?v.startedAt:null}catch{return null}};const c=async(v,w)=>{const x=Date.now();while(Date.now()-x<w){const T=await i();if(T!==null&&T!==v)return Date.now()-x;await tt(gn)}return null};const d=new Set;const l=new Set;const u=new Set((r.connectedDevices().find(v=>v.deviceId===o)?.tools??[]).map(v=>v.toolId));if(s==="all"){if(u.has("console")){const{payload:v}=await r.getSnapshot("console",o).catch(()=>({payload:null}));const w=v?.entries??[];for(const x of w)d.add(x.id)}if(u.has("network")){const{payload:v}=await r.getSnapshot("network",o).catch(()=>({payload:null}));const w=Array.isArray(v)?v:v?.events??[];for(const x of w)l.add(x.id)}}const f=async(v,w)=>{const x=Date.now();for(;;){if(Date.now()-x>=w||Date.now()-n>Ct){return{ok:false,ms:Date.now()-x}}let T=[];try{T=await a()}catch{}if(v(T))return{ok:true,ms:Date.now()-x};await tt(gn)}};const k=[];let y=null;let p=0;for(let v=0;v<t.steps.length;v++){const w=t.steps[v];const x=`${v+1}`;const T=w.timeoutMs??Va;if(Date.now()-n>Ct){k.push(`${x} \u2717 flow exceeded ${Ct/1e3}s \u2014 stopped here`);y=v;break}const O=[];const C=[];const En=w.reload||w.tap||w.type!==void 0||w.waitMs||w.waitFor||w.waitGone||w.expect||w.expectGone;if(!En){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 M=await i();await r.callAction(fn,"reloadApp",{strategy:"auto"},o);await tt(Ga);const E=await c(M,Math.max(T,2e4));if(E==null){O.push("app did not come back after reload")}else{C.push(`reloaded (${E}ms)`);await f(P=>P.length>0,1e4)}}if(w.type!==void 0){const M=w.into??w.tap;if(!M){O.push("`type` needs `into` (which input to type into)")}else{const E=await r.callAction(Ot,"tapElement",{...wn(M),text:w.type},o);if(!E?.tapped){O.push(E?.reason??`could not type into "${M}"`)}else if(E.matched?.via&&E.matched.via!=="onChangeText"){O.push(`"${M}" is not a text input \u2014 it ran ${E.matched.via} instead, and the text was not entered`)}else{C.push(`typed ${JSON.stringify(w.type)} into "${M}"`)}}}else if(w.tap){const M={...wn(w.tap)};if(w.longPress)M.longPress=true;if(w.set!==void 0)M.value=w.set;const E=await r.callAction(Ot,"tapElement",M,o);if(!E?.tapped){O.push(E?.reason??`no element matched "${w.tap}"`)}else{const P=E.matched;const st=P?.text??P?.label??P?.name??w.tap;if(w.set!==void 0&&P?.via&&P.via!=="onValueChange"){O.push(`"${st}" is not a toggle/slider \u2014 it ran ${P.via} instead, so it was not set to ${JSON.stringify(w.set)}`)}else{C.push(w.set!==void 0?`set "${st}" \u2192 ${JSON.stringify(P?.value??w.set)}`:`${w.longPress?"long-pressed":"tapped"} "${st}"`)}}}if(!O.length&&w.waitMs){await tt(w.waitMs);C.push(`waited ${w.waitMs}ms`)}if(!O.length&&w.waitFor){const M=await f(E=>E.some(P=>rt(P,w.waitFor)),T);if(M.ok)C.push(`"${w.waitFor}" appeared (${M.ms}ms)`);else O.push(`"${w.waitFor}" never appeared within ${T}ms`)}if(!O.length&&w.waitGone){const M=await f(E=>!E.some(P=>rt(P,w.waitGone)),T);if(M.ok)C.push(`"${w.waitGone}" gone (${M.ms}ms)`);else O.push(`"${w.waitGone}" was still there after ${T}ms`)}if(!O.length&&w.expect){const M=await f(E=>E.some(P=>rt(P,w.expect)),w.timeoutMs??vn);if(M.ok)C.push(`"${w.expect}" is on screen`);else O.push(`expected "${w.expect}" on screen \u2014 not found`)}if(!O.length&&w.expectGone){const M=await f(E=>!E.some(P=>rt(P,w.expectGone)),w.timeoutMs??vn);if(M.ok)C.push(`"${w.expectGone}" is gone`);else O.push(`expected "${w.expectGone}" to be gone \u2014 still on screen`)}}catch(M){O.push(Mt(M))}if(O.length){k.push(`${x} \u2717 ${bn(w)} \u2014 ${O.join("; ")}`);y=y??v;if(!t.continueOnFailure)break}else{p++;k.push(`${x} \u2713 ${C.join(", ")||bn(w)}`)}}const b=((Date.now()-n)/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(s!=="none"){try{const v=await a();const w=v.filter(x=>x.interactive).slice(0,30);g.push(`**Screen now (${w.length} interactive of ${v.length}):**
|
|
208
|
+
${w.map(Ha).join("\n")}`)}catch(v){g.push(`**Screen now:** unavailable \u2014 ${yn(Mt(v))}`)}}if(s==="all"){if(u.has("network")){const{payload:v}=await r.getSnapshot("network",o).catch(()=>({payload:null}));const w=Array.isArray(v)?v:v?.events??[];const x=w.filter(T=>!l.has(T.id)).slice(-15);if(x.length){g.push(`**Network during this flow (${x.length}):**
|
|
209
|
+
`+x.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 r.getSnapshot("console",o).catch(()=>({payload:null}));const w=v?.entries??[];const x=w.filter(T=>!d.has(T.id)&&(T.level==="error"||T.level==="warning")).slice(-10);if(x.length){g.push(`**Console during this flow (${x.length}):**
|
|
210
|
+
`+x.map(T=>`[${T.level==="error"?"ERR":"warn"}] ${yn(Xa(T.message??""),220)}`).join("\n"))}}}return Ja(g.join("\n\n"))}catch(o){return Wa(Mt(o))}})}function wn(e){return/\s/.test(e)?{query:e}:{testID:e,query:e}}function bn(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 yn=(e,r=160)=>e.length>r?`${e.slice(0,r)}\u2026`:e;var Xa=(e,r=3)=>e.split("\n").map(t=>t.trim()).filter(Boolean).slice(0,r).join(" \u23CE ");import{z as V}from"zod";var Ee="highlight-updates";var Za=e=>({content:[{type:"text",text:e}]});var Fe=e=>({isError:true,content:[{type:"text",text:e}]});var ei=e=>e instanceof Error?e.message:String(e);var nt=e=>new Promise(r=>setTimeout(r,e));var $n=3e3;var kn=400;var _n=12;var Sn=new Map;var ti=V.object({tap:V.string().optional().describe("Tap this element: exact testID, or fuzzy visible text."),type:V.string().optional().describe("Text to type (needs `into`)."),into:V.string().optional().describe("Target text input for `type`: testID or fuzzy text."),waitMs:V.number().min(0).max(1e4).optional().describe("Pause after the action, in ms."),repeat:V.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 An(e){return/\s/.test(e)?{query:e}:{testID:e,query:e}}function xn(e){if(!e)return"unknown";let r="unknown";let t=-1;for(const[n,o]of Object.entries(e)){if((o??0)>t){t=o??0;r=n}}return r}var Tn={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 ri(e,r){const t=e.summary;const n=t.wastedRenders??0;const o=t.totalRenders>0?Math.round(n/t.totalRenders*100):0;const s=[];const a=t.totalRenderMs??0;s.push(`**${t.totalRenders} component renders across ${t.totalCommits} commits in ${(e.windowMs/1e3).toFixed(1)}s**`+(a>0?` \xB7 ${a.toFixed(1)}ms of render work`:"")+` \xB7 ${n} wasted (${o}%)`);const i=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(i)s.push(`causes: ${i}`);s.push("");s.push("| component | self ms | renders | cause | dragged along by | changed props |");s.push("|---|---:|---:|---|---|---|");const c=[...t.topComponents].sort((u,f)=>(f.totalMs??0)-(u.totalMs??0)||f.renders-u.renders).slice(0,r);for(const u of c){s.push(`| ${u.name} | ${(u.totalMs??0).toFixed(1)} | ${u.renders} | ${xn(u.causes)} | ${u.parentName??"\u2014"} | ${(u.changedProps??[]).join(", ")||"\u2014"} |`)}if(t.topComponents.length>r){s.push(`_\u2026+${t.topComponents.length-r} more components_`)}const d=new Set(c.map(u=>xn(u.causes)));const l=[...d].filter(u=>Tn[u]).map(u=>`\`${u}\` = ${Tn[u]}`);if(l.length){s.push("");s.push(l.join(" \xB7 "))}s.push("");s.push("`wasted` classifies parent cascades and identity-only prop changes. Investigate whether these renders are needed before changing them. Rows are sorted by **self ms**. Compare timing and render counts for the measured workload, and check behavior before deciding whether memoization helps.");return s.join("\n")}function ni(e,r){const t=(l,u)=>{const f=u-l;return`${l} \u2192 ${u} (${f>0?"+":""}${f})`};const n=e.summary;const o=r.summary;const s=[`**vs "${e.label}"**`];s.push(`- total renders: ${t(n.totalRenders,o.totalRenders)}`);s.push(`- wasted: ${t(n.wastedRenders??0,o.wastedRenders??0)}`);const a=new Map(n.topComponents.map(l=>[l.name,l.renders]));const i=[];for(const l of o.topComponents.slice(0,20)){const u=a.get(l.name)??0;if(u!==l.renders)i.push(`${l.name} ${t(u,l.renders)}`);a.delete(l.name)}for(const[l,u]of a){if(u>0)i.push(`${l} ${t(u,0)}`)}if(i.length)s.push(`- per component: ${i.slice(0,10).join(" \xB7 ")}`);const c=o.totalRenders<n.totalRenders;const d=o.totalRenders>n.totalRenders;s.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 s.join("\n")}function oi(e,r){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:V.array(ti).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:V.number().min(500).max(2e4).optional().describe(`Idle sample length when no steps are given. Default ${$n}.`),label:V.string().optional().describe('Name this measurement, e.g. "before fix". Shown in the next comparison.'),compareToPrevious:V.boolean().optional().describe("Compare with the previous measurement on this device. Use equivalent steps and conditions; review warnings and behavior separately."),top:V.number().min(1).max(40).optional().describe(`Components to list. Default ${_n}.`),deviceId:S}},async t=>{try{const n=r.requireProDevice(t.deviceId);const o=r.connectedDevices().find(b=>b.deviceId===n);const s=(o?.tools??[]).find(b=>b.toolId===Ee);if(!s){return Fe("This app doesn't expose the highlight-updates tool, so renders can't be measured. Install @buoy-gg/highlight-updates.")}if(!(s.actions??[]).includes("beginMeasurement")){return Fe("This app's @buoy-gg/highlight-updates is too old to measure renders (needs the version with beginMeasurement). Upgrade it, then try again. Meanwhile run_benchmark_batch with captureRenders can still give counts if you have a test route.")}const a=await r.callAction(Ee,"beginMeasurement",{},n);if(a&&a.ok===false){return Fe(`Can't measure renders: ${a.reason??"capture unavailable"}`)}await nt(kn);const i=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 r.callAction(Ee,"tapElement",{...An(v),text:b.type},n);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 r.callAction(Ee,"tapElement",An(b.tap),n);if(!v?.tapped)c.push(v?.reason??`no element matched "${b.tap}"`)}if(b.waitMs)await nt(b.waitMs)}}await nt(kn)}else{await nt(t.idleMs??$n)}const d=Date.now()-i;const l=await r.callAction(Ee,"endMeasurement",{},n);const u=l?.summary;if(!u){return Fe("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=Sn.get(n);Sn.set(n,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}**`,"",ri(f,t.top??_n)];if(t.compareToPrevious){p.push("",k?ni(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 Za(p.join("\n"))}catch(n){return Fe(ei(n))}})}import si from"fs";import In from"path";var ai=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".json"]);var ii=new Set(["node_modules",".git",".expo","ios","android","dist","lib","build",".next","coverage","__snapshots__"]);var ci=400;function li(e){const r=(e??"").trim().toLowerCase();if(r==="always"||r==="never"||r==="auto")return r;return"auto"}var ui=class{constructor(){this.watcher=null;this.changed=new Set;this.lastEditAt=0;this.nudgedForCurrentBatch=false;this.mode="auto";this.started=false}start(e,r){this.mode=r;if(r==="never"||this.started)return;this.started=true;try{this.watcher=si.watch(e,{recursive:true},(t,n)=>{if(!n)return;const o=String(n);if(o.split(In.sep).some(s=>ii.has(s)))return;if(!ai.has(In.extname(o)))return;this.noteEdit(o)});this.watcher.on("error",()=>this.stop())}catch{this.stop()}}noteEdit(e){const r=Date.now();if(r-this.lastEditAt>ci)this.nudgedForCurrentBatch=false;this.lastEditAt=r;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 r=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** (${r}${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 Et=new ui;var di=`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 hi=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 pi(e){const r=new hs({name:"buoy",version:le},{capabilities:{tools:{}},instructions:di});Et.start(process.cwd(),li(process.env.BUOY_VERIFY));const t=r.registerTool.bind(r);r.registerTool=((n,o,s)=>t(n,o,(async(...a)=>{const i=await s(...a);const c=i?.isError===true;if(hi.has(n)&&!c){Et.markVerified();return i}const d=Et.nudge();if(!d)return i;const l=i;if(Array.isArray(l?.content)){return{...l,content:[...l.content,{type:"text",text:d}]}}return i})));za(r,e);Qa(r,e);oi(r,e);tr(r,e);lr(r,e);ur(r,e);ys(r,e);dr(r,e);hr(r,e);pr(r,e);gr(r,e);vr(r,e);yr(r,e);kr(r,e);_s(r,e);Ss(r,e);xs(r,e);Es(r,e);Ns(r,e);Ws(r,e);Ks(r,e);Tr(r,e);aa(r);la(r,e);ma(r,e);wa(r,e);ka(r,e);Ma(r,e);return r}var Ec={deviceId:ps.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 Ft}from"child_process";import j from"fs";import mi from"os";import B from"path";function qt(){return{BUOY_VERIFY:"auto"}}var Dn="https://registry.npmjs.org";var jt=3e3;function fi(e={}){const r=e.cwd??process.cwd();const t=e.skillSrcDir??B.resolve(__dirname,"../skill");const n=e.log??(a=>process.stdout.write(a+"\n"));const o=gi(e,n);const s=[];Pt(B.join(r,".mcp.json"),"mcpServers",o,r,s);j.mkdirSync(B.join(r,".cursor"),{recursive:true});Pt(B.join(r,".cursor","mcp.json"),"mcpServers",o,r,s);if(j.existsSync(B.join(r,".vscode"))){Pt(B.join(r,".vscode","mcp.json"),"servers",o,r,s)}_i(t,r,s);Mn(B.join(r,"CLAUDE.md"),r,s);Mn(B.join(r,"AGENTS.md"),r,s);n("Buoy MCP configuration written:");for(const a of s)n(" \u2022 "+a);n("");n("Next steps:");n(" 1. Restart your editor (or reconnect the MCP server) to load `buoy`.");n(" 2. Complete account setup, then open an app with the required Buoy tools and sync integration.");n(" 3. Confirm the device and tools are available. MCP data/action access requires Pro.");if(o.command==="npx"){n("");n(`The editor launches the server with \`npx -y ${oe}@latest\`, so it stays`);n(`Registry access may be needed. Re-run \`npx -y ${oe}@latest init\` to refresh configuration.`)}else if(!e.cliPath){n("");n(`This uses a pinned local install (no network on startup). To update it later,`);n(`To update the local package, run: npx -y ${o.args[0]?.replace(/dist[/\\]cli\.js$/,"")??""}@latest init --local`)}}function gi(e,r){if(e.cliPath){return{type:"stdio",command:"node",args:[e.cliPath],env:qt()}}const t=e.mode??"auto";if(t==="npx"){return Bt()}if(t==="local"){return Rn(e,r)}const n=wi();if(n.reachable){return Bt()}r(`\u26A0 npm registry ${n.registry?`(${n.registry}) `:""}looks unreachable \u2014 \`npx @latest\` would hang your editor at startup. Falling back to a pinned local install.`);return Rn(e,r)}function Bt(){return{type:"stdio",command:"npx",args:["-y",`${oe}@latest`],env:qt()}}function Rn(e,r){const t=e.installDir??process.env.BUOY_MCP_HOME??B.join(mi.homedir(),".buoy-mcp");const n=e.registry??Dn;const o=vi(t,n,r);if(o){return{type:"stdio",command:"node",args:[o],env:qt()}}r("\u26A0 local install failed \u2014 writing the npx entry instead (see the error above).");return Bt()}function vi(e,r,t){const n=`${oe}@${le==="0.0.0-dev"?"latest":le}`;j.mkdirSync(e,{recursive:true});const o=process.platform==="win32"?"npm.cmd":"npm";t(`Installing ${n} into ${e} from ${r} \u2026`);const s=Ft(o,["install",n,"--prefix",e,"--registry",r,`--@buoy-gg:registry=${r}`,"--no-audit","--no-fund","--loglevel=error"],{stdio:["ignore","ignore","inherit"],encoding:"utf8"});if(s.status!==0){t(`\u26A0 npm install exited with code ${s.status??"?"}${s.error?` (${s.error.message})`:""}.`);return null}const a=B.join(e,"node_modules",oe,"dist","cli.js");if(!j.existsSync(a)){t(`\u26A0 install finished but ${a} is missing.`);return null}return a}function wi(){const e=bi();if(!e)return{reachable:false,registry:null};if(/^https?:\/\/registry\.npmjs\.org\/?$/i.test(e)){return{reachable:true,registry:e}}return{reachable:yi(e),registry:e}}function bi(){const e=On("@buoy-gg:registry");if(e)return e;const r=On("registry");return r??Dn}function On(e){const r=process.platform==="win32"?"npm.cmd":"npm";const t=Ft(r,["config","get",e],{encoding:"utf8",timeout:jt});if(t.status!==0||typeof t.stdout!=="string")return null;const n=t.stdout.trim();if(!n||n==="undefined"||n==="null")return null;return n}function yi(e){const r=Ft(process.execPath,["-e",$i,e,String(jt)],{encoding:"utf8",timeout:jt+2e3});return r.status===0}var $i=`
|
|
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 Pt(e,r,t,n,o){let s={};if(j.existsSync(e)){try{s=JSON.parse(j.readFileSync(e,"utf8"))}catch{j.copyFileSync(e,e+".bak");o.push(`existing ${ce(e,n)} was invalid JSON \u2014 backed up to ${ce(e,n)}.bak`);s={}}}else{j.mkdirSync(B.dirname(e),{recursive:true})}const a=s[r]&&typeof s[r]==="object"?s[r]:{};const i="buoy"in a;a.buoy=t;s[r]=a;j.writeFileSync(e,JSON.stringify(s,null,2)+"\n");o.push(`${i?"updated":"added"} \`buoy\` in ${ce(e,n)}`)}var ot="# Debugging with Buoy";var ki=`${ot}
|
|
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 Mn(e,r,t){let n="";if(j.existsSync(e)){try{n=j.readFileSync(e,"utf8")}catch{t.push(`\u26A0 could not read ${ce(e,r)} \u2014 skipped the debugging guide`);return}if(n.includes(ot)){t.push(`${ce(e,r)} already has the "${ot}" block; preserved existing text. Review it against the current bundled guidance before relying on older instructions.`);return}}const o=n===""?"":n.endsWith("\n")?"\n":"\n\n";try{j.writeFileSync(e,n+o+ki);t.push(`${n?"appended":"created"} "${ot}" block in ${ce(e,r)}`)}catch{t.push(`\u26A0 could not write ${ce(e,r)} \u2014 skipped the debugging guide`)}}function _i(e,r,t){if(!j.existsSync(e)){t.push("\u26A0 no bundled skills found \u2014 skipped");return}const n=j.readdirSync(e,{withFileTypes:true}).filter(o=>o.isDirectory()&&j.existsSync(B.join(e,o.name,"SKILL.md")));if(n.length===0){t.push("\u26A0 no skills with a SKILL.md found \u2014 skipped");return}for(const o of n){const s=B.join(e,o.name);const a=B.join(r,".claude","skills",o.name);Cn(s,a);t.push(`installed the ${o.name} skill \u2192 ${ce(B.join(a,"SKILL.md"),r)}`)}}function Cn(e,r){j.mkdirSync(r,{recursive:true});for(const t of j.readdirSync(e,{withFileTypes:true})){const n=B.join(e,t.name);const o=B.join(r,t.name);if(t.isDirectory())Cn(n,o);else j.copyFileSync(n,o)}}function ce(e,r){const t=B.relative(r,e);return t&&!t.startsWith("..")?t:e}export{at as BROKER_PORT,Nt as BROKER_URL,Lt as DEFAULT_ACTION_TIMEOUT_MS,zt as DEFAULT_SNAPSHOT_TIMEOUT_MS,it as DASHBOARD_NAME,G as ALL_DEVICES,vo as SyncClient,le as VERSION,oe as PACKAGE_NAME,er as getUpdateNotice,tr as registerGenericTools,je as buildAutomationConfig,ut as estimateBatchMs,Be as rankBatchFromIndex,Pe as formatRankingMarkdown,or as compareReportStats,lr as registerPerfMonitorTools,ur as registerEventsTools,dr as registerReactQueryTools,hr as registerZustandTools,pr as registerJotaiTools,gr as registerReduxTools,vr as registerStorageTools,yr as registerRoutesTools,kr as registerConsoleTools,Tr as registerScreenshotTools,pi as createMcpServer,fi as runInit};
|