@buoy-gg/mcp 7.0.60 → 7.0.61

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/cli.js CHANGED
@@ -38,7 +38,7 @@ v.ontimeupdate=()=>{const ms=v.currentTime*1000;let cur=null;for(const li of lis
38
38
  draw();
39
39
  <\/script></body></html>
40
40
  `}function escapeHtml(e){return e.replace(/[&<>"']/g,n=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[n])}var import_node_child_process3,import_node_fs2,import_node_path2,MAX_RECORDING_MS,live;var init_recorder=__esm({"src/capture/recorder.ts"(){"use strict";import_node_child_process3=require("child_process");import_node_fs2=require("fs");import_node_path2=__toESM(require("path"));init_adb();init_iosDevice();MAX_RECORDING_MS=3*6e4;live=new Set}});function readProjectKey(e,n=process.env){for(const t of KEY_NAMES)if(n[t]!==void 0)return(0,import_headless.normalizeLicenseKey)(n[t])||null;for(const t of[".env.development.local",".env.local",".env"]){let r;try{r=(0,import_node_fs3.readFileSync)((0,import_node_path3.join)(e,t),"utf8")}catch{continue}const i=new Map;for(const s of r.split(/\r?\n/)){const o=s.match(/^\s*(?:export\s+)?([A-Z_][A-Z_0-9]*)\s*=\s*(.*)$/);if(!o)continue;const a=o[2].trim();const c=a.match(/^(['"])(.*?)\1\s*(?:#.*)?$/);i.set(o[1],c?c[2]:a.split("#")[0].trim())}for(const s of KEY_NAMES)if(i.has(s))return(0,import_headless.normalizeLicenseKey)(i.get(s))||null}return null}var import_node_fs3,import_node_path3,import_node_os2,import_node_crypto2,import_headless,KEY_NAMES,NodeAccount;var init_NodeAccount=__esm({"src/sync/NodeAccount.ts"(){"use strict";import_node_fs3=require("fs");import_node_path3=require("path");import_node_os2=require("os");import_node_crypto2=require("crypto");import_headless=require("@buoy-gg/license/headless");KEY_NAMES=["BUOY_LICENSE_KEY","BUOY_KEY","EXPO_PUBLIC_BUOY_KEY","VITE_BUOY_KEY","NEXT_PUBLIC_BUOY_KEY","REACT_APP_BUOY_KEY"];NodeAccount=class{constructor(e,n={}){this.changed=e;this.key=null;this.cache=null;this.timer=null;this.unsubscribeSession=null;this.generation=0;this.busy=false;this.nextCheck=0;this.retry=0;this.lastAdmission=false;this.hasAccess=()=>this.hasKeyAccess()||this.session?.getStatus().state==="active";this.lastSessionSync=0;this.projectDir=(0,import_node_path3.resolve)(n.projectDir??process.env.BUOY_PROJECT_DIR??process.cwd());const t=(0,import_node_crypto2.createHash)("sha256").update(this.projectDir).digest("hex").slice(0,20);this.cacheFile=n.cacheFile??(0,import_node_path3.join)((0,import_node_os2.homedir)(),".buoy",`account-${t}.json`);this.session=n.session!==void 0?n.session:(0,import_headless.createNodeSession)({audience:import_headless.CLI_AUDIENCE,openBrowser:()=>{throw new Error("The MCP does not open a browser. Run `npx buoy login`.")}})}hasKeyAccess(){return(0,import_headless.resolveAccountAccess)({initialized:true,validating:false,key:this.key,tierSource:this.cache?.tier?"key":"none",verifiedAt:this.cache?.cachedAt??null}).status==="admitted"}start(){if(this.timer)return;if(this.session){this.unsubscribeSession=this.session.subscribe(()=>this.notify());void this.session.load().then(()=>this.notify(),()=>{})}try{const e=JSON.parse((0,import_node_fs3.readFileSync)(this.cacheFile,"utf8"));if(e.valid&&(0,import_headless.verifyCacheSignature)(e))this.cache=e}catch{}void this.tick();this.timer=setInterval(()=>{void this.tick()},1e3);this.timer.unref()}stop(){++this.generation;this.unsubscribeSession?.();this.unsubscribeSession=null;if(this.timer)clearInterval(this.timer);this.timer=null;this.key=null;this.cache=null;this.notify()}notify(){const e=this.hasAccess();if(e===this.lastAdmission)return;this.lastAdmission=e;this.changed()}async tick(){if(this.session&&Date.now()-this.lastSessionSync>15e3){this.lastSessionSync=Date.now();void this.session.sync().catch(()=>{})}const e=readProjectKey(this.projectDir);if(e!==this.key){++this.generation;this.key=e;if(this.cache?.licenseKey!==e)this.cache=null;this.nextCheck=0;this.retry=0;if(!e)this.removeCache()}this.notify();if(!e||this.busy||Date.now()<this.nextCheck)return;if(this.cache&&this.hasKeyAccess()&&Date.now()-this.cache.lastValidatedAt<import_headless.LICENSE_LAUNCH_VALIDATION_TTL&&this.nextCheck===0){this.nextCheck=this.cache.lastValidatedAt+import_headless.LICENSE_LAUNCH_VALIDATION_TTL;return}this.busy=true;const n=this.generation;try{if((0,import_headless.isDevToken)(e)){const a=(0,import_headless.checkDevToken)(e);if(!a.ok){this.cache=null;this.removeCache()}else{const c=Math.min(Date.now(),a.claims.iat*1e3);const u=a.claims.tier==="free"?"free":"pro";this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`dev:${a.claims.sid}`,valid:true,tier:u,isPro:u==="pro",expiresAt:new Date(a.claims.exp*1e3).toISOString(),cachedAt:c,lastValidatedAt:Date.now()});this.persistCache()}this.nextCheck=Date.now()+import_headless.LICENSE_REVALIDATION_INTERVAL;return}if((0,import_headless.isServiceKey)(e)){const a=await(0,import_headless.exchangeServiceKey)(e,{origin:process.env.BUOY_SITE_URL||"https://buoy.gg"});if(n!==this.generation||readProjectKey(this.projectDir)!==e)return;if(!a.ok){if(a.reason==="rejected"){this.cache=null;this.removeCache();this.nextCheck=Date.now()+import_headless.LICENSE_REVALIDATION_INTERVAL}else{this.nextCheck=Date.now()+(import_headless.LICENSE_TRANSIENT_RETRY_DELAYS[this.retry++]??import_headless.LICENSE_REVALIDATION_INTERVAL)}return}const c=Date.now();const u=a.claims.exp*1e3;this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`service:${a.claims.sid}`,valid:true,tier:"pro",isPro:true,expiresAt:new Date(u).toISOString(),cachedAt:c,lastValidatedAt:c});this.persistCache();this.retry=0;this.nextCheck=Math.max(c+6e4,u-60*60*1e3);return}if((0,import_headless.isBuoyToken)(e)){const a=(0,import_headless.verifyFreeToken)(e);if(!a){this.cache=null;this.removeCache()}else{const c=Date.now();this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`token:${a.accountHash}`,valid:true,tier:"free",isPro:false,expiresAt:null,cachedAt:c,lastValidatedAt:c});this.persistCache()}this.nextCheck=Date.now()+import_headless.LICENSE_REVALIDATION_INTERVAL;return}const t=await(0,import_headless.validateLicense)(e);if(n!==this.generation||readProjectKey(this.projectDir)!==e)return;const r=t.data?.relationships?.product?.data?.id;const i=t.meta.code==="EXPIRED"&&((0,import_headless.isRecognizedAccount)(t.data)||this.cache?.licenseKey===e);if(r&&r!==import_headless.KEYGEN_CONFIG.productId||!i&&!(0,import_headless.isAcceptedValidation)(t)){this.cache=null;this.removeCache();this.nextCheck=Date.now()+import_headless.LICENSE_REVALIDATION_INTERVAL;return}const s=i?"free":(0,import_headless.resolveTier)(t.data);const o=Date.now();this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:t.data?.id??"",valid:true,tier:s,isPro:s==="pro",expiresAt:i?null:t.data.attributes.expiry,cachedAt:o,lastValidatedAt:o});this.persistCache();this.retry=0;this.nextCheck=o+import_headless.LICENSE_REVALIDATION_INTERVAL}catch(t){if(n!==this.generation)return;const r=(0,import_headless.isTransientLicenseError)(t)?import_headless.LICENSE_TRANSIENT_RETRY_DELAYS[this.retry++]:void 0;this.nextCheck=Date.now()+(r??import_headless.LICENSE_REVALIDATION_INTERVAL)}finally{this.busy=false;this.notify()}}persistCache(){try{(0,import_node_fs3.mkdirSync)((0,import_node_path3.dirname)(this.cacheFile),{recursive:true,mode:448});(0,import_node_fs3.writeFileSync)(`${this.cacheFile}.tmp`,JSON.stringify(this.cache),{mode:384});(0,import_node_fs3.renameSync)(`${this.cacheFile}.tmp`,this.cacheFile)}catch{}}removeCache(){try{(0,import_node_fs3.unlinkSync)(this.cacheFile)}catch{}}}}});var import_sync_broker,BROKER_PORT,BROKER_URL,DEFAULT_ACTION_TIMEOUT_MS,UNRESPONSIVE_ACTION_TIMEOUT_MS,UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS,RECOVERY_PROBE_MS,UNRESPONSIVE_AFTER_MS,DEFAULT_SNAPSHOT_TIMEOUT_MS,DEVICE_RETENTION_MS,DASHBOARD_NAME,ALL_DEVICES;var init_config=__esm({"src/config.ts"(){"use strict";import_sync_broker=require("@buoy-gg/sync-broker");BROKER_PORT=import_sync_broker.DEFAULT_BROKER_PORT;BROKER_URL=`http://localhost:${BROKER_PORT}`;DEFAULT_ACTION_TIMEOUT_MS=15e3;UNRESPONSIVE_ACTION_TIMEOUT_MS=2500;UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS=1200;RECOVERY_PROBE_MS=2e4;UNRESPONSIVE_AFTER_MS=3e4;DEFAULT_SNAPSHOT_TIMEOUT_MS=5e3;DEVICE_RETENTION_MS=15*6e4;DASHBOARD_NAME="Dashboard";ALL_DEVICES="All"}});async function devServerRoot(e){let n;try{n=new URL(e)}catch{return null}if(!isLocalHost(n.hostname))return null;const t=n.port||(n.protocol==="https:"?"443":"80");try{const{stdout:r}=await execFileAsync3("lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"],{timeout:3e3});const i=r.split("\n").map(a=>a.trim()).find(Boolean);if(!i)return null;const{stdout:s}=await execFileAsync3("lsof",["-a","-p",i,"-d","cwd","-Fn"],{timeout:3e3});const o=s.split("\n").find(a=>a.startsWith("n"));return o?import_node_path4.default.resolve(o.slice(1)):null}catch{return null}}function isLocalHost(e,n=import_node_os3.default.networkInterfaces()){const t=e.replace(/^\[|\]$/g,"").toLowerCase();if(t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="10.0.2.2"||t==="10.0.3.2")return true;return Object.values(n).flat().some(r=>r?.address?.toLowerCase()===t)}function pickByProject(e,n){const t=import_node_path4.default.resolve(n);const r=e.map(o=>({deviceId:o.deviceId,score:o.root?closeness(import_node_path4.default.resolve(o.root),t):-1})).filter(o=>o.score>=0);if(r.length===0)return null;const i=Math.min(...r.map(o=>o.score));const s=r.filter(o=>o.score===i);return s.length===1?s[0].deviceId:null}function closeness(e,n){if(e===n)return 0;const t=import_node_path4.default.relative(e,n);const r=import_node_path4.default.relative(n,e);const i=s=>s&&!s.startsWith("..")&&!import_node_path4.default.isAbsolute(s);if(i(t))return t.split(import_node_path4.default.sep).length;if(i(r))return r.split(import_node_path4.default.sep).length;return-1}var import_node_child_process4,import_node_util3,import_node_path4,import_node_os3,execFileAsync3;var init_projectRoot=__esm({"src/sync/projectRoot.ts"(){"use strict";import_node_child_process4=require("child_process");import_node_util3=require("util");import_node_path4=__toESM(require("path"));import_node_os3=__toESM(require("os"));execFileAsync3=(0,import_node_util3.promisify)(import_node_child_process4.execFile)}});function isRecoveryAction(e,n){return e==="app"&&(n==="ping"||n==="reloadApp")}function isUnresponsive(e){return e>=2}function actionTimeoutMs(e){if(isRecoveryAction(e.toolId,e.action)){return{timeoutMs:e.fullMs,usedFullBudget:false}}if(!isUnresponsive(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 diagnoseCrashed(e){if(e.consecutiveTimeouts>=2)return true;if(e.lastOkAt>0&&e.now-e.lastOkAt>e.unresponsiveAfterMs){return true}return false}var init_actionTimeout=__esm({"src/sync/actionTimeout.ts"(){"use strict"}});function probeBroker(e,n=800){return new Promise(t=>{const r=import_node_http.default.get(e,i=>{i.resume();t((i.statusCode??0)>0)});r.setTimeout(n,()=>{r.destroy();t(false)});r.on("error",()=>t(false))})}async function waitForBroker(e,n=20){for(let t=0;t<n;t++){if(await probeBroker(e,300))return;await delay(50)}throw new Error(`Spawned broker never became reachable at ${e}`)}var import_node_http,import_node_crypto3,import_socket,import_sync_broker2,NOT_READY_MARK,SyncClient,snapKey,delay;var init_SyncClient=__esm({"src/sync/SyncClient.ts"(){"use strict";init_NodeAccount();import_node_http=__toESM(require("http"));import_node_crypto3=require("crypto");import_socket=require("socket.io-client");import_sync_broker2=require("@buoy-gg/sync-broker");init_config();init_projectRoot();init_actionTimeout();NOT_READY_MARK="Not ready:";SyncClient=class{constructor(e={}){this.socket=null;this.admitted=false;this.createdAt=Date.now();this.lockedDevices=new Set;this.hostAccount=null;this.broker=null;this.capabilities=new Map;this.devices=[];this.sessionDevice=null;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.crashSeen=new Map;this.rootLookups=new Set;this.devServerRoots=new Map;this.originProbed=new Set;this.lastSeen=new Map;this.deviceConnections=new Map;this.port=e.port??BROKER_PORT;this.url=e.url??(e.port?`http://localhost:${e.port}`:BROKER_URL);this.actionTimeoutMs=e.actionTimeoutMs??DEFAULT_ACTION_TIMEOUT_MS;this.log=e.log??(n=>process.stderr.write(`[buoy-mcp] ${n}
41
- `));this.autoSpawn=e.autoSpawnBroker??true}async start(){const e=await probeBroker(this.url)||await probeBroker(this.url,8e3);let n="connected";if(!e){if(!this.autoSpawn){throw new Error(`No Buoy broker reachable at ${this.url} and autoSpawnBroker is off. Start the Buoy desktop app, or enable autoSpawnBroker.`)}this.log(`no broker at ${this.url} \u2014 spawning one in-process on :${this.port}`);this.hostAccount=new NodeAccount(()=>this.broker?.refreshAccess());this.hostAccount.start();let t=false;this.broker=(0,import_sync_broker2.createBroker)({canUseDesktop:this.hostAccount.hasAccess,port:this.port,onError:r=>{if(r.code==="EADDRINUSE")t=true;this.log(`broker error: ${r.code??r.message}`)}});await waitForBroker(this.url).catch(r=>{if(!t)throw r});if(!this.broker.httpServer.listening)t=true;if(t){this.log(`another broker holds :${this.port} \u2014 connecting to it as a dashboard`);await this.broker.close().catch(()=>void 0);this.broker=null;this.hostAccount.stop();this.hostAccount=null;await this.connectSocket();return"connected"}try{(0,import_sync_broker2.writeBrokerToken)(this.broker.dashboardToken,(0,import_sync_broker2.brokerTokenPath)(this.port))}catch(r){this.log(`could not write the broker token file: ${r.message}`)}n="spawned"}else{this.log(`found a running broker at ${this.url} \u2014 connecting as a dashboard`)}await this.connectSocket();return n}connectSocket(){return new Promise((e,n)=>{const t=(0,import_socket.io)(this.url,{transports:["websocket"],query:{deviceName:DASHBOARD_NAME},auth:a=>{const c=this.broker?.dashboardToken??(0,import_sync_broker2.readBrokerToken)((0,import_sync_broker2.brokerTokenPath)(this.port));a(c?{dashboardToken:c}:{})},reconnection:true,reconnectionDelay:500,timeout:4e3});this.socket=t;let r=false;const i=()=>{if(r)return;r=true;this.log("connected to broker");e()};const s=setTimeout(()=>{if(r)return;r=true;n(new Error("Broker account is locked or the broker needs an update. Sign in to Buoy Desktop or run npx buoy login for standalone MCP."))},5e3);t.on("buoy:access",a=>{const c=!!a&&typeof a==="object"&&a.protocol===1&&a.ready===true;this.setAdmission(c);if(c){clearTimeout(s);this.rearmWatches();i()}});t.on("connect",()=>{t.emit("buoy:access:request")});t.on("disconnect",()=>this.setAdmission(false,true));const o=a=>a.message===import_sync_broker2.DASHBOARD_TOKEN_REQUIRED;t.once("connect_error",a=>{if(r)return;r=true;clearTimeout(s);n(new Error(o(a)?`The broker at ${this.url} refused this MCP as a dashboard: the token in ${(0,import_sync_broker2.brokerTokenPath)(this.port)} is missing or stale. Update Buoy Desktop, or restart it so it writes the file.`:`failed to connect to broker at ${this.url}: ${a.message}`))});t.on("connect_error",a=>{if(!o(a)||t.active)return;setTimeout(()=>{if(this.socket===t&&!t.connected)t.connect()},1e3).unref?.()});t.on("devtool-capabilities",a=>{if(!this.admitted||this.lockedDevices.has(a.persistentDeviceId))return;this.capabilities.set(a.persistentDeviceId,a);this.trackRootLookup(this.learnDevServerOrigin(a.persistentDeviceId));if(a.tools?.some(c=>c.toolId==="console"))this.ensureWatching("console",a.persistentDeviceId)});t.on("all-devices-update",a=>{if(!this.admitted)return;if(!Array.isArray(a))return;let c=false;for(const l of a){if(l.deviceId&&l.tier==="locked")this.lockDevice(String(l.deviceId));else if(l.deviceId&&(l.tier==="free"||l.tier==="pro")){c=this.lockedDevices.delete(String(l.deviceId))||c}}this.devices=a;const u=Date.now();for(const l of a)if(l.deviceId)this.lastSeen.set(l.deviceId,u);this.pruneStaleDevices();if(c)this.rearmWatches();else this.rearmReconnectedDevices(a)});t.on("devtool-sync",a=>{if(!this.admitted||this.lockedDevices.has(a.persistentDeviceId))return;const c=snapKey(a.persistentDeviceId,a.toolId);this.snapshots.set(c,a.payload);this.snapshotAt.set(c,Date.now());if(a.toolId==="console")this.noteCrashReport(a.persistentDeviceId,a.payload);const u=this.snapshotWaiters.get(c);if(u&&u.length){this.snapshotWaiters.set(c,[]);for(const l of u)l(a.payload)}});t.on("devtool-action-result",a=>{if(!this.admitted)return;const c=this.pendingActions.get(a.requestId);if(!c)return;this.pendingActions.delete(a.requestId);clearTimeout(c.timer);c.resolve(a)})})}requireAdmission(){if(!this.admitted)throw new Error("A verified Buoy account and an updated broker are required. Sign in to Buoy Desktop, or run npx buoy login for standalone MCP.")}setAdmission(e,n=false){this.admitted=e;if(e)return;this.devices=[];this.lockedDevices.clear();this.capabilities.clear();this.snapshots.clear();this.snapshotAt.clear();this.devServerOrigins.clear();this.devServerRoots.clear();this.crashSeen.clear();this.originProbed.clear();this.health.clear();this.lastSeen.clear();if(!n)this.watching.clear();for(const t of this.pendingActions.values()){clearTimeout(t.timer);t.reject(new Error("Buoy account access ended while the action was pending."))}this.pendingActions.clear();for(const t of this.snapshotWaiters.values())for(const r of t)r(void 0);this.snapshotWaiters.clear();if(this.socket)this.socket.sendBuffer=[]}requireDeviceAccount(e){if(this.lockedDevices.has(e))throw new Error("The device's Buoy account access ended. Sign in and verify its key.")}lockDevice(e){this.lockedDevices.add(e);this.capabilities.delete(e);this.health.delete(e);this.devServerOrigins.delete(e);this.devServerRoots.delete(e);this.originProbed.delete(e);const n=`${e}::`;for(const t of this.snapshots.keys())if(t.startsWith(n)){this.snapshots.delete(t);this.snapshotAt.delete(t)}for(const[t,r]of this.snapshotWaiters)if(t.startsWith(n)){this.snapshotWaiters.delete(t);for(const i of r)i(void 0)}for(const[t,r]of this.pendingActions)if(r.target===e||r.target===ALL_DEVICES){clearTimeout(r.timer);this.pendingActions.delete(t);r.reject(new Error("Device account access ended while the action was pending."))}}pruneStaleDevices(){const e=Date.now()-DEVICE_RETENTION_MS;for(const[n,t]of this.lastSeen){if(t>e)continue;if(this.devices.some(i=>i.deviceId===n))continue;this.lastSeen.delete(n);this.capabilities.delete(n);this.health.delete(n);this.devServerOrigins.delete(n);this.devServerRoots.delete(n);this.originProbed.delete(n);const r=`${n}::`;for(const i of[...this.snapshots.keys()]){if(i.startsWith(r)){this.snapshots.delete(i);this.snapshotAt.delete(i)}}for(const i of[...this.watching.keys()]){if(i.startsWith(r))this.watching.delete(i)}}}async stop(){this.setAdmission(false);this.hostAccount?.stop();this.hostAccount=null;for(const[,e]of this.pendingActions){clearTimeout(e.timer);e.reject(new Error("SyncClient stopped"))}this.pendingActions.clear();for(const[,e]of this.snapshotWaiters)for(const n of e)n(void 0);this.snapshotWaiters.clear();this.socket?.close();this.socket=null;if(this.broker){await this.broker.close();this.broker=null}}listDevices(){if(!this.admitted)return[];return this.devices.filter(e=>e.deviceName!==DASHBOARD_NAME&&e.deviceId).map(e=>{const n=this.capabilities.get(e.deviceId);return{deviceId:e.deviceId,deviceName:e.deviceName,platform:e.platform,isConnected:e.isConnected!==false,isPro:e.isPro===true,tier:e.tier==="free"||e.tier==="pro"?e.tier:e.tier===void 0&&e.isPro===true?"pro":"locked",collision:e.collision===true,tools:n?.tools??[]}})}connectedDevices(){return this.listDevices().filter(e=>e.isConnected)}toolActions(e){return this.listDevices().map(n=>{const t=n.tools.find(r=>r.toolId===e);return t?{deviceId:n.deviceId,deviceName:n.deviceName,actions:t.actions}:null}).filter(n=>n!==null)}resolveDevice(e){this.requireAdmission();if(e){this.requireDeviceAccount(e);return e}const n=(u,l)=>new Error(`${NOT_READY_MARK} "${u}" (${l}) is not connected right now. If it is restarting, it usually takes a few seconds; to use another device, pass deviceId (run list_devices to see them).`);if(this.sessionDevice){const u=this.devices.find(l=>l.deviceId===this.sessionDevice);if(u&&u.isConnected!==false)return this.sessionDevice;throw n(this.sessionDevice,"the device this session was using")}const t=this.connectedDevices();const r=t.filter(u=>!this.lockedDevices.has(u.deviceId));const i=r.filter(u=>u.tools.length>0);const s=process.env.BUOY_PROJECT_ROOT||process.cwd();const o=pickByProject(i.map(u=>({deviceId:u.deviceId,root:this.devServerRoots.get(u.deviceId)})),s);if(o)return this.sessionDevice=o;const a=pickByProject(this.devices.filter(u=>u.deviceId&&u.isConnected===false&&!this.lockedDevices.has(u.deviceId)).map(u=>({deviceId:u.deviceId,root:this.devServerRoots.get(u.deviceId)})),s);if(a)throw n(a,"this project's app");if(r.length===0){if(t.length>0){throw new Error(`Devices are connected (${t.map(u=>u.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(r.length===1)return this.sessionDevice=r[0].deviceId;if(i.length===1)return this.sessionDevice=i[0].deviceId;if(i.length===0){const u=r.map(l=>l.deviceName).join(", ");throw new Error(`Connected devices (${u}) are not exposing any Buoy tools yet. Make sure the app is in the foreground with devtools mounted, then retry.`)}const c=i.map(u=>`${u.deviceName} (${u.deviceId})`).join(", ");throw new Error(`Multiple devices connected \u2014 specify deviceId. Connected: ${c}`)}requireProDevice(e){this.requireAdmission();if(e&&e!==ALL_DEVICES)this.sessionDevice=e;const n=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.${n(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===ALL_DEVICES){if(!this.connectedDevices().some(s=>s.isPro))throw new Error(t());return ALL_DEVICES}const r=this.resolveDevice(e);const i=this.connectedDevices().find(s=>s.deviceId===r);if(!i?.isPro){const s=this.accessState(r);if(s==="offline")throw new Error(`${NOT_READY_MARK} "${r}" is not connected right now. If the app is starting or reloading, it usually takes a few seconds. Run list_devices to check.`);if(s==="pending")throw new Error(`${NOT_READY_MARK} account access for "${r}" is still being confirmed (the app just connected). Try again in a moment.`);throw new Error(t(i))}return r}accessState(e){const n=this.devices.find(t=>t.deviceId===e);if(!n||n.isConnected===false)return"offline";if(n.isPro===true)return"ready";return n.tier===void 0?"pending":"denied"}healthOf(e){let n=this.health.get(e);if(!n){n={consecutiveTimeouts:0,lastOkAt:0,lastFullBudgetAt:0};this.health.set(e,n)}return n}noteOk(e){const n=this.healthOf(e);n.consecutiveTimeouts=0;n.lastOkAt=Date.now()}noteTimeout(e){this.healthOf(e).consecutiveTimeouts+=1}isUnresponsive(e){return isUnresponsive(this.healthOf(e).consecutiveTimeouts)}timeoutFor(e,n,t){const r=this.healthOf(e);const{timeoutMs:i,usedFullBudget:s}=actionTimeoutMs({consecutiveTimeouts:r.consecutiveTimeouts,lastFullBudgetAt:r.lastFullBudgetAt,now:Date.now(),fullMs:this.actionTimeoutMs,shortMs:UNRESPONSIVE_ACTION_TIMEOUT_MS,recoveryProbeMs:RECOVERY_PROBE_MS,toolId:n,action:t});if(s)r.lastFullBudgetAt=Date.now();return i}unresponsiveNote(e){const n=this.healthOf(e);const t=n.lastOkAt?Math.round((Date.now()-n.lastOkAt)/1e3):null;const r=diagnoseCrashed({consecutiveTimeouts:n.consecutiveTimeouts,lastOkAt:n.lastOkAt,now:Date.now(),unresponsiveAfterMs:UNRESPONSIVE_AFTER_MS});const i=[`The app on "${e}" is not responding (${n.consecutiveTimeouts} call${n.consecutiveTimeouts===1?"":"s"} unanswered${t!=null?`, last answered ${t}s ago`:""}).`,r?"It is most likely CRASHED \u2014 a fatal render error unmounts the React tree, and the dev tools live in that tree, so nothing on-device can answer until the app is reloaded.":"It may be busy, mid-reload, or crashing."];const s=this.lastFatalFor(e);if(s)i.push(`Last captured error: ${s}`);i.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 i.join(" ")}noteCrashReport(e,n){const t=n?.entries;if(!Array.isArray(t)||t.length===0)return;const r=Math.max(...t.map(o=>typeof o?.timestamp==="number"?o.timestamp:-Infinity));const i=this.crashSeen.get(e)??new Set;let s=false;for(const o of t){const a=o?.fatal||/^\[(RENDER ERROR|FATAL)/.test(o?.message??"");if(!a||typeof o.timestamp!=="number")continue;const c=`${o.id??""}|${o.timestamp}|${(o.message??"").slice(0,120)}`;if(i.has(c))continue;i.add(c);if(r-o.timestamp<3e4)s=true}if(i.size>200)for(const o of[...i].slice(0,i.size-200))i.delete(o);this.crashSeen.set(e,i);if(!s)return;if(![...this.pendingActions.values()].some(o=>o.target===e&&o.expire&&!o.cut))return;void this.callAction("app","ping",{},e,{timeoutMs:1500,silent:true}).then(()=>void 0,()=>{const o=Date.now();for(const a of this.pendingActions.values()){if(a.target!==e||!a.expire||a.cut)continue;a.cut=true;if(a.deadline!==void 0&&a.deadline-o<=UNRESPONSIVE_ACTION_TIMEOUT_MS)continue;clearTimeout(a.timer);a.timer=setTimeout(a.expire,UNRESPONSIVE_ACTION_TIMEOUT_MS)}})}lastFatalFor(e){const n=this.snapshots.get(snapKey(e,"console"));const t=n?.entries;if(!Array.isArray(t))return null;for(let r=t.length-1;r>=0;r--){const i=t[r];if(i?.fatal||i?.level==="error"){const s=(i.message??"").split("\n")[0];if(s)return s.length>300?`${s.slice(0,300)}\u2026`:s}}return null}snapshotAgeMs(e,n){this.requireAdmission();const t=this.snapshotAt.get(snapKey(n,e));return t?Date.now()-t:null}noteDevServerOrigin(e,n){if(typeof n==="string"&&/^https?:\/\//.test(n)){const t=this.devServerOrigins.get(e)!==n;this.devServerOrigins.set(e,n);if(t)this.devServerRoots.delete(e);if(t||!this.devServerRoots.has(e)){const r=devServerRoot(n).then(i=>{if(i&&this.devServerOrigins.get(e)===n)this.devServerRoots.set(e,i)});this.trackRootLookup(r)}}}async learnDevServerOrigin(e){if(this.devServerOrigins.has(e)||this.originProbed.has(e))return;this.originProbed.add(e);const n=this.capabilities.get(e)?.tools?.some(t=>t.toolId==="app");if(!n)return;try{const{payload:t}=await this.getSnapshot("app",e,{timeoutMs:4e3,silent:true});this.noteDevServerOrigin(e,t?.devServerOrigin)}catch{}}trackRootLookup(e){const n=e.catch(()=>void 0).finally(()=>this.rootLookups.delete(n));this.rootLookups.add(n)}async awaitBroker(){if(Date.now()-this.createdAt>15e3)return;for(let e=0;!this.admitted&&e<4e3;e+=100)await new Promise(n=>setTimeout(n,100));for(let e=0;this.admitted&&this.devices.length===0&&e<1500;e+=100)await new Promise(n=>setTimeout(n,100))}async settleDeviceChoice(e=1500){await this.awaitBroker();if(this.sessionDevice||this.rootLookups.size===0||this.connectedDevices().length<2)return;await Promise.race([Promise.all([...this.rootLookups]),new Promise(n=>setTimeout(n,e))]);if(this.rootLookups.size)await Promise.race([Promise.all([...this.rootLookups]),new Promise(n=>setTimeout(n,Math.min(800,e)))])}devServerOrigin(e){this.requireAdmission();const n=this.devServerOrigins.get(e);if(n)return n;const t=this.snapshots.get(snapKey(e,"app"));if(typeof t?.devServerOrigin==="string")return t.devServerOrigin;return null}ensureWatching(e,n){const t=snapKey(n,e);if(this.watching.has(t))return;this.watching.set(t,{toolId:e,targetDeviceId:n});this.sendWatch(e,n)}sendWatch(e,n){if(!this.admitted||!this.socket?.connected||this.lockedDevices.has(n))return;this.socket?.emit("devtool-watch",{toolId:e,targetDeviceId:n,watching:true,stream:false})}rearmWatches(){for(const{toolId:e,targetDeviceId:n}of this.watching.values()){this.sendWatch(e,n)}}rearmReconnectedDevices(e){for(const n of e){if(!n.deviceId||n.isConnected===false)continue;const t=String(n.deviceId);const r=`${n.id}|${n.connectionNonce??""}`;const i=this.deviceConnections.get(t);this.deviceConnections.set(t,r);if(i===void 0||i===r)continue;for(const{toolId:s,targetDeviceId:o}of this.watching.values()){if(o===t)this.sendWatch(s,o)}}}unwatch(e,n){const t=snapKey(n,e);if(!this.watching.delete(t))return;if(this.admitted&&this.socket?.connected)this.socket.emit("devtool-watch",{toolId:e,targetDeviceId:n,watching:false})}cachedSnapshot(e,n){this.requireAdmission();this.requireDeviceAccount(n);return this.snapshots.get(snapKey(n,e))}async getSnapshot(e,n,t={}){const r=this.resolveDevice(n);const i=snapKey(r,e);this.ensureWatching(e,r);let s=t.timeoutMs??DEFAULT_SNAPSHOT_TIMEOUT_MS;if(t.timeoutMs===void 0&&this.isUnresponsive(r)){const u=this.healthOf(r);if(Date.now()-u.lastFullBudgetAt>RECOVERY_PROBE_MS){u.lastFullBudgetAt=Date.now()}else{s=UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS}}const o=this.waitForSnapshot(i,s);this.socket?.emit("request-devtool-state",{toolId:e,targetDeviceId:r});const a=await o;this.requireAdmission();this.requireDeviceAccount(r);if(a!==void 0){if(!t.silent)this.noteOk(r);return{deviceId:r,payload:a}}if(!t.silent)this.noteTimeout(r);const c=this.snapshots.get(i);if(c!==void 0){return{deviceId:r,payload:c,stale:this.staleNote(e,r)}}throw new Error(`Timed out waiting for "${e}" state from ${r} (is the tool active?). ${this.unresponsiveNote(r)}`)}lastSync(e,n){const t=this.snapshots.get(snapKey(e,n));return t===void 0?void 0:{payload:t,ageMs:this.snapshotAgeMs(n,e)}}staleNote(e,n){const t=this.snapshotAgeMs(e,n);const r=t==null?"an earlier sync":`${Math.round(t/1e3)}s ago`;return`\u26A0\uFE0F Served from the last sync (${r}) \u2014 ${this.unresponsiveNote(n)}`}waitForSnapshot(e,n){return new Promise(t=>{const r=this.snapshotWaiters.get(e)??[];const i=setTimeout(()=>{const o=(this.snapshotWaiters.get(e)??[]).filter(a=>a!==s);this.snapshotWaiters.set(e,o);t(void 0)},n);const s=o=>{clearTimeout(i);t(o)};r.push(s);this.snapshotWaiters.set(e,r)})}async callAction(e,n,t,r,i={}){this.requireAdmission();const s=r===ALL_DEVICES?ALL_DEVICES:this.resolveDevice(r);if(!this.socket)throw new Error("SyncClient is not connected");const o=(0,import_node_crypto3.randomUUID)();const a=i.timeoutMs??this.timeoutFor(s,e,n);const c=await new Promise((u,l)=>{const d=Date.now();const h=()=>{this.pendingActions.delete(o);if(s!==ALL_DEVICES&&!i.silent)this.noteTimeout(s);l(new Error(`Action "${e}.${n}" got no answer in ${Date.now()-d}ms. `+(s===ALL_DEVICES?"No device responded.":this.unresponsiveNote(s))))};const p=setTimeout(h,a);this.pendingActions.set(o,{resolve:u,reject:l,timer:p,target:s,expire:h,deadline:d+a});this.socket.emit("devtool-action",{requestId:o,toolId:e,targetDeviceId:s,action:n,params:t??{}})});if(s!==ALL_DEVICES&&!i.silent)this.noteOk(s);if(!c.ok){throw new Error(c.error||`Action "${e}.${n}" failed on device`)}return c.result}};snapKey=(e,n)=>`${e}::${n}`;delay=e=>new Promise(n=>setTimeout(n,e))}});var VERSION,PACKAGE_NAME;var init_version=__esm({"src/version.ts"(){"use strict";VERSION="7.0.60"?"7.0.60":"0.0.0-dev";PACKAGE_NAME="@buoy-gg/mcp"}});function isNewer(e,n){const t=s=>s.split("-")[0].split(".").map(o=>Number(o)||0);const r=t(e);const i=t(n);for(let s=0;s<3;s++){const o=r[s]??0;const a=i[s]??0;if(o>a)return true;if(o<a)return false}return false}async function readCache(){try{const e=await import_node_fs4.promises.readFile(CACHE_FILE,"utf8");const n=JSON.parse(e);if(typeof n.checkedAt==="number"&&typeof n.latest==="string"){return n}}catch{}return null}async function fetchLatest(e){const n=new AbortController;const t=setTimeout(()=>n.abort(),FETCH_TIMEOUT_MS);try{const r=await fetch(REGISTRY_URL,{signal:n.signal});if(!r.ok)return null;const i=await r.json();const s=typeof i.version==="string"?i.version:null;if(s){await import_node_fs4.promises.writeFile(CACHE_FILE,JSON.stringify({checkedAt:e,latest:s})).catch(()=>{})}return s}catch{return null}finally{clearTimeout(t)}}async function resolveLatest(e){const n=await readCache();if(n&&e-n.checkedAt<CHECK_TTL_MS)return n.latest;return fetchLatest(e)}async function getUpdateNotice(e=Date.now()){if(VERSION==="0.0.0-dev")return null;try{const n=await resolveLatest(e);if(n&&isNewer(n,VERSION)){return`A newer buoy-mcp is available (${n}; you're on ${VERSION}). Update by re-running: npx -y ${PACKAGE_NAME}@latest init \u2014 then restart your editor.`}}catch{}return null}var import_node_fs4,import_node_os4,import_node_path5,CHECK_TTL_MS,FETCH_TIMEOUT_MS,REGISTRY_URL,CACHE_FILE;var init_checkForUpdate=__esm({"src/update/checkForUpdate.ts"(){"use strict";import_node_fs4=require("fs");import_node_os4=__toESM(require("os"));import_node_path5=__toESM(require("path"));init_version();CHECK_TTL_MS=24*60*60*1e3;FETCH_TIMEOUT_MS=1500;REGISTRY_URL=`https://registry.npmjs.org/${PACKAGE_NAME}/latest`;CACHE_FILE=import_node_path5.default.join(import_node_os4.default.tmpdir(),"buoy-mcp-update-check.json")}});function humanizeSimctlError(e){const n=e;if(n?.code==="ENOENT"){return"Xcode command-line tools (xcrun) not found. Install Xcode to capture the iOS Simulator."}const t=String(n?.stderr||n?.message||e);if(/No devices are booted|Unable to find device|current device/i.test(t)){return"No booted iOS Simulator found. Boot the Simulator with your app running, then try again."}return t.trim()||"Failed to capture the iOS Simulator."}function pngSize(e){const n=[137,80,78,71,13,10,26,10];if(e.length<24||!n.every((t,r)=>e[r]===t))return null;return{width:e.readUInt32BE(16),height:e.readUInt32BE(20)}}async function listDir(e){try{return await import_node_fs5.promises.readdir(e)}catch{return[]}}async function webViewInstallIds(e){const n=[];for(const t of await listDir(e))n.push(...await containerWebViewInstallIds(import_node_path6.default.join(e,t)));return n}async function containerWebViewInstallIds(e){const n=[];const t=import_node_path6.default.join(e,"Library","WebKit");for(const r of await listDir(t)){const i=import_node_path6.default.join(t,r,"WebsiteData","Default");for(const s of await listDir(i)){for(const o of await listDir(import_node_path6.default.join(i,s))){const a=import_node_path6.default.join(i,s,o,"LocalStorage","localstorage.sqlite3");try{await import_node_fs5.promises.access(a);const{stdout:c}=await execFileAsync4("sqlite3",["-readonly",a,`SELECT hex(value) FROM ItemTable WHERE key='${WEBVIEW_ID_KEY}' LIMIT 1;`],{timeout:1500});const u=c.trim();if(u)n.push(Buffer.from(u,"hex").toString("utf16le").trim())}catch{}}}}return n}async function resolveSimUdid(e){if(process.platform!=="darwin")return{ok:false,error:"Simulator lookup needs macOS."};let n=[];try{const{stdout:r}=await execFileAsync4("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const i=JSON.parse(r).devices;n=Object.entries(i).filter(([s])=>/iOS/.test(s)).flatMap(([,s])=>s.filter(o=>o.state==="Booted"))}catch(r){return{ok:false,error:humanizeSimctlError(r)}}if(n.length===0)return{ok:false,error:"No iOS Simulator is booted."};const t=e?.split("-").pop();if(t){for(const r of n){if(!r.dataPath)continue;const i=import_node_path6.default.join(r.dataPath,"Containers","Data","Application");let s=[];try{s=await import_node_fs5.promises.readdir(i)}catch{continue}for(const o of s){try{const a=(await import_node_fs5.promises.readFile(import_node_path6.default.join(i,o,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim();if(a===t)return{ok:true,udid:r.udid,how:`matched ${e} to "${r.name}"`}}catch{}}}}if(t&&e){const r=n.map(c=>c.udid).sort().join(",");const i=webViewLookups.get(e);const s=i?.booted===r&&(i.udid!==null||Date.now()-i.at<WEBVIEW_MISS_MS);const o=s&&i?.udid?n.find(c=>c.udid===i.udid):void 0;if(o)return{ok:true,udid:o.udid,how:`matched ${e} to "${o.name}" (WebView storage)`};const a=[];if(!s){const c=await Promise.all(n.map(u=>u.dataPath?webViewInstallIds(import_node_path6.default.join(u.dataPath,"Containers","Data","Application")):Promise.resolve([])));c.forEach((u,l)=>{if(u.includes(t))a.push(n[l])});webViewLookups.set(e,{booted:r,udid:a.length===1?a[0].udid:null,at:Date.now()})}if(a.length===1){return{ok:true,udid:a[0].udid,how:`matched ${e} to "${a[0].name}" (WebView storage)`}}if(a.length>1){return{ok:false,error:`${a.length} booted simulators (${a.map(c=>c.name).join(", ")}) hold ${e}. Pass the udid, or shut one down.`}}}if(n.length===1)return{ok:true,udid:n[0].udid,how:`only booted simulator "${n[0].name}"`};return{ok:false,error:`${n.length} iOS Simulators are booted (${n.map(r=>r.name).join(", ")}) and none could be matched to ${e??"this device"}. Shut down the others, or capture from a single booted simulator.`}}async function resolveSims(e){const n=new Map;if(process.platform!=="darwin"||e.length===0)return n;let t=[];try{const{stdout:i}=await execFileAsync4("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const s=JSON.parse(i).devices;t=Object.entries(s).filter(([o])=>/iOS/.test(o)).flatMap(([,o])=>o.filter(a=>a.state==="Booted"))}catch{return n}const r=new Map;for(const i of t){if(!i.dataPath)continue;const s=import_node_path6.default.join(i.dataPath,"Containers","Data","Application");let o=[];try{o=await import_node_fs5.promises.readdir(s)}catch{continue}for(const a of o){try{const c=(await import_node_fs5.promises.readFile(import_node_path6.default.join(s,a,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim();if(c)r.set(c,{name:i.name,udid:i.udid})}catch{}}}for(const i of e){const s=r.get(i.split("-").pop()??"");if(s)n.set(i,s)}return n}async function captureIosFramebuffer(e="booted"){if(process.platform!=="darwin"){return{ok:false,error:"Screenshotting a component requires macOS with Xcode's iOS Simulator (uses `xcrun simctl`)."}}const n=import_node_path6.default.join(import_node_os5.default.tmpdir(),`buoy-mcp-sim-${(0,import_node_crypto4.randomUUID)()}.png`);try{await execFileAsync4("xcrun",["simctl","io",e,"screenshot","--type=png",n],{timeout:15e3})}catch(t){return{ok:false,error:humanizeSimctlError(t)}}try{const t=await import_node_fs5.promises.readFile(n);const r=pngSize(t);if(!r)return{ok:false,error:"Captured file wasn't a valid PNG."};return{ok:true,srcPath:n,width:r.width,height:r.height}}catch(t){return{ok:false,error:`Failed to read screenshot: ${t.message}`}}}async function cropToBuffer(e,n,t){const r=clamp(Math.round(t.x),0,Math.max(0,n.width-1));const i=clamp(Math.round(t.y),0,Math.max(0,n.height-1));const s=clamp(Math.round(t.width),1,n.width-r);const o=clamp(Math.round(t.height),1,n.height-i);const a=import_node_path6.default.join(import_node_os5.default.tmpdir(),`buoy-mcp-crop-${(0,import_node_crypto4.randomUUID)()}.png`);try{await execFileAsync4("sips",["-c",String(o),String(s),"--cropOffset",String(i),String(r),e,"--out",a],{timeout:1e4});const c=await import_node_fs5.promises.readFile(a);return{ok:true,buffer:c,width:s,height:o}}catch(c){const u=c;return{ok:false,error:`Crop failed: ${u?.stderr||u?.message||c}`}}finally{await import_node_fs5.promises.unlink(a).catch(()=>{});await import_node_fs5.promises.unlink(e).catch(()=>{})}}var import_node_child_process5,import_node_util4,import_node_fs5,import_node_os5,import_node_path6,import_node_crypto4,execFileAsync4,clamp,WEBVIEW_ID_KEY,webViewLookups,WEBVIEW_MISS_MS;var init_simctl=__esm({"src/capture/simctl.ts"(){"use strict";import_node_child_process5=require("child_process");import_node_util4=require("util");import_node_fs5=require("fs");import_node_os5=__toESM(require("os"));import_node_path6=__toESM(require("path"));import_node_crypto4=require("crypto");execFileAsync4=(0,import_node_util4.promisify)(import_node_child_process5.execFile);clamp=(e,n,t)=>Math.min(Math.max(e,n),t);WEBVIEW_ID_KEY="@react_buoy_sync_device_id";webViewLookups=new Map;WEBVIEW_MISS_MS=3e4}});async function listDir2(e){return import_node_fs6.promises.readdir(e).catch(()=>[])}async function containerLocalStorageFiles(e){const n=[];const t=import_node_path7.default.join(e,"Library","WebKit");for(const r of await listDir2(t)){const i=import_node_path7.default.join(t,r,"WebsiteData","Default");for(const s of await listDir2(i)){for(const o of await listDir2(import_node_path7.default.join(i,s))){const a=import_node_path7.default.join(i,s,o);const c=import_node_path7.default.join(a,"LocalStorage","localstorage.sqlite3");if(!await import_node_fs6.promises.access(c).then(()=>true,()=>false))continue;const u=await import_node_fs6.promises.readFile(import_node_path7.default.join(a,"origin")).then(l=>l.toString("hex"),()=>"");if(u)n.push({db:c,origin:u})}}}return n}async function iosReadWebKeep(e){const n=[];for(const{db:t,origin:r}of await containerLocalStorageFiles(e)){const i=await sqlite(t,"SELECT key, hex(value) FROM ItemTable;");for(const s of i.split("\n")){const o=s.lastIndexOf("|");if(o<0)continue;const a=s.slice(0,o);if(WEB_KEEP_KEY.test(a))n.push({key:a,value:s.slice(o+1),origin:r})}}return n}async function iosWriteWebKeep(e,n){if(!n.length)return false;const t=await containerLocalStorageFiles(e);const r=new Set(n.map(i=>i.origin??""));for(const i of r){const s=i?t.find(a=>a.origin===i):void 0;if(!s)return false;const o=n.filter(a=>(a.origin??"")===i&&/^[0-9A-F]*$/i.test(a.value)).map(a=>`('${a.key.replace(/'/g,"''")}', X'${a.value}')`).join(",");if(o)await sqlite(s.db,`INSERT OR REPLACE INTO ItemTable (key, value) VALUES ${o};`,false)}return true}async function iosWaitForLocalStorage(e,n=15e3){const t=Date.now()+n;while(Date.now()<t){if((await containerLocalStorageFiles(e)).length)return true;await new Promise(r=>setTimeout(r,500))}return false}async function evaluateInWebView(e,n,t){const r=(await adbShell(e,`pidof ${n}`).catch(()=>"")).trim().split(/\s+/)[0];if(!r)throw new Error("the app is not running");const i=(await adb(e,["forward","tcp:0",`localabstract:webview_devtools_remote_${r}`])).trim();try{const s=await(await fetch(`http://127.0.0.1:${i}/json`)).json();const o=s.find(a=>a.type==="page"&&a.webSocketDebuggerUrl);if(!o?.webSocketDebuggerUrl)throw new Error("no debuggable WebView page (needs a debug build)");return await new Promise((a,c)=>{const u=new import_ws.WebSocket(o.webSocketDebuggerUrl);const l=setTimeout(()=>{u.close();c(new Error("the WebView did not answer"))},5e3);u.on("open",()=>u.send(JSON.stringify({id:1,method:"Runtime.evaluate",params:{expression:t,returnByValue:true}})));u.on("message",d=>{const h=JSON.parse(String(d));if(h.id!==1)return;clearTimeout(l);u.close();if(h.result?.exceptionDetails)c(new Error("the WebView script failed"));else a(h.result?.result?.value)});u.on("error",d=>{clearTimeout(l);c(d)})})}finally{await adb(e,["forward","--remove",`tcp:${i}`]).catch(()=>void 0)}}async function evaluateWhenReady(e,n,t,r=15e3){const i=Date.now()+r;let s;while(Date.now()<i){try{return await evaluateInWebView(e,n,t)}catch(o){s=o;await new Promise(a=>setTimeout(a,700))}}throw s instanceof Error?s:new Error("the WebView did not open")}async function androidHasWebViewStorage(e,n){const t=await adbShell(e,`run-as ${n} sh -c 'ls app_webview/Default/"Local Storage"/leveldb 2>/dev/null'`).catch(()=>"");return/CURRENT|\.log/.test(t)}async function androidReadWebKeep(e,n){if(!(await adbShell(e,`pidof ${n}`).catch(()=>"")).trim()){await adbShell(e,`monkey -p ${n} -c android.intent.category.LAUNCHER 1`)}const t=await evaluateWhenReady(e,n,`(() => { const re = ${WEB_KEEP_KEY}; const out = []; for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (k && re.test(k)) out.push({ key: k, value: localStorage.getItem(k) }); } return out; })()`);return Array.isArray(t)?t.filter(r=>typeof r.key==="string"&&typeof r.value==="string"):[]}async function androidWriteWebKeep(e,n,t){await evaluateWhenReady(e,n,`(() => { for (const r of ${JSON.stringify(t)}) localStorage.setItem(r.key, r.value); setTimeout(() => location.reload(), 50); return true; })()`)}var import_node_child_process6,import_node_util5,import_node_fs6,import_node_path7,import_ws,execFileAsync5,WEB_KEEP_KEY,sqlite;var init_webViewKeep=__esm({"src/capture/webViewKeep.ts"(){"use strict";import_node_child_process6=require("child_process");import_node_util5=require("util");import_node_fs6=require("fs");import_node_path7=__toESM(require("path"));import_ws=require("ws");init_adb();execFileAsync5=(0,import_node_util5.promisify)(import_node_child_process6.execFile);WEB_KEEP_KEY=/^(@buoy\/session:|buoy-gg-license|buoy-gg-device-fingerprint$|@react_buoy_sync_device_id$|@react_buoy_install)/;sqlite=(e,n,t=true)=>execFileAsync5("sqlite3",[...t?["-readonly"]:[],e,n],{timeout:5e3}).then(r=>r.stdout)}});function rememberedHost(e){return hosts.get(e)}async function sh(e,n,t=2e4){try{const{stdout:r}=await execFileAsync6(e,n,{timeout:t,maxBuffer:16*1024*1024});return r}catch(r){const i=r;if(i.code==="ENOENT")throw new Error(e==="xcrun"?"This needs macOS with Xcode (xcrun simctl).":`${e} is not installed.`);throw new Error(`${e} ${n.slice(0,2).join(" ")} failed: ${(i.stderr||i.message||"").trim().slice(0,300)}`)}}async function simsHolding(e){let n=[];try{const r=JSON.parse(await simctl(["list","devices","booted","-j"])).devices;n=Object.entries(r).filter(([i])=>/iOS/.test(i)).flatMap(([,i])=>i.filter(s=>s.state==="Booted"))}catch{return[]}const t=[];for(const r of n)if(await findIosContainer(e,r.udid))t.push(r);return t}function cloneError(e,n){return new Error(`${n.length} booted simulators hold "${e}" (one is probably a clone): ${n.map(t=>`${t.name} (${t.udid})`).join(", ")}. Pass udid to choose, or shut the extra one down.`)}async function findIosContainer(e,n){const t=tailOf(e);if(!t)return null;let r;try{const o=JSON.parse(await simctl(["list","devices","-j"])).devices;r=Object.values(o).flat().find(a=>a.udid===n)?.dataPath}catch{return null}if(!r)return null;const i=import_node_path8.default.join(r,"Containers","Data","Application");let s=[];try{s=await import_node_fs7.promises.readdir(i)}catch{return null}for(const o of s){const a=import_node_path8.default.join(i,o);if(!await iosContainerHolds(a,t))continue;let c=null;try{c=(await sh("plutil",["-extract","MCMMetadataIdentifier","raw","-o","-",import_node_path8.default.join(a,".com.apple.mobile_container_manager.metadata.plist")])).trim()||null}catch{}return{container:a,bundleId:c}}return null}async function iosContainerHolds(e,n){try{if((await import_node_fs7.promises.readFile(import_node_path8.default.join(e,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim()===n)return true}catch{}return(await containerWebViewInstallIds(e).catch(()=>[])).includes(n)}async function findAndroid(e,n){const t=tailOf(e);const r=n.serial?[n.serial]:await adbSerials();if(r.length===0)throw new Error("No Android device or emulator is connected to adb.");for(const i of r){const s=await adbForegroundPackage(i).catch(()=>null);const o=await adbUserPackages(i).catch(()=>[]);const a=[n.bundleId,s,...o].filter((c,u,l)=>!!c&&l.indexOf(c)===u).slice(0,80);for(const c of a){if(await adbInstallId(i,c).catch(()=>null)===t)return{platform:"android",serial:i,packageName:c}}}return null}async function findPhone(e){const n=tailOf(e);for(const t of await physicalPhones()){for(const r of await developerApps(t.udid).catch(()=>[])){if(await phoneInstallId(t.udid,r.bundleId)===n)return{platform:"ios-device",udid:t.udid,name:t.name,bundleId:r.bundleId}}}return null}async function findHost(e,n,t={}){if(e==="All")throw new Error('Device control acts on one app. Pass its deviceId, not "All".');const r=hosts.get(e);if(r&&!t.udid&&!t.serial&&await stillHolds(e,r)){if(r.platform==="ios"&&!r.picked){const c=await simsHolding(e);if(c.length>1)throw cloneError(e,c)}return r}if(r)hosts.delete(e);if(n==="android"){const c=await findAndroid(e,t);if(!c){throw new Error(`Could not prove which Android device and app run "${e}". Buoy checks the app's install id with run-as, which needs a debug build of the app on a device adb can reach${t.serial?` (looked on ${t.serial})`:""}.`)}hosts.set(e,c);return c}if(n&&n!=="ios")throw new Error(`Device control works on iOS Simulators and Android. This app runs on "${n}".`);if(process.platform!=="darwin")throw new Error("iOS control needs macOS with Xcode.");let i=t.udid;let s=i??"";if(!i){const c=await simsHolding(e);if(c.length>1)throw cloneError(e,c);const u=c.length===1?{ok:true,udid:c[0].udid,how:`matched ${e} to "${c[0].name}"`}:await resolveSimUdid(e);if(!u.ok||!/^matched /.test(u.how)){const l=await findPhone(e).catch(()=>null);if(l){hosts.set(e,l);return l}throw new Error(`Could not find which simulator or iPhone runs "${e}": no booted simulator holds its install id, and no connected iPhone has it (an iPhone must be unlocked, paired, and run a development build).`)}i=u.udid;s=/"([^"]+)"/.exec(u.how)?.[1]??i}const o=await findIosContainer(e,i);if(!o&&t.udid)throw new Error(`Simulator ${t.udid} does not hold "${e}".`);const a={platform:"ios",udid:i,name:s,bundleId:t.bundleId??o?.bundleId??null,container:o?.container??null,picked:!!t.udid};hosts.set(e,a);return a}async function verifyHost(e,n){if(n.platform==="ios"&&!n.picked){const t=await simsHolding(e);if(t.length>1)throw cloneError(e,t)}if(await stillHolds(e,n))return n;hosts.delete(e);return findHost(e,n.platform==="android"?"android":"ios",n.platform==="ios"&&n.picked?{udid:n.udid}:{})}async function stillHolds(e,n){const t=tailOf(e);if(n.platform==="android")return await adbInstallId(n.serial,n.packageName).catch(()=>null)===t;if(n.platform==="ios-device")return await phoneInstallId(n.udid,n.bundleId).catch(()=>null)===t;if(n.container)return iosContainerHolds(n.container,t);const r=await resolveSimUdid(e);return r.ok&&r.udid===n.udid&&/^matched /.test(r.how)}function needApp(e){if(e.platform==="android")return assertPackage(e.packageName);if(e.platform==="ios-device")return e.bundleId;if(!e.bundleId)throw new Error("Could not tell which app this is on the simulator (its container has no bundle metadata).");return e.bundleId}async function hostPng(e){if(e.platform==="android")return adbScreenshot(e.serial);if(e.platform==="ios-device")return phoneScreenshot(e.udid);const n=await captureIosFramebuffer(e.udid);if(!n.ok||!n.srcPath)throw new Error(n.error??"Screenshot failed.");try{return await import_node_fs7.promises.readFile(n.srcPath)}finally{await import_node_fs7.promises.unlink(n.srcPath).catch(()=>{})}}async function toSmallImage(e,n=1280){if(process.platform==="darwin"){const i=import_node_path8.default.join(import_node_os6.default.tmpdir(),`buoy-mcp-img-${(0,import_node_crypto5.randomUUID)()}.png`);const s=i.replace(/\.png$/,".jpg");await import_node_fs7.promises.writeFile(i,e);try{await sh("sips",["-Z",String(n),"-s","format","jpeg","-s","formatOptions","70",i,"--out",s],15e3);const o=await sh("sips",["-g","pixelWidth","-g","pixelHeight",s]);return{data:(await import_node_fs7.promises.readFile(s)).toString("base64"),mimeType:"image/jpeg",width:Number(/pixelWidth:\s*(\d+)/.exec(o)?.[1]??0),height:Number(/pixelHeight:\s*(\d+)/.exec(o)?.[1]??0)}}finally{await import_node_fs7.promises.unlink(i).catch(()=>{});await import_node_fs7.promises.unlink(s).catch(()=>{})}}const t=downscalePng(import_pngjs2.PNG.sync.read(e),Math.min(n,1024));const r=import_pngjs2.PNG.sync.write(t,{colorType:2,deflateLevel:9});return{data:r.toString("base64"),mimeType:"image/png",width:t.width,height:t.height}}function downscalePng(e,n){const t=Math.min(1,n/Math.max(e.width,e.height));if(t===1)return e;const r=Math.max(1,Math.round(e.width*t));const i=Math.max(1,Math.round(e.height*t));const s=new import_pngjs2.PNG({width:r,height:i});const o=e.width/r;const a=e.height/i;for(let c=0;c<i;c++){const u=Math.floor(c*a);const l=Math.max(u+1,Math.floor((c+1)*a));for(let d=0;d<r;d++){const h=Math.floor(d*o);const p=Math.max(h+1,Math.floor((d+1)*o));const m=[0,0,0,0];let g=0;for(let f=u;f<l;f++){for(let b=h;b<p;b++){const v=(f*e.width+b)*4;for(let y=0;y<4;y++)m[y]+=e.data[v+y];g++}}const w=(c*r+d)*4;for(let f=0;f<4;f++)s.data[w+f]=Math.round(m[f]/g)}}return s}async function withSteadyStatusBar(e,n){let t=false;try{if(e.platform==="ios"){const r=await simctl(["status_bar",e.udid,"list"]).catch(()=>"");const i=r.split(/^=+$/m).slice(1).join("").trim();if(!i){await simctl(["status_bar",e.udid,"override","--time","9:41","--batteryState","charged","--batteryLevel","100","--wifiBars","3","--cellularBars","4"]);t=true}}else if(e.platform==="android"){const r=(await adbShell(e.serial,"settings get global sysui_demo_allowed").catch(()=>"")).trim();if(r!=="1"&&!steadying.has(e.serial)){steadying.add(e.serial);await adbDemoMode(e.serial,true);t=true}}if(t)await new Promise(r=>setTimeout(r,400))}catch{t=false}try{return{result:await n(),steadied:t}}finally{if(t){if(e.platform==="ios")await simctl(["status_bar",e.udid,"clear"]).catch(()=>void 0);else if(e.platform==="android"){await adbDemoMode(e.serial,false);await adbShell(e.serial,"settings put global sysui_demo_allowed 0").catch(()=>void 0);steadying.delete(e.serial)}}}}async function hostQuit(e){const n=needApp(e);if(e.platform==="ios-device"){const t=await phoneQuit(e.udid,n);return t?`Quit ${n}.`:`${n} was not running.`}if(e.platform==="ios"){await simctl(["terminate",e.udid,n]).catch(t=>{if(!/found nothing to terminate|not running/i.test(String(t)))throw t})}else{await adbShell(e.serial,`am force-stop ${q(n)}`)}return`Quit ${n}.`}async function hostLaunch(e){const n=needApp(e);if(e.platform==="ios")await simctl(["launch",e.udid,n]);else if(e.platform==="ios-device")await phoneLaunch(e.udid,n);else await adbShell(e.serial,`monkey -p ${q(n)} -c android.intent.category.LAUNCHER 1`);return`Launched ${n}.`}async function hostBackground(e){if(e.platform==="ios-device"){await phoneLaunch(e.udid,"com.apple.Preferences");return"Sent to the background for real (Settings opened on top)."}if(e.platform==="ios"){await simctl(["launch",e.udid,"com.apple.Preferences"]);return"Sent to the background for real (Settings opened on top)."}await adbShell(e.serial,"input keyevent 3");return"Sent to the background for real (pressed Home)."}async function hostOpenUrl(e,n){if(!/^[a-zA-Z][\w+.-]*:/.test(n))throw new Error(`"${n}" is not a link with a scheme (like https://\u2026 or myapp://\u2026).`);if(e.platform==="ios-device"){await phoneOpenUrl(e.udid,n);return"Opened through the OS on the iPhone."}if(e.platform==="ios"){await simctl(["openurl",e.udid,n]);return'Opened through the OS. A custom scheme may first show an "Open in" prompt on the simulator.'}await adbShell(e.serial,`am start -a android.intent.action.VIEW -d ${q(n)}`);return"Opened through the OS (an Android VIEW intent)."}async function appBundleInfo(e){const n=import_node_path8.default.join(e,"Info.plist");const t=o=>sh("plutil",["-extract",o,"raw","-o","-",n]).then(a=>a.trim()).catch(()=>"");const r=await t("CFBundleIdentifier");if(!r)throw new Error(`${e} has no Info.plist with a bundle id. Pass a built .app folder.`);const i=(await sh("plutil",["-extract","CFBundleSupportedPlatforms","json","-o","-",n]).catch(()=>"[]")).toLowerCase();const s=(await t("DTPlatformName")).toLowerCase();return{bundleId:r,simulator:i.includes("iphonesimulator")||s==="iphonesimulator"}}async function apkPackage(e){const n=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT,import_node_path8.default.join(import_node_os6.default.homedir(),"Library","Android","sdk"),import_node_path8.default.join(import_node_os6.default.homedir(),"Android","Sdk")].filter(t=>!!t);for(const t of n){const r=import_node_path8.default.join(t,"build-tools");const i=(await import_node_fs7.promises.readdir(r).catch(()=>[])).sort().reverse();for(const s of i){for(const o of["aapt2","aapt"]){const a=import_node_path8.default.join(r,s,o);try{await import_node_fs7.promises.access(a)}catch{continue}const c=await sh(a,o==="aapt2"?["dump","packagename",e]:["dump","badging",e]).catch(()=>"");const u=o==="aapt2"?c.trim().split("\n")[0]:/package: name='([^']+)'/.exec(c)?.[1]??"";if(u)return u}}}throw new Error("Could not read the APK's package name (needs aapt2 from the Android SDK build-tools). Nothing was changed.")}async function hostReinstall(e,n,t=true){const r=needApp(e);const i=import_node_path8.default.resolve(n);try{await import_node_fs7.promises.access(i)}catch{throw new Error(`No build at ${i}. Pass appPath: the built .app folder (iOS Simulator) or .apk file (Android). Nothing was changed.`)}if(e.platform==="android")return reinstallAndroid(e,r,i,t);if(e.platform==="ios-device")return reinstallPhone(e,r,i,t);if(!/\.app\/?$/i.test(i))throw new Error("On the iOS Simulator, appPath must be a built .app folder. Nothing was changed.");const s=await appBundleInfo(i);if(s.bundleId!==r)throw new Error(`${import_node_path8.default.basename(i)} is ${s.bundleId}, but this app is ${r}. Nothing was changed.`);if(!s.simulator)throw new Error(`${import_node_path8.default.basename(i)} is a device build, not a simulator build. Nothing was changed.`);const o=t?await import_node_fs7.promises.mkdtemp(import_node_path8.default.join(import_node_os6.default.tmpdir(),"buoy-mcp-keep-")):null;try{let a=false;let c=[];if(o){await import_node_fs7.promises.chmod(o,448);const l=(await simctl(["get_app_container",e.udid,r,"data"]).catch(()=>"")).trim();if(l)a=await copyBuoyFiles(import_node_path8.default.join(l,"Documents"),o);if(l&&!a){try{c=await iosReadWebKeep(l)}catch(d){throw new Error(`Couldn't read Buoy's sign-in from the app's WebView storage (${d.message}). Nothing was changed. Pass keepBuoy: false to reinstall anyway.`)}}}await simctl(["terminate",e.udid,r]).catch(()=>void 0);await simctl(["uninstall",e.udid,r]);try{await simctl(["install",e.udid,i],18e4)}catch(l){throw new Error(`The app was removed, but installing ${import_node_path8.default.basename(i)} failed: ${l.message}. Install it again by hand.`)}let u="";if(o&&a){try{const l=(await simctl(["get_app_container",e.udid,r,"data"])).trim();await copyBuoyFiles(o,import_node_path8.default.join(l,"Documents"));e.container=l;u=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(l){u=` Buoy's sign-in could not be restored (${l.message}): sign in to Buoy again in the app.`}}else if(c.length){try{const l=(await simctl(["get_app_container",e.udid,r,"data"])).trim();await simctl(["launch",e.udid,r]);const d=await iosWaitForLocalStorage(l);await simctl(["terminate",e.udid,r]).catch(()=>void 0);if(!d||!await iosWriteWebKeep(l,c))throw new Error("the app made no WebView storage");e.container=l;u=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(l){u=` Buoy's sign-in could not be restored (${l.message}): sign in to Buoy again in the app.`}}else if(t){u=" The old install had no Buoy sign-in to keep."}await simctl(["launch",e.udid,r]);return`Reinstalled ${r} from ${i} and launched it. The app's own data is gone, like a new user.${u}`}finally{if(o)await import_node_fs7.promises.rm(o,{recursive:true,force:true}).catch(()=>void 0)}}async function copyBuoyFiles(e,n){let t=false;for(const r of BUOY_KEEP){const i=import_node_path8.default.join(e,r);try{await import_node_fs7.promises.access(i)}catch{continue}const s=import_node_path8.default.join(n,r);await import_node_fs7.promises.mkdir(import_node_path8.default.dirname(s),{recursive:true});await import_node_fs7.promises.cp(i,s,{recursive:true,force:true});t=true}return t}async function reinstallAndroid(e,n,t,r){if(!/\.apk$/i.test(t))throw new Error("On Android, appPath must be an .apk file. Nothing was changed.");const i=await apkPackage(t);if(i!==n)throw new Error(`${import_node_path8.default.basename(t)} is ${i}, but this app is ${n}. Nothing was changed.`);const s=[];if(r){const c=await adbShell(e.serial,`run-as ${q(n)} find files/buoy-license files/react-buoy -maxdepth 1 -type f 2>/dev/null`).catch(()=>"");const u=c.split("\n").map(l=>l.trim()).filter(l=>l.startsWith("files/buoy-license/")||/react-buoy\/@react_buoy_(sync_device_id|install)\.json$/.test(l));for(const l of u){const d=await adbShell(e.serial,`run-as ${q(n)} base64 ${q(l)}`).catch(()=>"");if(d.trim())s.push({rel:l,data:d.replace(/\s+/g,"")})}}let o=[];if(r&&!s.length&&await androidHasWebViewStorage(e.serial,n)){try{o=await androidReadWebKeep(e.serial,n)}catch(c){throw new Error(`Couldn't read Buoy's sign-in from the app's WebView (${c.message}). Nothing was changed. Pass keepBuoy: false to reinstall anyway.`)}}await adb(e.serial,["install","-r","-d",t],18e4);await adbShell(e.serial,`pm clear ${q(n)}`);let a="";if(o.length){await hostLaunch(e);try{await androidWriteWebKeep(e.serial,n,o);a=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(c){a=` Buoy's sign-in could not be restored (${c.message}): sign in to Buoy again in the app.`}return`Reinstalled ${n} from ${t} and launched it. The app's data is gone, like a new user.${a}`}if(s.length){try{for(const c of s){const u=import_node_path8.default.posix.dirname(c.rel);await adbShell(e.serial,`echo ${q(c.data)} | run-as ${q(n)} sh -c ${q(`mkdir -p ${q(u)} && base64 -d > ${q(c.rel)}`)}`)}a=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(c){a=` Buoy's sign-in could not be restored (${c.message}): sign in to Buoy again in the app.`}}else if(r){a=" No Buoy sign-in could be read to keep (needs a debug build): sign in to Buoy again in the app."}await hostLaunch(e);return`Reinstalled ${n} from ${t} and launched it. The app's data is gone, like a new user.${a}`}async function reinstallPhone(e,n,t,r){if(!/\.app\/?$/i.test(t))throw new Error("On an iPhone, appPath must be a built .app folder (a device build). Nothing was changed.");const i=await appBundleInfo(t);if(i.bundleId!==n)throw new Error(`${import_node_path8.default.basename(t)} is ${i.bundleId}, but this app is ${n}. Nothing was changed.`);if(i.simulator)throw new Error(`${import_node_path8.default.basename(t)} is a simulator build, not a device build. Nothing was changed.`);const s=["Documents/buoy-license/buoy-gg-license.json","Documents/react-buoy/@react_buoy_sync_device_id.json","Documents/react-buoy/@react_buoy_install.json"];const o=r?await import_node_fs7.promises.mkdtemp(import_node_path8.default.join(import_node_os6.default.tmpdir(),"buoy-mcp-keep-")):null;try{const a=[];if(o){await import_node_fs7.promises.chmod(o,448);for(const u of s){let l;try{l=await readAppFile(e.udid,n,u)}catch(h){throw new Error(`Could not back up Buoy's ${import_node_path8.default.basename(u)} from the iPhone (${h.message}). Nothing was changed.`)}if(!l)continue;const d=import_node_path8.default.join(o,u.replace(/\//g,"__"));await import_node_fs7.promises.writeFile(d,l,{mode:384});a.push({rel:u,local:d})}}await phoneQuit(e.udid,n).catch(()=>false);await phoneUninstall(e.udid,n);try{await phoneInstall(e.udid,t)}catch(u){throw new Error(`The app was removed, but installing ${import_node_path8.default.basename(t)} failed: ${u.message}. Install it again from Xcode.`)}let c="";if(a.length){try{for(const d of a)await writeAppFile(e.udid,n,d.local,d.rel);const u=a.some(d=>d.rel.includes("buoy-license"));const l=a.some(d=>d.rel.includes("sync_device_id"));c=u?` Kept Buoy's sign-in${l?" and device id, so the same deviceId still works":""}.`:` Kept the device id; there was no Buoy sign-in to keep, so sign in to Buoy in the app.`}catch(u){c=` Buoy's sign-in could not be restored (${u.message}): sign in to Buoy again in the app.`}}else if(r)c=" The old install had no Buoy sign-in to keep.";await phoneLaunch(e.udid,n);return`Reinstalled ${n} on the iPhone and launched it. The app's own data is gone, like a new user.${c}`}finally{if(o)await import_node_fs7.promises.rm(o,{recursive:true,force:true}).catch(()=>void 0)}}async function bootSimulator(e){const n=JSON.parse(await simctl(["list","devices","available","-j"])).devices;const t=Object.entries(n).filter(([a])=>/iOS/.test(a)).flatMap(([,a])=>a);const r=e.trim().toLowerCase();const i=t.filter(a=>a.udid.toLowerCase()===r||a.name.toLowerCase()===r);const s=i.length?i:t.filter(a=>a.name.toLowerCase().includes(r));if(s.length===0)throw new Error(`No iOS Simulator matches "${e}". Run \`xcrun simctl list devices available\` to see them.`);if(s.length>1)throw new Error(`${s.length} simulators match "${e}": ${s.map(a=>`${a.name} (${a.udid})`).join(", ")}. Pass the udid.`);const o=s[0];if(o.state!=="Booted")await simctl(["boot",o.udid],12e4);await sh("open",["-a","Simulator","--args","-CurrentDeviceUDID",o.udid]).catch(()=>void 0);return o.state==="Booted"?`${o.name} (${o.udid}) was already booted.`:`Booted ${o.name} (${o.udid}).`}var import_node_child_process7,import_node_util6,import_node_fs7,import_node_os6,import_node_path8,import_node_crypto5,import_pngjs2,execFileAsync6,hosts,simctl,tailOf,steadying,BUOY_KEEP;var init_hostDevice=__esm({"src/capture/hostDevice.ts"(){"use strict";import_node_child_process7=require("child_process");import_node_util6=require("util");import_node_fs7=require("fs");import_node_os6=__toESM(require("os"));import_node_path8=__toESM(require("path"));import_node_crypto5=require("crypto");import_pngjs2=__toESM(require_png());init_simctl();init_iosDevice();init_webViewKeep();init_adb();execFileAsync6=(0,import_node_util6.promisify)(import_node_child_process7.execFile);hosts=new Map;simctl=(e,n)=>sh("xcrun",["simctl",...e],n);tailOf=e=>e.split("-").pop()??"";steadying=new Set;BUOY_KEEP=["buoy-license","react-buoy/@react_buoy_sync_device_id.json","react-buoy/@react_buoy_install.json"]}});async function hostTarget(e,n,t={},r={}){if(n==="All")throw new Error('Device control acts on one app. Pass its deviceId, not "All".');let i;let s=true;try{i=e.requireProDevice(n)}catch(c){const u=c instanceof Error?c.message:String(c);const l=u.startsWith(NOT_READY_MARK)&&/is not connected right now/.test(u)?/"([^"]+)"/.exec(u)?.[1]:void 0;const d=l?e.listDevices().some(h=>h.deviceId===l&&h.isPro):false;if(!r.allowOffline||!l||!d)throw c;i=l;s=false}const o=e.listDevices().find(c=>c.deviceId===i)?.platform;let a=await findHost(i,o,t);if(r.changesApp&&rememberedHost(i)===a)a=await verifyHost(i,a);return{id:i,host:a,online:s}}function hostLabel(e){if(e.platform==="ios")return`simulator "${e.name}"`;if(e.platform==="ios-device")return`iPhone "${e.name}"`;return`Android device ${e.serial}`}function has(e){if(!onPath.has(e))onPath.set(e,execFileAsync7("which",[e],{timeout:3e3}).then(()=>true,()=>false));return onPath.get(e)}async function hostSummary(e,n){let t=n;if(e.platform==="android"){const i=rememberedHost(e.deviceId);const s=i??(e.isConnected?await Promise.race([findHost(e.deviceId,"android").catch(()=>void 0),new Promise(a=>setTimeout(()=>a(void 0),3e3))]):void 0);const o=await has("adb");return{kind:"android",...s&&s.platform==="android"?{id:s.serial,name:s.packageName}:{},can:["screenshot","screen_recording","baseline diffs","quit/launch/reinstall","real lifecycle events","native_tap/type/swipe"],...!o?{missing:["adb (Android SDK platform-tools)"]}:!s?{missing:["proof of which phone runs it (needs a debug build reachable by adb)"]}:{}}}if(e.platform!=="ios")return{kind:e.platform??"unknown",can:[],missing:["host control works on iOS and Android apps"]};let r=rememberedHost(e.deviceId);if(!r&&!t&&e.isConnected){r=await Promise.race([findHost(e.deviceId,"ios").catch(()=>void 0),new Promise(i=>setTimeout(()=>i(void 0),4e3))])}if(!t&&r?.platform==="ios")t={name:r.name,udid:r.udid};if(r?.platform==="ios-device"){return{kind:"physical iPhone",id:r.udid,name:r.name,can:["screenshot","screen_recording (if this iPhone supports it)","baseline diffs","quit/launch/reinstall","open_url","native_tap/type/swipe (by query, testID, nativeTag or x/y; not label)"]}}if(t){const i=await has("idb");return{kind:"ios simulator",id:t.udid,name:t.name,can:["screenshot","screen_recording","baseline diffs","quit/launch/reinstall/boot","real lifecycle events",...i?["native_tap/type/swipe"]:[]],...i?{}:{missing:["idb for real touches (brew install facebook/fb/idb-companion && pipx install fb-idb)"]}}}return void 0}var import_node_child_process8,import_node_util7,execFileAsync7,onPath;var init_hostKit=__esm({"src/tools/hostKit.ts"(){"use strict";init_SyncClient();import_node_child_process8=require("child_process");import_node_util7=require("util");init_hostDevice();execFileAsync7=(0,import_node_util7.promisify)(import_node_child_process8.execFile);onPath=new Map}});function json(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function fail(e){return{isError:true,content:[{type:"text",text:e}]}}function registerGenericTools(e,n){e.registerTool("list_devices",{description:"List the apps connected to Buoy: id, name, platform, whether it is connected and has MCP access, the simulator or phone it runs on with the host controls that work there (screenshot, recording, app control, real touches) and anything missing, and the Buoy tools it exposes. Start here. Pass details:true for every tool's action names.",inputSchema:{details:import_zod.z.boolean().optional().describe("Also list every action of every tool. Default false (tool names only); list_tool_actions gives one tool's actions."),includeDisconnected:import_zod.z.boolean().optional().describe("Also list apps that were seen before but are not connected now. Default false.")}},async(t={})=>{const r=await getUpdateNotice();let i=n.listDevices();for(let p=0;i.length===0&&p<10;p++){await new Promise(m=>setTimeout(m,200));i=n.listDevices()}if(i.length===0){return json({devices:[],hint:"No devices connected. Open the app with Buoy devtools running, then retry.",...r?{updateAvailable:r}:{}})}const s=t.includeDisconnected?0:i.filter(p=>!p.isConnected).length;if(!t.includeDisconnected)i=i.filter(p=>p.isConnected);if(i.length===0){return json({devices:[],hint:`No app is connected right now${s?` (${s} seen before; pass includeDisconnected:true to list them)`:""}. Open the app with Buoy devtools running, then retry.`,...r?{updateAvailable:r}:{}})}const o=await resolveSims(i.filter(p=>p.platform==="ios").map(p=>p.deviceId)).catch(()=>new Map);const a=i.filter(p=>p.isConnected);const c=a.some(p=>p.isPro);const u=a.some(p=>p.tier!=="locked");const l=a.filter(p=>p.collision);const d=await Promise.all(i.map(p=>p.isConnected?hostSummary(p,o.get(p.deviceId)).catch(()=>void 0):void 0));const h=i.map((p,m)=>{const g=o.get(p.deviceId);const w=d[m];return{deviceId:p.deviceId,deviceName:p.deviceName,platform:p.platform,isConnected:p.isConnected,isPro:p.isPro,tier:p.tier,access:n.accessState(p.deviceId),...g?{simulator:g}:{},...w?{host:w}:{},...p.collision?{collision:true}:{},tools:t.details?p.tools:p.tools.map(f=>f.toolId)}});return json({devices:h,...t.details?{}:{note:`Tool names only. Pass details:true, or list_tool_actions({toolId}), for action names.${s?` ${s} apps seen before but not connected now are left out (includeDisconnected:true lists them).`:""}`},...l.length>0?{warning:`${l.map(p=>`"${p.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.`}:{},...c?{}:{hint:u?"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."},...r?{updateAvailable:r}:{}})});e.registerTool("list_tool_actions",{description:"List the actions a tool exposes, and which connected devices offer it. Leave toolId out to list every tool's actions. Use the action names with call_action.",inputSchema:{toolId:import_zod.z.string().optional().describe('The tool id, e.g. "perf-monitor", "network", "react-query". Leave out for every tool.'),tool:import_zod.z.string().optional().describe("Same as toolId."),deviceId:import_zod.z.string().optional().describe("Only list what this device offers.")}},async({toolId:t,tool:r,deviceId:i})=>{const s=t??r;if(!s){const c=n.connectedDevices().filter(l=>!i||l.deviceId===i);if(c.length===0)return fail(i?`No connected device "${i}". Call list_devices.`:"No devices are connected. Call list_devices.");const u=c.map(l=>[`**${l.deviceName}** (${l.deviceId})`,...l.tools.map(d=>`- ${d.toolId}: ${d.actions.join(", ")}`)].join("\n"));return{content:[{type:"text",text:`${u.join("\n\n")}
41
+ `));this.autoSpawn=e.autoSpawnBroker??true}async start(){const e=await probeBroker(this.url)||await probeBroker(this.url,8e3);let n="connected";if(!e){if(!this.autoSpawn){throw new Error(`No Buoy broker reachable at ${this.url} and autoSpawnBroker is off. Start the Buoy desktop app, or enable autoSpawnBroker.`)}this.log(`no broker at ${this.url} \u2014 spawning one in-process on :${this.port}`);this.hostAccount=new NodeAccount(()=>this.broker?.refreshAccess());this.hostAccount.start();let t=false;this.broker=(0,import_sync_broker2.createBroker)({canUseDesktop:this.hostAccount.hasAccess,port:this.port,onError:r=>{if(r.code==="EADDRINUSE")t=true;this.log(`broker error: ${r.code??r.message}`)}});await waitForBroker(this.url).catch(r=>{if(!t)throw r});if(!this.broker.httpServer.listening)t=true;if(t){this.log(`another broker holds :${this.port} \u2014 connecting to it as a dashboard`);await this.broker.close().catch(()=>void 0);this.broker=null;this.hostAccount.stop();this.hostAccount=null;await this.connectSocket();return"connected"}try{(0,import_sync_broker2.writeBrokerToken)(this.broker.dashboardToken,(0,import_sync_broker2.brokerTokenPath)(this.port))}catch(r){this.log(`could not write the broker token file: ${r.message}`)}n="spawned"}else{this.log(`found a running broker at ${this.url} \u2014 connecting as a dashboard`)}await this.connectSocket();return n}connectSocket(){return new Promise((e,n)=>{const t=(0,import_socket.io)(this.url,{transports:["websocket"],query:{deviceName:DASHBOARD_NAME},auth:a=>{const c=this.broker?.dashboardToken??(0,import_sync_broker2.readBrokerToken)((0,import_sync_broker2.brokerTokenPath)(this.port));a(c?{dashboardToken:c}:{})},reconnection:true,reconnectionDelay:500,timeout:4e3});this.socket=t;let r=false;const i=()=>{if(r)return;r=true;this.log("connected to broker");e()};const s=setTimeout(()=>{if(r)return;r=true;n(new Error("Broker account is locked or the broker needs an update. Sign in to Buoy Desktop or run npx buoy login for standalone MCP."))},5e3);t.on("buoy:access",a=>{const c=!!a&&typeof a==="object"&&a.protocol===1&&a.ready===true;this.setAdmission(c);if(c){clearTimeout(s);this.rearmWatches();i()}});t.on("connect",()=>{t.emit("buoy:access:request")});t.on("disconnect",()=>this.setAdmission(false,true));const o=a=>a.message===import_sync_broker2.DASHBOARD_TOKEN_REQUIRED;t.once("connect_error",a=>{if(r)return;r=true;clearTimeout(s);n(new Error(o(a)?`The broker at ${this.url} refused this MCP as a dashboard: the token in ${(0,import_sync_broker2.brokerTokenPath)(this.port)} is missing or stale. Update Buoy Desktop, or restart it so it writes the file.`:`failed to connect to broker at ${this.url}: ${a.message}`))});t.on("connect_error",a=>{if(!o(a)||t.active)return;setTimeout(()=>{if(this.socket===t&&!t.connected)t.connect()},1e3).unref?.()});t.on("devtool-capabilities",a=>{if(!this.admitted||this.lockedDevices.has(a.persistentDeviceId))return;this.capabilities.set(a.persistentDeviceId,a);this.trackRootLookup(this.learnDevServerOrigin(a.persistentDeviceId));if(a.tools?.some(c=>c.toolId==="console"))this.ensureWatching("console",a.persistentDeviceId)});t.on("all-devices-update",a=>{if(!this.admitted)return;if(!Array.isArray(a))return;let c=false;for(const l of a){if(l.deviceId&&l.tier==="locked")this.lockDevice(String(l.deviceId));else if(l.deviceId&&(l.tier==="free"||l.tier==="pro")){c=this.lockedDevices.delete(String(l.deviceId))||c}}this.devices=a;const u=Date.now();for(const l of a)if(l.deviceId)this.lastSeen.set(l.deviceId,u);this.pruneStaleDevices();if(c)this.rearmWatches();else this.rearmReconnectedDevices(a)});t.on("devtool-sync",a=>{if(!this.admitted||this.lockedDevices.has(a.persistentDeviceId))return;const c=snapKey(a.persistentDeviceId,a.toolId);this.snapshots.set(c,a.payload);this.snapshotAt.set(c,Date.now());if(a.toolId==="console")this.noteCrashReport(a.persistentDeviceId,a.payload);const u=this.snapshotWaiters.get(c);if(u&&u.length){this.snapshotWaiters.set(c,[]);for(const l of u)l(a.payload)}});t.on("devtool-action-result",a=>{if(!this.admitted)return;const c=this.pendingActions.get(a.requestId);if(!c)return;this.pendingActions.delete(a.requestId);clearTimeout(c.timer);c.resolve(a)})})}requireAdmission(){if(!this.admitted)throw new Error("A verified Buoy account and an updated broker are required. Sign in to Buoy Desktop, or run npx buoy login for standalone MCP.")}setAdmission(e,n=false){this.admitted=e;if(e)return;this.devices=[];this.lockedDevices.clear();this.capabilities.clear();this.snapshots.clear();this.snapshotAt.clear();this.devServerOrigins.clear();this.devServerRoots.clear();this.crashSeen.clear();this.originProbed.clear();this.health.clear();this.lastSeen.clear();if(!n)this.watching.clear();for(const t of this.pendingActions.values()){clearTimeout(t.timer);t.reject(new Error("Buoy account access ended while the action was pending."))}this.pendingActions.clear();for(const t of this.snapshotWaiters.values())for(const r of t)r(void 0);this.snapshotWaiters.clear();if(this.socket)this.socket.sendBuffer=[]}requireDeviceAccount(e){if(this.lockedDevices.has(e))throw new Error("The device's Buoy account access ended. Sign in and verify its key.")}lockDevice(e){this.lockedDevices.add(e);this.capabilities.delete(e);this.health.delete(e);this.devServerOrigins.delete(e);this.devServerRoots.delete(e);this.originProbed.delete(e);const n=`${e}::`;for(const t of this.snapshots.keys())if(t.startsWith(n)){this.snapshots.delete(t);this.snapshotAt.delete(t)}for(const[t,r]of this.snapshotWaiters)if(t.startsWith(n)){this.snapshotWaiters.delete(t);for(const i of r)i(void 0)}for(const[t,r]of this.pendingActions)if(r.target===e||r.target===ALL_DEVICES){clearTimeout(r.timer);this.pendingActions.delete(t);r.reject(new Error("Device account access ended while the action was pending."))}}pruneStaleDevices(){const e=Date.now()-DEVICE_RETENTION_MS;for(const[n,t]of this.lastSeen){if(t>e)continue;if(this.devices.some(i=>i.deviceId===n))continue;this.lastSeen.delete(n);this.capabilities.delete(n);this.health.delete(n);this.devServerOrigins.delete(n);this.devServerRoots.delete(n);this.originProbed.delete(n);const r=`${n}::`;for(const i of[...this.snapshots.keys()]){if(i.startsWith(r)){this.snapshots.delete(i);this.snapshotAt.delete(i)}}for(const i of[...this.watching.keys()]){if(i.startsWith(r))this.watching.delete(i)}}}async stop(){this.setAdmission(false);this.hostAccount?.stop();this.hostAccount=null;for(const[,e]of this.pendingActions){clearTimeout(e.timer);e.reject(new Error("SyncClient stopped"))}this.pendingActions.clear();for(const[,e]of this.snapshotWaiters)for(const n of e)n(void 0);this.snapshotWaiters.clear();this.socket?.close();this.socket=null;if(this.broker){await this.broker.close();this.broker=null}}listDevices(){if(!this.admitted)return[];return this.devices.filter(e=>e.deviceName!==DASHBOARD_NAME&&e.deviceId).map(e=>{const n=this.capabilities.get(e.deviceId);return{deviceId:e.deviceId,deviceName:e.deviceName,platform:e.platform,isConnected:e.isConnected!==false,isPro:e.isPro===true,tier:e.tier==="free"||e.tier==="pro"?e.tier:e.tier===void 0&&e.isPro===true?"pro":"locked",collision:e.collision===true,tools:n?.tools??[]}})}connectedDevices(){return this.listDevices().filter(e=>e.isConnected)}toolActions(e){return this.listDevices().map(n=>{const t=n.tools.find(r=>r.toolId===e);return t?{deviceId:n.deviceId,deviceName:n.deviceName,actions:t.actions}:null}).filter(n=>n!==null)}resolveDevice(e){this.requireAdmission();if(e){this.requireDeviceAccount(e);return e}const n=(u,l)=>new Error(`${NOT_READY_MARK} "${u}" (${l}) is not connected right now. If it is restarting, it usually takes a few seconds; to use another device, pass deviceId (run list_devices to see them).`);if(this.sessionDevice){const u=this.devices.find(l=>l.deviceId===this.sessionDevice);if(u&&u.isConnected!==false)return this.sessionDevice;throw n(this.sessionDevice,"the device this session was using")}const t=this.connectedDevices();const r=t.filter(u=>!this.lockedDevices.has(u.deviceId));const i=r.filter(u=>u.tools.length>0);const s=process.env.BUOY_PROJECT_ROOT||process.cwd();const o=pickByProject(i.map(u=>({deviceId:u.deviceId,root:this.devServerRoots.get(u.deviceId)})),s);if(o)return this.sessionDevice=o;const a=pickByProject(this.devices.filter(u=>u.deviceId&&u.isConnected===false&&!this.lockedDevices.has(u.deviceId)).map(u=>({deviceId:u.deviceId,root:this.devServerRoots.get(u.deviceId)})),s);if(a)throw n(a,"this project's app");if(r.length===0){if(t.length>0){throw new Error(`Devices are connected (${t.map(u=>u.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(r.length===1)return this.sessionDevice=r[0].deviceId;if(i.length===1)return this.sessionDevice=i[0].deviceId;if(i.length===0){const u=r.map(l=>l.deviceName).join(", ");throw new Error(`Connected devices (${u}) are not exposing any Buoy tools yet. Make sure the app is in the foreground with devtools mounted, then retry.`)}const c=i.map(u=>`${u.deviceName} (${u.deviceId})`).join(", ");throw new Error(`Multiple devices connected \u2014 specify deviceId. Connected: ${c}`)}requireProDevice(e){this.requireAdmission();if(e&&e!==ALL_DEVICES)this.sessionDevice=e;const n=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.${n(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===ALL_DEVICES){if(!this.connectedDevices().some(s=>s.isPro))throw new Error(t());return ALL_DEVICES}const r=this.resolveDevice(e);const i=this.connectedDevices().find(s=>s.deviceId===r);if(!i?.isPro){const s=this.accessState(r);if(s==="offline")throw new Error(`${NOT_READY_MARK} "${r}" is not connected right now. If the app is starting or reloading, it usually takes a few seconds. Run list_devices to check.`);if(s==="pending")throw new Error(`${NOT_READY_MARK} account access for "${r}" is still being confirmed (the app just connected). Try again in a moment.`);throw new Error(t(i))}return r}accessState(e){const n=this.devices.find(t=>t.deviceId===e);if(!n||n.isConnected===false)return"offline";if(n.isPro===true)return"ready";return n.tier===void 0?"pending":"denied"}healthOf(e){let n=this.health.get(e);if(!n){n={consecutiveTimeouts:0,lastOkAt:0,lastFullBudgetAt:0};this.health.set(e,n)}return n}noteOk(e){const n=this.healthOf(e);n.consecutiveTimeouts=0;n.lastOkAt=Date.now()}noteTimeout(e){this.healthOf(e).consecutiveTimeouts+=1}isUnresponsive(e){return isUnresponsive(this.healthOf(e).consecutiveTimeouts)}timeoutFor(e,n,t){const r=this.healthOf(e);const{timeoutMs:i,usedFullBudget:s}=actionTimeoutMs({consecutiveTimeouts:r.consecutiveTimeouts,lastFullBudgetAt:r.lastFullBudgetAt,now:Date.now(),fullMs:this.actionTimeoutMs,shortMs:UNRESPONSIVE_ACTION_TIMEOUT_MS,recoveryProbeMs:RECOVERY_PROBE_MS,toolId:n,action:t});if(s)r.lastFullBudgetAt=Date.now();return i}unresponsiveNote(e){const n=this.healthOf(e);const t=n.lastOkAt?Math.round((Date.now()-n.lastOkAt)/1e3):null;const r=diagnoseCrashed({consecutiveTimeouts:n.consecutiveTimeouts,lastOkAt:n.lastOkAt,now:Date.now(),unresponsiveAfterMs:UNRESPONSIVE_AFTER_MS});const i=[`The app on "${e}" is not responding (${n.consecutiveTimeouts} call${n.consecutiveTimeouts===1?"":"s"} unanswered${t!=null?`, last answered ${t}s ago`:""}).`,r?"It is most likely CRASHED \u2014 a fatal render error unmounts the React tree, and the dev tools live in that tree, so nothing on-device can answer until the app is reloaded.":"It may be busy, mid-reload, or crashing."];const s=this.lastFatalFor(e);if(s)i.push(`Last captured error: ${s}`);i.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 i.join(" ")}noteCrashReport(e,n){const t=n?.entries;if(!Array.isArray(t)||t.length===0)return;const r=Math.max(...t.map(o=>typeof o?.timestamp==="number"?o.timestamp:-Infinity));const i=this.crashSeen.get(e)??new Set;let s=false;for(const o of t){const a=o?.fatal||/^\[(RENDER ERROR|FATAL)/.test(o?.message??"");if(!a||typeof o.timestamp!=="number")continue;const c=`${o.id??""}|${o.timestamp}|${(o.message??"").slice(0,120)}`;if(i.has(c))continue;i.add(c);if(r-o.timestamp<3e4)s=true}if(i.size>200)for(const o of[...i].slice(0,i.size-200))i.delete(o);this.crashSeen.set(e,i);if(!s)return;if(![...this.pendingActions.values()].some(o=>o.target===e&&o.expire&&!o.cut))return;void this.callAction("app","ping",{},e,{timeoutMs:1500,silent:true}).then(()=>void 0,()=>{const o=Date.now();for(const a of this.pendingActions.values()){if(a.target!==e||!a.expire||a.cut)continue;a.cut=true;if(a.deadline!==void 0&&a.deadline-o<=UNRESPONSIVE_ACTION_TIMEOUT_MS)continue;clearTimeout(a.timer);a.timer=setTimeout(a.expire,UNRESPONSIVE_ACTION_TIMEOUT_MS)}})}lastFatalFor(e){const n=this.snapshots.get(snapKey(e,"console"));const t=n?.entries;if(!Array.isArray(t))return null;for(let r=t.length-1;r>=0;r--){const i=t[r];if(i?.fatal||i?.level==="error"){const s=(i.message??"").split("\n")[0];if(s)return s.length>300?`${s.slice(0,300)}\u2026`:s}}return null}snapshotAgeMs(e,n){this.requireAdmission();const t=this.snapshotAt.get(snapKey(n,e));return t?Date.now()-t:null}noteDevServerOrigin(e,n){if(typeof n==="string"&&/^https?:\/\//.test(n)){const t=this.devServerOrigins.get(e)!==n;this.devServerOrigins.set(e,n);if(t)this.devServerRoots.delete(e);if(t||!this.devServerRoots.has(e)){const r=devServerRoot(n).then(i=>{if(i&&this.devServerOrigins.get(e)===n)this.devServerRoots.set(e,i)});this.trackRootLookup(r)}}}async learnDevServerOrigin(e){if(this.devServerOrigins.has(e)||this.originProbed.has(e))return;this.originProbed.add(e);const n=this.capabilities.get(e)?.tools?.some(t=>t.toolId==="app");if(!n)return;try{const{payload:t}=await this.getSnapshot("app",e,{timeoutMs:4e3,silent:true});this.noteDevServerOrigin(e,t?.devServerOrigin)}catch{}}trackRootLookup(e){const n=e.catch(()=>void 0).finally(()=>this.rootLookups.delete(n));this.rootLookups.add(n)}async awaitBroker(){if(Date.now()-this.createdAt>15e3)return;for(let e=0;!this.admitted&&e<4e3;e+=100)await new Promise(n=>setTimeout(n,100));for(let e=0;this.admitted&&this.devices.length===0&&e<1500;e+=100)await new Promise(n=>setTimeout(n,100))}async settleDeviceChoice(e=1500){await this.awaitBroker();if(this.sessionDevice||this.rootLookups.size===0||this.connectedDevices().length<2)return;await Promise.race([Promise.all([...this.rootLookups]),new Promise(n=>setTimeout(n,e))]);if(this.rootLookups.size)await Promise.race([Promise.all([...this.rootLookups]),new Promise(n=>setTimeout(n,Math.min(800,e)))])}devServerOrigin(e){this.requireAdmission();const n=this.devServerOrigins.get(e);if(n)return n;const t=this.snapshots.get(snapKey(e,"app"));if(typeof t?.devServerOrigin==="string")return t.devServerOrigin;return null}ensureWatching(e,n){const t=snapKey(n,e);if(this.watching.has(t))return;this.watching.set(t,{toolId:e,targetDeviceId:n});this.sendWatch(e,n)}sendWatch(e,n){if(!this.admitted||!this.socket?.connected||this.lockedDevices.has(n))return;this.socket?.emit("devtool-watch",{toolId:e,targetDeviceId:n,watching:true,stream:false})}rearmWatches(){for(const{toolId:e,targetDeviceId:n}of this.watching.values()){this.sendWatch(e,n)}}rearmReconnectedDevices(e){for(const n of e){if(!n.deviceId||n.isConnected===false)continue;const t=String(n.deviceId);const r=`${n.id}|${n.connectionNonce??""}`;const i=this.deviceConnections.get(t);this.deviceConnections.set(t,r);if(i===void 0||i===r)continue;for(const{toolId:s,targetDeviceId:o}of this.watching.values()){if(o===t)this.sendWatch(s,o)}}}unwatch(e,n){const t=snapKey(n,e);if(!this.watching.delete(t))return;if(this.admitted&&this.socket?.connected)this.socket.emit("devtool-watch",{toolId:e,targetDeviceId:n,watching:false})}cachedSnapshot(e,n){this.requireAdmission();this.requireDeviceAccount(n);return this.snapshots.get(snapKey(n,e))}async getSnapshot(e,n,t={}){const r=this.resolveDevice(n);const i=snapKey(r,e);this.ensureWatching(e,r);let s=t.timeoutMs??DEFAULT_SNAPSHOT_TIMEOUT_MS;if(t.timeoutMs===void 0&&this.isUnresponsive(r)){const u=this.healthOf(r);if(Date.now()-u.lastFullBudgetAt>RECOVERY_PROBE_MS){u.lastFullBudgetAt=Date.now()}else{s=UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS}}const o=this.waitForSnapshot(i,s);this.socket?.emit("request-devtool-state",{toolId:e,targetDeviceId:r});const a=await o;this.requireAdmission();this.requireDeviceAccount(r);if(a!==void 0){if(!t.silent)this.noteOk(r);return{deviceId:r,payload:a}}if(!t.silent)this.noteTimeout(r);const c=this.snapshots.get(i);if(c!==void 0){return{deviceId:r,payload:c,stale:this.staleNote(e,r)}}throw new Error(`Timed out waiting for "${e}" state from ${r} (is the tool active?). ${this.unresponsiveNote(r)}`)}lastSync(e,n){const t=this.snapshots.get(snapKey(e,n));return t===void 0?void 0:{payload:t,ageMs:this.snapshotAgeMs(n,e)}}staleNote(e,n){const t=this.snapshotAgeMs(e,n);const r=t==null?"an earlier sync":`${Math.round(t/1e3)}s ago`;return`\u26A0\uFE0F Served from the last sync (${r}) \u2014 ${this.unresponsiveNote(n)}`}waitForSnapshot(e,n){return new Promise(t=>{const r=this.snapshotWaiters.get(e)??[];const i=setTimeout(()=>{const o=(this.snapshotWaiters.get(e)??[]).filter(a=>a!==s);this.snapshotWaiters.set(e,o);t(void 0)},n);const s=o=>{clearTimeout(i);t(o)};r.push(s);this.snapshotWaiters.set(e,r)})}async callAction(e,n,t,r,i={}){this.requireAdmission();const s=r===ALL_DEVICES?ALL_DEVICES:this.resolveDevice(r);if(!this.socket)throw new Error("SyncClient is not connected");const o=(0,import_node_crypto3.randomUUID)();const a=i.timeoutMs??this.timeoutFor(s,e,n);const c=await new Promise((u,l)=>{const d=Date.now();const h=()=>{this.pendingActions.delete(o);if(s!==ALL_DEVICES&&!i.silent)this.noteTimeout(s);l(new Error(`Action "${e}.${n}" got no answer in ${Date.now()-d}ms. `+(s===ALL_DEVICES?"No device responded.":this.unresponsiveNote(s))))};const p=setTimeout(h,a);this.pendingActions.set(o,{resolve:u,reject:l,timer:p,target:s,expire:h,deadline:d+a});this.socket.emit("devtool-action",{requestId:o,toolId:e,targetDeviceId:s,action:n,params:t??{}})});if(s!==ALL_DEVICES&&!i.silent)this.noteOk(s);if(!c.ok){throw new Error(c.error||`Action "${e}.${n}" failed on device`)}return c.result}};snapKey=(e,n)=>`${e}::${n}`;delay=e=>new Promise(n=>setTimeout(n,e))}});var VERSION,PACKAGE_NAME;var init_version=__esm({"src/version.ts"(){"use strict";VERSION="7.0.61"?"7.0.61":"0.0.0-dev";PACKAGE_NAME="@buoy-gg/mcp"}});function isNewer(e,n){const t=s=>s.split("-")[0].split(".").map(o=>Number(o)||0);const r=t(e);const i=t(n);for(let s=0;s<3;s++){const o=r[s]??0;const a=i[s]??0;if(o>a)return true;if(o<a)return false}return false}async function readCache(){try{const e=await import_node_fs4.promises.readFile(CACHE_FILE,"utf8");const n=JSON.parse(e);if(typeof n.checkedAt==="number"&&typeof n.latest==="string"){return n}}catch{}return null}async function fetchLatest(e){const n=new AbortController;const t=setTimeout(()=>n.abort(),FETCH_TIMEOUT_MS);try{const r=await fetch(REGISTRY_URL,{signal:n.signal});if(!r.ok)return null;const i=await r.json();const s=typeof i.version==="string"?i.version:null;if(s){await import_node_fs4.promises.writeFile(CACHE_FILE,JSON.stringify({checkedAt:e,latest:s})).catch(()=>{})}return s}catch{return null}finally{clearTimeout(t)}}async function resolveLatest(e){const n=await readCache();if(n&&e-n.checkedAt<CHECK_TTL_MS)return n.latest;return fetchLatest(e)}async function getUpdateNotice(e=Date.now()){if(VERSION==="0.0.0-dev")return null;try{const n=await resolveLatest(e);if(n&&isNewer(n,VERSION)){return`A newer buoy-mcp is available (${n}; you're on ${VERSION}). Update by re-running: npx -y ${PACKAGE_NAME}@latest init \u2014 then restart your editor.`}}catch{}return null}var import_node_fs4,import_node_os4,import_node_path5,CHECK_TTL_MS,FETCH_TIMEOUT_MS,REGISTRY_URL,CACHE_FILE;var init_checkForUpdate=__esm({"src/update/checkForUpdate.ts"(){"use strict";import_node_fs4=require("fs");import_node_os4=__toESM(require("os"));import_node_path5=__toESM(require("path"));init_version();CHECK_TTL_MS=24*60*60*1e3;FETCH_TIMEOUT_MS=1500;REGISTRY_URL=`https://registry.npmjs.org/${PACKAGE_NAME}/latest`;CACHE_FILE=import_node_path5.default.join(import_node_os4.default.tmpdir(),"buoy-mcp-update-check.json")}});function humanizeSimctlError(e){const n=e;if(n?.code==="ENOENT"){return"Xcode command-line tools (xcrun) not found. Install Xcode to capture the iOS Simulator."}const t=String(n?.stderr||n?.message||e);if(/No devices are booted|Unable to find device|current device/i.test(t)){return"No booted iOS Simulator found. Boot the Simulator with your app running, then try again."}return t.trim()||"Failed to capture the iOS Simulator."}function pngSize(e){const n=[137,80,78,71,13,10,26,10];if(e.length<24||!n.every((t,r)=>e[r]===t))return null;return{width:e.readUInt32BE(16),height:e.readUInt32BE(20)}}async function listDir(e){try{return await import_node_fs5.promises.readdir(e)}catch{return[]}}async function webViewInstallIds(e){const n=[];for(const t of await listDir(e))n.push(...await containerWebViewInstallIds(import_node_path6.default.join(e,t)));return n}async function containerWebViewInstallIds(e){const n=[];const t=import_node_path6.default.join(e,"Library","WebKit");for(const r of await listDir(t)){const i=import_node_path6.default.join(t,r,"WebsiteData","Default");for(const s of await listDir(i)){for(const o of await listDir(import_node_path6.default.join(i,s))){const a=import_node_path6.default.join(i,s,o,"LocalStorage","localstorage.sqlite3");try{await import_node_fs5.promises.access(a);const{stdout:c}=await execFileAsync4("sqlite3",["-readonly",a,`SELECT hex(value) FROM ItemTable WHERE key='${WEBVIEW_ID_KEY}' LIMIT 1;`],{timeout:1500});const u=c.trim();if(u)n.push(Buffer.from(u,"hex").toString("utf16le").trim())}catch{}}}}return n}async function resolveSimUdid(e){if(process.platform!=="darwin")return{ok:false,error:"Simulator lookup needs macOS."};let n=[];try{const{stdout:r}=await execFileAsync4("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const i=JSON.parse(r).devices;n=Object.entries(i).filter(([s])=>/iOS/.test(s)).flatMap(([,s])=>s.filter(o=>o.state==="Booted"))}catch(r){return{ok:false,error:humanizeSimctlError(r)}}if(n.length===0)return{ok:false,error:"No iOS Simulator is booted."};const t=e?.split("-").pop();if(t){for(const r of n){if(!r.dataPath)continue;const i=import_node_path6.default.join(r.dataPath,"Containers","Data","Application");let s=[];try{s=await import_node_fs5.promises.readdir(i)}catch{continue}for(const o of s){try{const a=(await import_node_fs5.promises.readFile(import_node_path6.default.join(i,o,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim();if(a===t)return{ok:true,udid:r.udid,how:`matched ${e} to "${r.name}"`}}catch{}}}}if(t&&e){const r=n.map(c=>c.udid).sort().join(",");const i=webViewLookups.get(e);const s=i?.booted===r&&(i.udid!==null||Date.now()-i.at<WEBVIEW_MISS_MS);const o=s&&i?.udid?n.find(c=>c.udid===i.udid):void 0;if(o)return{ok:true,udid:o.udid,how:`matched ${e} to "${o.name}" (WebView storage)`};const a=[];if(!s){const c=await Promise.all(n.map(u=>u.dataPath?webViewInstallIds(import_node_path6.default.join(u.dataPath,"Containers","Data","Application")):Promise.resolve([])));c.forEach((u,l)=>{if(u.includes(t))a.push(n[l])});webViewLookups.set(e,{booted:r,udid:a.length===1?a[0].udid:null,at:Date.now()})}if(a.length===1){return{ok:true,udid:a[0].udid,how:`matched ${e} to "${a[0].name}" (WebView storage)`}}if(a.length>1){return{ok:false,error:`${a.length} booted simulators (${a.map(c=>c.name).join(", ")}) hold ${e}. Pass the udid, or shut one down.`}}}if(n.length===1)return{ok:true,udid:n[0].udid,how:`only booted simulator "${n[0].name}"`};return{ok:false,error:`${n.length} iOS Simulators are booted (${n.map(r=>r.name).join(", ")}) and none could be matched to ${e??"this device"}. Shut down the others, or capture from a single booted simulator.`}}async function resolveSims(e){const n=new Map;if(process.platform!=="darwin"||e.length===0)return n;let t=[];try{const{stdout:i}=await execFileAsync4("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const s=JSON.parse(i).devices;t=Object.entries(s).filter(([o])=>/iOS/.test(o)).flatMap(([,o])=>o.filter(a=>a.state==="Booted"))}catch{return n}const r=new Map;for(const i of t){if(!i.dataPath)continue;const s=import_node_path6.default.join(i.dataPath,"Containers","Data","Application");let o=[];try{o=await import_node_fs5.promises.readdir(s)}catch{continue}for(const a of o){try{const c=(await import_node_fs5.promises.readFile(import_node_path6.default.join(s,a,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim();if(c)r.set(c,{name:i.name,udid:i.udid})}catch{}}}for(const i of e){const s=r.get(i.split("-").pop()??"");if(s)n.set(i,s)}return n}async function captureIosFramebuffer(e="booted"){if(process.platform!=="darwin"){return{ok:false,error:"Screenshotting a component requires macOS with Xcode's iOS Simulator (uses `xcrun simctl`)."}}const n=import_node_path6.default.join(import_node_os5.default.tmpdir(),`buoy-mcp-sim-${(0,import_node_crypto4.randomUUID)()}.png`);try{await execFileAsync4("xcrun",["simctl","io",e,"screenshot","--type=png",n],{timeout:15e3})}catch(t){return{ok:false,error:humanizeSimctlError(t)}}try{const t=await import_node_fs5.promises.readFile(n);const r=pngSize(t);if(!r)return{ok:false,error:"Captured file wasn't a valid PNG."};return{ok:true,srcPath:n,width:r.width,height:r.height}}catch(t){return{ok:false,error:`Failed to read screenshot: ${t.message}`}}}async function cropToBuffer(e,n,t){const r=clamp(Math.round(t.x),0,Math.max(0,n.width-1));const i=clamp(Math.round(t.y),0,Math.max(0,n.height-1));const s=clamp(Math.round(t.width),1,n.width-r);const o=clamp(Math.round(t.height),1,n.height-i);const a=import_node_path6.default.join(import_node_os5.default.tmpdir(),`buoy-mcp-crop-${(0,import_node_crypto4.randomUUID)()}.png`);try{await execFileAsync4("sips",["-c",String(o),String(s),"--cropOffset",String(i),String(r),e,"--out",a],{timeout:1e4});const c=await import_node_fs5.promises.readFile(a);return{ok:true,buffer:c,width:s,height:o}}catch(c){const u=c;return{ok:false,error:`Crop failed: ${u?.stderr||u?.message||c}`}}finally{await import_node_fs5.promises.unlink(a).catch(()=>{});await import_node_fs5.promises.unlink(e).catch(()=>{})}}var import_node_child_process5,import_node_util4,import_node_fs5,import_node_os5,import_node_path6,import_node_crypto4,execFileAsync4,clamp,WEBVIEW_ID_KEY,webViewLookups,WEBVIEW_MISS_MS;var init_simctl=__esm({"src/capture/simctl.ts"(){"use strict";import_node_child_process5=require("child_process");import_node_util4=require("util");import_node_fs5=require("fs");import_node_os5=__toESM(require("os"));import_node_path6=__toESM(require("path"));import_node_crypto4=require("crypto");execFileAsync4=(0,import_node_util4.promisify)(import_node_child_process5.execFile);clamp=(e,n,t)=>Math.min(Math.max(e,n),t);WEBVIEW_ID_KEY="@react_buoy_sync_device_id";webViewLookups=new Map;WEBVIEW_MISS_MS=3e4}});async function listDir2(e){return import_node_fs6.promises.readdir(e).catch(()=>[])}async function containerLocalStorageFiles(e){const n=[];const t=import_node_path7.default.join(e,"Library","WebKit");for(const r of await listDir2(t)){const i=import_node_path7.default.join(t,r,"WebsiteData","Default");for(const s of await listDir2(i)){for(const o of await listDir2(import_node_path7.default.join(i,s))){const a=import_node_path7.default.join(i,s,o);const c=import_node_path7.default.join(a,"LocalStorage","localstorage.sqlite3");if(!await import_node_fs6.promises.access(c).then(()=>true,()=>false))continue;const u=await import_node_fs6.promises.readFile(import_node_path7.default.join(a,"origin")).then(l=>l.toString("hex"),()=>"");if(u)n.push({db:c,origin:u})}}}return n}async function iosReadWebKeep(e){const n=[];for(const{db:t,origin:r}of await containerLocalStorageFiles(e)){const i=await sqlite(t,"SELECT key, hex(value) FROM ItemTable;");for(const s of i.split("\n")){const o=s.lastIndexOf("|");if(o<0)continue;const a=s.slice(0,o);if(WEB_KEEP_KEY.test(a))n.push({key:a,value:s.slice(o+1),origin:r})}}return n}async function iosWriteWebKeep(e,n){if(!n.length)return false;const t=await containerLocalStorageFiles(e);const r=new Set(n.map(i=>i.origin??""));for(const i of r){const s=i?t.find(a=>a.origin===i):void 0;if(!s)return false;const o=n.filter(a=>(a.origin??"")===i&&/^[0-9A-F]*$/i.test(a.value)).map(a=>`('${a.key.replace(/'/g,"''")}', X'${a.value}')`).join(",");if(o)await sqlite(s.db,`INSERT OR REPLACE INTO ItemTable (key, value) VALUES ${o};`,false)}return true}async function iosWaitForLocalStorage(e,n=15e3){const t=Date.now()+n;while(Date.now()<t){if((await containerLocalStorageFiles(e)).length)return true;await new Promise(r=>setTimeout(r,500))}return false}async function evaluateInWebView(e,n,t){const r=(await adbShell(e,`pidof ${n}`).catch(()=>"")).trim().split(/\s+/)[0];if(!r)throw new Error("the app is not running");const i=(await adb(e,["forward","tcp:0",`localabstract:webview_devtools_remote_${r}`])).trim();try{const s=await(await fetch(`http://127.0.0.1:${i}/json`)).json();const o=s.find(a=>a.type==="page"&&a.webSocketDebuggerUrl);if(!o?.webSocketDebuggerUrl)throw new Error("no debuggable WebView page (needs a debug build)");return await new Promise((a,c)=>{const u=new import_ws.WebSocket(o.webSocketDebuggerUrl);const l=setTimeout(()=>{u.close();c(new Error("the WebView did not answer"))},5e3);u.on("open",()=>u.send(JSON.stringify({id:1,method:"Runtime.evaluate",params:{expression:t,returnByValue:true}})));u.on("message",d=>{const h=JSON.parse(String(d));if(h.id!==1)return;clearTimeout(l);u.close();if(h.result?.exceptionDetails)c(new Error("the WebView script failed"));else a(h.result?.result?.value)});u.on("error",d=>{clearTimeout(l);c(d)})})}finally{await adb(e,["forward","--remove",`tcp:${i}`]).catch(()=>void 0)}}async function evaluateWhenReady(e,n,t,r=15e3){const i=Date.now()+r;let s;while(Date.now()<i){try{return await evaluateInWebView(e,n,t)}catch(o){s=o;await new Promise(a=>setTimeout(a,700))}}throw s instanceof Error?s:new Error("the WebView did not open")}async function androidHasWebViewStorage(e,n){const t=await adbShell(e,`run-as ${n} sh -c 'ls app_webview/Default/"Local Storage"/leveldb 2>/dev/null'`).catch(()=>"");return/CURRENT|\.log/.test(t)}async function androidReadWebKeep(e,n){if(!(await adbShell(e,`pidof ${n}`).catch(()=>"")).trim()){await adbShell(e,`monkey -p ${n} -c android.intent.category.LAUNCHER 1`)}const t=await evaluateWhenReady(e,n,`(() => { const re = ${WEB_KEEP_KEY}; const out = []; for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (k && re.test(k)) out.push({ key: k, value: localStorage.getItem(k) }); } return out; })()`);return Array.isArray(t)?t.filter(r=>typeof r.key==="string"&&typeof r.value==="string"):[]}async function androidWriteWebKeep(e,n,t){await evaluateWhenReady(e,n,`(() => { for (const r of ${JSON.stringify(t)}) localStorage.setItem(r.key, r.value); setTimeout(() => location.reload(), 50); return true; })()`)}var import_node_child_process6,import_node_util5,import_node_fs6,import_node_path7,import_ws,execFileAsync5,WEB_KEEP_KEY,sqlite;var init_webViewKeep=__esm({"src/capture/webViewKeep.ts"(){"use strict";import_node_child_process6=require("child_process");import_node_util5=require("util");import_node_fs6=require("fs");import_node_path7=__toESM(require("path"));import_ws=require("ws");init_adb();execFileAsync5=(0,import_node_util5.promisify)(import_node_child_process6.execFile);WEB_KEEP_KEY=/^(@buoy\/session:|buoy-gg-license|buoy-gg-device-fingerprint$|@react_buoy_sync_device_id$|@react_buoy_install)/;sqlite=(e,n,t=true)=>execFileAsync5("sqlite3",[...t?["-readonly"]:[],e,n],{timeout:5e3}).then(r=>r.stdout)}});function rememberedHost(e){return hosts.get(e)}async function sh(e,n,t=2e4){try{const{stdout:r}=await execFileAsync6(e,n,{timeout:t,maxBuffer:16*1024*1024});return r}catch(r){const i=r;if(i.code==="ENOENT")throw new Error(e==="xcrun"?"This needs macOS with Xcode (xcrun simctl).":`${e} is not installed.`);throw new Error(`${e} ${n.slice(0,2).join(" ")} failed: ${(i.stderr||i.message||"").trim().slice(0,300)}`)}}async function simsHolding(e){let n=[];try{const r=JSON.parse(await simctl(["list","devices","booted","-j"])).devices;n=Object.entries(r).filter(([i])=>/iOS/.test(i)).flatMap(([,i])=>i.filter(s=>s.state==="Booted"))}catch{return[]}const t=[];for(const r of n)if(await findIosContainer(e,r.udid))t.push(r);return t}function cloneError(e,n){return new Error(`${n.length} booted simulators hold "${e}" (one is probably a clone): ${n.map(t=>`${t.name} (${t.udid})`).join(", ")}. Pass udid to choose, or shut the extra one down.`)}async function findIosContainer(e,n){const t=tailOf(e);if(!t)return null;let r;try{const o=JSON.parse(await simctl(["list","devices","-j"])).devices;r=Object.values(o).flat().find(a=>a.udid===n)?.dataPath}catch{return null}if(!r)return null;const i=import_node_path8.default.join(r,"Containers","Data","Application");let s=[];try{s=await import_node_fs7.promises.readdir(i)}catch{return null}for(const o of s){const a=import_node_path8.default.join(i,o);if(!await iosContainerHolds(a,t))continue;let c=null;try{c=(await sh("plutil",["-extract","MCMMetadataIdentifier","raw","-o","-",import_node_path8.default.join(a,".com.apple.mobile_container_manager.metadata.plist")])).trim()||null}catch{}return{container:a,bundleId:c}}return null}async function iosContainerHolds(e,n){try{if((await import_node_fs7.promises.readFile(import_node_path8.default.join(e,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim()===n)return true}catch{}return(await containerWebViewInstallIds(e).catch(()=>[])).includes(n)}async function findAndroid(e,n){const t=tailOf(e);const r=n.serial?[n.serial]:await adbSerials();if(r.length===0)throw new Error("No Android device or emulator is connected to adb.");for(const i of r){const s=await adbForegroundPackage(i).catch(()=>null);const o=await adbUserPackages(i).catch(()=>[]);const a=[n.bundleId,s,...o].filter((c,u,l)=>!!c&&l.indexOf(c)===u).slice(0,80);for(const c of a){if(await adbInstallId(i,c).catch(()=>null)===t)return{platform:"android",serial:i,packageName:c}}}return null}async function findPhone(e){const n=tailOf(e);for(const t of await physicalPhones()){for(const r of await developerApps(t.udid).catch(()=>[])){if(await phoneInstallId(t.udid,r.bundleId)===n)return{platform:"ios-device",udid:t.udid,name:t.name,bundleId:r.bundleId}}}return null}async function findHost(e,n,t={}){if(e==="All")throw new Error('Device control acts on one app. Pass its deviceId, not "All".');const r=hosts.get(e);if(r&&!t.udid&&!t.serial&&await stillHolds(e,r)){if(r.platform==="ios"&&!r.picked){const c=await simsHolding(e);if(c.length>1)throw cloneError(e,c)}return r}if(r)hosts.delete(e);if(n==="android"){const c=await findAndroid(e,t);if(!c){throw new Error(`Could not prove which Android device and app run "${e}". Buoy checks the app's install id with run-as, which needs a debug build of the app on a device adb can reach${t.serial?` (looked on ${t.serial})`:""}.`)}hosts.set(e,c);return c}if(n&&n!=="ios")throw new Error(`Device control works on iOS Simulators and Android. This app runs on "${n}".`);if(process.platform!=="darwin")throw new Error("iOS control needs macOS with Xcode.");let i=t.udid;let s=i??"";if(!i){const c=await simsHolding(e);if(c.length>1)throw cloneError(e,c);const u=c.length===1?{ok:true,udid:c[0].udid,how:`matched ${e} to "${c[0].name}"`}:await resolveSimUdid(e);if(!u.ok||!/^matched /.test(u.how)){const l=await findPhone(e).catch(()=>null);if(l){hosts.set(e,l);return l}throw new Error(`Could not find which simulator or iPhone runs "${e}": no booted simulator holds its install id, and no connected iPhone has it (an iPhone must be unlocked, paired, and run a development build).`)}i=u.udid;s=/"([^"]+)"/.exec(u.how)?.[1]??i}const o=await findIosContainer(e,i);if(!o&&t.udid)throw new Error(`Simulator ${t.udid} does not hold "${e}".`);const a={platform:"ios",udid:i,name:s,bundleId:t.bundleId??o?.bundleId??null,container:o?.container??null,picked:!!t.udid};hosts.set(e,a);return a}async function verifyHost(e,n){if(n.platform==="ios"&&!n.picked){const t=await simsHolding(e);if(t.length>1)throw cloneError(e,t)}if(await stillHolds(e,n))return n;hosts.delete(e);return findHost(e,n.platform==="android"?"android":"ios",n.platform==="ios"&&n.picked?{udid:n.udid}:{})}async function stillHolds(e,n){const t=tailOf(e);if(n.platform==="android")return await adbInstallId(n.serial,n.packageName).catch(()=>null)===t;if(n.platform==="ios-device")return await phoneInstallId(n.udid,n.bundleId).catch(()=>null)===t;if(n.container)return iosContainerHolds(n.container,t);const r=await resolveSimUdid(e);return r.ok&&r.udid===n.udid&&/^matched /.test(r.how)}function needApp(e){if(e.platform==="android")return assertPackage(e.packageName);if(e.platform==="ios-device")return e.bundleId;if(!e.bundleId)throw new Error("Could not tell which app this is on the simulator (its container has no bundle metadata).");return e.bundleId}async function hostPng(e){if(e.platform==="android")return adbScreenshot(e.serial);if(e.platform==="ios-device")return phoneScreenshot(e.udid);const n=await captureIosFramebuffer(e.udid);if(!n.ok||!n.srcPath)throw new Error(n.error??"Screenshot failed.");try{return await import_node_fs7.promises.readFile(n.srcPath)}finally{await import_node_fs7.promises.unlink(n.srcPath).catch(()=>{})}}async function toSmallImage(e,n=1280){if(process.platform==="darwin"){const i=import_node_path8.default.join(import_node_os6.default.tmpdir(),`buoy-mcp-img-${(0,import_node_crypto5.randomUUID)()}.png`);const s=i.replace(/\.png$/,".jpg");await import_node_fs7.promises.writeFile(i,e);try{await sh("sips",["-Z",String(n),"-s","format","jpeg","-s","formatOptions","70",i,"--out",s],15e3);const o=await sh("sips",["-g","pixelWidth","-g","pixelHeight",s]);return{data:(await import_node_fs7.promises.readFile(s)).toString("base64"),mimeType:"image/jpeg",width:Number(/pixelWidth:\s*(\d+)/.exec(o)?.[1]??0),height:Number(/pixelHeight:\s*(\d+)/.exec(o)?.[1]??0)}}finally{await import_node_fs7.promises.unlink(i).catch(()=>{});await import_node_fs7.promises.unlink(s).catch(()=>{})}}const t=downscalePng(import_pngjs2.PNG.sync.read(e),Math.min(n,1024));const r=import_pngjs2.PNG.sync.write(t,{colorType:2,deflateLevel:9});return{data:r.toString("base64"),mimeType:"image/png",width:t.width,height:t.height}}function downscalePng(e,n){const t=Math.min(1,n/Math.max(e.width,e.height));if(t===1)return e;const r=Math.max(1,Math.round(e.width*t));const i=Math.max(1,Math.round(e.height*t));const s=new import_pngjs2.PNG({width:r,height:i});const o=e.width/r;const a=e.height/i;for(let c=0;c<i;c++){const u=Math.floor(c*a);const l=Math.max(u+1,Math.floor((c+1)*a));for(let d=0;d<r;d++){const h=Math.floor(d*o);const p=Math.max(h+1,Math.floor((d+1)*o));const m=[0,0,0,0];let g=0;for(let f=u;f<l;f++){for(let b=h;b<p;b++){const v=(f*e.width+b)*4;for(let y=0;y<4;y++)m[y]+=e.data[v+y];g++}}const w=(c*r+d)*4;for(let f=0;f<4;f++)s.data[w+f]=Math.round(m[f]/g)}}return s}async function withSteadyStatusBar(e,n){let t=false;try{if(e.platform==="ios"){const r=await simctl(["status_bar",e.udid,"list"]).catch(()=>"");const i=r.split(/^=+$/m).slice(1).join("").trim();if(!i){await simctl(["status_bar",e.udid,"override","--time","9:41","--batteryState","charged","--batteryLevel","100","--wifiBars","3","--cellularBars","4"]);t=true}}else if(e.platform==="android"){const r=(await adbShell(e.serial,"settings get global sysui_demo_allowed").catch(()=>"")).trim();if(r!=="1"&&!steadying.has(e.serial)){steadying.add(e.serial);await adbDemoMode(e.serial,true);t=true}}if(t)await new Promise(r=>setTimeout(r,400))}catch{t=false}try{return{result:await n(),steadied:t}}finally{if(t){if(e.platform==="ios")await simctl(["status_bar",e.udid,"clear"]).catch(()=>void 0);else if(e.platform==="android"){await adbDemoMode(e.serial,false);await adbShell(e.serial,"settings put global sysui_demo_allowed 0").catch(()=>void 0);steadying.delete(e.serial)}}}}async function hostQuit(e){const n=needApp(e);if(e.platform==="ios-device"){const t=await phoneQuit(e.udid,n);return t?`Quit ${n}.`:`${n} was not running.`}if(e.platform==="ios"){await simctl(["terminate",e.udid,n]).catch(t=>{if(!/found nothing to terminate|not running/i.test(String(t)))throw t})}else{await adbShell(e.serial,`am force-stop ${q(n)}`)}return`Quit ${n}.`}async function hostLaunch(e){const n=needApp(e);if(e.platform==="ios")await simctl(["launch",e.udid,n]);else if(e.platform==="ios-device")await phoneLaunch(e.udid,n);else await adbShell(e.serial,`monkey -p ${q(n)} -c android.intent.category.LAUNCHER 1`);return`Launched ${n}.`}async function hostBackground(e){if(e.platform==="ios-device"){await phoneLaunch(e.udid,"com.apple.Preferences");return"Sent to the background for real (Settings opened on top)."}if(e.platform==="ios"){await simctl(["launch",e.udid,"com.apple.Preferences"]);return"Sent to the background for real (Settings opened on top)."}await adbShell(e.serial,"input keyevent 3");return"Sent to the background for real (pressed Home)."}async function hostOpenUrl(e,n){if(!/^[a-zA-Z][\w+.-]*:/.test(n))throw new Error(`"${n}" is not a link with a scheme (like https://\u2026 or myapp://\u2026).`);if(e.platform==="ios-device"){await phoneOpenUrl(e.udid,n);return"Opened through the OS on the iPhone."}if(e.platform==="ios"){await simctl(["openurl",e.udid,n]);return'Opened through the OS. A custom scheme may first show an "Open in" prompt on the simulator.'}await adbShell(e.serial,`am start -a android.intent.action.VIEW -d ${q(n)}`);return"Opened through the OS (an Android VIEW intent)."}async function appBundleInfo(e){const n=import_node_path8.default.join(e,"Info.plist");const t=o=>sh("plutil",["-extract",o,"raw","-o","-",n]).then(a=>a.trim()).catch(()=>"");const r=await t("CFBundleIdentifier");if(!r)throw new Error(`${e} has no Info.plist with a bundle id. Pass a built .app folder.`);const i=(await sh("plutil",["-extract","CFBundleSupportedPlatforms","json","-o","-",n]).catch(()=>"[]")).toLowerCase();const s=(await t("DTPlatformName")).toLowerCase();return{bundleId:r,simulator:i.includes("iphonesimulator")||s==="iphonesimulator"}}async function apkPackage(e){const n=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT,import_node_path8.default.join(import_node_os6.default.homedir(),"Library","Android","sdk"),import_node_path8.default.join(import_node_os6.default.homedir(),"Android","Sdk")].filter(t=>!!t);for(const t of n){const r=import_node_path8.default.join(t,"build-tools");const i=(await import_node_fs7.promises.readdir(r).catch(()=>[])).sort().reverse();for(const s of i){for(const o of["aapt2","aapt"]){const a=import_node_path8.default.join(r,s,o);try{await import_node_fs7.promises.access(a)}catch{continue}const c=await sh(a,o==="aapt2"?["dump","packagename",e]:["dump","badging",e]).catch(()=>"");const u=o==="aapt2"?c.trim().split("\n")[0]:/package: name='([^']+)'/.exec(c)?.[1]??"";if(u)return u}}}throw new Error("Could not read the APK's package name (needs aapt2 from the Android SDK build-tools). Nothing was changed.")}async function hostReinstall(e,n,t=true){const r=needApp(e);const i=import_node_path8.default.resolve(n);try{await import_node_fs7.promises.access(i)}catch{throw new Error(`No build at ${i}. Pass appPath: the built .app folder (iOS Simulator) or .apk file (Android). Nothing was changed.`)}if(e.platform==="android")return reinstallAndroid(e,r,i,t);if(e.platform==="ios-device")return reinstallPhone(e,r,i,t);if(!/\.app\/?$/i.test(i))throw new Error("On the iOS Simulator, appPath must be a built .app folder. Nothing was changed.");const s=await appBundleInfo(i);if(s.bundleId!==r)throw new Error(`${import_node_path8.default.basename(i)} is ${s.bundleId}, but this app is ${r}. Nothing was changed.`);if(!s.simulator)throw new Error(`${import_node_path8.default.basename(i)} is a device build, not a simulator build. Nothing was changed.`);const o=t?await import_node_fs7.promises.mkdtemp(import_node_path8.default.join(import_node_os6.default.tmpdir(),"buoy-mcp-keep-")):null;try{let a=false;let c=[];if(o){await import_node_fs7.promises.chmod(o,448);const l=(await simctl(["get_app_container",e.udid,r,"data"]).catch(()=>"")).trim();if(l)a=await copyBuoyFiles(import_node_path8.default.join(l,"Documents"),o);if(l&&!a){try{c=await iosReadWebKeep(l)}catch(d){throw new Error(`Couldn't read Buoy's sign-in from the app's WebView storage (${d.message}). Nothing was changed. Pass keepBuoy: false to reinstall anyway.`)}}}await simctl(["terminate",e.udid,r]).catch(()=>void 0);await simctl(["uninstall",e.udid,r]);try{await simctl(["install",e.udid,i],18e4)}catch(l){throw new Error(`The app was removed, but installing ${import_node_path8.default.basename(i)} failed: ${l.message}. Install it again by hand.`)}let u="";if(o&&a){try{const l=(await simctl(["get_app_container",e.udid,r,"data"])).trim();await copyBuoyFiles(o,import_node_path8.default.join(l,"Documents"));e.container=l;u=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(l){u=` Buoy's sign-in could not be restored (${l.message}): sign in to Buoy again in the app.`}}else if(c.length){try{const l=(await simctl(["get_app_container",e.udid,r,"data"])).trim();await simctl(["launch",e.udid,r]);const d=await iosWaitForLocalStorage(l);await simctl(["terminate",e.udid,r]).catch(()=>void 0);if(!d||!await iosWriteWebKeep(l,c))throw new Error("the app made no WebView storage");e.container=l;u=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(l){u=` Buoy's sign-in could not be restored (${l.message}): sign in to Buoy again in the app.`}}else if(t){u=" The old install had no Buoy sign-in to keep."}await simctl(["launch",e.udid,r]);return`Reinstalled ${r} from ${i} and launched it. The app's own data is gone, like a new user.${u}`}finally{if(o)await import_node_fs7.promises.rm(o,{recursive:true,force:true}).catch(()=>void 0)}}async function copyBuoyFiles(e,n){let t=false;for(const r of BUOY_KEEP){const i=import_node_path8.default.join(e,r);try{await import_node_fs7.promises.access(i)}catch{continue}const s=import_node_path8.default.join(n,r);await import_node_fs7.promises.mkdir(import_node_path8.default.dirname(s),{recursive:true});await import_node_fs7.promises.cp(i,s,{recursive:true,force:true});t=true}return t}async function reinstallAndroid(e,n,t,r){if(!/\.apk$/i.test(t))throw new Error("On Android, appPath must be an .apk file. Nothing was changed.");const i=await apkPackage(t);if(i!==n)throw new Error(`${import_node_path8.default.basename(t)} is ${i}, but this app is ${n}. Nothing was changed.`);const s=[];if(r){const c=await adbShell(e.serial,`run-as ${q(n)} find files/buoy-license files/react-buoy -maxdepth 1 -type f 2>/dev/null`).catch(()=>"");const u=c.split("\n").map(l=>l.trim()).filter(l=>l.startsWith("files/buoy-license/")||/react-buoy\/@react_buoy_(sync_device_id|install)\.json$/.test(l));for(const l of u){const d=await adbShell(e.serial,`run-as ${q(n)} base64 ${q(l)}`).catch(()=>"");if(d.trim())s.push({rel:l,data:d.replace(/\s+/g,"")})}}let o=[];if(r&&!s.length&&await androidHasWebViewStorage(e.serial,n)){try{o=await androidReadWebKeep(e.serial,n)}catch(c){throw new Error(`Couldn't read Buoy's sign-in from the app's WebView (${c.message}). Nothing was changed. Pass keepBuoy: false to reinstall anyway.`)}}await adb(e.serial,["install","-r","-d",t],18e4);await adbShell(e.serial,`pm clear ${q(n)}`);let a="";if(o.length){await hostLaunch(e);try{await androidWriteWebKeep(e.serial,n,o);a=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(c){a=` Buoy's sign-in could not be restored (${c.message}): sign in to Buoy again in the app.`}return`Reinstalled ${n} from ${t} and launched it. The app's data is gone, like a new user.${a}`}if(s.length){try{for(const c of s){const u=import_node_path8.default.posix.dirname(c.rel);await adbShell(e.serial,`echo ${q(c.data)} | run-as ${q(n)} sh -c ${q(`mkdir -p ${q(u)} && base64 -d > ${q(c.rel)}`)}`)}a=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(c){a=` Buoy's sign-in could not be restored (${c.message}): sign in to Buoy again in the app.`}}else if(r){a=" No Buoy sign-in could be read to keep (needs a debug build): sign in to Buoy again in the app."}await hostLaunch(e);return`Reinstalled ${n} from ${t} and launched it. The app's data is gone, like a new user.${a}`}async function reinstallPhone(e,n,t,r){if(!/\.app\/?$/i.test(t))throw new Error("On an iPhone, appPath must be a built .app folder (a device build). Nothing was changed.");const i=await appBundleInfo(t);if(i.bundleId!==n)throw new Error(`${import_node_path8.default.basename(t)} is ${i.bundleId}, but this app is ${n}. Nothing was changed.`);if(i.simulator)throw new Error(`${import_node_path8.default.basename(t)} is a simulator build, not a device build. Nothing was changed.`);const s=["Documents/buoy-license/buoy-gg-license.json","Documents/react-buoy/@react_buoy_sync_device_id.json","Documents/react-buoy/@react_buoy_install.json"];const o=r?await import_node_fs7.promises.mkdtemp(import_node_path8.default.join(import_node_os6.default.tmpdir(),"buoy-mcp-keep-")):null;try{const a=[];if(o){await import_node_fs7.promises.chmod(o,448);for(const u of s){let l;try{l=await readAppFile(e.udid,n,u)}catch(h){throw new Error(`Could not back up Buoy's ${import_node_path8.default.basename(u)} from the iPhone (${h.message}). Nothing was changed.`)}if(!l)continue;const d=import_node_path8.default.join(o,u.replace(/\//g,"__"));await import_node_fs7.promises.writeFile(d,l,{mode:384});a.push({rel:u,local:d})}}await phoneQuit(e.udid,n).catch(()=>false);await phoneUninstall(e.udid,n);try{await phoneInstall(e.udid,t)}catch(u){throw new Error(`The app was removed, but installing ${import_node_path8.default.basename(t)} failed: ${u.message}. Install it again from Xcode.`)}let c="";if(a.length){try{for(const d of a)await writeAppFile(e.udid,n,d.local,d.rel);const u=a.some(d=>d.rel.includes("buoy-license"));const l=a.some(d=>d.rel.includes("sync_device_id"));c=u?` Kept Buoy's sign-in${l?" and device id, so the same deviceId still works":""}.`:` Kept the device id; there was no Buoy sign-in to keep, so sign in to Buoy in the app.`}catch(u){c=` Buoy's sign-in could not be restored (${u.message}): sign in to Buoy again in the app.`}}else if(r)c=" The old install had no Buoy sign-in to keep.";await phoneLaunch(e.udid,n);return`Reinstalled ${n} on the iPhone and launched it. The app's own data is gone, like a new user.${c}`}finally{if(o)await import_node_fs7.promises.rm(o,{recursive:true,force:true}).catch(()=>void 0)}}async function bootSimulator(e){const n=JSON.parse(await simctl(["list","devices","available","-j"])).devices;const t=Object.entries(n).filter(([a])=>/iOS/.test(a)).flatMap(([,a])=>a);const r=e.trim().toLowerCase();const i=t.filter(a=>a.udid.toLowerCase()===r||a.name.toLowerCase()===r);const s=i.length?i:t.filter(a=>a.name.toLowerCase().includes(r));if(s.length===0)throw new Error(`No iOS Simulator matches "${e}". Run \`xcrun simctl list devices available\` to see them.`);if(s.length>1)throw new Error(`${s.length} simulators match "${e}": ${s.map(a=>`${a.name} (${a.udid})`).join(", ")}. Pass the udid.`);const o=s[0];if(o.state!=="Booted")await simctl(["boot",o.udid],12e4);await sh("open",["-a","Simulator","--args","-CurrentDeviceUDID",o.udid]).catch(()=>void 0);return o.state==="Booted"?`${o.name} (${o.udid}) was already booted.`:`Booted ${o.name} (${o.udid}).`}var import_node_child_process7,import_node_util6,import_node_fs7,import_node_os6,import_node_path8,import_node_crypto5,import_pngjs2,execFileAsync6,hosts,simctl,tailOf,steadying,BUOY_KEEP;var init_hostDevice=__esm({"src/capture/hostDevice.ts"(){"use strict";import_node_child_process7=require("child_process");import_node_util6=require("util");import_node_fs7=require("fs");import_node_os6=__toESM(require("os"));import_node_path8=__toESM(require("path"));import_node_crypto5=require("crypto");import_pngjs2=__toESM(require_png());init_simctl();init_iosDevice();init_webViewKeep();init_adb();execFileAsync6=(0,import_node_util6.promisify)(import_node_child_process7.execFile);hosts=new Map;simctl=(e,n)=>sh("xcrun",["simctl",...e],n);tailOf=e=>e.split("-").pop()??"";steadying=new Set;BUOY_KEEP=["buoy-license","react-buoy/@react_buoy_sync_device_id.json","react-buoy/@react_buoy_install.json"]}});async function hostTarget(e,n,t={},r={}){if(n==="All")throw new Error('Device control acts on one app. Pass its deviceId, not "All".');let i;let s=true;try{i=e.requireProDevice(n)}catch(c){const u=c instanceof Error?c.message:String(c);const l=u.startsWith(NOT_READY_MARK)&&/is not connected right now/.test(u)?/"([^"]+)"/.exec(u)?.[1]:void 0;const d=l?e.listDevices().some(h=>h.deviceId===l&&h.isPro):false;if(!r.allowOffline||!l||!d)throw c;i=l;s=false}const o=e.listDevices().find(c=>c.deviceId===i)?.platform;let a=await findHost(i,o,t);if(r.changesApp&&rememberedHost(i)===a)a=await verifyHost(i,a);return{id:i,host:a,online:s}}function hostLabel(e){if(e.platform==="ios")return`simulator "${e.name}"`;if(e.platform==="ios-device")return`iPhone "${e.name}"`;return`Android device ${e.serial}`}function has(e){if(!onPath.has(e))onPath.set(e,execFileAsync7("which",[e],{timeout:3e3}).then(()=>true,()=>false));return onPath.get(e)}async function hostSummary(e,n){let t=n;if(e.platform==="android"){const i=rememberedHost(e.deviceId);const s=i??(e.isConnected?await Promise.race([findHost(e.deviceId,"android").catch(()=>void 0),new Promise(a=>setTimeout(()=>a(void 0),3e3))]):void 0);const o=await has("adb");return{kind:"android",...s&&s.platform==="android"?{id:s.serial,name:s.packageName}:{},can:["screenshot","screen_recording","baseline diffs","quit/launch/reinstall","real lifecycle events","native_tap/type/swipe"],...!o?{missing:["adb (Android SDK platform-tools)"]}:!s?{missing:["proof of which phone runs it (needs a debug build reachable by adb)"]}:{}}}if(e.platform!=="ios")return{kind:e.platform??"unknown",can:[],missing:["host control works on iOS and Android apps"]};let r=rememberedHost(e.deviceId);if(!r&&!t&&e.isConnected){r=await Promise.race([findHost(e.deviceId,"ios").catch(()=>void 0),new Promise(i=>setTimeout(()=>i(void 0),4e3))])}if(!t&&r?.platform==="ios")t={name:r.name,udid:r.udid};if(r?.platform==="ios-device"){return{kind:"physical iPhone",id:r.udid,name:r.name,can:["screenshot","screen_recording (if this iPhone supports it)","baseline diffs","quit/launch/reinstall","open_url","native_tap/type/swipe (by query, testID, nativeTag or x/y; not label)"]}}if(t){const i=await has("idb");return{kind:"ios simulator",id:t.udid,name:t.name,can:["screenshot","screen_recording","baseline diffs","quit/launch/reinstall/boot","real lifecycle events",...i?["native_tap/type/swipe"]:[]],...i?{}:{missing:["idb for real touches (brew install facebook/fb/idb-companion && pipx install fb-idb)"]}}}return void 0}var import_node_child_process8,import_node_util7,execFileAsync7,onPath;var init_hostKit=__esm({"src/tools/hostKit.ts"(){"use strict";init_SyncClient();import_node_child_process8=require("child_process");import_node_util7=require("util");init_hostDevice();execFileAsync7=(0,import_node_util7.promisify)(import_node_child_process8.execFile);onPath=new Map}});function json(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function fail(e){return{isError:true,content:[{type:"text",text:e}]}}function registerGenericTools(e,n){e.registerTool("list_devices",{description:"List the apps connected to Buoy: id, name, platform, whether it is connected and has MCP access, the simulator or phone it runs on with the host controls that work there (screenshot, recording, app control, real touches) and anything missing, and the Buoy tools it exposes. Start here. Pass details:true for every tool's action names.",inputSchema:{details:import_zod.z.boolean().optional().describe("Also list every action of every tool. Default false (tool names only); list_tool_actions gives one tool's actions."),includeDisconnected:import_zod.z.boolean().optional().describe("Also list apps that were seen before but are not connected now. Default false.")}},async(t={})=>{const r=await getUpdateNotice();let i=n.listDevices();for(let p=0;i.length===0&&p<10;p++){await new Promise(m=>setTimeout(m,200));i=n.listDevices()}if(i.length===0){return json({devices:[],hint:"No devices connected. Open the app with Buoy devtools running, then retry.",...r?{updateAvailable:r}:{}})}const s=t.includeDisconnected?0:i.filter(p=>!p.isConnected).length;if(!t.includeDisconnected)i=i.filter(p=>p.isConnected);if(i.length===0){return json({devices:[],hint:`No app is connected right now${s?` (${s} seen before; pass includeDisconnected:true to list them)`:""}. Open the app with Buoy devtools running, then retry.`,...r?{updateAvailable:r}:{}})}const o=await resolveSims(i.filter(p=>p.platform==="ios").map(p=>p.deviceId)).catch(()=>new Map);const a=i.filter(p=>p.isConnected);const c=a.some(p=>p.isPro);const u=a.some(p=>p.tier!=="locked");const l=a.filter(p=>p.collision);const d=await Promise.all(i.map(p=>p.isConnected?hostSummary(p,o.get(p.deviceId)).catch(()=>void 0):void 0));const h=i.map((p,m)=>{const g=o.get(p.deviceId);const w=d[m];return{deviceId:p.deviceId,deviceName:p.deviceName,platform:p.platform,isConnected:p.isConnected,isPro:p.isPro,tier:p.tier,access:n.accessState(p.deviceId),...g?{simulator:g}:{},...w?{host:w}:{},...p.collision?{collision:true}:{},tools:t.details?p.tools:p.tools.map(f=>f.toolId)}});return json({devices:h,...t.details?{}:{note:`Tool names only. Pass details:true, or list_tool_actions({toolId}), for action names.${s?` ${s} apps seen before but not connected now are left out (includeDisconnected:true lists them).`:""}`},...l.length>0?{warning:`${l.map(p=>`"${p.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.`}:{},...c?{}:{hint:u?"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."},...r?{updateAvailable:r}:{}})});e.registerTool("list_tool_actions",{description:"List the actions a tool exposes, and which connected devices offer it. Leave toolId out to list every tool's actions. Use the action names with call_action.",inputSchema:{toolId:import_zod.z.string().optional().describe('The tool id, e.g. "perf-monitor", "network", "react-query". Leave out for every tool.'),tool:import_zod.z.string().optional().describe("Same as toolId."),deviceId:import_zod.z.string().optional().describe("Only list what this device offers.")}},async({toolId:t,tool:r,deviceId:i})=>{const s=t??r;if(!s){const c=n.connectedDevices().filter(l=>!i||l.deviceId===i);if(c.length===0)return fail(i?`No connected device "${i}". Call list_devices.`:"No devices are connected. Call list_devices.");const u=c.map(l=>[`**${l.deviceName}** (${l.deviceId})`,...l.tools.map(d=>`- ${d.toolId}: ${d.actions.join(", ")}`)].join("\n"));return{content:[{type:"text",text:`${u.join("\n\n")}
42
42
 
43
43
  Call one with call_action({toolId, action, params}).`}]}}const o=new Set(n.connectedDevices().map(c=>c.deviceId));const a=n.toolActions(s).filter(c=>o.has(c.deviceId)&&(!i||c.deviceId===i));if(a.length===0){const c=[...new Set(n.connectedDevices().flatMap(u=>u.tools.map(l=>l.toolId)))].sort();return fail(`No connected device exposes tool "${s}". Tool ids: ${c.join(", ")||"(none connected)"}. MCP tool names like "${s}" are not tool ids.`)}return json({toolId:s,offerings:a})});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:import_zod.z.string().optional().describe("The tool id to read state from."),tool:import_zod.z.string().optional().describe("Same as toolId."),deviceId:import_zod.z.string().optional().describe("The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out."),timeoutMs:import_zod.z.number().optional().describe("How long to wait for a fresh snapshot before falling back to the cached one.")}},async({toolId:t,tool:r,deviceId:i,timeoutMs:s})=>{try{const o=t??r;if(!o)return fail("get_snapshot needs toolId (see list_tool_actions).");const a=n.requireProDevice(i);const{payload:c,stale:u}=await n.getSnapshot(o,a,{timeoutMs:s});return json({toolId:o,deviceId:a,...u?{stale:u}:{},snapshot:c})}catch(o){return fail(errMsg(o))}});e.registerTool("call_action",{description:"Invoke any action a tool exposes (see list_tool_actions) and return its result. This is the generic escape hatch that works for every Buoy tool.",inputSchema:{toolId:import_zod.z.string().optional().describe('The tool id, e.g. "perf-monitor".'),tool:import_zod.z.string().optional().describe("Same as toolId."),action:import_zod.z.string().describe('The action name, e.g. "startRecording", "clearAll".'),params:import_zod.z.union([import_zod.z.record(import_zod.z.unknown()),import_zod.z.string()]).optional().describe("JSON params object for the action (shape depends on the action)."),args:import_zod.z.union([import_zod.z.record(import_zod.z.unknown()),import_zod.z.string()]).optional().describe("Same as params."),deviceId:import_zod.z.string().optional().describe('The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out. Or "All" to broadcast.'),timeoutMs:import_zod.z.number().optional().describe("Max time to wait for the device's result.")}},async({toolId:t,tool:r,action:i,params:s,args:o,deviceId:a,timeoutMs:c})=>{try{const u=t??r;if(!u)return fail("call_action needs toolId (see list_tool_actions).");const l=actionParams(s??o);const d=n.requireProDevice(a);const h=await n.callAction(u,i,l,d,{timeoutMs:c});return json({toolId:u,action:i,ok:true,result:h??null})}catch(u){return fail(errMsg(u))}})}function actionParams(e){if(e===void 0||typeof e==="object")return e;const n=e.trim();if(!n)return void 0;let t;try{t=JSON.parse(n)}catch{throw new Error('params is a string but not JSON. Pass an object, e.g. {"user": {...}}.')}if(!t||typeof t!=="object"||Array.isArray(t))throw new Error("params must be a JSON object.");return t}function errMsg(e){return e instanceof Error?e.message:String(e)}var import_zod;var init_generic=__esm({"src/tools/generic.ts"(){"use strict";import_zod=require("zod");init_checkForUpdate();init_simctl();init_hostKit()}});function clampLimit(e,n){return typeof e==="number"&&e>0?e:n}function staleHeader(e){return e?`${e}
44
44
 
package/dist/cli.mjs CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as d}from"module";const h=d(import.meta.url);import{runInit as w}from"./chunk-HKTKHDRR.mjs";import{SyncClient as u,createMcpServer as m,stopAllRecordingsNow as f}from"./chunk-4LPT4F4I.mjs";import"./chunk-6EOB4FHJ.mjs";import"./chunk-OPHPYPJD.mjs";import"./chunk-MTTWR4T7.mjs";import{StdioServerTransport as g}from"@modelcontextprotocol/sdk/server/stdio.js";console.log=(...e)=>console.error(...e);console.info=(...e)=>console.error(...e);console.debug=(...e)=>console.error(...e);async function b(){const e=process.env.BUOY_BROKER_PORT;const s=new u({url:process.env.BUOY_BROKER_URL,port:e?Number(e):void 0,autoSpawnBroker:process.env.BUOY_NO_SPAWN!=="1"});const r=m(s);const o=new g;let n=false;const c=t=>{if(n)return;n=true;process.stderr.write(`[buoy-mcp] shutting down (${t})
2
+ import{createRequire as d}from"module";const h=d(import.meta.url);import{runInit as w}from"./chunk-QBPXMMWS.mjs";import{SyncClient as u,createMcpServer as m,stopAllRecordingsNow as f}from"./chunk-CRYV6OHD.mjs";import"./chunk-6EOB4FHJ.mjs";import"./chunk-OPHPYPJD.mjs";import"./chunk-MTTWR4T7.mjs";import{StdioServerTransport as g}from"@modelcontextprotocol/sdk/server/stdio.js";console.log=(...e)=>console.error(...e);console.info=(...e)=>console.error(...e);console.debug=(...e)=>console.error(...e);async function b(){const e=process.env.BUOY_BROKER_PORT;const s=new u({url:process.env.BUOY_BROKER_URL,port:e?Number(e):void 0,autoSpawnBroker:process.env.BUOY_NO_SPAWN!=="1"});const r=m(s);const o=new g;let n=false;const c=t=>{if(n)return;n=true;process.stderr.write(`[buoy-mcp] shutting down (${t})
3
3
  `);f();setTimeout(()=>process.exit(0),2e3).unref();void(async()=>{await s.stop().catch(()=>{});await r.close().catch(()=>{});process.exit(0)})()};process.stdin.once("end",()=>c("stdin closed"));process.stdin.once("close",()=>c("stdin closed"));r.server.onclose=()=>c("transport closed");process.on("SIGINT",()=>c("SIGINT"));process.on("SIGTERM",()=>c("SIGTERM"));process.on("SIGHUP",()=>c("SIGHUP"));await r.connect(o);process.stderr.write(`[buoy-mcp] serving MCP over stdio; connecting to broker\u2026
4
4
  `);s.start().then(t=>process.stderr.write(`[buoy-mcp] broker ${t}
5
5
  `)).catch(t=>process.stderr.write(`[buoy-mcp] broker connection failed: ${t?.message??t} \u2014 tools will report no devices until it recovers
6
6
  `))}async function y(){const e=process.env.BUOY_BROKER_PORT;const s=new u({url:process.env.BUOY_BROKER_URL,port:e?Number(e):void 0,autoSpawnBroker:false});try{const r=await Promise.race([s.start().then(()=>true,()=>false),new Promise(o=>setTimeout(()=>o(false),4e3))]);if(!r)return false;for(let o=0;o<10;o++){if(s.connectedDevices().some(n=>n.tier==="pro"))return true;await new Promise(n=>setTimeout(n,300))}return false}finally{await Promise.race([s.stop().catch(()=>{}),new Promise(r=>setTimeout(r,2e3))])}}if(process.argv[2]==="web-bench"){void(async()=>{try{const e=process.argv.slice(3);const s=e.find(a=>!a.startsWith("--"));if(!s)throw new Error("usage: buoy-mcp web-bench <config.json> [--json]");const{readFileSync:r}=await import("fs");const{runWebBench:o,formatWebBenchMarkdown:n}=await import("./webBench-QCHYXYCA.mjs");const{readEntitlement:c}=await import("./camera-JI2FMAKN.mjs");if(!c().isPro&&!await y()){throw new Error("web-bench is a Buoy Pro feature. Sign in to Buoy Desktop with a Pro account, or open an app signed in to Pro. See https://buoy.gg/pricing.")}const t=JSON.parse(r(s,"utf8"));const i=await o({...t,durationMs:t.durationMs??t.perCaseDurationMs},a=>process.stderr.write(`[web-bench] ${a}
7
7
  `));const p=i.status==="failed"||i.browserLeftRunning?1:0;const l=(e.includes("--json")?JSON.stringify(i,null,2):n(i))+"\n";setTimeout(()=>process.exit(p),5e3).unref();process.stdout.write(l,()=>process.exit(p))}catch(e){process.stderr.write(`[buoy-mcp] web-bench failed: ${e?.message??e}
8
- `,()=>process.exit(1));setTimeout(()=>process.exit(1),5e3).unref()}})()}else if(process.argv[2]==="flow"&&process.argv[3]==="run"){void(async()=>{try{const{parseFlowRunArgs:e,runFlows:s,formatFlowResults:r}=await import("./flowRun-VQDAJKWD.mjs");const o=e(process.argv.slice(4));const n=await s(o);const c=o.json?JSON.stringify(n,null,2):r(n);const t=n.every(i=>i.passed)?0:1;setTimeout(()=>process.exit(t),5e3).unref();process.stdout.write(`${c}
8
+ `,()=>process.exit(1));setTimeout(()=>process.exit(1),5e3).unref()}})()}else if(process.argv[2]==="flow"&&process.argv[3]==="run"){void(async()=>{try{const{parseFlowRunArgs:e,runFlows:s,formatFlowResults:r}=await import("./flowRun-WQQBDMBN.mjs");const o=e(process.argv.slice(4));const n=await s(o);const c=o.json?JSON.stringify(n,null,2):r(n);const t=n.every(i=>i.passed)?0:1;setTimeout(()=>process.exit(t),5e3).unref();process.stdout.write(`${c}
9
9
  `,()=>process.exit(t))}catch(e){process.stderr.write(`[buoy-mcp] flow run failed: ${e?.message??e}
10
10
  `,()=>process.exit(1));setTimeout(()=>process.exit(1),5e3).unref()}})()}else if(process.argv[2]==="init"){try{const e=process.argv.slice(3);let s="auto";if(e.includes("--local"))s="local";else if(e.includes("--npx"))s="npx";const r=e.indexOf("--registry");const o=r!==-1?e[r+1]:void 0;w({mode:s,registry:o});process.exit(0)}catch(e){process.stderr.write(`[buoy-mcp] init failed: ${e?.message??e}
11
11
  `);process.exit(1)}}else{b().catch(e=>{process.stderr.write(`[buoy-mcp] fatal: ${e?.message??e}
@@ -1,2 +1,2 @@
1
- import{createRequire as v}from"module";const E=v(import.meta.url);import{SyncClient as y,createMcpServer as R}from"./chunk-4LPT4F4I.mjs";import"./chunk-6EOB4FHJ.mjs";import"./chunk-OPHPYPJD.mjs";import"./chunk-MTTWR4T7.mjs";import{promises as S}from"fs";import $ from"path";import{Client as _}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as B}from"@modelcontextprotocol/sdk/inMemory.js";function P(e){const o={names:[]};for(let n=0;n<e.length;n++){const t=e[n];if(t==="--device")o.deviceId=e[++n];else if(t==="--update-snapshots")o.updateSnapshots=true;else if(t==="--json")o.json=true;else if(t==="--wait")o.waitMs=Number(e[++n])*1e3;else if(t==="--all")continue;else if(!t.startsWith("--"))o.names.push(t);else throw new Error(`Unknown option ${t}.`)}return o}async function I(){const e=$.join(process.cwd(),".buoy","flows");return(await S.readdir(e).catch(()=>[])).filter(o=>o.endsWith(".json")).map(o=>o.replace(/\.json$/,"")).sort()}async function g(e,o=n=>process.stderr.write(`${n}
1
+ import{createRequire as v}from"module";const E=v(import.meta.url);import{SyncClient as y,createMcpServer as R}from"./chunk-CRYV6OHD.mjs";import"./chunk-6EOB4FHJ.mjs";import"./chunk-OPHPYPJD.mjs";import"./chunk-MTTWR4T7.mjs";import{promises as S}from"fs";import $ from"path";import{Client as _}from"@modelcontextprotocol/sdk/client/index.js";import{InMemoryTransport as B}from"@modelcontextprotocol/sdk/inMemory.js";function P(e){const o={names:[]};for(let n=0;n<e.length;n++){const t=e[n];if(t==="--device")o.deviceId=e[++n];else if(t==="--update-snapshots")o.updateSnapshots=true;else if(t==="--json")o.json=true;else if(t==="--wait")o.waitMs=Number(e[++n])*1e3;else if(t==="--all")continue;else if(!t.startsWith("--"))o.names.push(t);else throw new Error(`Unknown option ${t}.`)}return o}async function I(){const e=$.join(process.cwd(),".buoy","flows");return(await S.readdir(e).catch(()=>[])).filter(o=>o.endsWith(".json")).map(o=>o.replace(/\.json$/,"")).sort()}async function g(e,o=n=>process.stderr.write(`${n}
2
2
  `)){const n=e.names.length?e.names:await I();if(n.length===0)throw new Error('No saved flows. Save one with run_flow and save:"name", or pass a flow name.');const t=process.env.BUOY_BROKER_PORT;const s=new y({url:process.env.BUOY_BROKER_URL,port:t?Number(t):void 0,autoSpawnBroker:process.env.BUOY_NO_SPAWN!=="1"});const p=R(s);const[w,f]=B.createLinkedPair();const i=new _({name:"buoy-flow-run",version:"1"});try{await p.connect(f);await i.connect(w);await s.start();const a=Date.now()+(e.waitMs??6e4);while(Date.now()<a&&!s.connectedDevices().some(r=>r.isPro&&(!e.deviceId||r.deviceId===e.deviceId))){await new Promise(r=>setTimeout(r,500))}if(!s.connectedDevices().some(r=>r.isPro)){throw new Error("No Buoy Pro app connected. Start the app (with Buoy) on a simulator or device, then run again.")}const u=[];for(const r of n){const m=Date.now();o(`\u25B6 ${r}`);const l=await i.callTool({name:"run_flow",arguments:{flow:r,include:"none",...e.deviceId?{deviceId:e.deviceId}:{},...e.updateSnapshots?{updateSnapshots:true}:{}}},void 0,{timeout:10*6e4});const h=(l.content??[]).filter(c=>c.type==="text").map(c=>c.text).join("\n");const d=l.isError!==true;u.push({name:r,passed:d,ms:Date.now()-m,report:h});o(`${d?"\u2713":"\u2717"} ${r} (${((Date.now()-m)/1e3).toFixed(1)}s)`)}return u}finally{await i.close().catch(()=>void 0);await Promise.race([s.stop().catch(()=>void 0),new Promise(a=>setTimeout(a,2e3))])}}function j(e){const o=e.filter(t=>!t.passed);const n=[`${e.length-o.length} of ${e.length} flows passed.`];for(const t of o){n.push("",`\u2717 ${t.name}`,t.report.trim(),` Rerun: npx @buoy-gg/mcp flow run ${t.name}`)}return n.join("\n")}export{j as formatFlowResults,P as parseFlowRunArgs,g as runFlows};