@buoy-gg/mcp 7.0.70 → 7.0.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,422 @@
1
+ import{createRequire as is}from"module";const Ui=is(import.meta.url);var F=1;var fe=1;var Te={parkAfterMinutes:10,maxConcurrentBoots:3,reserveRamGB:24,reserveDiskGB:40,slimSimGB:2,stockSimGB:6,cloneDiskGB:2,freezePilot:false,runCapMinutes:60,keepRunsHours:24,fairMinFreeShare:.25,fairMaxSwingShare:.12,fairMaxThermalLevel:0,fairMaxSwapGrowthMB:256,phoneProfile:"iphone-se-2nd-gen",phoneOnLimit:"warn",phoneCapMB:0};var d=class extends Error{constructor(e,t,s,i=false){super(t);this.code=e;this.next=s;this.retryable=i;this.name="FarmError"}toJSON(){return{code:this.code,message:this.message,next:this.next,retryable:this.retryable}}};import{createHash as ns}from"crypto";var Ve=["com.apple.sharingd"];var ie=[{"id":"widgets","name":"Widgets & Wallpaper","downside":"Home and Lock Screen widgets, wallpaper posters, and Live Activities stop updating.","approxMemoryMB":675,"labels":["com.apple.PosterBoard","com.apple.chronod","com.apple.liveactivitiesd"]},{"id":"siri","name":"Siri & Intelligence","downside":"Siri, speech features, and Apple Intelligence services are unavailable.","approxMemoryMB":265,"labels":["com.apple.assistantd","com.apple.assistant_cdmd","com.apple.assistant_service","com.apple.siriactionsd","com.apple.siriinferenced","com.apple.siriknowledged","com.apple.sirittsd","com.apple.siri.context.service","com.apple.siri.acousticsignature","com.apple.corespeechd","com.apple.voiced","com.apple.voicebankingd","com.apple.speechmodeltrainingd","com.apple.intelligenceplatformd","com.apple.intelligencecontextd","com.apple.intelligenceflowd","com.apple.intelligencetasksd","com.apple.generativeexperiencesd","com.apple.knowledgeconstructiond","com.apple.naturallanguaged","com.apple.textunderstandingd","com.apple.modelcatalogd","com.apple.modelmanagerd","com.apple.mlhostd","com.apple.mlruntimed","com.apple.suggestd","com.apple.parsecd","com.apple.parsec-fbf","com.apple.proactiveeventtrackerd"]},{"id":"search","name":"Spotlight & Search","downside":"Spotlight and Settings search return no results.","approxMemoryMB":50,"labels":["com.apple.searchd","com.apple.searchtoold","com.apple.spotlightknowledged","com.apple.spotlightknowledged.updater","com.apple.corespotlightservice"]},{"id":"icloud","name":"iCloud & Apple Account","downside":"iCloud sync, Apple Account, Keychain, and backup workflows will not work.","approxMemoryMB":100,"labels":["com.apple.appleaccountd","com.apple.appleaccounttransparencyd","com.apple.appleidsetupd","com.apple.akd","com.apple.amsaccountsd","com.apple.amsengagementd","com.apple.amsondevicestoraged","com.apple.cloudd","com.apple.cloudphotod","com.apple.ckdiscretionaryd","com.apple.cloudsettingssyncagent","com.apple.bird","com.apple.syncdefaultsd","com.apple.cdpd","com.apple.sosd","com.apple.SecureBackupDaemon","com.apple.TrustedPeersHelper","com.apple.protectedcloudstorage.protectedcloudkeysyncing","com.apple.icloudmailagent","com.apple.icloudsubscriptionoptimizerd","com.apple.communicationtrustd"]},{"id":"store","name":"App Store, Push & Media","downside":"Remote push notifications and StoreKit or App Store testing will not work.","approxMemoryMB":80,"labels":["com.apple.appstored","com.apple.appstorecomponentsd","com.apple.apsd","com.apple.itunescloudd","com.apple.itunesstored","com.apple.storekitd","com.apple.amsaccountsd","com.apple.amsengagementd","com.apple.amsondevicestoraged","com.apple.passd","com.apple.financed","com.apple.videosubscriptionsd","com.apple.assetsubscriptiond","com.apple.musicd"]},{"id":"pim","name":"Mail, Calendar & Contacts","downside":"Contacts, Calendar, Reminders, and Mail-backed pickers or sync may fail.","approxMemoryMB":80,"labels":["com.apple.email.maild","com.apple.exchangesyncd","com.apple.dataaccess.dataaccessd","com.apple.calaccessd","com.apple.remindd","com.apple.contactsd","com.apple.contacts.postersyncd","com.apple.peopled"]},{"id":"web","name":"Safari Sync & Web Services","downside":"Universal links and Safari sync or background web services will not work.","approxMemoryMB":50,"labels":["com.apple.SafariBookmarksSyncAgent","com.apple.Safari.History","com.apple.Safari.passwordbreachd","com.apple.Safari.SafeBrowsing.Service","com.apple.safarifetcherd","com.apple.WebBookmarks.webbookmarksd","com.apple.webkit.adattributiond","com.apple.webkit.webpushd","com.apple.webprivacyd","com.apple.swcd"]},{"id":"family","name":"Family & Screen Time","downside":"Family Sharing, Screen Time, and usage tracking stop working.","approxMemoryMB":65,"labels":["com.apple.familycircled","com.apple.FamilyControlsAgent","com.apple.familynotification","com.apple.askpermissiond","com.apple.asktod","com.apple.ScreenTimeAgent","com.apple.ScreenTimeSettingsAgent","com.apple.UsageTrackingAgent"]},{"id":"health","name":"Health, Home & Fitness","downside":"HealthKit, HomeKit, and Fitness integrations will not work.","approxMemoryMB":135,"labels":["com.apple.healthd","com.apple.healthappd","com.apple.healthcontentd","com.apple.healtheventsd","com.apple.healthrecordsd","com.apple.finhealthd","com.apple.homed","com.apple.homeeventsd","com.apple.fitcore","com.apple.fitcore.session","com.apple.fitnesscoachingd","com.apple.fitnessintelligenced","com.apple.activityawardsd","com.apple.activitysharingd"]},{"id":"photos","name":"Photos & Media Analysis","downside":"Photo picker, Photos-library workflows, and media analysis may fail.","approxMemoryMB":60,"labels":["com.apple.photoanalysisd","com.apple.photosface","com.apple.mediaanalysisd","com.apple.mediaanalysisd.service","com.apple.mediastream.mstreamd","com.apple.medialibraryd","com.apple.assetsd","com.apple.assetsd.nebulad"]},{"id":"apps","name":"News, Weather, Maps & Games","downside":"News, Weather, Maps background data, and game-controller services are unavailable.","approxMemoryMB":90,"labels":["com.apple.newsd","com.apple.weatherd","com.apple.Maps.mapssyncd","com.apple.Maps.mapspushd","com.apple.Maps.geocorrectiond","com.apple.maps.destinationd","com.apple.MapKit.SnapshotService","com.apple.jetpackassetd","com.apple.tipsd","com.apple.gamed","com.apple.gamesaved","com.apple.GameController.gamecontrollerd"]},{"id":"messaging","name":"Messaging & FaceTime","downside":"iMessage, FaceTime, and related identity services will not work.","approxMemoryMB":60,"labels":["com.apple.identityservicesd","com.apple.ids_simd","com.apple.imautomatichistorydeletionagent","com.apple.imcore.imtransferagent","com.apple.imdpersistence.IMDPersistenceAgent","com.apple.facetimemessagestored","com.apple.telephonyutilities.callservicesd"]},{"id":"connectivity","name":"Sharing & Device Connectivity","downside":"AirDrop, Continuity, CarPlay, Watch, and Find My connectivity will not work.","approxMemoryMB":65,"labels":["com.apple.rapportd","com.apple.companiond","com.apple.carkitd","com.apple.wcd","com.apple.tvremoted","com.apple.avatarsd","com.apple.stickersd","com.apple.sociallayerd","com.apple.announced","com.apple.navd","com.apple.findmy.findmylocated"]},{"id":"telemetry","name":"Ads, Diagnostics & Telemetry","downside":"DeviceCheck plus analytics, diagnostics, and feedback services are unavailable.","approxMemoryMB":105,"labels":["com.apple.ap.adprivacyd","com.apple.ap.promotedcontentd","com.apple.diagnosticextensionsd","com.apple.feedbackd","com.apple.rtcreportingd","com.apple.securityuploadd","com.apple.geoanalyticsd","com.apple.triald","com.apple.followupd","com.apple.purplebuddy.budd","com.apple.devicecheckd"]},{"id":"other","name":"Other Background Services","downside":"Wallet, merchant, business, asset, and miscellaneous background services are unavailable.","approxMemoryMB":195,"labels":["com.apple.financed","com.apple.passd","com.apple.merchantd","com.apple.coreidvd","com.apple.businessservicesd","com.apple.deviceaccessd","com.apple.replicatord","com.apple.linkd","com.apple.ind","com.apple.storagedatad","com.apple.StatusKitAgent","com.apple.countryd","com.apple.mobileassetd","com.apple.managedconfiguration.passcodenagd"]}];function Xe(){const e=new Set(Ve);const t=new Set;for(const s of ie)for(const i of s.labels)if(!e.has(i))t.add(i);return[...t].sort()}function J(e){return e==="slim"?Xe():[]}function Ze(e){return ns("sha256").update(e+"\n"+J(e).join("\n")).digest("hex").slice(0,16)}import{promises as A,existsSync as et}from"fs";import D from"path";import{AsyncLocalStorage as as}from"async_hooks";import{createHash as os,randomBytes as we}from"crypto";import{promises as V}from"fs";import Re from"path";import{randomBytes as rs}from"crypto";import{spawn as ls}from"child_process";var ne=new Set;function Ne(){return ne.size}function cs(){for(const e of ne){try{e.kill("SIGKILL")}catch{}}}function M(e,t,s={}){const{timeoutMs:i=3e4,maxBytes:n=4*1024*1024}=s;return new Promise(a=>{const o=ls(e,t,{env:s.env??process.env,stdio:[s.input==null?"ignore":"pipe","pipe","pipe"]});ne.add(o);let r="";let l="";let c=false;o.stdout.on("data",h=>{if(r.length<n)r+=h.toString("utf8")});o.stderr.on("data",h=>{if(l.length<n)l+=h.toString("utf8")});if(s.input!=null)o.stdin.end(s.input);const p=setTimeout(()=>{c=true;o.kill("SIGTERM");setTimeout(()=>o.kill("SIGKILL"),2e3).unref?.()},i);o.on("error",h=>{ne.delete(o);clearTimeout(p);a({code:null,stdout:r,stderr:l+String(h),timedOut:c})});o.on("close",h=>{ne.delete(o);clearTimeout(p);a({code:h,stdout:r,stderr:l,timedOut:c})})})}async function P(e,t,s={}){const i=await M(e,t,s);if(i.timedOut)throw new Error(`${e} ${t.slice(0,3).join(" ")} timed out after ${s.timeoutMs??3e4} ms`);if(i.code!==0)throw new Error(`${e} ${t.slice(0,3).join(" ")} failed (${i.code}): ${(i.stderr||i.stdout).trim().slice(0,500)}`);return i.stdout}async function tt(){const e=await P("ps",["-axww","-o","pid=,ppid=,lstart=,stat=,comm="],{timeoutMs:15e3});const t=await P("ps",["-axww","-o","pid=,command="],{timeoutMs:15e3});const s=new Map;for(const n of t.split("\n")){const a=/^\s*(\d+)\s+(.*)$/.exec(n);if(a)s.set(Number(a[1]),a[2])}const i=[];for(const n of e.split("\n")){const a=/^\s*(\d+)\s+(\d+)\s+(\w{3}\s+\w{3}\s+\d+\s+[\d:]+\s+\d{4})\s+(\S+)\s+(.*)$/.exec(n);if(!a)continue;const o=Number(a[1]);i.push({pid:o,ppid:Number(a[2]),start:a[3].replace(/\s+/g," "),stat:a[4],comm:a[5].trim(),command:s.get(o)??a[5].trim()})}return i}function st(e,t){const s=new Map;const i=new Map;for(const l of e){i.set(l.pid,l);const c=s.get(l.ppid)??[];c.push(l);s.set(l.ppid,c)}const n=[];const a=i.get(t);if(!a)return n;const o=[a];const r=new Set;while(o.length){const l=o.pop();if(r.has(l.pid))continue;r.add(l.pid);n.push(l);for(const c of s.get(l.pid)??[])o.push(c)}return n}async function ae(e){const t=await M("ps",["-o","lstart=","-p",String(e)],{timeoutMs:5e3});const s=t.stdout.trim().replace(/\s+/g," ");return t.code===0&&s?s:null}async function q(e,t,s=false){if(!Number.isInteger(e)||e<=0)return false;try{process.kill(e,0)}catch(n){if(n.code!=="EPERM")return false}if(!t)return true;const i=await ae(e);if(i===null)return s;return i===t}function $e(e=process.env){return Object.fromEntries(Object.entries(e).filter(([t])=>!t.startsWith("SIMCTL_CHILD_")))}var W=e=>new Promise(t=>setTimeout(t,e));var X=process.env.BUOY_FARM_DISABLED_ROOT||"/private/var/tmp";function it(e,t=X){if(!/^[0-9A-F-]{36}$/i.test(e))throw new Error(`not a UDID: ${e}`);return Re.join(t,`com.apple.CoreSimulator.SimDevice.${e}`)}function nt(e,t=X){return Re.join(it(e,t),"disabled.plist")}async function at(e,t=X){const s=nt(e,t);let i;try{i=await V.lstat(s)}catch{return{}}if(!i.isFile())throw new Error(`refusing ${s}: not a regular file`);const n=await P("plutil",["-convert","json","-o","-",s],{timeoutMs:1e4});const a=JSON.parse(n);const o={};for(const[r,l]of Object.entries(a))if(typeof l==="boolean")o[r]=l;return o}function ds(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function us(e){const t=Object.keys(e).sort();let s='<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0">\n<dict>\n';for(const i of t)s+=` <key>${ds(i)}</key>
2
+ <${e[i]?"true":"false"}/>
3
+ `;return s+"</dict>\n</plist>\n"}async function ot(e,t,s=X){const i=it(e,s);await V.mkdir(i,{recursive:true});const n=await V.lstat(i);if(!n.isDirectory())throw new Error(`refusing ${i}: not a directory`);const a=await at(e,s);const o=Re.join(i,"buoy-farm-prior.json");let r={};try{r=JSON.parse(await V.readFile(o,"utf8"))}catch{}const l={...a};for(const c of t){if(!(c in r))r[c]=c in a?a[c]:null;l[c]=true}await rt(o,JSON.stringify(r,null,2)+"\n");await rt(nt(e,s),us(l))}async function ps(e,t,s=X){const i=await at(e,s);return t.every(n=>i[n]===true)}async function rt(e,t){const s=`${e}.${rs(4).toString("hex")}.tmp`;const i=await V.open(s,"w",420);try{await i.writeFile(t);await i.sync()}finally{await i.close()}await V.rename(s,e)}import{promises as T,existsSync as Y,readFileSync as Ji}from"fs";import S from"path";import{createHash as lt}from"crypto";var ct=["@react_buoy_sync_device_id.json","@react_buoy_install.json"];var hs="@buoy~1floating-tool~1*";function oe(e){if(!Y(S.join(e,"seed.json")))return`No seed at ${e}. Run: pnpm e2e:pool seed`;if(Y(S.join(e,"Documents/buoy-license"))){for(const t of["buoy-gg-license.json","buoy-gg-device-fingerprint.json"]){if(!Y(S.join(e,"Documents/buoy-license",t)))return`The seed lacks ${t}.`}}return null}async function ms(e){const t=lt("sha256");async function s(i){let n;try{n=await T.readdir(i,{withFileTypes:true})}catch{return}n.sort((a,o)=>a.name.localeCompare(o.name));for(const a of n){const o=S.join(i,a.name);if(a.isDirectory())await s(o);else{const r=await T.stat(o);t.update(`${S.relative(e,o)}:${r.size}:${Math.floor(r.mtimeMs)}
4
+ `)}}}await s(e);return t.digest("hex").slice(0,16)}async function fs(e){const t=lt("sha256");const s=S.join(e,"Info.plist");t.update(await T.readFile(s));const i=JSON.parse(await P("plutil",["-convert","json","-o","-",s],{timeoutMs:1e4}));const n=S.join(e,String(i.CFBundleExecutable??""));const a=await T.stat(n);t.update(`${a.size}:${Math.floor(a.mtimeMs)}`);return t.digest("hex").slice(0,16)}async function ws(e){const t=JSON.parse(await P("plutil",["-convert","json","-o","-",S.join(e,"Info.plist")],{timeoutMs:1e4}));if(!t.CFBundleIdentifier)throw new Error(`${e} has no CFBundleIdentifier`);return String(t.CFBundleIdentifier)}async function ge(e,t){const s=S.join(e,"Containers/Data/Application");let i;try{i=await T.readdir(s)}catch{return null}for(const n of i){const a=S.join(s,n,".com.apple.mobile_container_manager.metadata.plist");if(!Y(a))continue;const o=await M("plutil",["-extract","MCMMetadataIdentifier","raw","-o","-",a],{timeoutMs:5e3});if(o.code===0&&o.stdout.trim()===t)return S.join(s,n)}return null}function gs(e,t){return S.join(e,"Library/Application Support",t,"RCTAsyncLocalStorage_V1")}async function dt(e,t,s,i){i();await T.mkdir(t,{recursive:true});const n=["-a","--delete"];for(const a of s)n.push("--exclude",a);n.push(e.replace(/\/?$/,"/"),t.replace(/\/?$/,"/"));i();await P("rsync",n,{timeoutMs:6e4})}async function ut(e,t,s,i=()=>{}){i();const n=oe(s);if(n)throw new Error(n);const a=[...ct.map(l=>`react-buoy/${l}`),`react-buoy/${hs}`];if(Y(S.join(s,"Documents")))await dt(S.join(s,"Documents"),S.join(e,"Documents"),a,i);if(Y(S.join(s,"AsyncStorage/manifest.json"))){await dt(S.join(s,"AsyncStorage"),gs(e,t),[],i)}const o=S.join(s,"Preferences",`${t}.plist`);if(Y(o)){i();await T.mkdir(S.join(e,"Library/Preferences"),{recursive:true});await T.copyFile(o,S.join(e,"Library/Preferences",`${t}.plist`))}const r=S.join(e,"Documents/react-buoy");try{for(const l of await T.readdir(r)){i();if(l.startsWith("@buoy~1floating-tool~1"))await T.rm(S.join(r,l),{force:true,recursive:true})}}catch{}}async function ye(e,t=()=>{}){t();const s=[];const i=S.join(e,"Documents/react-buoy");let n=[];try{n=await T.readdir(i)}catch{return s}for(const a of n){if(ct.includes(a)||a.startsWith("@buoy~1floating-tool~1")){t();await T.rm(S.join(i,a),{force:true,recursive:true});s.push(a)}}return s}async function pt(e){let t;try{t=await T.readFile(S.join(e,"Documents/react-buoy/@react_buoy_sync_device_id.json"),"utf8")}catch{return null}try{const s=JSON.parse(t);if(typeof s==="string")return s||null;if(typeof s?.value==="string")return s.value||null}catch{}return t.trim()||null}var ht=2*60*6e4;var ys=10;var vs=5;var Ss=.8;var z=e=>Math.round(e*10)/10;var ks=e=>{if(!e.length)return 0;const t=[...e].sort((i,n)=>i-n);const s=t.length>>1;return t.length%2?t[s]:(t[s-1]+t[s])/2};var mt=class{constructor(e,t,s=1e3,i=Date.now){this.host=e;this.target=t;this.periodMs=s;this.now=i;this.samples=[];this.prev=null;this.pids=[];this.treeAge=0;this.treeKey="";this.sampling=false;this.ticks=0;this.lastProcs=null;this.rates={ours:0,graphics:0,gpuPct:null};this.cpuCount=0}async tick(){if(this.sampling)return;this.sampling=true;try{const e=this.target();if(!e){this.prev=null;this.treeKey="";return}const t=`${e.leaseId}:${e.udids.join(",")}`;if(t!==this.treeKey||++this.treeAge>=ys){const g=await Promise.all(e.udids.map(w=>this.host.simTree(w)));this.pids=g.flat().map(w=>w.pid);this.treeAge=0;if(t!==this.treeKey){this.prev=null;this.lastProcs=null;this.ticks=0;this.rates={ours:0,graphics:0,gpuPct:null}}this.treeKey=t}const s=this.ticks++;const i=await this.host.loadCounters(this.pids,s<2||s%vs===0);this.cpuCount=i.cpuCount;const n=this.now();const a=this.prev;this.prev={...i,at:n,leaseId:e.leaseId};const o=g=>(i.hostTotalMs-g)/Math.max(1,i.cpuCount);if(i.pidsCpuMs!==null&&i.graphicsCpuMs!==null){const g=this.lastProcs;const w=g?o(g.hostTotalMs):0;if(g&&w>0){this.rates.ours=Math.max(0,(i.pidsCpuMs-g.pidsCpuMs)/w);this.rates.graphics=Math.max(0,(i.graphicsCpuMs-g.graphicsCpuMs)/w)}this.rates.gpuPct=i.gpuPct;this.lastProcs={hostTotalMs:i.hostTotalMs,pidsCpuMs:i.pidsCpuMs,graphicsCpuMs:i.graphicsCpuMs}}if(!a||a.leaseId!==e.leaseId)return;const r=o(a.hostTotalMs);if(r<=0)return;const l=Math.max(0,(i.hostBusyMs-a.hostBusyMs)/r);const c=this.rates.ours;const p=this.rates.graphics;this.samples.push({at:Math.round((n+a.at)/2),leaseId:e.leaseId,freeCores:z(Math.max(0,i.cpuCount-l)),ourCores:z(c),graphicsCores:z(p),outsideCores:z(Math.max(0,l-c-p)),gpuPct:this.rates.gpuPct,memLevel:i.memPressureLevel,swapMB:i.swapUsedMB,thermal:i.thermalLevel});const h=n-ht;while(this.samples.length&&this.samples[0].at<h)this.samples.shift()}finally{this.sampling=false}}before(e,t){for(let s=this.samples.length-1;s>=0;s--){const i=this.samples[s];if(i.at<t)return i.leaseId===e?i:void 0}return void 0}latest(){return this.samples[this.samples.length-1]}verdicts(e,t,s){const i=this.periodMs/2;const n=t.map(o=>{const r=this.samples.filter(c=>c.at>=o.from-i&&c.at<=o.to+i);const l=r.filter(c=>c.leaseId===e);return{w:o,all:r,mine:l}});const a=ks(n.filter(o=>o.mine.length).map(o=>Le(o.mine.map(r=>r.outsideCores))));return n.map(({w:o,all:r,mine:l})=>{const c=Math.max(1,Math.round((o.to-o.from)/this.periodMs));const p={id:o.id,fair:false,seconds:l.length};if(!r.length&&(o.from>this.now()+6e4||o.to<this.now()-ht)){return{...p,reason:"This run's time doesn't match the Mac's clock. Was the app's clock moved? Put it back and run again."}}if(!l.length||l.length<r.length||l.length<Math.floor(c*Ss)){return{...p,reason:"No load record for all of this run. Hold perf-slot for the whole test."}}const h=l.map(f=>f.outsideCores);const g=l.map(f=>f.gpuPct).filter(f=>f!==null);const w=l.map(f=>f.thermal).filter(f=>f!==null);const k={...p,freeCoresMin:Math.min(...l.map(f=>f.freeCores)),outsideCoresAvg:z(Le(h)),outsideCoresMax:Math.max(...h),ourCoresAvg:z(Le(l.map(f=>f.ourCores))),graphicsCoresMax:Math.max(...l.map(f=>f.graphicsCores)),gpuMaxPct:g.length?Math.max(...g):null,swapGrowthMB:Math.round(Math.max(0,l[l.length-1].swapMB-(this.before(e,o.from)?.swapMB??l[0].swapMB))),thermalMax:w.length?Math.max(...w):null};if(k.thermalMax!=null&&k.thermalMax>s.maxThermalLevel){return{...k,reason:"The Mac got hot and slowed itself down. Let it cool, then run again."}}if(l.some(f=>f.memLevel>=4)){return{...k,reason:"The Mac ran low on memory. Close apps or stop sims you don't need."}}if(k.swapGrowthMB>s.maxSwapGrowthMB){return{...k,reason:`The Mac swapped ${k.swapGrowthMB} MB of memory to disk.`}}if(k.freeCoresMin<s.minFreeCores){return{...k,reason:`The Mac ran out of spare CPU (${k.freeCoresMin} cores free, needs ${s.minFreeCores}).`}}const $=z(k.outsideCoresMax-a);if($>s.maxSwingCores){return{...k,reason:`Other work on the Mac jumped by ${$} cores during this run.`}}return{...k,fair:true}})}};function Le(e){return e.length?e.reduce((t,s)=>t+s,0)/e.length:0}function ft(e){const t=e.trim().split(":").map(Number);if(!t.length||t.some(s=>!Number.isFinite(s)))return 0;return Math.round(t.reduce((s,i)=>s*60+i,0)*1e3)}import{execFile as bs}from"child_process";import{promises as B,readFileSync as Ms}from"fs";import Ce from"os";import R from"path";import{promisify as _s}from"util";var Es=`// BuoyPhoneProfile: makes an app on the iOS Simulator act like a real iPhone.
5
+ //
6
+ // A simulator app is a plain Mac process. It sees the Mac's RAM and cores and
7
+ // nothing ever stops it from growing. The farm loads this library into the app
8
+ // (simctl launch passes SIMCTL_CHILD_DYLD_INSERT_LIBRARIES) so that:
9
+ // - the app is told the phone's RAM and CPU count,
10
+ // - it gets low-memory warnings where the phone would send them,
11
+ // - going past the phone's per-app limit is reported (or ends the app), and
12
+ // - a safety cap always ends a runaway app before it eats the Mac's RAM.
13
+ //
14
+ // Settings (env vars, all optional; bad values fall back to the default and are
15
+ // listed in the "profile_loaded" event as "ignored"):
16
+ // BUOY_PROFILE_NAME label in events (default "iPhone SE (2nd generation)")
17
+ // BUOY_PROFILE_RAM_MB RAM the app is told about (default 2957, a real SE 2)
18
+ // BUOY_PROFILE_CPUS CPU count the app is told (default 6)
19
+ // BUOY_PROFILE_LIMIT_MB the phone's per-app limit (default 2098, a real SE 2)
20
+ // BUOY_PROFILE_WARN_MB first low-memory warning (default 1707, a real SE 2)
21
+ // BUOY_PROFILE_ON_LIMIT "warn" (default): report it, keep running; "kill": end the app like the phone
22
+ // BUOY_PROFILE_CAP_MB safety cap, always ends the app (default limit + 1024; "0" = off)
23
+ // BUOY_PROFILE_EVENTS file to append one JSON event per line to
24
+ // BUOY_PROFILE_OBSERVE "1": change nothing, only report (for measuring a real phone)
25
+ // BUOY_PROFILE_SAMPLE_MS also report the footprint this often (default 0 = off, min 100)
26
+ //
27
+ // Footprint is phys_footprint, the number iOS jetsam uses on a real phone.
28
+ // The library never links UIKit, so it is safe in any process.
29
+
30
+ #import <Foundation/Foundation.h>
31
+ #import <objc/runtime.h>
32
+ #import <objc/message.h>
33
+ #import <mach/mach.h>
34
+ #import <sys/sysctl.h>
35
+ #import <os/proc.h>
36
+ #import <os/log.h>
37
+ #import <signal.h>
38
+ #import <string.h>
39
+ #import <stdlib.h>
40
+ #import <errno.h>
41
+ #import <fcntl.h>
42
+ #import <unistd.h>
43
+
44
+ #define MB (1024ull * 1024ull)
45
+
46
+ static uint64_t gRamBytes, gLimitBytes, gWarnBytes, gCapBytes;
47
+ static int gCpus;
48
+ static bool gKillAtLimit, gObserve;
49
+ static long gSampleMs;
50
+ static NSString *gName;
51
+ static int gEventsFd = -1;
52
+ static os_log_t gLog;
53
+ static dispatch_queue_t gEmitQueue;
54
+ static NSMutableArray<NSString *> *gIgnored;
55
+
56
+ // ---- Settings ---------------------------------------------------------------
57
+
58
+ // A whole number in [lo, hi], or \`fallback\` (and the key is noted) when the
59
+ // value is missing, not a number, or out of range. Never returns garbage.
60
+ static long envNumber(const char *key, long fallback, long lo, long hi) {
61
+ const char *v = getenv(key);
62
+ if (!v || !*v) return fallback;
63
+ errno = 0;
64
+ char *end = NULL;
65
+ long n = strtol(v, &end, 10);
66
+ if (errno || end == v || *end != '\\0' || n < lo || n > hi) {
67
+ [gIgnored addObject:[NSString stringWithFormat:@"%s=%s", key, v]];
68
+ return fallback;
69
+ }
70
+ return n;
71
+ }
72
+
73
+ static uint64_t footprintBytes(void) {
74
+ task_vm_info_data_t info;
75
+ mach_msg_type_number_t count = TASK_VM_INFO_COUNT;
76
+ if (task_info(mach_task_self(), TASK_VM_INFO, (task_info_t)&info, &count) != KERN_SUCCESS) return 0;
77
+ return info.phys_footprint;
78
+ }
79
+
80
+ // One JSON object per line. Writes are serialized and use O_APPEND with a
81
+ // single write(), so lines from several threads (or several apps sharing a
82
+ // file) never interleave.
83
+ static void emit(NSString *event, NSDictionary *extra) {
84
+ NSMutableDictionary *d = [NSMutableDictionary dictionaryWithDictionary:@{
85
+ @"event": event,
86
+ @"profile": gName ?: @"",
87
+ @"pid": @(getpid()),
88
+ @"footprintMB": @(footprintBytes() / MB),
89
+ @"limitMB": @(gLimitBytes / MB),
90
+ @"t": @([[NSDate date] timeIntervalSince1970]),
91
+ }];
92
+ if (extra) [d addEntriesFromDictionary:extra];
93
+ NSData *json = [NSJSONSerialization dataWithJSONObject:d options:0 error:nil];
94
+ if (!json) return;
95
+ NSMutableData *line = [json mutableCopy];
96
+ [line appendBytes:"\\n" length:1];
97
+ dispatch_sync(gEmitQueue, ^{
98
+ os_log(gLog, "%{public}.*s", (int)json.length, (const char *)json.bytes);
99
+ if (gEventsFd >= 0) (void)write(gEventsFd, line.bytes, line.length);
100
+ });
101
+ }
102
+
103
+ // ---- What the app is told about the hardware -------------------------------
104
+
105
+ // libSystem calls sysctl before our constructor runs. Until gReady is set,
106
+ // every hook passes straight through. Calls made from this file are not
107
+ // interposed, so they reach the real functions.
108
+ static volatile bool gReady;
109
+
110
+ static unsigned long long fakePhysicalMemory(id self, SEL _cmd) { return gRamBytes; }
111
+ static NSUInteger fakeProcessorCount(id self, SEL _cmd) { return (NSUInteger)gCpus; }
112
+
113
+ // Answer like the real sysctl: same value size, same NULL-buffer size query,
114
+ // same ENOMEM when the caller's buffer is too small.
115
+ static int fakeValue(void *oldp, size_t *oldlenp, size_t realSize, uint64_t value) {
116
+ if (realSize != 4 && realSize != 8) return -2; // unknown shape: let the real call answer
117
+ if (!oldlenp) { errno = EINVAL; return -1; }
118
+ if (!oldp) { *oldlenp = realSize; return 0; }
119
+ if (*oldlenp < realSize) { errno = ENOMEM; return -1; }
120
+ if (realSize == 8) { uint64_t v = value; memcpy(oldp, &v, 8); }
121
+ else { uint32_t v = value > UINT32_MAX ? UINT32_MAX : (uint32_t)value; memcpy(oldp, &v, 4); }
122
+ *oldlenp = realSize;
123
+ return 0;
124
+ }
125
+
126
+ typedef enum { FAKE_NONE, FAKE_RAM, FAKE_CPUS, FAKE_ONE } FakeKind;
127
+
128
+ static FakeKind kindForName(const char *name) {
129
+ if (!strcmp(name, "hw.memsize") || !strcmp(name, "hw.physmem") || !strcmp(name, "hw.memsize_usable")) return FAKE_RAM;
130
+ if (!strcmp(name, "hw.ncpu") || !strcmp(name, "hw.activecpu") || !strcmp(name, "hw.physicalcpu") ||
131
+ !strcmp(name, "hw.logicalcpu") || !strcmp(name, "hw.physicalcpu_max") || !strcmp(name, "hw.logicalcpu_max"))
132
+ return FAKE_CPUS;
133
+ // Core types: report one kind with all the phone's cores, so code that sizes
134
+ // thread pools per core type (perflevel0 = fastest) sees the phone's count.
135
+ if (!strcmp(name, "hw.nperflevels")) return FAKE_ONE;
136
+ if (!strncmp(name, "hw.perflevel0.", 14)) {
137
+ const char *k = name + 14;
138
+ if (!strcmp(k, "physicalcpu") || !strcmp(k, "logicalcpu") || !strcmp(k, "physicalcpu_max") || !strcmp(k, "logicalcpu_max"))
139
+ return FAKE_CPUS;
140
+ }
141
+ return FAKE_NONE;
142
+ }
143
+
144
+ static int hookSysctlbyname(const char *name, void *oldp, size_t *oldlenp, void *newp, size_t newlen) {
145
+ if (gReady && name && !newp) {
146
+ FakeKind k = kindForName(name);
147
+ if (k != FAKE_NONE) {
148
+ size_t realSize = 0;
149
+ if (sysctlbyname(name, NULL, &realSize, NULL, 0) == 0) {
150
+ uint64_t v = k == FAKE_RAM ? gRamBytes : k == FAKE_ONE ? 1 : (uint64_t)gCpus;
151
+ int r = fakeValue(oldp, oldlenp, realSize, v);
152
+ if (r != -2) return r;
153
+ }
154
+ }
155
+ }
156
+ return sysctlbyname(name, oldp, oldlenp, newp, newlen);
157
+ }
158
+
159
+ static int hookSysctl(int *mib, u_int len, void *oldp, size_t *oldlenp, void *newp, size_t newlen) {
160
+ if (gReady && mib && len == 2 && mib[0] == CTL_HW && !newp) {
161
+ FakeKind k = (mib[1] == HW_MEMSIZE || mib[1] == HW_PHYSMEM) ? FAKE_RAM
162
+ : (mib[1] == HW_NCPU || mib[1] == HW_AVAILCPU) ? FAKE_CPUS : FAKE_NONE;
163
+ if (k != FAKE_NONE) {
164
+ size_t realSize = 0;
165
+ if (sysctl(mib, len, NULL, &realSize, NULL, 0) == 0) {
166
+ int r = fakeValue(oldp, oldlenp, realSize, k == FAKE_RAM ? gRamBytes : (uint64_t)gCpus);
167
+ if (r != -2) return r;
168
+ }
169
+ }
170
+ }
171
+ return sysctl(mib, len, oldp, oldlenp, newp, newlen);
172
+ }
173
+
174
+ // Dart (Flutter), .NET and plain C ask through sysconf instead of sysctl.
175
+ static long hookSysconf(int name) {
176
+ if (gReady) {
177
+ if (name == _SC_NPROCESSORS_CONF || name == _SC_NPROCESSORS_ONLN) return gCpus;
178
+ if (name == _SC_PHYS_PAGES) {
179
+ long page = sysconf(_SC_PAGESIZE);
180
+ if (page > 0) return (long)(gRamBytes / (uint64_t)page);
181
+ }
182
+ }
183
+ return sysconf(name);
184
+ }
185
+
186
+ // On a real phone this is "how much more can I use before jetsam". In the
187
+ // simulator it is always 0, so apps that read it behave very differently.
188
+ static size_t hookAvailableMemory(void) {
189
+ if (!gReady) return os_proc_available_memory();
190
+ uint64_t used = footprintBytes();
191
+ return used >= gLimitBytes ? 0 : (size_t)(gLimitBytes - used);
192
+ }
193
+
194
+ // DYLD interposing works for libraries loaded with DYLD_INSERT_LIBRARIES.
195
+ typedef struct { const void *replacement; const void *original; } Interpose;
196
+ __attribute__((used, section("__DATA,__interpose")))
197
+ static const Interpose kInterposes[] = {
198
+ { (const void *)hookSysctlbyname, (const void *)sysctlbyname },
199
+ { (const void *)hookSysctl, (const void *)sysctl },
200
+ { (const void *)hookSysconf, (const void *)sysconf },
201
+ { (const void *)hookAvailableMemory, (const void *)os_proc_available_memory },
202
+ };
203
+
204
+ // ---- Memory watchdog --------------------------------------------------------
205
+
206
+ static void sendMemoryWarning(uint64_t atBytes) {
207
+ NSNumber *atMB = @(atBytes / MB);
208
+ dispatch_async(dispatch_get_main_queue(), ^{
209
+ // Looked up at run time: this library does not link UIKit.
210
+ Class appClass = NSClassFromString(@"UIApplication");
211
+ id app = nil;
212
+ if (appClass && [appClass respondsToSelector:@selector(sharedApplication)]) {
213
+ app = ((id (*)(id, SEL))objc_msgSend)(appClass, @selector(sharedApplication));
214
+ }
215
+ // The same private call the Simulator's "Simulate Memory Warning" uses. It
216
+ // runs the app delegate, view controllers and caches, like a real warning.
217
+ SEL perform = NSSelectorFromString(@"_performMemoryWarning");
218
+ if (app && [app respondsToSelector:perform]) {
219
+ ((void (*)(id, SEL))objc_msgSend)(app, perform);
220
+ emit(@"memory_warning", @{@"via": @"_performMemoryWarning", @"triggeredAtMB": atMB});
221
+ } else {
222
+ [NSNotificationCenter.defaultCenter postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:app];
223
+ emit(@"memory_warning", @{@"via": @"notification", @"triggeredAtMB": atMB});
224
+ }
225
+ });
226
+ }
227
+
228
+ static void endApp(NSString *event, NSDictionary *info) {
229
+ emit(event, info);
230
+ kill(getpid(), SIGKILL);
231
+ }
232
+
233
+ static void startWatchdog(void) {
234
+ dispatch_queue_t q = dispatch_queue_create("gg.buoy.phone-profile.watch",
235
+ // User-initiated so a busy Mac can't delay the check much; it is a few
236
+ // microseconds every 50 ms (about 0.1% of a core).
237
+ dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, 0));
238
+ dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, q);
239
+ dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, 0), 50 * NSEC_PER_MSEC, 10 * NSEC_PER_MSEC);
240
+ __block BOOL warned = NO, over = NO;
241
+ __block uint64_t lastSample = 0, peak = 0, lastWarn = 0;
242
+ dispatch_source_set_event_handler(timer, ^{
243
+ uint64_t now = footprintBytes();
244
+ if (now > peak) peak = now;
245
+ if (gSampleMs > 0) {
246
+ uint64_t t = clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / NSEC_PER_MSEC;
247
+ if (t - lastSample >= (uint64_t)gSampleMs) {
248
+ lastSample = t;
249
+ emit(@"sample", @{@"peakMB": @(peak / MB), @"availableMB": @(os_proc_available_memory() / MB)});
250
+ }
251
+ }
252
+ if (gObserve) return;
253
+ if (gCapBytes && now >= gCapBytes) {
254
+ endApp(@"safety_kill", @{@"capMB": @(gCapBytes / MB), @"peakMB": @(peak / MB), @"triggeredAtMB": @(now / MB)});
255
+ }
256
+ if (now >= gLimitBytes && !over) {
257
+ over = YES;
258
+ if (gKillAtLimit) endApp(@"jetsam_kill", @{@"peakMB": @(peak / MB), @"triggeredAtMB": @(now / MB)});
259
+ // Warn mode: a real phone would have ended the app here. Keep going.
260
+ emit(@"over_limit", @{@"peakMB": @(peak / MB), @"triggeredAtMB": @(now / MB)});
261
+ }
262
+ if (over && now < gLimitBytes * 9 / 10) over = NO;
263
+ uint64_t ms = clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / NSEC_PER_MSEC;
264
+ // Like a phone under pressure: warn when the line is crossed, and again
265
+ // every 10 s while the app stays above it.
266
+ if (now >= gWarnBytes && (!warned || ms - lastWarn >= 10000)) { warned = YES; lastWarn = ms; sendMemoryWarning(now); }
267
+ // Re-arm once the app has freed a good share of its memory.
268
+ if (warned && now < gWarnBytes * 9 / 10) warned = NO;
269
+ });
270
+ dispatch_resume(timer);
271
+ // Keep the timer alive for the life of the process.
272
+ objc_setAssociatedObject(NSProcessInfo.processInfo, "buoyPhoneProfileTimer", (id)timer, OBJC_ASSOCIATION_RETAIN);
273
+ }
274
+
275
+ // Take our own path out of DYLD_INSERT_LIBRARIES (keeping anything else, such
276
+ // as Detox's library) so a process this app starts does not get the profile.
277
+ static void dropSelfFromInsertList(void) {
278
+ const char *list = getenv("DYLD_INSERT_LIBRARIES");
279
+ if (!list) return;
280
+ NSString *all = [NSString stringWithUTF8String:list];
281
+ if (!all) return; // not UTF-8: leave it as it is rather than lose someone's library
282
+ NSMutableArray *keep = [NSMutableArray array];
283
+ for (NSString *p in [all componentsSeparatedByString:@":"]) {
284
+ if (p.length && ![p.lastPathComponent hasPrefix:@"BuoyPhoneProfile"]) [keep addObject:p];
285
+ }
286
+ if (keep.count) setenv("DYLD_INSERT_LIBRARIES", [keep componentsJoinedByString:@":"].UTF8String, 1);
287
+ else unsetenv("DYLD_INSERT_LIBRARIES");
288
+ }
289
+
290
+ __attribute__((constructor))
291
+ static void buoyPhoneProfileInit(void) {
292
+ @autoreleasepool {
293
+ gLog = os_log_create("gg.buoy.phone-profile", "profile");
294
+ gEmitQueue = dispatch_queue_create("gg.buoy.phone-profile.emit", DISPATCH_QUEUE_SERIAL);
295
+ gIgnored = [NSMutableArray array];
296
+
297
+ const char *name = getenv("BUOY_PROFILE_NAME");
298
+ gName = (name && *name) ? @(name) : @"iPhone SE (2nd generation)";
299
+ long ramMB = envNumber("BUOY_PROFILE_RAM_MB", 2957, 256, 1024 * 1024);
300
+ long cpus = envNumber("BUOY_PROFILE_CPUS", 6, 1, 256);
301
+ long limitMB = envNumber("BUOY_PROFILE_LIMIT_MB", 2098, 64, 1024 * 1024);
302
+ if (limitMB > ramMB) {
303
+ [gIgnored addObject:[NSString stringWithFormat:@"BUOY_PROFILE_LIMIT_MB=%ld (above RAM)", limitMB]];
304
+ limitMB = ramMB * 7 / 10;
305
+ }
306
+ // The default warning is the SE's measured one when it fits under the
307
+ // limit, else 80% of the limit.
308
+ long defaultWarnMB = 1707 < limitMB ? 1707 : limitMB * 8 / 10;
309
+ long warnMB = envNumber("BUOY_PROFILE_WARN_MB", defaultWarnMB, 32, 1024 * 1024);
310
+ if (warnMB >= limitMB) {
311
+ [gIgnored addObject:[NSString stringWithFormat:@"BUOY_PROFILE_WARN_MB=%ld (not below the limit)", warnMB]];
312
+ warnMB = defaultWarnMB;
313
+ }
314
+ long capMB = envNumber("BUOY_PROFILE_CAP_MB", limitMB + 1024, 0, 1024 * 1024);
315
+ if (capMB != 0 && capMB <= limitMB) {
316
+ // A cap under the phone's limit would end apps a real phone keeps. Never.
317
+ [gIgnored addObject:[NSString stringWithFormat:@"BUOY_PROFILE_CAP_MB=%ld (not above the limit)", capMB]];
318
+ capMB = limitMB + 1024;
319
+ }
320
+ gRamBytes = (uint64_t)ramMB * MB;
321
+ gCpus = (int)cpus;
322
+ gLimitBytes = (uint64_t)limitMB * MB;
323
+ gWarnBytes = (uint64_t)warnMB * MB;
324
+ gCapBytes = (uint64_t)capMB * MB;
325
+
326
+ const char *onLimit = getenv("BUOY_PROFILE_ON_LIMIT");
327
+ gKillAtLimit = onLimit && !strcmp(onLimit, "kill");
328
+ if (onLimit && *onLimit && strcmp(onLimit, "kill") && strcmp(onLimit, "warn"))
329
+ [gIgnored addObject:[NSString stringWithFormat:@"BUOY_PROFILE_ON_LIMIT=%s", onLimit]];
330
+ const char *observe = getenv("BUOY_PROFILE_OBSERVE");
331
+ gObserve = observe && !strcmp(observe, "1");
332
+ gSampleMs = envNumber("BUOY_PROFILE_SAMPLE_MS", 0, 0, 3600 * 1000);
333
+ if (gSampleMs > 0 && gSampleMs < 100) gSampleMs = 100;
334
+
335
+ const char *events = getenv("BUOY_PROFILE_EVENTS");
336
+ if (events && *events) {
337
+ gEventsFd = open(events, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644);
338
+ if (gEventsFd < 0) os_log(gLog, "BuoyPhoneProfile: cannot open events file %{public}s (errno %d)", events, errno);
339
+ }
340
+ dropSelfFromInsertList();
341
+
342
+ if (gObserve) {
343
+ emit(@"observe_loaded", @{@"sampleMs": @(gSampleMs), @"ignored": gIgnored});
344
+ startWatchdog();
345
+ return;
346
+ }
347
+
348
+ Class pi = NSProcessInfo.class;
349
+ SEL sels[] = { @selector(physicalMemory), @selector(processorCount), @selector(activeProcessorCount) };
350
+ IMP imps[] = { (IMP)fakePhysicalMemory, (IMP)fakeProcessorCount, (IMP)fakeProcessorCount };
351
+ for (int i = 0; i < 3; i++) {
352
+ Method m = class_getInstanceMethod(pi, sels[i]);
353
+ if (m) method_setImplementation(m, imps[i]);
354
+ }
355
+ gReady = true;
356
+ emit(@"profile_loaded", @{
357
+ @"ramMB": @(ramMB), @"cpus": @(gCpus), @"warnMB": @(warnMB), @"capMB": @(capMB),
358
+ @"onLimit": gKillAtLimit ? @"kill" : @"warn", @"ignored": gIgnored,
359
+ });
360
+ startWatchdog();
361
+ }
362
+ }
363
+ `;var Bs="499c4e3de0f8";var Is='// PhoneProbe: a tiny app `farm phone measure` puts on a real iPhone for a few\n// seconds. It prints what the phone reports, then quits:\n// physicalMemory the RAM iOS reports\n// cpus the CPU count\n// footprint this app\'s own footprint right now\n// available os_proc_available_memory(): how much more this app may use\n// footprint + available is the per-app limit (jetsam) on this phone.\n\n#import <UIKit/UIKit.h>\n#import <mach/mach.h>\n#import <os/proc.h>\n\nstatic uint64_t footprintBytes(void) {\n task_vm_info_data_t info;\n mach_msg_type_number_t count = TASK_VM_INFO_COUNT;\n if (task_info(mach_task_self(), TASK_VM_INFO, (task_info_t)&info, &count) != KERN_SUCCESS) return 0;\n return info.phys_footprint;\n}\n\n// iOS 27 ends apps that don\'t use scenes, so the window comes from a scene delegate.\n@interface ProbeSceneDelegate : UIResponder <UIWindowSceneDelegate>\n@property (nonatomic, strong) UIWindow *window;\n@end\n\n@implementation ProbeSceneDelegate\n- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)options {\n self.window = [[UIWindow alloc] initWithWindowScene:(UIWindowScene *)scene];\n self.window.rootViewController = [UIViewController new];\n self.window.rootViewController.view.backgroundColor = UIColor.systemTealColor;\n [self.window makeKeyAndVisible];\n}\n@end\n\n@interface ProbeDelegate : UIResponder <UIApplicationDelegate>\n@end\n\n@implementation ProbeDelegate\n- (UISceneConfiguration *)application:(UIApplication *)app configurationForConnectingSceneSession:(UISceneSession *)session options:(UISceneConnectionOptions *)options {\n UISceneConfiguration *c = [[UISceneConfiguration alloc] initWithName:@"Default" sessionRole:session.role];\n c.delegateClass = ProbeSceneDelegate.class;\n return c;\n}\n- (BOOL)application:(UIApplication *)app didFinishLaunchingWithOptions:(NSDictionary *)opts {\n NSProcessInfo *pi = NSProcessInfo.processInfo;\n fprintf(stdout, "BUOY_PROBE physicalMemory=%llu cpus=%lu footprint=%llu available=%zu\\n",\n pi.physicalMemory, (unsigned long)pi.processorCount, footprintBytes(), os_proc_available_memory());\n fflush(stdout);\n dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), dispatch_get_main_queue(), ^{ exit(0); });\n return YES;\n}\n@end\n\nint main(int argc, char *argv[]) {\n @autoreleasepool {\n return UIApplicationMain(argc, argv, nil, NSStringFromClass(ProbeDelegate.class));\n }\n}\n';var ve=_s(bs);var wt={"iphone-se-2nd-gen":{name:"iPhone SE (2nd generation)",productType:"iPhone12,8",ramMB:2957,cpus:6,limitMB:2098,warnMB:1707,warnSource:"measured (plain memory test); the phone warned at 1,134 MB in a photos test",ios:"26.5",measuredAt:"2026-10-14"}};var gt="iphone-se-2nd-gen";var xe="off";function x(){return process.env.BUOY_FARM_HOME||R.join(Ce.homedir(),".buoy","farm")}function Se(e=x()){return R.join(e,"phone")}function yt(e=x()){return R.join(Se(e),"phones.json")}function vt(e){const t=e;const s=(i,n,a)=>typeof i==="number"&&Number.isInteger(i)&&i>=n&&i<=a;return!!t&&typeof t==="object"&&typeof t.name==="string"&&t.name.length>0&&t.name.length<=100&&typeof t.productType==="string"&&s(t.ramMB,256,1<<20)&&s(t.cpus,1,256)&&s(t.limitMB,64,t.ramMB)&&s(t.warnMB,32,t.limitMB-1)}function Z(e=x()){const t={...wt};try{const s=JSON.parse(Ms(yt(e),"utf8"));for(const[i,n]of Object.entries(s?.phones??{})){if(/^[a-z0-9][a-z0-9-]{0,63}$/.test(i)&&vt(n))t[i]=n}}catch{}return t}async function St(e,t,s=x()){if(!/^[a-z0-9][a-z0-9-]{0,63}$/.test(e))throw new Error(`Bad phone id ${e}.`);if(!vt(t))throw new Error(`Bad phone numbers for ${e}.`);const i=yt(s);let n={phones:{}};try{n=JSON.parse(await B.readFile(i,"utf8"));if(!n||typeof n.phones!=="object")n={phones:{}}}catch{}n.phones[e]=t;await B.mkdir(R.dirname(i),{recursive:true});const a=`${i}.${process.pid}.tmp`;await B.writeFile(a,JSON.stringify(n,null,2)+"\n");await B.rename(a,i)}function kt(e){return Math.max(3072,e.limitMB+1024)}function bt(e,t,s){const i=t.capMB>e.limitMB?t.capMB:kt(e);return{BUOY_PROFILE_NAME:e.name,BUOY_PROFILE_RAM_MB:String(e.ramMB),BUOY_PROFILE_CPUS:String(e.cpus),BUOY_PROFILE_LIMIT_MB:String(e.limitMB),BUOY_PROFILE_WARN_MB:String(e.warnMB),BUOY_PROFILE_ON_LIMIT:t.onLimit,BUOY_PROFILE_CAP_MB:String(i),BUOY_PROFILE_EVENTS:s}}function Ue(...e){const t=new Set;const s=[];for(const i of e){for(const n of(i??"").split(":")){const a=n.trim();if(a&&!t.has(a)){t.add(a);s.push(a)}}}return s.join(":")}function re(e,t=x()){if(!/^[0-9A-F-]{36}$/i.test(e))throw new Error(`not a UDID: ${e}`);return R.join(Se(t),`${e}.launch.json`)}function ke(e,t=x()){if(!/^[0-9A-F-]{36}$/i.test(e))throw new Error(`not a UDID: ${e}`);return R.join(Se(t),`${e}.events.jsonl`)}async function Mt(e,t=x()){const s=re(e.udid,t);await B.mkdir(R.dirname(s),{recursive:true});const i=`${s}.${process.pid}.tmp`;await B.writeFile(i,JSON.stringify(e,null,2)+"\n");await B.rename(i,s)}async function be(e,t=x()){await B.rm(re(e,t),{force:true})}async function _t(e,t=x()){try{const s=JSON.parse(await B.readFile(re(e,t),"utf8"));if(s?.udid!==e||typeof s.dylib!=="string"||!s.vars||typeof s.vars!=="object")return null;await B.access(s.dylib);return s}catch{return null}}async function Os(e){try{const{stdout:t}=await ve("xcrun",["simctl","spawn",e,"launchctl","getenv","DYLD_INSERT_LIBRARIES"],{timeout:1e4});return t.trim()}catch{return""}}async function je(e,t,s,i=x(),n=Os){const a=await _t(e,i);if(!a||a.bundleId!==t){return s?{SIMCTL_CHILD_DYLD_INSERT_LIBRARIES:Ue(process.env.SIMCTL_CHILD_DYLD_INSERT_LIBRARIES,await n(e),s)}:{}}const o={};for(const[r,l]of Object.entries(a.vars))o[`SIMCTL_CHILD_${r}`]=l;o.SIMCTL_CHILD_DYLD_INSERT_LIBRARIES=Ue(process.env.SIMCTL_CHILD_DYLD_INSERT_LIBRARIES,await n(e),s,a.dylib);return o}function Et(e){const t=[];for(const s of e.split("\n")){if(!s.trim())continue;try{const i=JSON.parse(s);if(i&&typeof i.event==="string"&&typeof i.pid==="number")t.push(i)}catch{}}return t}function Bt(e){let t=-1;for(let a=e.length-1;a>=0;a--)if(e[a].event==="profile_loaded"){t=a;break}if(t<0)return{loaded:false,ignored:[],memoryWarnings:0,overLimit:false,peakMB:0};const s=e[t];const i=e.slice(t).filter(a=>a.pid===s.pid);const n={pid:s.pid,loaded:true,ignored:Array.isArray(s.ignored)?s.ignored:[],memoryWarnings:0,overLimit:false,peakMB:0};for(const a of i){n.peakMB=Math.max(n.peakMB,a.footprintMB??0,typeof a.peakMB==="number"?a.peakMB:0);n.lastFootprintMB=a.footprintMB;if(a.event==="memory_warning")n.memoryWarnings++;if(a.event==="over_limit")n.overLimit=true;if(a.event==="jetsam_kill"){n.overLimit=true;n.ended="limit"}if(a.event==="safety_kill"){n.overLimit=true;n.ended="safety"}}return n}async function Me(e,t=x()){const s=ke(e,t);try{const i=await B.open(s,"r");try{const{size:n}=await i.stat();const a=Math.min(n,256*1024);const o=Buffer.alloc(a);await i.read(o,0,a,n-a);let r=o.toString("utf8");if(a<n)r=r.slice(r.indexOf("\n")+1);return Bt(Et(r))}finally{await i.close()}}catch{return null}}async function As(){try{const{stdout:e}=await ve("xcodebuild",["-version"],{timeout:3e4});return e.trim().split("\n").pop().replace(/^Build version\s*/,"").replace(/[^\w.-]/g,"")||"unknown"}catch{return"unknown"}}async function It(e){const t=R.join(e,"BuoyPhoneProfile.dylib");try{await B.access(t);return t}catch{}const s=await B.mkdtemp(R.join(Ce.tmpdir(),"buoy-phone-profile-"));try{const i=R.join(s,"BuoyPhoneProfile.m");await B.writeFile(i,Es);const n=R.join(s,"BuoyPhoneProfile.dylib");await ve("xcrun",["--sdk","iphonesimulator","clang","-arch","arm64","-arch","x86_64","-mios-simulator-version-min=13.0","-fobjc-arc","-O2","-Wall","-Werror","-dynamiclib","-framework","Foundation","-install_name","@rpath/BuoyPhoneProfile.dylib",i,"-o",n],{timeout:18e4,maxBuffer:8*1024*1024,env:{...process.env,TMPDIR:s}});await ve("codesign",["-f","-s","-",n],{timeout:6e4});await B.mkdir(e,{recursive:true});const a=`${t}.${process.pid}`;await B.copyFile(n,a);await B.rename(a,t);return t}finally{await B.rm(s,{recursive:true,force:true}).catch(()=>void 0)}}var Ot=class{constructor(e=R.join(Ce.homedir(),".buoy","phone-profile")){this.root=e;this.built=null;this.key="";this.error="";this.failedAt=0}dylib(){if(process.platform!=="darwin"){this.error="Phone profiles need a Mac.";return Promise.resolve(null)}const e=process.env.DEVELOPER_DIR??"";if(this.built&&this.key===e)return this.built;if(this.key===e&&this.failedAt&&Date.now()-this.failedAt<5*6e4)return Promise.resolve(null);if(this.key!==e)this.failedAt=0;this.key=e;this.error="";this.built=As().then(t=>It(R.join(this.root,`${t}-${Bs}`))).catch(t=>{const s=t;this.error=(s.stderr||s.message||"build failed").trim().split("\n").slice(-3).join(" ").slice(0,300);this.built=null;this.failedAt=Date.now();return null});return this.built}lastError(){return this.error}};var ee=1024**3;var Fe="Buoy Farm ";var We=".buoy-farm.json";var Ds=120;var Ps=180;var Ge=9e4;var At=500;var Dt=200;var Ts=3;var H=["done","failed","stopped","interrupted"];var Pt=["setting-up","working","waiting","passed","failed","needs-help"];var Rs={now:()=>performance.now()};var Ns=10*6e4;var Tt=class{constructor(){this.tails=new Map}run(e,t){const s=this.tails.get(e)??Promise.resolve();const i=s.catch(()=>{}).then(t);this.tails.set(e,i);i.finally(()=>{if(this.tails.get(e)===i)this.tails.delete(e)}).catch(()=>{});return i}};var $s=class{constructor(){this.counts=new Map}get size(){return this.counts.size}has(e){return this.counts.has(e)}add(e){this.counts.set(e,(this.counts.get(e)??0)+1)}delete(e){const t=(this.counts.get(e)??0)-1;if(t>0)this.counts.set(e,t);else this.counts.delete(e)}};var Ls=class{constructor(e){this.free=e;this.waiting=[]}async use(e){if(this.free>0)this.free--;else await new Promise(t=>this.waiting.push(t));try{return await e()}finally{const t=this.waiting.shift();if(t)t();else this.free++}}};var Rt=class{constructor(e){this.phoneFailed=new Map;this.simLock=new Tt;this.deadlines=new Map;this.reservations=new Map;this.busy=new $s;this.ticking=false;this.hardDeadlines=new Map;this.acquiring=new Set;this.budgetLock=new Tt;this.labels=new Map;this.inflight=new Map;this.workContext=new as;this.activeWork=0;this.lockQueues=new Map;this.fileTasks=new Set;this.checkActive=()=>this.store.assertActive();this.shotsInFlight=0;this.pendingBg=0;this.host=new Proxy(e.host,{get:(t,s)=>{const i=Reflect.get(t,s);if(typeof i!=="function")return i;return async(...n)=>{this.store.assertActive();const a=await i.apply(t,n);this.store.assertActive();return a}}});this.store=e.store;this.clock=e.clock??Rs;this.log=e.log??(()=>{});this.pollMs=e.pollMs??1e3;this.readyTimeoutMs=e.readyTimeoutMs??12e4;this.phoneBuilder=e.phoneBuilder??new Ot;this.phoneLoadTimeoutMs=e.phoneLoadTimeoutMs??1e4;this.bootGate=new Ls(this.state.settings.maxConcurrentBoots);this.meter=new mt(this.host,()=>{const t=this.state.locks["perf-slot"];const s=t&&this.state.leases[t.leaseId];return s?{leaseId:s.id,udids:s.sims}:null})}async createTemplate(e){return this.work(void 0,()=>this.createTemplateWork(e))}async cloneSim(e,t){return this.work(void 0,()=>this.cloneSimWork(e,t))}async bootSim(e,t){return this.work(t,()=>this.bootSimWork(e,t))}async parkSim(e,t="idle"){return this.work(void 0,()=>this.parkSimWork(e,t))}async deleteSim(e,t){return this.work(t,()=>this.deleteSimWork(e,t))}async rebuildSim(e,t){return this.work(void 0,()=>this.simLock.run(`rebuild:${e}`,()=>this.rebuildSimWork(e,t)))}async fastReset(e,t){return this.work(void 0,()=>this.fastResetWork(e,t))}async claimOne(e,t){return this.work(e.id,()=>this.claimOneWork(e,t))}async action(e,t,s,i,n,a){this.touch(this.liveLease(e,t,a));const o=this.state.locks["perf-slot"];if(i==="screenshot"&&o&&o.leaseId!==e)throw new d("HOST_BUSY","A speed test is running. No screenshots right now.",void 0,true);return this.work(i==="reset"||i==="rebuild"?void 0:e,()=>this.actionWork(e,t,s,i,n,a))}async work(e,t){this.store.assertActive();if(this.workContext.getStore()?.active)return t();while(this.state.locks["perf-slot"]&&this.state.locks["perf-slot"].leaseId!==e){await W(this.pollMs);this.store.assertActive()}const s={active:true,leaseId:e};this.activeWork++;try{return await this.workContext.run(s,t)}finally{s.active=false;this.activeWork--}}async files(e){this.checkActive();const t=e();this.fileTasks.add(t);try{const s=await t;this.checkActive();return s}finally{this.fileTasks.delete(t)}}fence(){this.store.fence()}async settleFiles(){await Promise.allSettled([...this.fileTasks])}get state(){return this.store.state}async recover(){for(const[i,n]of Object.entries(this.state.locks)){if(!this.state.leases[n.leaseId])delete this.state.locks[i]}const e=await this.host.listDevices();const t=new Map(e.map(i=>[i.udid,i]));for(const i of Object.values(this.state.sims)){const n=t.get(i.udid);if(!n){this.store.event({kind:"lost",message:`${i.name} was deleted outside the farm.`,udid:i.udid});if(i.leaseId)this.dropFromLease(i.leaseId,i.udid);await this.files(()=>this.forgetPhone(i.udid)).catch(()=>void 0);delete this.state.sims[i.udid];continue}if(n.state==="Booted"){i.power=i.power==="frozen"?"frozen":"awake";if(i.power!=="frozen"){const a=this.state.templates[i.templateId];const o=await this.health(i.udid,a?J(a.profile):[]);i.profile=o.profile;i.lastCheckAt=new Date().toISOString();if(!o.ok||a?.profile==="slim"&&o.profile==="unknown"){i.health="suspect";i.lastError=o.faults.join("; ")||"Slim state is not known."}}}else{i.power=i.power==="parked"?"parked":"cold"}if(["creating","booting","thawing","deleting"].includes(i.power))i.power=n.state==="Booted"?"awake":"cold"}for(const i of Object.values(this.state.templates)){const n=t.get(i.udid);if(!n){i.usable=false;i.note="Its sim was deleted outside the farm."}else if(!et(i.appPath)){i.note="Its app build is gone. Clones still work; rebuild the template for a new build."}}for(const i of Object.keys(this.state.orphans)){if(!t.has(i))delete this.state.orphans[i]}for(const i of this.store.pending){if(i.op==="clone"){const n=i.data?.name;const a=e.find(o=>o.name===n&&!this.state.sims[o.udid]);if(a){this.state.orphans[a.udid]={udid:a.udid,name:a.name,cloneIntentName:n};this.store.event({kind:"orphan",message:`Found ${a.name} with no record after a crash. Held for review. Use farm delete to remove it.`,udid:a.udid})}}if(i.op!=="rebuild")this.store.result(i.seq,i.op,{recovered:true})}const s=new Set;for(const i of[...this.store.pending]){if(i.op!=="rebuild")continue;const{udid:n,name:a,templateId:o}=i.data;if(Object.values(this.state.orphans).some(r=>r.name===a))continue;s.add(n);this.busy.add(n);this.background(`resume rebuild ${a}`,()=>this.work(void 0,async()=>{try{const r=Object.values(this.state.sims).find(l=>l.name===a&&l.udid!==n);if(!r){if(this.state.sims[n]){const l=this.state.sims[n];if(l.leaseId)this.dropFromLease(l.leaseId,n);l.leaseId=void 0;await this.deleteSim(n)}await this.cloneSim(o,a)}this.store.result(i.seq,"rebuild",{recovered:true})}finally{this.busy.delete(n)}}))}for(const i of Object.values(this.state.leases)){this.deadlines.set(i.id,this.clock.now()+Ge);const n=Date.parse(i.createdAt)+i.ttlMs-Date.now();this.hardDeadlines.set(i.id,this.clock.now()+Math.max(n,0));if(n<=0)this.background(`expire ${i.id}`,()=>this.endLease(i.id,"ran out of time while the farm was down","full","deadline"))}for(const i of Object.values(this.state.sims)){if(i.health==="dirty"&&!i.leaseId&&!s.has(i.udid)){this.busy.add(i.udid);this.background(`resume reset ${i.name}`,async()=>{try{await this.rebuildSim(i.udid)}finally{this.busy.delete(i.udid)}})}}this.store.save()}async dataPath(e){const t=await this.host.dataPathOf?.(e);if(t)return t;const s=(await this.host.listDevices()).find(i=>i.udid===e);if(!s)throw new d("NOT_FOUND",`No sim ${e} on this Mac.`);return s.dataPath}async isOwned(e){const t=this.state.sims[e]??Object.values(this.state.templates).find(i=>i.udid===e);if(!t)return false;let s;try{s=await this.dataPath(e)}catch(i){if(i instanceof d&&i.code==="NOT_FOUND")return false;throw i}try{const i=JSON.parse(await A.readFile(D.join(s,We),"utf8"));return i.farmId===this.state.farmId}catch{return false}}async assertOwned(e){if(!await this.isOwned(e)){throw new d("NOT_OWNED",`Sim ${e} is not a farm sim. The farm never changes sims it did not make.`)}}async writeMarker(e,t){const s=await this.dataPath(e);await this.files(async()=>{await A.mkdir(s,{recursive:true});this.checkActive();await A.writeFile(D.join(s,We),JSON.stringify({farmId:this.state.farmId,...t})+"\n")})}farmAwakeGB(){const e=this.state.settings;let t=0;for(const s of Object.values(this.state.sims)){if(["awake","booting","frozen","thawing"].includes(s.power))t+=s.profile==="slim"?e.slimSimGB:e.stockSimGB}return t}async budget(e={ramGB:0,diskGB:0}){const t=this.state.settings;const s=await this.host.hostStats();let i=0;let n=0;for(const w of this.reservations.values()){i+=w.ramGB;n+=w.diskGB}const a=s.totalMemBytes/ee;const o=xs(a)*(s.memPressure==="warn"?2:1);const r=s.availableMemBytes/ee-i;const l=a-Cs(a,t.reserveRamGB)-this.farmAwakeGB()-i;const c=s.freeDiskBytes/ee-n-t.reserveDiskGB;const p=Math.max(0,Math.floor(Math.min(r-o,l,c/t.cloneDiskGB*t.slimSimGB)/t.slimSimGB));const h=(w,k)=>({ok:false,code:w,reason:k,stats:s,roomFor:0});if(s.memPressure==="critical")return h("RAM_LOW","This Mac is low on memory. New sims will wait.");if(e.diskGB>0&&c-e.diskGB<0){return h("DISK_LOW",`Need ${t.reserveDiskGB} GB free after this. This Mac has ${Math.floor(s.freeDiskBytes/ee)} GB.`)}if(e.ramGB>0){if(r-e.ramGB<o||l-e.ramGB<0){return h("RAM_LOW",`Not enough free memory for another sim (${Math.max(0,Math.floor(r))} GB free).`)}}const g=this.state.locks["perf-slot"];if(g&&(!this.workContext.getStore()?.active||this.workContext.getStore()?.leaseId!==g.leaseId))return h("HOST_BUSY","A speed test is running. New sims will wait.");return{ok:true,stats:s,roomFor:p}}async withReservation(e,t){const s=we(4).toString("hex");await this.budgetLock.run("budget",async()=>{const i=await this.budget(e);if(!i.ok)throw new d(i.code,i.reason,void 0,true);this.reservations.set(s,e)});try{return await t()}finally{this.reservations.delete(s)}}async health(e,t=[]){const s=[];let i;try{i=await this.host.simTree(e)}catch(r){this.checkActive();return{ok:false,profile:"unknown",faults:[`Could not read sim processes: ${r.message}`],procs:0}}if(i.length===0)return{ok:false,profile:"unknown",faults:["launchd_sim is not running"],procs:0};const n=new Set(i.map(r=>r.comm.split("/").pop()));for(const r of["SpringBoard","backboardd"])if(!n.has(r))s.push(`${r} is not running`);const a=Nt(await this.host.launchdLogTail(e));if(a)s.push(`${a} keeps crashing`);if(s.length===0){const r=await this.host.spawn(e,["launchctl","getenv","OS_ACTIVITY_MODE"],1e4);if(r.code===0&&r.stdout.trim())s.push(`OS_ACTIVITY_MODE=${r.stdout.trim()} is set for the whole sim (it was booted with SIMCTL_CHILD_OS_ACTIVITY_MODE)`)}if(s.length===0){const r=D.join(this.store.shotsPath,`${e}.png`);await this.files(()=>A.mkdir(D.dirname(r),{recursive:true}));if(!await this.host.screenshot(e,r,1e4))s.push("screenshot did not come back")}let o=i.length<Ds?"slim":i.length>Ps?"stock":"unknown";if(s.length===0&&t.length){const r=await this.host.spawn(e,["launchctl","print-disabled","system"],2e4);if(r.code===0&&!r.timedOut){const l=new Set([...r.stdout.matchAll(/"([^"]+)" => (?:disabled|true)/g)].map(p=>p[1]));const c=t.filter(p=>!l.has(p)).length;o=c===0?"slim":c===t.length?"stock":"unknown"}else{o="unknown"}}return{ok:s.length===0,profile:o,faults:s,procs:i.length}}async waitHealthy(e,t=[]){const s=performance.now()+this.readyTimeoutMs;let i=await this.health(e,t);while(!i.ok&&performance.now()<s){await W(this.pollMs);i=await this.health(e,t)}return i}async createTemplateWork(e){if(!["slim","stock"].includes(e.profile)||!Number.isInteger(e.metroPort)||e.metroPort<1||e.metroPort>65535){throw new d("BAD_REQUEST","Use slim or stock and a port from 1 to 65535.")}const t=e.seedDir==null?null:oe(e.seedDir);if(t)throw new d("NO_SEED",t,"Run: pnpm e2e:pool seed");if(!et(D.join(e.appPath,"Info.plist"))){throw new d("BAD_REQUEST",`No app build at ${e.appPath}.`,"Build the app first.")}const s=await ws(e.appPath);const i=`t-${we(3).toString("hex")}`;const n=e.name??`${Fe}Template ${i.slice(2)}`;return this.withReservation({ramGB:this.state.settings.stockSimGB,diskGB:4},async()=>{const a=this.store.intent("create-template",{id:i,name:n});const o=await this.host.create(n,e.deviceType,e.runtime);const r={id:i,udid:o,name:n,bundleId:s,appPath:e.appPath,appHash:await fs(e.appPath),seedDir:e.seedDir??null,seedHash:e.seedDir?await ms(e.seedDir):null,launchUrl:e.launchUrl,deviceType:e.deviceType,runtime:e.runtime,xcodeBuild:await this.host.xcodeBuild(),profile:e.profile,profileHash:Ze(e.profile),metroPort:e.metroPort,createdAt:new Date().toISOString(),usable:false,note:"Being built."};this.state.templates[i]=r;await this.writeMarker(o,{template:i});this.store.result(a,"create-template",{udid:o});try{await this.buildTemplate(r,e.warmLaunch!==false);r.usable=true;r.note=void 0;this.store.event({kind:"template",message:`Template ${n} is ready.`,udid:o})}catch(l){r.note=`Build failed: ${l.message}`;this.store.event({kind:"template-failed",message:r.note,udid:o});await this.host.shutdown(o).catch(()=>{});throw l}finally{this.store.save()}return r})}async buildTemplate(e,t){const s=J(e.profile);if(s.length)await this.files(()=>ot(e.udid,s,this.host.disabledRoot));await this.host.boot(e.udid);const i=await this.waitHealthy(e.udid,s);if(!i.ok)throw new Error(`template did not come up: ${i.faults.join("; ")}`);if(e.profile==="slim"&&i.profile!=="slim")throw new Error(`slim did not apply (${i.procs} processes)`);await this.host.install(e.udid,e.appPath);const n=await this.host.appContainer(e.udid,e.bundleId);if(!n)throw new Error("app installed but has no data container");if(e.seedDir)await this.files(()=>ut(n,e.bundleId,e.seedDir,this.checkActive));else await this.files(()=>ye(n,this.checkActive));await this.setPrefs(e.udid,e);if(t){await this.launchApp(e.udid,e,{phone:false});await W(Math.min(15e3,this.pollMs*15));await this.host.terminate(e.udid,e.bundleId)}await this.host.shutdown(e.udid);await this.files(()=>ye(n,this.checkActive))}async launchApp(e,t,s={}){if(s.phone===false){await this.host.launch(e,t.bundleId)}else{await this.launchAsPhone(e,t.bundleId)}if(t.launchUrl)await this.host.openUrl(e,t.launchUrl)}async launchAsPhone(e,t){const s=this.store.homeDir;const i=this.state.settings;const n=E=>{const L=this.state.sims[e];if(L)L.phone=E};const a=async E=>{const L=await this.host.spawn(E,["launchctl","getenv","DYLD_INSERT_LIBRARIES"],1e4).catch(()=>null);return L&&L.code===0?L.stdout.trim():""};const o=async E=>{await this.files(()=>be(e,s));const L=await je(e,t,void 0,s,a);await this.host.launch(e,t,L);n(E)};if(i.phoneProfile===xe)return o({status:"off"});const r=Z(s);const l=r[i.phoneProfile]?i.phoneProfile:gt;const c=r[l];const p=l!==i.phoneProfile?`No phone "${i.phoneProfile}" on this Mac, so it uses ${c.name}. `:"";const h=this.phoneFailed.get(t);if(h!==void 0&&performance.now()-h<Ns){return o({status:"fallback",phoneId:l,phoneName:c.name,note:`${p}This app did not start with the phone profile a moment ago, so it runs as a plain simulator app. The farm tries again in a few minutes.`})}const g=await this.phoneBuilder.dylib();if(!g){const E=this.phoneBuilder.lastError()||"unknown error";this.log(`phone profile: could not build the library: ${E}`);return o({status:"fallback",phoneId:l,phoneName:c.name,note:`${p}The phone profile could not be built (${E}), so the app runs as a plain simulator app.`})}const w=ke(e,s);await this.files(async()=>{await A.mkdir(D.dirname(w),{recursive:true});await A.writeFile(w,"");await Mt({udid:e,bundleId:t,dylib:g,phoneId:l,vars:bt(c,{phone:l,onLimit:i.phoneOnLimit,capMB:i.phoneCapMB},w),writtenAt:new Date().toISOString()},s)});const k=await je(e,t,void 0,s,a);await this.host.launch(e,t,k);const $=performance.now()+this.phoneLoadTimeoutMs;let f=null;for(;;){f=await Me(e,s);if(f?.loaded||performance.now()>=$)break;await W(Math.min(250,Math.max(10,this.pollMs/4)))}if(f?.loaded){this.phoneFailed.delete(t);const E=f.ignored.length?` Ignored bad settings: ${f.ignored.join(", ")}.`:"";n({status:"on",phoneId:l,phoneName:c.name,pid:f.pid,note:(p+E).trim()||void 0});return}this.log(`phone profile: ${t} on ${e} did not report it; launching without it`);this.phoneFailed.set(t,performance.now());await this.host.terminate(e,t);await o({status:"fallback",phoneId:l,phoneName:c.name,note:`${p}The app did not start with the phone profile, so it runs as a plain simulator app.`})}async setPrefs(e,t){const s=["defaults","write","com.apple.keyboard.preferences"];await this.host.spawn(e,[...s,"AutomaticMinimizationEnabled","-bool","true"]);await this.host.spawn(e,[...s,"DidShowContinuousPathIntroduction","-bool","true"]);await this.host.spawn(e,["defaults","write",t.bundleId,"RCT_jsLocation",`localhost:${t.metroPort}`])}async nextName(){const e=await this.host.listDevices();const t=new Set([...e.map(i=>i.name),...Object.values(this.state.sims).map(i=>i.name)]);let s=this.state.nextIndex;while(t.has(`${Fe}${String(s).padStart(2,"0")}`))s++;this.state.nextIndex=s+1;return`${Fe}${String(s).padStart(2,"0")}`}template(e){const t=this.state.templates[e];if(!t)throw new d("NO_TEMPLATE",`No template ${e}.`,"Run sim_farm_setup to make one.");if(!t.usable)throw new d("NO_TEMPLATE",`Template ${t.name} can't be used: ${t.note??"not ready"}.`);return t}async cloneSimWork(e,t,s){t??=await this.nextName();const i=t;const n=this.template(e);return this.withReservation({ramGB:0,diskGB:this.state.settings.cloneDiskGB},()=>this.simLock.run(`template:${n.id}`,async()=>{await this.assertOwned(n.udid);const a=this.store.intent("clone",{templateId:e,name:i});const o=await this.host.clone(n.udid,i);const r={udid:o,name:i,templateId:e,power:"creating",profile:"unknown",health:"ok",bootEpoch:0,failures:0,createdAt:new Date().toISOString()};this.state.sims[o]=r;this.store.result(a,"clone",{udid:o});await this.writeMarker(o,{template:n.id});const l=await ge(await this.dataPath(o),n.bundleId);if(l)await this.files(()=>ye(l,this.checkActive));const c=s?this.state.leases[s.leaseId]:void 0;if(c&&!this.leaseOverdue(c)){r.leaseId=c.id;c.sims=c.sims.map(p=>p===s.udid?o:p)}r.power="cold";this.store.event({kind:"clone",message:`Made ${t}.`,udid:o});this.store.save();return r}))}async bootSimWork(e,t){await this.assertOwned(e);const s=this.sim(e);if(s.power==="frozen"||s.power==="thawing"){throw new d("BAD_REQUEST",`${s.name} is frozen. Thaw it first.`)}const i=this.state.templates[s.templateId];const n=this.state.settings;const a={ramGB:i?.profile==="slim"?n.slimSimGB:n.stockSimGB,diskGB:0};return this.withReservation(a,()=>this.bootGate.use(()=>this.simLock.run(e,async()=>{this.assertLeaseState(s,t);if(s.power==="awake")return s;const o=i?J(i.profile):[];if(o.length&&!await ps(e,o,this.host.disabledRoot)){await this.files(()=>ot(e,o,this.host.disabledRoot))}s.power="booting";s.bootEpoch++;this.store.save();await this.host.boot(e);const r=await this.waitHealthy(e,i?.profile==="slim"?o:[]);s.lastCheckAt=new Date().toISOString();s.profile=r.profile;s.power="awake";if(!r.ok){s.failures++;s.health=s.failures>=2?"broken":"suspect";s.lastError=r.faults.join("; ");this.store.event({kind:"unhealthy",message:`${s.name}: ${s.lastError}`,udid:e});this.store.save();throw new d("HOST_ERROR",`${s.name} did not come up: ${s.lastError}`,"The farm will rebuild it.",true)}s.failures=0;if(s.health==="suspect")s.health="ok";s.idleSince=new Date().toISOString();if(i?.profile==="slim"&&r.profile==="unknown"){s.health="suspect";s.lastError="can't tell if slim applied";this.store.event({kind:"unknown-profile",message:`${s.name}: can't tell if slim worked. Held for now.`,udid:e});this.store.save();throw new d("HOST_ERROR",`${s.name}: can't tell if slim applied.`,"The farm will rebuild it.",true)}if(i?.profile==="slim"&&r.profile==="stock"){this.store.event({kind:"stock",message:`${s.name}: slim didn't work here (${r.profile}). It uses full RAM.`,udid:e});const l=await this.budget({ramGB:n.stockSimGB-n.slimSimGB,diskGB:0});if(!l.ok){s.health="suspect";s.lastError="slim did not apply and there is no RAM for a full sim";await this.host.shutdown(e).catch(()=>{});s.power="parked";this.store.save();throw new d("RAM_LOW",`${s.name}: slim didn't apply and there's no room for a full sim.`,void 0,true)}}this.store.save();return s})))}assertLeaseState(e,t){if(!this.state.sims[e.udid])throw new d("NOT_FOUND",`${e.name} is gone.`);if(t){const s=this.state.leases[t];if(e.leaseId!==t||!s||this.leaseOverdue(s)){throw new d("LEASE_EXPIRED",`${e.name} is no longer in lease ${t}.`)}}else if(e.leaseId){throw new d("BAD_REQUEST",`${e.name} is in use. End its lease first.`)}}async parkSimWork(e,t="idle"){await this.assertOwned(e);const s=this.sim(e);await this.simLock.run(e,async()=>{this.assertLeaseState(s);if(this.busy.has(e))throw new d("BAD_REQUEST",`${s.name} is being reset.`);if(s.power==="frozen"||s.power==="thawing")throw new d("BAD_REQUEST",`${s.name} is frozen. Wake it before parking.`);if(s.power!=="awake")return;this.busy.add(e);try{await this.host.shutdown(e);s.power="parked"}finally{this.busy.delete(e)}this.store.event({kind:"park",message:`Parked ${s.name} (${t}).`,udid:e});this.store.save()})}sim(e){const t=this.state.sims[e];if(!t)throw new d("NOT_OWNED",`Sim ${e} is not a farm sim.`);return t}async deleteSimWork(e,t){const s=this.state.orphans[e];if(s){await this.simLock.run(e,async()=>{const n=(await this.host.listDevices()).find(r=>r.udid===e);if(!n)throw new d("NOT_FOUND","This sim is gone.");let a=false;try{const r=JSON.parse(await A.readFile(D.join(n.dataPath,We),"utf8"));a=r.farmId===this.state.farmId}catch(r){a=r.code==="ENOENT"&&n.name===s.cloneIntentName}if(!a)throw new d("NOT_OWNED","This sim has no valid farm mark.");const o=this.store.intent("delete",{udid:e});await this.host.shutdown(e);await this.host.delete(e);await this.files(()=>A.rm(D.join(this.host.disabledRoot,`com.apple.CoreSimulator.SimDevice.${e}`),{recursive:true,force:true}));await this.files(()=>this.forgetPhone(e));delete this.state.orphans[e];this.store.result(o,"delete",{})});return}await this.assertOwned(e);const i=this.sim(e);await this.simLock.run(e,async()=>{this.assertLeaseState(i,t);if(i.power==="frozen"||i.power==="thawing")throw new d("BAD_REQUEST",`${i.name} is frozen. Wake it first.`);i.power="deleting";const n=this.store.intent("delete",{udid:e});await this.host.shutdown(e).catch(()=>{});await this.host.delete(e);await this.files(()=>A.rm(D.join(this.host.disabledRoot,`com.apple.CoreSimulator.SimDevice.${e}`),{recursive:true,force:true}));await this.files(()=>this.forgetPhone(e));delete this.state.sims[e];this.store.result(n,"delete",{});this.store.event({kind:"delete",message:`Deleted ${i.name}.`,udid:e})})}async rebuildSimWork(e,t){const s=this.sim(e);const{name:i,templateId:n}=s;await this.assertOwned(e);await this.simLock.run(e,async()=>{this.assertLeaseState(s,t);this.busy.add(e)});const a=this.store.intent("rebuild",{udid:e,name:i,templateId:n});try{await this.deleteSim(e,t);const o=await this.cloneSimWork(n,i,t?{udid:e,leaseId:t}:void 0);this.store.result(a,"rebuild",{udid:o.udid});return o}finally{this.busy.delete(e)}}async fastResetWork(e,t){await this.assertOwned(e);const s=this.sim(e);const i=this.template(s.templateId);await this.simLock.run(e,async()=>{this.assertLeaseState(s,t);if(s.power==="frozen"||s.power==="thawing")throw new d("BAD_REQUEST",`${s.name} is frozen. Wake it first.`);this.busy.add(e);try{if(s.power==="awake")await this.host.terminate(e,i.bundleId);const n=await ge(await this.dataPath(e),i.bundleId);if(!n)throw new Error("app container not found");if(i.seedDir)await this.files(()=>ut(n,i.bundleId,i.seedDir,this.checkActive));else await this.files(()=>ye(n,this.checkActive));s.health="ok";this.store.save()}finally{this.busy.delete(e)}})}async grow(e,t){if(!Number.isInteger(t)||t<1||t>64)throw new d("BAD_REQUEST","count must be 1 to 64.");const s=[];for(let i=0;i<t;i++)s.push(await this.cloneSim(e));return s}async shrink(e,t){if(!Number.isInteger(t)||t<1||t>64)throw new d("BAD_REQUEST","count must be 1 to 64.");const s=["cold","parked","awake"];const i=Object.values(this.state.sims).filter(a=>a.templateId===e&&!a.leaseId&&s.includes(a.power)&&!this.busy.has(a.udid)).sort((a,o)=>s.indexOf(a.power)-s.indexOf(o.power));const n=[];for(const a of i.slice(0,t)){try{await this.deleteSim(a.udid);n.push(a.name)}catch(o){if(!(o instanceof d))throw o}}return n}async removeTemplate(e){return this.work(void 0,async()=>{const t=this.state.templates[e];if(!t)throw new d("NO_TEMPLATE",`No template ${e}.`);const s=Object.values(this.state.sims).filter(o=>o.templateId===e);const i=s.filter(o=>o.leaseId||this.busy.has(o.udid));if(i.length){throw new d("HOST_BUSY",`${i.map(o=>o.name).join(", ")} ${i.length===1?"is":"are"} in use.`,"End those uses first.",true)}const n=[];for(const o of s){await this.deleteSim(o.udid);n.push(o.name)}const a=(await this.host.listDevices()).some(o=>o.udid===t.udid);if(a){await this.assertOwned(t.udid);await this.simLock.run(t.udid,async()=>{const o=this.store.intent("delete",{udid:t.udid});await this.host.shutdown(t.udid).catch(()=>{});await this.host.delete(t.udid);await this.files(()=>A.rm(D.join(this.host.disabledRoot,`com.apple.CoreSimulator.SimDevice.${t.udid}`),{recursive:true,force:true}));this.store.result(o,"delete",{})})}delete this.state.templates[e];n.push(t.name);this.store.event({kind:"delete",message:`Removed template ${t.name} and its ${s.length} sim(s).`});return{removed:n}})}leaseOverdue(e){const t=this.clock.now();if(t>(this.hardDeadlines.get(e.id)??Infinity))return true;return!this.acquiring.has(e.id)&&t>(this.deadlines.get(e.id)??0)}leaseDeadline(e){return Math.min(this.deadlines.get(e.id)??0,this.hardDeadlines.get(e.id)??Infinity)}async acquire(e){if(e.ttlMs!==void 0&&(typeof e.ttlMs!=="number"||!Number.isFinite(e.ttlMs)||e.ttlMs<=0)){throw new d("BAD_REQUEST","ttlMs must be a finite number above zero.")}const t=this.template(e.templateId);if(!Number.isInteger(e.count)||e.count<1||e.count>64)throw new d("BAD_REQUEST","count must be 1 to 64.");const s=Math.min(Math.max(e.ttlMs??15*6e4,3e4),24*36e5);const i=e.runId?this.ownRun(e.runId,e.owner.clientId):this.newRun(e,t.id,s);const n=Date.parse(i.deadlineAt)-Date.now();if(n<3e4)throw new d("RUN_ENDED","This run is almost out of time.","Ask for more with sim_farm_extend, or finish it and start a new run.");const a={id:`l-${we(4).toString("hex")}`,epoch:1,owner:e.owner,purpose:e.purpose,runId:i.id,templateId:t.id,sims:[],createdAt:new Date().toISOString(),ttlMs:Math.min(s,n)};i.leases.push(a.id);i.lastActivityAt=a.createdAt;if(e.labels?.length)this.labels.set(a.id,e.labels);this.state.leases[a.id]=a;this.hardDeadlines.set(a.id,this.clock.now()+a.ttlMs);this.acquiring.add(a.id);const o=()=>this.deadlines.set(a.id,this.clock.now()+Math.min(a.ttlMs,Ge));o();const r=performance.now()+(e.waitMs??0);const l=()=>{if(!this.state.leases[a.id])throw new d("LEASE_EXPIRED","The lease ended while sims were being prepared.");if(this.leaseOverdue(a))throw new d("LEASE_EXPIRED","The lease ran out of time while sims were being prepared.")};try{while(a.sims.length<e.count){l();o();const c=await this.claimOne(a,t);l();if(c)continue;if(performance.now()>=r)break;if(!a.sims.length&&i.state==="active"&&!Object.keys(i.lanes).length)i.state="waiting";await W(Math.max(this.pollMs,2e3))}if(a.sims.length<e.count&&!e.allowPartial){const c=await this.budget({ramGB:this.state.settings.slimSimGB,diskGB:0});throw new d(c.code??"HOST_BUSY",`Got ${a.sims.length} of ${e.count} sims. ${c.reason??"Others are in use."}`,"Try again later or ask for fewer.",true)}if(a.sims.length===0)throw new d("HOST_BUSY","No sim is free right now.","Try again later.",true);if(e.launch)await this.work(a.id,async()=>{l();await Promise.all(a.sims.map(c=>this.launchApp(c,t)));o();await this.checkIdentities(a,6e4);l()});o();this.store.event({kind:"lease",message:`${e.owner.label} took ${a.sims.length} sim(s) for ${i.goal}.`,leaseId:a.id,runId:i.id});this.note(i,"farm",`Got ${a.sims.length} sim${a.sims.length===1?"":"s"}.`);this.store.save();return{lease:a,run:i,sims:a.sims.map(c=>this.state.sims[c])}}catch(c){if(this.state.leases[a.id])this.note(i,"farm",`Could not get sims: ${c.message}`);await this.endLease(a.id,"acquire failed","fast","acquire-failed").catch(()=>{});throw c}finally{this.acquiring.delete(a.id);this.labels.delete(a.id)}}async claimOneWork(e,t){const s=Object.values(this.state.sims).filter(o=>o.templateId===t.id&&!o.leaseId&&o.health==="ok"&&!this.busy.has(o.udid));const i=s.find(o=>o.power==="awake")??s.find(o=>o.power==="parked"||o.power==="cold");const n=async o=>{const r=await this.isOwned(o.udid);return this.simLock.run(o.udid,async()=>{if(o.leaseId||this.busy.has(o.udid)||o.health!=="ok"||!this.state.sims[o.udid])return null;if(!r){o.health="broken";o.lastError="farm marker missing";this.store.save();return null}if(!this.state.leases[e.id]||this.leaseOverdue(e))return null;o.leaseId=e.id;e.sims.push(o.udid);o.idleSince=void 0;this.addLane(e,o);this.store.save();return o})};if(i?.power==="awake")return n(i);let a=null;try{if(i){a=await n(i)}else{const o=await this.budget({ramGB:t.profile==="slim"?this.state.settings.slimSimGB:this.state.settings.stockSimGB,diskGB:this.state.settings.cloneDiskGB});if(!o.ok)return null;a=await n(await this.cloneSim(t.id))}if(!a)return null;await this.bootSim(a.udid,e.id);return a}catch(o){if(a)this.unclaim(e,a.udid);if(o instanceof d&&(o.code==="RAM_LOW"||o.code==="DISK_LOW"||o.code==="HOST_BUSY"||o.code==="LEASE_EXPIRED")){return null}if(a&&this.state.sims[a.udid]?.health!=="ok"){const r=a.udid;this.background(`rebuild ${r}`,()=>this.rebuildSim(r))}throw o}}unclaim(e,t){e.sims=e.sims.filter(n=>n!==t);const s=e.runId?this.state.runs[e.runId]:void 0;if(s?.lanes[t])delete s.lanes[t];const i=this.state.sims[t];if(i&&i.leaseId===e.id)i.leaseId=void 0;this.store.save()}async checkIdentities(e,t=6e4){const s=this.template(e.templateId);const i=performance.now()+t;const n=new Map;for(;;){for(const o of e.sims){if(n.has(o))continue;const r=await ge(await this.dataPath(o),s.bundleId);const l=r?await pt(r):null;if(!l)continue;const c=[...n.entries()].find(([,h])=>h===l);if(c)throw new d("ID_CLASH",`${this.state.sims[o].name} and ${this.state.sims[c[0]].name} share one Buoy ID.`);const p=Object.values(this.state.sims).find(h=>h.udid!==o&&!e.sims.includes(h.udid)&&h.buoyDeviceId===l);if(p)throw new d("ID_CLASH",`${this.state.sims[o].name} and ${p.name} share one Buoy ID.`);n.set(o,l);this.state.sims[o].buoyDeviceId=l}if(n.size===e.sims.length||performance.now()>=i)break;await W(Math.max(this.pollMs,1e3))}const a=e.sims.filter(o=>!n.has(o));if(a.length){this.store.event({kind:"no-id",message:`No Buoy ID yet on ${a.map(o=>this.state.sims[o].name).join(", ")}. Is the app loading? Check Metro.`,leaseId:e.id})}}liveLease(e,t,s){const i=this.state.leases[e];if(!i){const n=this.runOfLease(e);if(n&&(n.endedBy==="user"||n.endedBy==="deadline"))this.assertRunOpen(n);throw new d("LEASE_EXPIRED",`Lease ${e} has ended.`,"Acquire new sims.")}if(i.epoch!==t)throw new d("STALE_EPOCH",`Lease ${e} is at epoch ${i.epoch}, not ${t}.`);if(s&&i.owner.clientId!==s)throw new d("NOT_OWNED",`Lease ${e} belongs to ${i.owner.label}.`);if(this.leaseOverdue(i)){const n=this.overdueEnd(i);this.background(`expire ${i.id}`,()=>this.endLease(i.id,"expired","full",n));if(n==="deadline")throw new d("RUN_ENDED","This run's time expired.","Ask for more time with sim_farm_extend before the end next time. Start a new run to go on.");throw new d("LEASE_EXPIRED",`Lease ${e} has expired.`,"Acquire new sims.")}return i}renew(e,t,s){const i=this.liveLease(e,t,s);const n=Math.min(this.clock.now()+Math.min(i.ttlMs,Ge),this.hardDeadlines.get(i.id)??Infinity);this.deadlines.set(i.id,n);return{expiresInMs:Math.round(n-this.clock.now())}}async release(e,t,s="fast",i,n=false){if(s!=="fast"&&s!=="full")throw new d("BAD_REQUEST","Use fast or full reset.");this.liveLease(e,t,i);return this.endLease(e,"released",s,n?null:"released")}async endLease(e,t,s,i="released"){const n=this.state.leases[e];if(!n)return{};n.epoch++;delete this.state.leases[e];this.deadlines.delete(e);this.hardDeadlines.delete(e);for(const[r,l]of Object.entries(this.state.locks))if(l.leaseId===e)delete this.state.locks[r];const a=new Set(n.sims.filter(r=>{const l=this.state.sims[r];return l?.bootEpoch===0&&l.power==="cold"&&l.health==="ok"}));const o={};for(const r of n.sims){const l=this.state.sims[r];if(!l||l.leaseId!==e)continue;l.leaseId=void 0;l.health="dirty";l.idleSince=new Date().toISOString();this.busy.add(r);o[l.name]="resetting";void this.files(()=>be(r,this.store.homeDir)).catch(()=>void 0)}this.store.event({kind:"lease-end",message:`${n.owner.label}'s ${n.purpose} ended (${t}).`,leaseId:e,runId:n.runId});this.settleRun(n,i);this.store.save();this.background(`reset after ${e}`,()=>this.work(void 0,async()=>{for(const r of n.sims){if(!this.state.sims[r])continue;try{const l=Date.parse(n.createdAt)-2e3;for(const c of await this.host.clientsOf(r)){if(Date.parse(c.start)>=l)await this.host.kill(c.pid,c.start)}if(s==="full"&&!a.has(r)||this.state.sims[r].failures>0)await this.rebuildSim(r);else await this.fastReset(r)}catch(l){this.store.event({kind:"reset-failed",message:`${this.state.sims[r]?.name??r}: ${l.message}. Rebuilding.`,udid:r});await this.rebuildSim(r).catch(()=>{})}finally{this.busy.delete(r)}}}));return o}dropFromLease(e,t){const s=this.state.leases[e];if(s)s.sims=s.sims.filter(i=>i!==t)}async actionWork(e,t,s,i,n,a){const o=this.liveLease(e,t,a);const r={};for(const l of s){if(!o.sims.includes(l))throw new d("NOT_OWNED",`${l} is not in lease ${e}.`);await this.assertOwned(l);this.liveLease(e,t,a);const c=this.template(o.templateId);switch(i){case"screenshot":{const p=this.state.locks["perf-slot"];if(p&&p.leaseId!==o.id)throw new d("HOST_BUSY","A speed test is running. No screenshots right now.",void 0,true);const h=D.join(this.store.shotsPath,`${l}.png`);r[l]=await this.host.screenshot(l,h)?h:null;break}case"open-url":if(!n)throw new d("BAD_REQUEST","open-url needs a url.");await this.host.openUrl(l,n);r[l]="opened";break;case"launch":await this.launchApp(l,c);r[l]="launched";break;case"reset":await this.fastReset(l,o.id);r[l]="reset";break;case"rebuild":{const p=await this.rebuildSim(l,o.id);if(!this.state.leases[o.id])throw new d("LEASE_EXPIRED",`Lease ${e} ended during the rebuild.`);p.leaseId=o.id;o.sims=o.sims.map(w=>w===l?p.udid:w);const h=o.runId?this.state.runs[o.runId]:void 0;const g=h?.lanes[l];if(h&&g){delete h.lanes[l];h.lanes[p.udid]={...g,udid:p.udid,name:p.name,state:"setting-up",note:"Rebuilt"}}await this.bootSim(p.udid,o.id);r[l]=p.udid;break}default:throw new d("BAD_REQUEST",`Unknown action ${i}.`)}}this.store.save();return r}async lock(e,t,s,i=0,n){if(typeof e!=="string"||!/^[a-z0-9-]{1,40}$/.test(e))throw new d("BAD_REQUEST","Lock names are short lowercase words.");this.touch(this.liveLease(t,s,n));if(this.state.locks[e]?.leaseId===t)return{held:true};const a=this.lockQueues.get(e)??[];this.lockQueues.set(e,a);const o={};a.push(o);const r=performance.now()+i;try{for(;;){this.store.assertActive();this.liveLease(t,s,n);const l=this.state.locks[e];const c=e==="perf-slot"&&(this.activeWork>0||this.busy.size>0||this.pendingBg>0);if(a[0]===o&&!l&&!c){this.state.locks[e]={name:e,leaseId:t,since:new Date().toISOString()};this.store.save();return{held:true}}if(performance.now()>=r){return{held:false,holder:l?this.state.leases[l.leaseId]?.owner.label??"someone":"the farm (work is still running)",since:l?.since}}await W(Math.max(1,Math.min(this.pollMs,r-performance.now())))}}finally{a.splice(a.indexOf(o),1);if(!a.length)this.lockQueues.delete(e)}}fairness(e,t,s,i){this.liveLease(e,t,i);const n=this.state.settings;const a=Us(n,this.meter.cpuCount);const o=this.meter.verdicts(e,s,a);return{rules:a,fair:o.filter(r=>r.fair).length,unfair:o.filter(r=>!r.fair).length,runs:o}}unlock(e,t,s,i){this.liveLease(t,s,i);if(this.state.locks[e]?.leaseId===t)delete this.state.locks[e];this.store.save();return{held:false}}async shot(e){if(this.state.locks["perf-slot"])throw new d("HOST_BUSY","A speed test is running. No stills right now.",void 0,true);if(this.shotsInFlight>=Ts)throw new d("HOST_BUSY","Taking other pictures. Try again in a moment.",void 0,true);this.shotsInFlight++;try{return await this.work(void 0,()=>this.shotWork(e))}finally{this.shotsInFlight--}}async shotWork(e){await this.assertOwned(e);const t=this.sim(e);if(this.state.locks["perf-slot"])throw new d("HOST_BUSY","A speed test is running. No stills right now.",void 0,true);if(t.power!=="awake")throw new d("BAD_REQUEST",`${t.name} is ${t.power}.`);const s=D.join(this.store.shotsPath,`${e}.png`);await this.files(()=>A.mkdir(D.dirname(s),{recursive:true}));if(!await this.host.screenshot(e,s,8e3))throw new d("HOST_ERROR",`No still from ${t.name} in time.`,void 0,true);return{file:s,at:new Date().toISOString()}}async show(e){return this.work(this.state.sims[e]?.leaseId,()=>this.showWork(e))}async showWork(e){await this.assertOwned(e);const t=this.sim(e);if(t.power==="frozen"||t.power==="thawing")throw new d("BAD_REQUEST",`${t.name} is paused. Wake it first.`);if(t.power!=="awake")await this.bootSim(e,t.leaseId);await this.host.showWindow(e);return"shown"}async tick(){if(this.ticking)return;this.ticking=true;try{for(const s of Object.values(this.state.leases)){const i=!await q(s.owner.pid,s.owner.pidStart,true);if(i)await this.endLease(s.id,"its owner exited","full","owner-exited");else if(this.leaseOverdue(s))await this.endLease(s.id,"no renewal","full",this.overdueEnd(s))}await this.tickRuns();await this.tickPhones().catch(s=>this.log(`phones: ${s.message}`));const e=this.state.settings.parkAfterMinutes;if(e>0){for(const s of Object.values(this.state.sims)){if(s.power!=="awake"||s.leaseId||this.busy.has(s.udid)||!s.idleSince)continue;if(Date.now()-Date.parse(s.idleSince)>e*6e4){await this.parkSim(s.udid).catch(i=>this.log(`park ${s.name}: ${i.message}`))}}}const t=Object.keys(this.state.requests);if(t.length>At)for(const s of t.slice(0,t.length-At))delete this.state.requests[s]}finally{this.ticking=false}}async drain(e=10*6e4){const t=performance.now()+e;while((this.busy.size>0||this.pendingBg>0||this.activeWork>0)&&performance.now()<t)await W(200);return this.busy.size===0&&this.pendingBg===0&&this.activeWork===0}idle(){return Object.keys(this.state.leases).length===0&&this.busy.size===0&&this.activeWork===0&&this.pendingBg===0&&this.acquiring.size===0}async parkAllIdle(){for(const e of Object.values(this.state.sims)){if(e.power==="awake"&&!e.leaseId&&!this.busy.has(e.udid))await this.parkSim(e.udid,"farm stopping").catch(()=>{})}}background(e,t){this.pendingBg++;this.workContext.exit(t).catch(s=>{this.log(`${e}: ${s.message}`);try{this.store.event({kind:"error",message:`${e}: ${s.message}`})}catch{}}).finally(()=>this.pendingBg--)}async once(e,t,s,i){if(!t)return i();const n=`${e}:${t}`;const a=os("sha256").update(JSON.stringify(s)).digest("hex").slice(0,16);const o=this.state.requests[n];if(o){if(o.hash!==a)throw new d("REQUEST_REUSED",`Request ${t} was already used for a different call.`);return o.result}const r=this.inflight.get(n);if(r){if(r.hash!==a)throw new d("REQUEST_REUSED",`Request ${t} was already used for a different call.`);return r.promise}const l=i();this.inflight.set(n,{hash:a,promise:l});try{const c=await l;this.state.requests[n]={hash:a,result:c,at:new Date().toISOString()};this.store.save();return c}finally{this.inflight.delete(n)}}newRun(e,t,s){const i=Date.now();const n=e.owner.agent?this.state.settings.runCapMinutes*6e4:24*36e5;const a=(e.goal??"").trim()||e.purpose;const o={id:`r-${we(4).toString("hex")}`,goal:a.slice(0,200),kind:e.kind?.slice(0,40),owner:e.owner,templateId:t,state:"active",createdAt:new Date(i).toISOString(),deadlineAt:new Date(i+Math.min(s,n)).toISOString(),capAt:new Date(i+n).toISOString(),leases:[],lanes:{},notes:[],lastActivityAt:new Date(i).toISOString(),auto:!e.goal};this.state.runs[o.id]=o;return o}touch(e){const t=e.runId?this.state.runs[e.runId]:void 0;if(t)t.lastActivityAt=new Date().toISOString()}runOfLease(e){return Object.values(this.state.runs).find(t=>t.leases.includes(e))}assertRunOpen(e){if(e.state==="stopping"||e.state==="stopped"){if(e.endedBy==="user")throw new d("RUN_STOPPED","The person stopped this run in Buoy Desktop (reason=user).","Tell them: You stopped this run in Sims. Start a new run only if they ask.");if(e.endedBy==="deadline")throw new d("RUN_ENDED","This run ran out of time.","Start a new run to go on. Ask for more time with sim_farm_extend before the end next time.")}if(H.includes(e.state)||e.state==="stopping")throw new d("RUN_ENDED",`This run has ended (${e.state}).`,"Start a new run.")}ownRun(e,t){const s=this.state.runs[e];if(!s)throw new d("NOT_FOUND",`No run ${e}.`,"Use the runId that sim_farm_acquire returned.");if(t&&s.owner.clientId!==t)throw new d("NOT_OWNED",`Run ${e} belongs to ${s.owner.label}.`);this.assertRunOpen(s);return s}async forgetPhone(e){await A.rm(re(e,this.store.homeDir),{force:true});await A.rm(ke(e,this.store.homeDir),{force:true})}async tickPhones(){for(const e of Object.values(this.state.sims)){if(e.phone?.status!=="on"||e.power!=="awake")continue;const t=e.leaseId?this.state.leases[e.leaseId]:void 0;const s=t?.runId?this.state.runs[t.runId]:void 0;if(!s||H.includes(s.state))continue;const i=await Me(e.udid,this.store.homeDir);if(!i?.overLimit||!i.pid||e.phone.notedPid===i.pid)continue;e.phone.notedPid=i.pid;const n=s.lanes[e.udid]?.label??e.name;const a=e.phone.phoneName??"the phone";this.note(s,"farm",i.ended==="safety"?`${n}: the app used ${i.peakMB} MB and hit the farm's safety cap, so it was closed. ${a} would have closed it sooner.`:i.ended==="limit"?`${n}: the app went past ${a}'s memory limit (${i.peakMB} MB) and was closed, like on a real phone.`:`${n}: the app went past ${a}'s memory limit (${i.peakMB} MB). A real phone would close it.`,e.udid);this.store.save()}}note(e,t,s,i){e.notes.push({at:new Date().toISOString(),by:t,text:s.slice(0,500),udid:i});if(e.notes.length>Dt)e.notes.splice(0,e.notes.length-Dt)}addLane(e,t){const s=e.runId?this.state.runs[e.runId]:void 0;if(!s)return;const i=this.labels.get(e.id)?.[e.sims.length-1];s.lanes[t.udid]={udid:t.udid,name:t.name,label:i?.slice(0,80),state:"setting-up",at:new Date().toISOString()};if(s.state==="waiting")s.state="active"}overdueEnd(e){return this.clock.now()>=(this.hardDeadlines.get(e.id)??Infinity)?"deadline":"lost"}settleRun(e,t){const s=e.runId?this.state.runs[e.runId]:void 0;if(!s)return;for(const n of e.sims)if(s.lanes[n])s.lanes[n].gone=true;if(H.includes(s.state)||s.state==="stopping"||t===null)return;const i=s.leases.some(n=>this.state.leases[n]);switch(t){case"released":if(!i)this.endRun(s,this.outcomeOf(s)==="failed"?"failed":"done","released");return;case"acquire-failed":if(!i&&!Object.keys(s.lanes).length)this.endRun(s,"failed","acquire-failed");return;case"user":return this.endRun(s,"stopped","user","You stopped this run.");case"deadline":return this.endRun(s,"stopped","deadline","Ran out of time. The sims were taken back.");case"owner-exited":return this.endRun(s,"interrupted","owner-exited","The chat closed. Cleaning up.");case"lost":return this.endRun(s,"interrupted","lost","Lost touch with the chat. Cleaning up.");case"finished":return this.endRun(s,"done","finished")}}endRun(e,t,s,i,n="full"){if(H.includes(e.state))return;e.state="stopping";e.endedBy=s;if(i)this.note(e,s==="user"?"person":"farm",i);for(const a of e.leases){if(this.state.leases[a])void this.endLease(a,i??s,s==="finished"||s==="released"?n:"full",null)}for(const a of Object.values(e.lanes))a.gone=true;e.state=t;e.endedAt=new Date().toISOString();e.outcome=e.outcome??this.outcomeOf(e);this.store.event({kind:"run-end",message:`${e.owner.label}: "${e.goal}" ${t==="done"?"finished":t}.`,runId:e.id})}outcomeOf(e){const t=Object.values(e.lanes);const s=t.filter(n=>n.state==="passed").length;const i=t.filter(n=>n.state==="failed").length;if(!s&&!i)return"unknown";if(i&&s)return"mixed";return i?"failed":"passed"}report(e,t){const s=this.ownRun(e.runId,t);const i=new Date().toISOString();if(e.sequence!==void 0){if(!Number.isInteger(e.sequence)||e.sequence<0)throw new d("BAD_REQUEST","sequence must be a whole number.");if(s.lastSeq!==void 0&&e.sequence<=s.lastSeq)return{applied:false,reason:"already have this report",...this.timeLeft(s)};s.lastSeq=e.sequence}if(e.state!==void 0&&!Pt.includes(e.state))throw new d("BAD_REQUEST",`state must be one of ${Pt.join(", ")}.`);if(e.udid!==void 0){const n=s.lanes[e.udid];if(!n)throw new d("NOT_FOUND",`That sim is not in run ${s.id}.`,"Use a UDID from this run's sims.");if(e.state)n.state=e.state;if(e.state==="passed"||e.state==="failed")n.resultSource=e.resultSource==="test"?"test":"agent";if(e.note!==void 0)n.note=String(e.note).slice(0,200);n.at=i}if(e.counts!==void 0){const n=e.counts;const a=o=>o===void 0||Number.isInteger(o)&&o>=0;if(!n||typeof n!=="object"||!a(n.done)||!a(n.total)||!a(n.passed)||!a(n.failed)||n.done>n.total){throw new d("BAD_REQUEST","counts needs whole numbers, with done no more than total.")}s.counts={done:n.done,total:n.total,passed:n.passed,failed:n.failed}}if(e.note)this.note(s,"agent",String(e.note),e.udid);s.lastReportAt=s.lastActivityAt=i;this.store.save();return{applied:true,...this.timeLeft(s)}}extend(e,t,s){const i=this.ownRun(e,s);if(!Number.isFinite(t)||t<=0)throw new d("BAD_REQUEST","minutes must be above zero.");const n=Date.parse(i.deadlineAt);const a=Date.now()+t*6e4;const o=Math.min(a,Date.parse(i.capAt));if(o<=n){return{granted:false,partly:false,reason:"This run is at its time limit.",...this.timeLeft(i)}}i.deadlineAt=new Date(o).toISOString();i.lastActivityAt=new Date().toISOString();for(const r of i.leases){const l=this.state.leases[r];if(!l)continue;l.ttlMs=o-Date.parse(l.createdAt);this.hardDeadlines.set(r,this.clock.now()+(o-Date.now()))}this.note(i,"farm",`More time: until ${new Date(o).toLocaleTimeString()}.`);this.store.save();return{granted:true,partly:o<a,...this.timeLeft(i)}}finish(e,t,s,i){const n=this.state.runs[e];if(n?.endedBy==="finished"&&n.owner.clientId===i)return{state:n.state,outcome:n.outcome};const a=this.ownRun(e,i);if(t&&!["passed","failed","mixed","unknown"].includes(t))throw new d("BAD_REQUEST","outcome must be passed, failed, mixed or unknown.");a.outcome=t??this.outcomeOf(a);if(s)a.summary=s.slice(0,600);this.endRun(a,a.outcome==="failed"?"failed":"done","finished",void 0,"fast");this.store.save();return{state:a.state,outcome:a.outcome}}stopRun(e,t="you"){const s=this.state.runs[e];if(!s)throw new d("NOT_FOUND",`No run ${e}.`);if(H.includes(s.state))return{state:s.state};this.endRun(s,"stopped","user",t==="you"?"You stopped this run.":`Stopped by ${t}.`);this.store.save();return{state:s.state}}stopAll(e="you"){const t=Object.values(this.state.runs).filter(s=>!H.includes(s.state));for(const s of t)this.stopRun(s.id,e);return{stopped:t.length}}timeLeft(e){return{deadlineAt:e.deadlineAt,capAt:e.capAt,secondsLeft:Math.max(0,Math.round((Date.parse(e.deadlineAt)-Date.now())/1e3))}}async tickRuns(){const e=Date.now();for(const n of Object.values(this.state.runs)){if(H.includes(n.state))continue;if(e>=Date.parse(n.deadlineAt)){this.endRun(n,"stopped","deadline","Ran out of time. The sims were taken back.");this.store.save()}else if(!n.leases.some(a=>this.state.leases[a])&&!await q(n.owner.pid,n.owner.pidStart,true)){this.endRun(n,"interrupted","owner-exited","The chat closed.");this.store.save()}}const t=this.state.settings.keepRunsHours*36e5;const s=Object.values(this.state.runs).filter(n=>H.includes(n.state)).sort((n,a)=>Date.parse(a.endedAt??a.createdAt)-Date.parse(n.endedAt??n.createdAt));let i=false;s.forEach((n,a)=>{if(a>=200||e-Date.parse(n.endedAt??n.createdAt)>t){delete this.state.runs[n.id];i=true}});if(i)this.store.save()}async status(e={}){const t=await this.budget();const s=await Promise.all(Object.values(this.state.sims).map(async n=>{const a=n.leaseId?this.state.leases[n.leaseId]:void 0;const o=a?.runId?this.state.runs[a.runId]:void 0;const r=n.phone?.status==="on"?await Me(n.udid,this.store.homeDir):null;const l=n.phone&&{...n.phone,notedPid:void 0,...r?.loaded?{pid:r.pid,peakMB:r.peakMB,memoryWarnings:r.memoryWarnings,overLimit:r.overLimit,ended:r.ended}:{}};return{...n,phone:l,owner:a?.owner.label,purpose:o?.goal??a?.purpose,runId:o?.id,lane:o?.lanes[n.udid]?.label,busy:this.busy.has(n.udid)}}));const i={farmId:this.state.farmId,counts:{pool:s.length,awake:s.filter(n=>n.power==="awake").length,leased:s.filter(n=>n.leaseId).length},budget:{roomForMoreSims:t.roomFor,freeDiskGB:Math.floor(t.stats.freeDiskBytes/ee),availableMemGB:Math.floor(t.stats.availableMemBytes/ee),memPressure:t.stats.memPressure,loadAvg1:Number(t.stats.loadAvg1.toFixed(1)),cpuCount:t.stats.cpuCount},templates:Object.values(this.state.templates),sims:s,orphans:Object.values(this.state.orphans),leases:Object.values(this.state.leases).map(n=>({...n,expiresInMs:Math.max(0,Math.round(this.leaseDeadline(n)-this.clock.now()))})),runs:Object.values(this.state.runs).sort((n,a)=>Date.parse(a.createdAt)-Date.parse(n.createdAt)).map(n=>({...n,notes:n.notes.slice(-50),secondsLeft:H.includes(n.state)?0:Math.max(0,Math.round((Date.parse(n.deadlineAt)-Date.now())/1e3))})),locks:Object.values(this.state.locks),recentEvents:this.state.events.slice(-25),settings:this.state.settings};if(e.outside){const n=new Set([...Object.keys(this.state.sims),...Object.keys(this.state.orphans),...Object.values(this.state.templates).map(a=>a.udid)]);i.outsideSims=(await this.host.listDevices()).filter(a=>!n.has(a.udid)&&a.available).map(a=>({udid:a.udid,name:a.name,state:a.state,runtime:a.runtime}))}return i}setSettings(e){const t=this.state.settings;const s={parkAfterMinutes:[0,24*60],maxConcurrentBoots:[1,8],reserveRamGB:[4,512],reserveDiskGB:[5,2048],slimSimGB:[.5,16],stockSimGB:[1,32],cloneDiskGB:[.1,32],runCapMinutes:[5,24*60],keepRunsHours:[1,24*14],fairMinFreeShare:[0,1],fairMaxSwingShare:[.02,1],fairMaxThermalLevel:[0,4],fairMaxSwapGrowthMB:[0,65536],phoneCapMB:[0,1048576]};if(!e||typeof e!=="object")throw new d("BAD_REQUEST","settings must be an object.");if("phoneProfile"in e){const n=Z(this.store.homeDir);if(e.phoneProfile!==xe&&!(typeof e.phoneProfile==="string"&&n[e.phoneProfile])){throw new d("BAD_REQUEST",`phoneProfile must be "off" or one of: ${Object.keys(n).join(", ")}.`)}}if("phoneOnLimit"in e&&e.phoneOnLimit!=="warn"&&e.phoneOnLimit!=="kill"){throw new d("BAD_REQUEST",`phoneOnLimit must be "warn" or "kill".`)}if("phoneCapMB"in e&&(!Number.isInteger(e.phoneCapMB)||e.phoneCapMB!==0&&e.phoneCapMB<3072)){throw new d("BAD_REQUEST","phoneCapMB must be 0 (automatic) or a whole number of MB, at least 3072.")}for(const[n,a]of Object.entries(e)){if(!(n in t)||typeof a!==typeof t[n])throw new d("BAD_REQUEST",`Bad setting ${n}.`);const o=s[n];if(o&&(typeof a!=="number"||!Number.isFinite(a)||a<o[0]||a>o[1])){throw new d("BAD_REQUEST",`${n} must be ${o[0]} to ${o[1]}.`)}}const i=["phoneProfile","phoneOnLimit","phoneCapMB"].some(n=>n in e&&e[n]!==t[n]);for(const[n,a]of Object.entries(e))t[n]=a;this.store.save();if(i){for(const n of Object.keys(this.state.sims))void be(n,this.store.homeDir).catch(()=>void 0)}return t}};function Cs(e,t){return Math.min(t,Math.max(4,Math.round(e*.375)))}function xs(e){return Math.min(4,Math.max(1.5,e*.1))}function Us(e,t){const s=i=>Math.round(i*10)/10;return{minFreeCores:s(Math.max(2,e.fairMinFreeShare*t)),maxSwingCores:s(Math.max(1,e.fairMaxSwingShare*t)),maxThermalLevel:e.fairMaxThermalLevel,maxSwapGrowthMB:e.fairMaxSwapGrowthMB}}function Nt(e,t=Date.now()-3*6e4){const s=new Map;for(const i of e.split("\n")){const n=/^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)\.\d+ \((?:user|system)\/\d*\/?([\w.-]+) \[\d+\]\) <\w+>: exited due to (SIG\w+)/.exec(i);if(!n||n[3]==="SIGKILL"||n[3]==="SIGTERM")continue;const a=Date.parse(n[1].replace(" ","T"));if(!(a>=t))continue;const o=s.get(n[2])??[];o.push(a);s.set(n[2],o)}for(const[i,n]of s){n.sort((a,o)=>a-o);for(let a=2;a<n.length;a++)if(n[a]-n[a-2]<=6e4)return i.replace(/^com\.apple\./,"")}return null}import{promises as $t}from"fs";import te from"os";import se from"path";var Lt=6e4;var He=class{constructor(){this.disabledRoot=X;this.devicesDir=se.join(te.homedir(),"Library/Developer/CoreSimulator/Devices");this.graphicsPids=[];this.loadCalls=0}simctl(e,t=Lt){return P("xcrun",["simctl",...e],{timeoutMs:t})}async listDevices(){const e=JSON.parse(await this.simctl(["list","devices","--json"],3e4));const t=[];for(const[s,i]of Object.entries(e.devices??{})){for(const n of i){t.push({udid:n.udid,name:n.name,state:n.state,runtime:s,deviceType:n.deviceTypeIdentifier,dataPath:n.dataPath??se.join(this.devicesDir,n.udid,"data"),available:n.isAvailable!==false})}}return t}async dataPathOf(e){if(!/^[0-9A-F-]{36}$/i.test(e))return null;const t=se.join(this.devicesDir,e);try{await $t.access(se.join(t,"device.plist"));return se.join(t,"data")}catch{return null}}async create(e,t,s){return(await this.simctl(["create",e,t,s])).trim()}async clone(e,t){return(await this.simctl(["clone",e,t])).trim()}async boot(e){const t=await M("xcrun",["simctl","boot",e],{timeoutMs:Lt,env:$e()});if(t.code!==0&&!/current state: Booted/i.test(t.stderr)){throw new Error(`simctl boot ${e} failed: ${t.stderr.trim().slice(0,300)}`)}}async shutdown(e){const t=await M("xcrun",["simctl","shutdown",e],{timeoutMs:9e4});if(t.code!==0&&!/current state: Shutdown/i.test(t.stderr)){throw new Error(`simctl shutdown ${e} failed: ${t.stderr.trim().slice(0,300)}`)}}async delete(e){await this.simctl(["delete",e],9e4)}async install(e,t){await this.simctl(["install",e,t],18e4)}async launch(e,t,s){await P("xcrun",["simctl","launch","--terminate-running-process",e,t],{timeoutMs:6e4,env:s&&Object.keys(s).length?{...process.env,...s}:void 0})}async terminate(e,t){await M("xcrun",["simctl","terminate",e,t],{timeoutMs:2e4})}async openUrl(e,t){await this.simctl(["openurl",e,t],2e4)}async screenshot(e,t,s=1e4){const i=await M("xcrun",["simctl","io",e,"screenshot",t],{timeoutMs:s});return i.code===0&&!i.timedOut}spawn(e,t,s=2e4){return M("xcrun",["simctl","spawn",e,...t],{timeoutMs:s})}async appContainer(e,t){const s=await M("xcrun",["simctl","get_app_container",e,t,"data"],{timeoutMs:2e4});return s.code===0?s.stdout.trim()||null:null}async simTree(e){const t=await tt();const s=t.find(i=>/launchd_sim/.test(i.command)&&i.command.includes(e));return s?st(t,s.pid):[]}async signal(e,t){for(const s of e){try{process.kill(s,t)}catch{}}}async launchdLogTail(e,t=256*1024){const s=se.join(this.disabledRoot,`com.apple.CoreSimulator.SimDevice.${e}`,"launchd.log");try{const i=await $t.open(s,"r");try{const{size:n}=await i.stat();const a=Math.max(0,n-t);const o=Buffer.alloc(n-a);await i.read(o,0,o.length,a);return o.toString("utf8")}finally{await i.close()}}catch{return""}}async hostStats(){const[e,t,s,i]=await Promise.all([P("vm_stat",[],{timeoutMs:1e4}),M("sysctl",["-n","kern.memorystatus_vm_pressure_level"],{timeoutMs:5e3}),M("sysctl",["-n","vm.swapusage"],{timeoutMs:5e3}),P("df",["-k",te.homedir()],{timeoutMs:1e4})]);const n=Number(/page size of (\d+)/.exec(e)?.[1]??16384);const a=h=>Number(new RegExp(`${h}:\\s+(\\d+)`).exec(e)?.[1]??0);const o=a("Pages free")+a("Pages inactive")+a("Pages speculative")+a("Pages purgeable");const r=Number(t.stdout.trim());const l=/used = ([\d.]+)M/.exec(s.stdout)?.[1];const c=i.trim().split("\n").pop()??"";const p=Number(c.split(/\s+/)[3]??0);return{totalMemBytes:te.totalmem(),availableMemBytes:o*n,memPressure:r>=4?"critical":r>=2?"warn":"normal",swapUsedBytes:l?Number(l)*1024*1024:0,freeDiskBytes:p*1024,cpuCount:te.cpus().length,loadAvg1:te.loadavg()[0]}}async showWindow(e){const t=await M("open",["-b","com.apple.iphonesimulator","--args","-CurrentDeviceUDID",e],{timeoutMs:2e4});if(t.code===0)return;await P("open",["-b","com.apple.dt.Devices"],{timeoutMs:2e4})}async loadCounters(e,t=true){if(t&&this.loadCalls++%10===0){const $=await M("pgrep",["-x","SimMetalHost"],{timeoutMs:5e3});this.graphicsPids=$.stdout.split("\n").map(Number).filter(f=>f>0)}const s=te.cpus();let i=0;let n=0;for(const $ of s){const f=$.times;const E=f.user+f.nice+f.sys+f.idle+f.irq;n+=E;i+=E-f.idle}const a=[...e,...this.graphicsPids];const[o,r,l,c]=await Promise.all([t&&a.length?M("ps",["-o","pid=,time=","-p",a.join(",")],{timeoutMs:5e3}):null,t?M("ioreg",["-r","-c","IOAccelerator","-d","1"],{timeoutMs:5e3}):null,M("sysctl",["-n","kern.memorystatus_vm_pressure_level","vm.swapusage"],{timeoutMs:5e3}),M("notifyutil",["-g","com.apple.system.thermalpressurelevel"],{timeoutMs:5e3})]);const p=new Set(this.graphicsPids);let h=0;let g=0;for(const $ of o?.stdout.split("\n")??[]){const f=/^\s*(\d+)\s+(\S+)/.exec($);if(!f)continue;const E=ft(f[2]);if(p.has(Number(f[1])))g+=E;else h+=E}const w=r&&/"Device Utilization %"=(\d+)/.exec(r.stdout);const k=/thermalpressurelevel\s+(\d+)/.exec(c.stdout);return{hostBusyMs:i,hostTotalMs:n,cpuCount:s.length,pidsCpuMs:t?h:null,graphicsCpuMs:t?g:null,gpuPct:w?Number(w[1]):null,memPressureLevel:Number(l.stdout.trim().split("\n")[0])||1,swapUsedMB:Number(/used = ([\d.]+)M/.exec(l.stdout)?.[1]??0),thermalLevel:k?Number(k[1]):null}}async xcodeBuild(){const e=await M("xcodebuild",["-version"],{timeoutMs:2e4});return e.stdout.trim().replace(/\s+/g," ")||"unknown"}async clientsOf(e){const t=await tt();const s=new Set((await this.simTree(e)).map(n=>n.pid));const i=new Set(st(t,process.pid).map(n=>n.pid));return t.filter(n=>!i.has(n.pid)&&!s.has(n.pid)&&n.command.includes(e)&&!/launchd_sim|CoreSimulator/.test(n.command))}async kill(e,t){if(!await q(e,t))return;try{process.kill(e,"SIGTERM")}catch{return}for(let s=0;s<20;s++){await new Promise(i=>setTimeout(i,100));if(!await q(e,t))return}if(await q(e,t)){try{process.kill(e,"SIGKILL")}catch{}}}};import js from"net";import{chmodSync as Fs,rmSync as Ws,appendFileSync as Ct,mkdirSync as Gs}from"fs";import{timingSafeEqual as Hs}from"crypto";import{promises as qs,existsSync as qe,mkdirSync as Ye,readFileSync as K,renameSync as ze,writeFileSync as _e,rmSync as le,openSync as Ys,fsyncSync as zs,closeSync as Ks,chmodSync as Qs,readdirSync as Js,statSync as xt}from"fs";import Vs from"os";import I from"path";import{createHash as Xs,randomBytes as ce}from"crypto";function G(){return process.env.BUOY_FARM_HOME||I.join(Vs.homedir(),".buoy","farm")}var U=(e=G())=>({home:e,lock:I.join(e,"owner.lock"),lockOwner:I.join(e,"owner.lock","owner.json"),socket:I.join(e,"farmd.sock"),token:I.join(e,"token"),state:I.join(e,"state.json"),journal:I.join(e,"journal.ndjson"),log:I.join(e,"farmd.log"),shots:I.join(e,"shots")});function Ke(e=G()){Ye(e,{recursive:true,mode:448});try{Qs(e,448)}catch{}}function Ut(e=G()){const t=U(e).token;try{const s=K(t,"utf8").trim();if(s)return s}catch{}Ke(e);try{_e(t,ce(24).toString("hex")+"\n",{mode:384,flag:"wx"})}catch(s){if(s.code!=="EEXIST")throw s}for(let s=0;s<20;s++){const i=K(t,"utf8").trim();if(i)return i;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,25)}throw new Error(`farm token at ${t} is empty`)}async function de(e=G()){try{return JSON.parse(await qs.readFile(U(e).lockOwner,"utf8"))}catch{return null}}async function ue(e){return!!e&&await q(e.pid,e.start,true)}async function Zs(e,t){const s=I.join(e,"owner.claim");for(let i=0;i<20;i++){try{Ye(s,{mode:448});_e(I.join(s,"pid"),`${process.pid}
364
+ ${await ae(process.pid)??""}`);try{return await t()}finally{le(s,{recursive:true,force:true})}}catch(n){if(n.code!=="EEXIST")throw n;const a=xt(s,{throwIfNoEntry:false});if(a&&Date.now()-a.mtimeMs>3e4){let o=true;try{const[r,l]=K(I.join(s,"pid"),"utf8").split("\n");o=!await q(Number(r),l||void 0)}catch{}if(o){try{ze(s,I.join(e,`owner.claim-dead-${ce(4).toString("hex")}`))}catch{}}}await new Promise(o=>setTimeout(o,100))}}return null}async function ei(e,t,s=G()){Ke(s);const i=U(s);const n=await ae(process.pid)??"";for(let a=0;a<3;a++){try{Ye(i.lock,{mode:448})}catch(r){if(r.code!=="EEXIST")throw r;const l=await de(s);if(l&&await ue(l))return null;if(!l){await new Promise(h=>setTimeout(h,300));const p=await de(s);if(p&&await ue(p))return null}const c=await Zs(s,async()=>{const p=await de(s);if(p&&await ue(p))return false;if(!qe(i.lock))return true;ze(i.lock,I.join(s,`owner.stale-${ce(4).toString("hex")}`));return true});if(c===false)return null;continue}const o={pid:process.pid,start:n,version:e,host:t,since:new Date().toISOString()};_e(i.lockOwner,JSON.stringify(o),{mode:384});ti(s);return{info:o,release(){try{const r=JSON.parse(K(i.lockOwner,"utf8"));if(r.pid!==process.pid)return}catch{return}try{le(i.socket,{force:true})}catch{}le(i.lock,{recursive:true,force:true})}}}return null}function ti(e){try{for(const t of Js(e)){if(t.startsWith("owner.stale-")||t.startsWith("owner.claim-dead-"))le(I.join(e,t),{recursive:true,force:true})}}catch{}}function jt(){return{version:fe,seq:0,farmId:ce(6).toString("hex"),nextIndex:1,templates:{},sims:{},orphans:{},leases:{},runs:{},locks:{},requests:{},events:[],settings:{...Te}}}var Ft=e=>Xs("sha256").update(JSON.stringify(e)).digest("hex").slice(0,12);function Wt(e,t,s){const i=Ys(e,s,384);try{_e(i,t);zs(i)}finally{Ks(i)}}var Gt=class{constructor(e=G()){this.fenced=false;this.pending=[];this.open=new Map;this.p=U(e);Ke(e);this.state=this.load()}get shotsPath(){return this.p.shots}get homeDir(){return this.p.home}fence(){this.fenced=true}assertActive(){if(this.fenced)throw new Error("This farm has stopped.")}load(){let e=jt();if(qe(this.p.state)){const n=JSON.parse(K(this.p.state,"utf8"));if(n.version>fe){throw new Error(`farm state is version ${n.version}; this farmd understands ${fe}. Update Buoy.`)}e={...jt(),...n,settings:{...Te,...n.settings}}}delete e.settings.activeSlots;const t=new Map;const s=new Set;let i=e.seq;if(qe(this.p.journal)){for(const n of K(this.p.journal,"utf8").split("\n")){if(!n.trim())continue;let a;try{a=JSON.parse(n)}catch{continue}const{sum:o,...r}=a;if(Ft(r)!==o||a.seq<=e.seq)continue;i=Math.max(i,a.seq);if(a.type==="intent")t.set(a.seq,a);else{t.delete(a.seq);s.add(a.seq)}}}for(const n of e.openIntents??[]){if(!s.has(n.seq)&&!t.has(n.seq))t.set(n.seq,{...n,type:"intent",sum:""})}this.pending=[...t.values()].sort((n,a)=>n.seq-a.seq);for(const n of this.pending)this.open.set(n.seq,n);e.seq=i;e.openIntents=[];return e}intent(e,t){this.assertActive();const s=++this.state.seq;const i={seq:s,at:new Date().toISOString(),type:"intent",op:e,data:t};this.append(i);this.open.set(s,{...i,sum:""});return s}result(e,t,s){this.assertActive();this.open.delete(e);this.pending=this.pending.filter(i=>i.seq!==e);this.save();this.append({seq:e,at:new Date().toISOString(),type:"result",op:t,data:s})}append(e){this.assertActive();Wt(this.p.journal,JSON.stringify({...e,sum:Ft(e)})+"\n","a")}save(){this.assertActive();const e=`${this.p.state}.${ce(4).toString("hex")}.tmp`;this.state.openIntents=[...this.open.values()].map(({seq:t,at:s,op:i,data:n})=>({seq:t,at:s,op:i,data:n}));Wt(e,JSON.stringify(this.state,null,1),"w");ze(e,this.p.state);try{if(xt(this.p.journal).size>2*1024*1024)le(this.p.journal,{force:true})}catch{}}event(e){this.assertActive();this.state.events.push({at:new Date().toISOString(),...e});if(this.state.events.length>300)this.state.events.splice(0,this.state.events.length-300)}};function si(e=G()){try{const t=JSON.parse(K(U(e).state,"utf8"));return new Set([...Object.keys(t.sims??{}),...Object.keys(t.orphans??{}),...Object.values(t.templates??{}).map(s=>s.udid)])}catch{return new Set}}var Ht=new Set(["setup","grow","shrink","acquire","release","action","lock","unlock","park","wake","reset","rebuild","delete","endLease","settings","deleteFarm","show","removeTemplate","report","extend","finish","stopRun","stopAll"]);async function qt(e={}){const t=e.home??G();const s=U(t);if(Buffer.byteLength(s.socket)>103){const a=new d("BAD_REQUEST",`The farm folder's path is too long for macOS (${Buffer.byteLength(s.socket)} of 103 bytes).`,"Set BUOY_FARM_HOME to a shorter folder.");try{Gs(t,{recursive:true});Ct(s.log,`${new Date().toISOString()} ${a.message} ${a.next}
365
+ `)}catch{}throw a}const i=await ei(F,e.hostLabel??"node",t);if(!i)return null;const n=a=>{try{Ct(s.log,`${new Date().toISOString()} ${a}
366
+ `)}catch{}e.log?.(a)};try{return await ii(e,t,i,n)}catch(a){i.release();throw a}}async function ii(e,t,s,i){const n=U(t);const a=Ut(t);const o=new Gt(t);const r=new Rt({host:e.host??new He,store:o,log:i,pollMs:e.pollMs,readyTimeoutMs:e.readyTimeoutMs,phoneBuilder:e.phoneBuilder});await r.recover();Ws(n.socket,{force:true});const l=new Set;let c=Date.now();let p=false;let h=0;const g=js.createServer(y=>{l.add(y);y.on("close",()=>l.delete(y));y.on("error",()=>{});let u="";y.on("data",m=>{u+=m.toString("utf8");if(u.length>1024*1024)return y.destroy();let v;while((v=u.indexOf("\n"))>=0){const b=u.slice(0,v);u=u.slice(v+1);if(b.trim())void k(y,b)}})});const w=(y,u,m)=>{if(!y.destroyed)y.write(JSON.stringify({id:u,...m})+"\n")};async function k(y,u){c=Date.now();let m;try{m=JSON.parse(u)}catch{return w(y,-1,{ok:false,error:{code:"BAD_REQUEST",message:"Not JSON."}})}h++;try{if(!m||typeof m!=="object")throw new d("BAD_REQUEST","Use a request object.");if(!ni(m.token,a))throw new d("UNAUTHORIZED","Bad farm token.");if(!m.client||typeof m.client.clientId!=="string"||!m.client.clientId.trim())throw new d("BAD_REQUEST","Each call needs a clientId.");if(p&&!["hello","status"].includes(m.method)){throw new d("HOST_BUSY","The farm is stopping.","Try again in a few seconds.",true)}if(m.v>F&&Ht.has(m.method)){throw new d("FARMD_VERSION",`This farm runs protocol ${F}; the client speaks ${m.v}.`,"Ask it to stop when idle (method shutdown), then start a newer farm.")}if(m.v<F&&Ht.has(m.method)){throw new d("READ_ONLY",`This client speaks farm protocol ${m.v}; the farm runs ${F}.`,"Update Buoy to change the farm.")}ai(m);const v=await $(m);w(y,m.id,{ok:true,result:v})}catch(v){const b=v instanceof d?v.toJSON():{code:"HOST_ERROR",message:v.message,retryable:false};w(y,m?.id??-1,{ok:false,error:b})}finally{h--}}async function $(y){const u=y.params??{};const m=y.client;const v=b=>r.once(m.clientId,y.requestId,{m:y.method,q:u},b);switch(y.method){case"hello":return{protocol:F,pid:process.pid,host:s.info.host,farmId:r.state.farmId};case"status":return r.status({outside:u.outside});case"budget":return r.budget({ramGB:u.ramGB??0,diskGB:u.diskGB??0});case"setup":return v(()=>r.createTemplate(u));case"grow":return v(async()=>(await r.grow(u.templateId,u.count)).map(b=>b.name));case"shrink":return v(()=>r.shrink(u.templateId,u.count));case"removeTemplate":return v(()=>r.removeTemplate(u.templateId));case"acquire":return v(async()=>{const{lease:b,run:C,sims:Pe}=await r.acquire({...u,owner:m});return{runId:C.id,leaseId:b.id,epoch:b.epoch,deadlineAt:C.deadlineAt,capAt:C.capAt,sims:Pe.map(me=>({udid:me.udid,name:me.name,buoyDeviceId:me.buoyDeviceId,profile:me.profile}))}});case"renew":return r.renew(u.leaseId,u.epoch,m.clientId);case"release":return v(()=>r.release(u.leaseId,u.epoch,u.reset,m.clientId,u.keepRun===true));case"action":return v(()=>r.action(u.leaseId,u.epoch,u.udids,u.action,u.arg,m.clientId));case"lock":return r.lock(u.name,u.leaseId,u.epoch,u.waitMs??0,m.clientId);case"unlock":return r.unlock(u.name,u.leaseId,u.epoch,m.clientId);case"fairness":return r.fairness(u.leaseId,u.epoch,u.windows,m.clientId);case"park":return v(async()=>(await r.parkSim(u.udid,"asked"),"parked"));case"wake":return v(async()=>(await r.bootSim(u.udid)).power);case"reset":return v(async()=>(await r.fastReset(u.udid),"reset"));case"rebuild":return v(async()=>(await r.rebuildSim(u.udid)).udid);case"delete":return v(async()=>(await r.deleteSim(u.udid),"deleted"));case"endLease":{const b=r.state.leases[u.leaseId];if(!b)return{};if(b.owner.clientId!==m.clientId&&u.force!==true){throw new d("NOT_OWNED",`Lease ${u.leaseId} belongs to ${b.owner.label}.`,"Pass force: true only after a person confirms.")}return v(()=>r.endLease(u.leaseId,`ended by ${m.label}`,"full",b.owner.clientId===m.clientId?"released":"user"))}case"report":return v(async()=>r.report(u,m.clientId));case"extend":return v(async()=>r.extend(u.runId,u.minutes,m.clientId));case"finish":return v(async()=>r.finish(u.runId,u.outcome,u.summary,m.clientId));case"stopRun":{const b=r.state.runs[u.runId];if(b&&b.owner.clientId!==m.clientId&&u.force!==true){throw new d("NOT_OWNED",`Run ${u.runId} belongs to ${b.owner.label}.`,"Pass force: true only after a person confirms.")}return v(async()=>r.stopRun(u.runId))}case"stopAll":if(u.force!==true)throw new d("BAD_REQUEST","stopAll needs force: true, after a person confirms.");return v(async()=>r.stopAll());case"settings":return r.setSettings(u);case"shot":return r.shot(u.udid);case"show":return r.show(u.udid);case"shutdown":if(u.ifIdle!==false&&(!r.idle()||h>1))return{stopping:false,reason:"busy"};void De("asked to stop");return{stopping:true};default:throw new d("BAD_REQUEST",`Unknown method ${y.method}.`)}}await new Promise((y,u)=>{g.once("error",u);g.listen(n.socket,()=>y())});Fs(n.socket,384);i(`farmd ${F} up, pid ${process.pid}, host ${e.hostLabel??"node"}`);const f=setInterval(()=>{void r.tick().catch(u=>i(`tick: ${u.message}`));const y=Date.now()-c;if(e.idleExitMs&&l.size===0&&y>e.idleExitMs){void(async()=>{await r.parkAllIdle();if(r.idle()&&l.size===0&&h===0&&Date.now()-c>e.idleExitMs)await De("idle")})()}},e.tickMs??5e3);f.unref?.();const E=setInterval(()=>void r.meter.tick().catch(y=>i(`meter: ${y.message}`)),1e3);E.unref?.();let L=null;function De(y,u=10*6e4){if(!L)L=ss(y,u);return L}async function ss(y,u){if(p)return;p=true;clearInterval(f);clearInterval(E);i(`farmd stopping: ${y}`);const m=Date.now()+u;while(h>0&&Date.now()<m)await new Promise(C=>setTimeout(C,200));const v=await r.drain(Math.max(0,m-Date.now()));let b=false;if(h>0||!v||Ne()>0){o.save();r.fence();b=true;i(`farmd stopping with ${h} call(s) and ${Ne()} child process(es) still running; killing them`);cs();const C=Date.now()+5e3;while(Ne()>0&&Date.now()<C)await new Promise(Pe=>setTimeout(Pe,100))}await r.settleFiles();if(!b&&h===0){try{await r.parkAllIdle()}catch{}}for(const C of l)C.destroy();await new Promise(C=>g.close(()=>C()));if(!b){o.save();r.fence()}s.release();e.onExit?.(y)}return{engine:r,owner:s,stop:De}}function ni(e,t){if(typeof e!=="string"||e.length!==t.length)return false;return Hs(Buffer.from(e),Buffer.from(t))}function ai(e){const t=o=>{throw new d("BAD_REQUEST",o)};const s=e.params??{};if(typeof s!=="object"||Array.isArray(s))t("Params must be an object.");const i=(o,r=false)=>{if(r&&s[o]===void 0)return;if(typeof s[o]!=="string"||!s[o].trim())t(`${o} must be text.`)};const n=o=>{if(s[o]!==void 0&&typeof s[o]!=="boolean")t(`${o} must be true or false.`)};const a=(o,r,l,c=false,p=false)=>{const h=s[o];if(p&&h===void 0)return;if(typeof h!=="number"||!Number.isFinite(h)||h<r||h>l||c&&!Number.isInteger(h))t(`${o} must be a number from ${r} to ${l}.`)};switch(e.method){case"status":n("outside");break;case"budget":a("ramGB",0,Number.MAX_VALUE,false,true);a("diskGB",0,Number.MAX_VALUE,false,true);break;case"setup":for(const o of["appPath","deviceType","runtime"])i(o);if(s.seedDir!=null)i("seedDir");i("name",true);i("launchUrl",true);n("warmLaunch");if(!["slim","stock"].includes(s.profile))t("Use slim or stock.");a("metroPort",1,65535,true);break;case"removeTemplate":i("templateId");break;case"grow":case"shrink":case"acquire":i("templateId");a("count",1,64,true);if(e.method==="acquire"){i("purpose");a("ttlMs",1,Number.MAX_VALUE,false,true);a("waitMs",0,Number.MAX_SAFE_INTEGER,false,true);n("launch");n("allowPartial");i("goal",true);i("runId",true);i("kind",true);if(s.labels!==void 0&&(!Array.isArray(s.labels)||s.labels.some(o=>typeof o!=="string")))t("labels must be a list of text.");if(!Number.isInteger(e.client.pid)||e.client.pid<=0)t("The client needs a valid pid.")}break;case"release":if(s.reset!==void 0&&!["fast","full"].includes(s.reset))t("Use fast or full reset.");break;case"action":if(!Array.isArray(s.udids)||s.udids.some(o=>typeof o!=="string"||!o))t("udids must be a list of sim ids.");if(!["reset","rebuild","open-url","screenshot","launch"].includes(s.action))t("Unknown sim action.");i("arg",s.action!=="open-url");break;case"lock":case"unlock":i("name");if(!/^[a-z0-9-]{1,40}$/.test(s.name))t("Lock names are short lowercase words.");a("waitMs",0,Number.MAX_SAFE_INTEGER,false,true);break;case"fairness":if(!Array.isArray(s.windows)||s.windows.length>500||s.windows.some(o=>!o||typeof o.id!=="string"||!Number.isFinite(o.from)||!Number.isFinite(o.to)||o.to<o.from)){t("windows must be a list of { id, from, to } times in ms.")}break;case"endLease":i("leaseId");break;case"report":i("runId");i("udid",true);i("note",true);a("sequence",0,Number.MAX_SAFE_INTEGER,true,true);if(s.state!==void 0&&typeof s.state!=="string")t("state must be text.");break;case"extend":i("runId");a("minutes",1,24*60);break;case"finish":i("runId");i("summary",true);i("outcome",true);break;case"stopRun":i("runId");n("force");break;case"stopAll":n("force");break;case"shutdown":n("ifIdle");break}if(["renew","release","action","lock","unlock","fairness"].includes(e.method))i("leaseId")}import oi from"net";import{existsSync as ri}from"fs";import{spawn as li}from"child_process";import{randomBytes as Yt}from"crypto";function zt(e,t=["farmd"]){return()=>{const s=li(process.execPath,[...process.execArgv,e,...t],{detached:true,stdio:"ignore",env:$e()});s.unref()}}var Kt=class{constructor(e){this.opts=e;this.sock=null;this.nextId=1;this.pending=new Map;this.buf="";this.renewals=new Map;this.reconnecting=null;this.closed=false;this.home=e.home??G();this.clientIdValue=`c-${Yt(5).toString("hex")}`}get clientId(){return this.owner?.clientId}async connect(){this.token=Ut(this.home);this.owner={clientId:this.clientIdValue,pid:process.pid,pidStart:await ae(process.pid)??void 0,label:this.opts.label,...this.opts.agent?{agent:this.opts.agent}:{}};if(await this.tryOpen())return this.checkVersion();const e=await de(this.home);if(!await ue(e)){if(!this.opts.launcher)throw new d("HOST_ERROR","The farm is not running.","Start it from Buoy Desktop or `pnpm farm status`.");this.opts.launcher()}const t=Date.now()+(this.opts.startTimeoutMs??2e4);while(Date.now()<t){await W(250);if(await this.tryOpen())return this.checkVersion()}throw new d("HOST_ERROR","The farm did not start in time.",`Check ${U(this.home).log}.`)}async checkVersion(){const e=await this.send("hello",void 0,{});if(e.protocol<F&&this.opts.launcher){const t=await this.send("shutdown",{ifIdle:true},{});if(t.stopping){this.close();await W(500);return this.connect()}}return this}tryOpen(){const e=U(this.home).socket;if(!ri(e))return Promise.resolve(false);return new Promise(t=>{const s=oi.createConnection(e);s.once("connect",()=>{this.sock=s;s.on("data",i=>this.onData(i));s.on("close",()=>this.onClose());s.on("error",()=>{});t(true)});s.once("error",()=>t(false))})}onData(e){this.buf+=e.toString("utf8");let t;while((t=this.buf.indexOf("\n"))>=0){const s=this.buf.slice(0,t);this.buf=this.buf.slice(t+1);let i;try{i=JSON.parse(s)}catch{continue}const n=this.pending.get(i.id);if(!n)continue;this.pending.delete(i.id);clearTimeout(n.timer);if(i.ok)n.resolve(i.result);else{const a=i.error??{};n.reject(new d(a.code??"HOST_ERROR",a.message??"farm error",a.next,a.retryable))}}}onClose(){this.sock=null;for(const[,e]of this.pending){clearTimeout(e.timer);e.reject(new d("HOST_ERROR","Lost the connection to the farm.",void 0,true))}this.pending.clear()}reconnect(){if(!this.reconnecting){this.reconnecting=this.connect().then(()=>void 0).finally(()=>{this.reconnecting=null})}return this.reconnecting}async call(e,t,s={}){if(!this.sock&&!this.closed)await this.reconnect();return this.send(e,t,s)}send(e,t,s){if(!this.sock)return Promise.reject(new d("HOST_ERROR","Not connected to the farm.",void 0,true));const i=this.nextId++;const n={id:i,v:F,token:this.token,client:this.owner,method:e,params:t,requestId:s.requestId};return new Promise((a,o)=>{const r=setTimeout(()=>{this.pending.delete(i);o(new d("HOST_ERROR",`Farm call ${e} timed out.`,void 0,true))},s.timeoutMs??3e4);this.pending.set(i,{resolve:a,reject:o,timer:r});this.sock.write(JSON.stringify(n)+"\n")})}async acquire(e){const{requestId:t,...s}=e;const i=t??`acq-${Yt(4).toString("hex")}`;const n=await this.call("acquire",s,{timeoutMs:15*6e4+(e.waitMs??0),requestId:i});if(this.renewals.has(n.leaseId))return n;const a=setInterval(()=>{this.call("renew",{leaseId:n.leaseId,epoch:n.epoch}).catch(o=>{if(["LEASE_EXPIRED","STALE_EPOCH","RUN_STOPPED","RUN_ENDED"].includes(o.code))this.stopRenew(n.leaseId)})},15e3);a.unref?.();this.renewals.set(n.leaseId,a);return n}stopRenew(e){const t=this.renewals.get(e);if(t)clearInterval(t);this.renewals.delete(e)}async release(e,t,s="fast",i=false){this.stopRenew(e);return this.call("release",{leaseId:e,epoch:t,reset:s,keepRun:i},{timeoutMs:6e4,requestId:`rel-${e}-${t}`})}close(){this.closed=true;for(const e of[...this.renewals.keys()])this.stopRenew(e);this.sock?.end();this.sock=null}};async function Qt(e){return new Kt(e).connect()}import pe from"path";import ci from"os";import{existsSync as Qe,readdirSync as di,statSync as ui}from"fs";function he(e=process.cwd()){let t=e;for(;;){if(Qe(pe.join(t,"buoy.tools.json")))return t;const s=pe.dirname(t);if(s===t)return null;t=s}}function Ee(){const e=pe.join(ci.homedir(),"Library/Developer/Xcode/DerivedData");let t=null;try{for(const s of di(e)){if(!s.startsWith("exampledevbuild-"))continue;const i=pe.join(e,s,"Build/Products/Debug-iphonesimulator/exampledevbuild.app");if(!Qe(i))continue;const n=ui(i).mtimeMs;if(!t||n>t.t)t={p:i,t:n}}}catch{}return t?.p??null}function Jt(e=he()){return e?pe.join(e,"example-dev-build/artifacts/pool-seed"):null}async function pi(e=he()){const t=Jt(e);let s=[];let i=[];try{const n=JSON.parse(await P("xcrun",["simctl","list","runtimes","--json"],{timeoutMs:3e4}));s=(n.runtimes??[]).filter(o=>o.isAvailable!==false&&/^iOS/.test(o.name??"")).map(o=>({id:o.identifier,name:o.name}));const a=JSON.parse(await P("xcrun",["simctl","list","devicetypes","--json"],{timeoutMs:3e4}));i=(a.devicetypes??[]).filter(o=>/iPhone|iPad/.test(o.name??"")).map(o=>({id:o.identifier,name:o.name}))}catch{}return{appPath:Ee(),seedDir:t&&Qe(t)?t:null,seedProblem:t?oe(t):"Could not find the repo's seed folder.",runtimes:s,deviceTypes:i,slimTurnsOff:ie.map(n=>({name:n.name,downside:n.downside}))}}import hi from"path";var Vt=[{app:"claude",name:"Claude",match:/(^|\/)claude$/i},{app:"codex",name:"Codex",match:/(^|\/)codex$/i},{app:"cursor",name:"Cursor",match:/cursor/i}];async function mi(e){const t=await M("ps",["-o","ppid=,comm=","-p",String(e)],{timeoutMs:3e3});const s=/^\s*(\d+)\s+(.+?)\s*$/.exec(t.stdout);return t.code===0&&s?{ppid:Number(s[1]),comm:s[2]}:null}async function fi(e){const t=await M("lsof",["-a","-p",String(e),"-d","cwd","-Fn"],{timeoutMs:3e3});const s=t.stdout.split("\n").find(i=>i.startsWith("n"));return s?s.slice(1):null}function wi(e){if(!e)return void 0;return Vt.find(t=>e.toLowerCase().includes(t.app))}async function gi(e={}){const t=e.env??process.env;let s=e.pid??process.pid;let i=null;for(let p=0;p<5&&s>1;p++){const h=await mi(s).catch(()=>null);if(!h)break;const g=Vt.find(w=>w.match.test(h.comm));if(p>0&&g){i={app:g,pid:s};break}s=h.ppid}const n=i?.app??wi(e.clientName);const a=(i?await fi(i.pid).catch(()=>null):null)??process.cwd();const o=(await M("git",["-C",a,"rev-parse","--abbrev-ref","HEAD"],{timeoutMs:3e3}).catch(()=>null))?.stdout.trim();const r=t.CLAUDE_CODE_SESSION_ID?.trim();let l;let c="none";if(r&&(n?.app??"claude")==="claude"){l=`claude:${r}`;c="claude-session"}else if(i){l=`${i.app.app}:${i.pid}:${await ae(i.pid)??""}`;c="parent-process"}return{app:n?.app??"other",appName:n?.name??(e.clientName||"Agent"),chatKey:l,chatKeySource:c,project:hi.basename(a)||void 0,projectPath:a,branch:o&&o!=="HEAD"?o:void 0,clientName:e.clientName}}function yi(e){return e.project?`${e.appName} \xB7 ${e.project}`:e.appName}import Xt from"path";import{existsSync as vi}from"fs";import Si from"os";import{execFile as ki,spawn as bi}from"child_process";import{createHash as Mi}from"crypto";import{promises as j}from"fs";import Be from"os";import N from"path";import{promisify as _i}from"util";var Q=_i(ki);var Ie="gg.buoy.phoneprobe";var Oe=1024*1024;function Ei(e){const t=e.match(/BUOY_PROBE physicalMemory=(\d+) cpus=(\d+) footprint=(\d+) available=(\d+)/);if(!t)return null;const[s,i,n,a]=t.slice(1).map(Number);const o=n+a;if(!s||!i||a<=0||o>s)return null;return{ramMB:Math.floor(s/Oe),cpus:i,limitMB:Math.floor(o/Oe)}}function Zt(e,t){return e.match(new RegExp(`<key>${t}</key>\\s*<string>([^<]*)</string>`))?.[1]}function Je(e,t,s){const i=e.match(new RegExp(`<key>${t}</key>\\s*<array>([\\s\\S]*?)</array>`))?.[1]??"";return[...i.matchAll(new RegExp(`<${s}>([\\s\\S]*?)</${s}>`,"g"))].map(n=>n[1].replace(/\s+/g,""))}function Bi(e,t){const s=t.match(/<key>Entitlements<\/key>\s*<dict>([\s\S]*?)<\/dict>/)?.[1]??"";const i=Zt(s,"application-identifier");const n=Je(t,"TeamIdentifier","string")[0];const a=t.match(/<key>ExpirationDate<\/key>\s*<date>([^<]+)<\/date>/)?.[1];if(!i||!n||!a)return null;return{file:e,name:Zt(t,"Name")??N.basename(e),team:n,appId:i,expires:new Date(a),devices:Je(t,"ProvisionedDevices","string"),allDevices:/<key>ProvisionsAllDevices<\/key>\s*<true\/>/.test(t),getTaskAllow:/<key>get-task-allow<\/key>\s*<true\/>/.test(s),certSha1s:Je(t,"DeveloperCertificates","data").map(o=>Mi("sha1").update(Buffer.from(o,"base64")).digest("hex").toUpperCase())}}function Ii(e,t,s,i=new Date){const n=e.filter(o=>o.getTaskAllow&&o.expires>i&&(o.allDevices||o.devices.includes(t))&&(o.appId===`${o.team}.*`||o.appId===`${o.team}.${Ie}`)&&o.certSha1s.some(r=>s.has(r)));n.sort((o,r)=>Number(r.appId.endsWith(".*"))-Number(o.appId.endsWith(".*"))||r.expires.getTime()-o.expires.getTime());const a=n[0];return a?{profile:a,identity:a.certSha1s.find(o=>s.has(o))}:null}async function Oi(){const e=[N.join(Be.homedir(),"Library/Developer/Xcode/UserData/Provisioning Profiles"),N.join(Be.homedir(),"Library/MobileDevice/Provisioning Profiles")];const t=[];for(const s of e){let i=[];try{i=(await j.readdir(s)).filter(n=>n.endsWith(".mobileprovision"))}catch{continue}for(const n of i){const a=N.join(s,n);try{const{stdout:o}=await Q("security",["cms","-D","-i",a],{timeout:15e3,maxBuffer:16*Oe});const r=Bi(a,o);if(r)t.push(r)}catch{}}}return t}async function Ai(){const{stdout:e}=await Q("security",["find-identity","-v","-p","codesigning"],{timeout:15e3});return new Set([...e.matchAll(/^\s*\d+\)\s+([0-9A-F]{40})\s/gm)].map(t=>t[1]))}async function Di(){const e=await j.mkdtemp(N.join(Be.tmpdir(),"buoy-phones-"));try{const t=N.join(e,"devices.json");await Q("xcrun",["devicectl","list","devices","--json-output",t],{timeout:3e4});const s=JSON.parse(await j.readFile(t,"utf8"))?.result?.devices??[];return s.filter(i=>i.hardwareProperties?.reality==="physical"&&i.hardwareProperties?.deviceType==="iPhone"&&i.connectionProperties?.pairingState==="paired").map(i=>({udid:i.hardwareProperties.udid,name:i.hardwareProperties.marketingName??"iPhone",productType:i.hardwareProperties.productType,ios:i.deviceProperties?.osVersionNumber??""}))}finally{await j.rm(e,{recursive:true,force:true}).catch(()=>void 0)}}function Pi(e,t,s){const i=Object.keys(e).find(a=>e[a].productType===t);if(i)return i;const n=a=>a.toLowerCase().replace(/[()]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");return`${n(s)}-${n(t)}`.slice(0,64).replace(/-$/,"")}async function Ti(e,t,s,i){const n=N.join(e,"PhoneProbe.app");await j.mkdir(n,{recursive:true});const a=N.join(e,"PhoneProbe.m");await j.writeFile(a,Is);await Q("xcrun",["--sdk","iphoneos","clang","-arch","arm64","-miphoneos-version-min=13.0","-fobjc-arc","-O2","-framework","Foundation","-framework","UIKit",a,"-o",N.join(n,"PhoneProbe")],{timeout:18e4,maxBuffer:8*Oe,env:{...process.env,TMPDIR:e}});const o=Ie;await j.writeFile(N.join(n,"Info.plist"),`<?xml version="1.0" encoding="UTF-8"?>
367
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
368
+ <plist version="1.0"><dict>
369
+ <key>CFBundleIdentifier</key><string>${o}</string>
370
+ <key>CFBundleExecutable</key><string>PhoneProbe</string>
371
+ <key>CFBundleName</key><string>Buoy Probe</string>
372
+ <key>CFBundlePackageType</key><string>APPL</string>
373
+ <key>CFBundleShortVersionString</key><string>1.0</string>
374
+ <key>CFBundleVersion</key><string>1</string>
375
+ <key>CFBundleSupportedPlatforms</key><array><string>iPhoneOS</string></array>
376
+ <key>MinimumOSVersion</key><string>13.0</string>
377
+ <key>UIDeviceFamily</key><array><integer>1</integer></array>
378
+ <key>UIApplicationSceneManifest</key><dict><key>UIApplicationSupportsMultipleScenes</key><false/></dict>
379
+ <key>UILaunchScreen</key><dict/>
380
+ <key>UIRequiredDeviceCapabilities</key><array><string>arm64</string></array>
381
+ </dict></plist>
382
+ `);await j.copyFile(s,N.join(n,"embedded.mobileprovision"));const r=N.join(e,"probe.entitlements");await j.writeFile(r,`<?xml version="1.0" encoding="UTF-8"?>
383
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
384
+ <plist version="1.0"><dict>
385
+ <key>application-identifier</key><string>${t}.${o}</string>
386
+ <key>com.apple.developer.team-identifier</key><string>${t}</string>
387
+ <key>get-task-allow</key><true/>
388
+ </dict></plist>
389
+ `);await Q("codesign",["-f","-s",i,"--entitlements",r,n],{timeout:6e4});return n}function Ri(e,t=45e3){return new Promise(s=>{const i=bi("xcrun",["devicectl","device","process","launch","--device",e,"--terminate-existing","--console",Ie]);let n="";let a=false;const o=()=>{if(a)return;a=true;clearTimeout(r);i.kill("SIGTERM");s(n)};const r=setTimeout(o,t);const l=c=>{n+=c.toString();if(/BUOY_PROBE .*available=\d+/.test(n))setTimeout(o,300)};i.stdout.on("data",l);i.stderr.on("data",l);i.on("close",o);i.on("error",o)})}async function es(e={}){const t=e.log??(()=>{});const s=(await Di()).filter(o=>!e.device||o.udid===e.device);if(s.length===0)throw new Error(e.device?`No paired iPhone ${e.device}.`:"No paired iPhone. Plug one in, unlock it and trust this Mac.");if(s.length>1)throw new Error(`More than one iPhone. Pick one with --device:
390
+ ${s.map(o=>` ${o.udid} ${o.name}`).join("\n")}`);const i=s[0];t(`Measuring ${i.name} (${i.productType}, iOS ${i.ios})...`);const n=Ii(await Oi(),i.udid,await Ai());if(!n){throw new Error(`No provisioning profile on this Mac can install the measuring app on this iPhone. It needs a development profile for any app ("TEAM.*"), which comes with a paid Apple Developer team: in Xcode, sign in with that team and run any app with automatic signing on this phone once. Free Apple accounts only get profiles for one app, and they can't be used here.`)}const a=await j.mkdtemp(N.join(Be.tmpdir(),"buoy-probe-"));try{const o=await Ti(a,n.profile.team,n.profile.file,n.identity);await Q("xcrun",["devicectl","device","install","app","--device",i.udid,o],{timeout:12e4});let r=null;try{const w=await Ri(i.udid);r=Ei(w);if(!r){const k=/locked/i.test(w)?" The phone looks locked: unlock it and try again.":"";throw new Error(`Could not read the phone.${k} Output: ${w.trim().slice(-300)}`)}}finally{await Q("xcrun",["devicectl","device","uninstall","app","--device",i.udid,Ie],{timeout:6e4}).catch(()=>void 0)}const l=Z();const c=Pi(l,i.productType,i.name);const p=l[c];const h=p?.warnSource?.startsWith("measured")&&p.warnMB<r.limitMB;const g={name:p?.name??i.name,productType:i.productType,ramMB:r.ramMB,cpus:r.cpus,limitMB:r.limitMB,warnMB:h?p.warnMB:Math.round(r.limitMB*.8),warnSource:h?p.warnSource:"80% of the limit (not measured)",ios:i.ios,measuredAt:new Date().toISOString().slice(0,10)};await St(c,g);return{id:c,phone:g,previous:p}}finally{await j.rm(a,{recursive:true,force:true}).catch(()=>void 0)}}var Ae=e=>`Usage: ${e} <command>
391
+
392
+ status [--outside] Pool, budgets, sims, leases, recent events
393
+ setup [options] Make a template (the sim clones are made from)
394
+ --app <path.app> App build (default: example-dev-build Debug build)
395
+ --no-seed Skip the seed
396
+ --launch-url <url> Open this URL after each app launch. iOS asks
397
+ "Open in \u2026?" for a custom scheme, so a dev-client
398
+ app is better seeded with Preferences/ (it reopens
399
+ its last Metro URL by itself)
400
+ --seed <dir> Seed folder (default: example-dev-build/artifacts/pool-seed)
401
+ --device <type id> Default: iPhone 17 Pro
402
+ --runtime <runtime id> Default: iOS 26.3
403
+ --profile slim|stock Default: slim
404
+ --metro <port> Default: 8802
405
+ --dry-run Show what it would do and what it costs
406
+ grow <n> [--template id] Add n sims
407
+ shrink <n> [--template id] Remove n idle sims
408
+ remove-template <id> Delete a template and all its sims (none may be in use)
409
+ acquire <n> [--template id] [--purpose text] [--launch]
410
+ Take n sims and hold them until Ctrl-C
411
+ park|wake|reset|rebuild|delete <udid>
412
+ end-lease <leaseId> Force-end a lease (its sims are rebuilt)
413
+ settings [key=value ...] Show or change settings
414
+ phone list Phones a sim can act like (RAM, CPUs, memory limit)
415
+ phone use <id|off> Launch apps as this phone (default: iphone-se-2nd-gen)
416
+ phone measure [--device <udid>]
417
+ Read the iPhone plugged into this Mac and add it
418
+ doctor Check Xcode, disk, memory, the farm service
419
+ stop [--now] Stop the farm service and park free sims
420
+ --now Stop even if leases are still held
421
+ farmd Run the farm service in this process
422
+ `;var Tn=Ae("pnpm farm");function O(e,t){const s=e.indexOf(`--${t}`);if(s<0)return void 0;const i=e[s+1];if(!i||i.startsWith("--"))throw new d("BAD_REQUEST",`--${t} needs a value.`);return i}async function Ni(e){return Qt({label:`CLI (${Si.userInfo().username})`,launcher:zt(e,["farmd"])})}function _(e){console.log(typeof e==="string"?e:JSON.stringify(e,null,2))}async function ts(e,t,s){if(s)return s;const i=await e.call("status");const n=i.templates.filter(a=>a.usable);if(n.length===0)throw new d("NO_TEMPLATE","No template yet.",`Run: ${t} setup`);return n[n.length-1].id}function $i(e){const t=[`Pool ${e.counts.pool} \xB7 awake ${e.counts.awake} \xB7 in use ${e.counts.leased} \xB7 room for about ${e.budget.roomForMoreSims} more`,`Memory ${e.budget.availableMemGB} GB free (${e.budget.memPressure}) \xB7 disk ${e.budget.freeDiskGB} GB free \xB7 load ${e.budget.loadAvg1}/${e.budget.cpuCount}`];for(const s of e.templates){t.push(`Template ${s.id} ${s.name}: ${s.usable?"ready":s.note??"not ready"} (${s.profile}, ${s.runtime.split(".").pop()})`);t.push(` seed: ${s.seedDir??"none"} \xB7 launch URL: ${s.launchUrl??"none"}`)}for(const s of e.sims){t.push(` ${s.name.padEnd(14)} ${s.power.padEnd(8)} ${s.health.padEnd(7)} ${s.profile.padEnd(7)} ${s.owner?`in use by ${s.owner}`:""} ${s.udid}`);const i=s.phone;if(i?.status==="on"){t.push(` as ${i.phoneName}${i.peakMB?`, peak ${i.peakMB} MB`:""}${i.overLimit?", WENT PAST THE PHONE'S LIMIT":""}${i.ended?` (closed: ${i.ended})`:""}`)}else if(i?.status==="fallback"){t.push(` plain sim app: ${i.note??"the phone profile did not load"}`)}}for(const s of e.orphans??[])t.push(` ${s.name} ${s.udid}: held after crash`);for(const s of e.recentEvents.slice(-8))t.push(` \xB7 ${new Date(s.at).toLocaleTimeString(void 0,{hour12:false})} ${s.message}`);if(e.outsideSims)t.push(`Other sims (never touched): ${e.outsideSims.length}`);return t.join("\n")}async function Li(e,{prog:t,entry:s}){const[i,...n]=e;if(!i||i==="help"||i==="--help")return _(Ae(t));Ci(i,n);if(i==="farmd"){const o=await qt({hostLabel:"node",idleExitMs:10*6e4,onExit:()=>process.exit(0)});if(!o){console.error("Another farm service is already running.");process.exit(0)}for(const r of["SIGTERM","SIGINT"])process.on(r,()=>void o.stop(r));return}if(i==="phone"&&n[0]!=="use"){const o=n[0];if(o==="list"||!o){const r=Z();for(const[l,c]of Object.entries(r)){_(`${l}: ${c.name} (${c.productType}), ${c.ramMB} MB RAM, ${c.cpus} CPUs, app limit ${c.limitMB} MB, first warning ${c.warnMB} MB, iOS ${c.ios}, measured ${c.measuredAt}`)}return}if(o==="measure"){const r=await es({device:O(n,"device"),log:l=>console.log(l)});_(`Saved "${r.id}": ${r.phone.ramMB} MB RAM, ${r.phone.cpus} CPUs, app limit ${r.phone.limitMB} MB, first warning ${r.phone.warnMB} MB.`);if(r.previous&&r.previous.limitMB!==r.phone.limitMB)_(`(The limit was ${r.previous.limitMB} MB before.)`);_(`Use it with: ${t} phone use ${r.id}`);return}throw new d("BAD_REQUEST",`Unknown phone command ${o}.`,"Try: phone list, phone use <id|off>, phone measure")}if(i==="doctor"){const o=new He;const r=await o.hostStats();const l=await de();const c=await o.listDevices().catch(()=>[]);const p=he();const h=p?Xt.join(p,"example-dev-build/artifacts/pool-seed"):null;const g=p?{exampleBuild:Ee(),seed:h?oe(h)??"ok":"none"}:{};_({xcode:await o.xcodeBuild(),runtimes:[...new Set(c.map(w=>w.runtime.split(".").pop()))],freeDiskGB:Math.floor(r.freeDiskBytes/1024**3),availableMemGB:Math.floor(r.availableMemBytes/1024**3),memPressure:r.memPressure,farmService:l?{...l,alive:await ue(l)}:"not running",socket:vi(U().socket),...g,slimLabels:J("slim").length,slimTurnsOff:ie.map(w=>w.name)});return}const a=await Ni(s);try{switch(i){case"status":{const o=await a.call("status",{outside:n.includes("--outside")});return _(n.includes("--json")?o:$i(o))}case"setup":{const o=he();const r={appPath:O(n,"app")??Ee(),seedDir:n.includes("--no-seed")?null:O(n,"seed")??(o?Xt.join(o,"example-dev-build/artifacts/pool-seed"):void 0),launchUrl:O(n,"launch-url"),deviceType:O(n,"device")??"com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",runtime:O(n,"runtime")??"com.apple.CoreSimulator.SimRuntime.iOS-26-3",profile:O(n,"profile")??"slim",metroPort:Number(O(n,"metro")??8802)};if(!r.appPath)throw new d("BAD_REQUEST","No app build found.","Pass --app <path.app>.");if(!r.seedDir&&!n.includes("--no-seed"))throw new d("NO_SEED","No seed folder found.","Pass --seed <dir>, or --no-seed for an app that needs no saved data.");if(n.includes("--dry-run")){const l=await a.call("budget",{ramGB:6,diskGB:4});return _({wouldCreateTemplate:r,seed:r.seedDir?oe(r.seedDir)??"ok":"none",slimTurnsOff:r.profile==="slim"?ie.map(c=>`${c.name}: ${c.downside}`):[],budget:l.ok?"ok":l.reason,roomForSims:l.roomFor})}return _(await a.call("setup",r,{timeoutMs:15*6e4,requestId:`setup-${Date.now()}`}))}case"grow":case"shrink":{const o=await ts(a,t,O(n,"template"));return _(await a.call(i,{templateId:o,count:Number(n[0]??1)},{timeoutMs:30*6e4,requestId:`${i}-${Date.now()}`}))}case"acquire":{const o=await ts(a,t,O(n,"template"));const r=await a.acquire({templateId:o,count:Number(n[0]??1),purpose:O(n,"purpose")??"CLI",launch:n.includes("--launch")});_(r);console.error("Holding these sims. Press Ctrl-C to release them.");await new Promise(l=>process.once("SIGINT",()=>l()));await a.release(r.leaseId,r.epoch);return _("Released.")}case"remove-template":if(!n[0])throw new d("BAD_REQUEST",`Usage: ${t} remove-template <id>`);return _(await a.call("removeTemplate",{templateId:n[0]},{timeoutMs:30*6e4,requestId:`rmt-${n[0]}-${Date.now()}`}));case"park":case"wake":case"reset":case"rebuild":case"delete":if(!n[0])throw new d("BAD_REQUEST",`Usage: ${t} ${i} <udid>`);return _(await a.call(i,{udid:n[0]},{timeoutMs:5*6e4,requestId:`${i}-${n[0]}-${Date.now()}`}));case"stop":return _(await a.call("shutdown",{ifIdle:!n.includes("--now")}));case"end-lease":return _(await a.call("endLease",{leaseId:n[0],force:true},{requestId:`end-${n[0]}`}));case"phone":{if(!n[1])throw new d("BAD_REQUEST","phone use needs a phone id or off.",`See: ${t} phone list`);const o=await a.call("settings",{phoneProfile:n[1]});return _(o.phoneProfile==="off"?"Apps now launch as plain simulator apps.":`Apps now launch as ${Z()[o.phoneProfile]?.name??o.phoneProfile}. Apps that are already open keep their old setting until the farm launches them again.`)}case"settings":{if(n.length===0)return _((await a.call("status")).settings);const o={};for(const r of n){const[l,c]=r.split("=");o[l]=c==="true"?true:c==="false"?false:Number.isNaN(Number(c))?c:Number(c)}return _(await a.call("settings",o))}default:_(Ae(t));process.exitCode=2}}finally{a.close()}}function Ci(e,t){const s={setup:["app","seed","launch-url","device","runtime","profile","metro"],grow:["template"],shrink:["template"],acquire:["template","purpose"],phone:["device"]};for(const i of s[e]??[])O(t,i);if(e==="setup"){if(t.includes("--no-seed")&&t.includes("--seed"))throw new d("BAD_REQUEST","Use --seed or --no-seed.");const i=O(t,"profile");const n=Number(O(t,"metro")??8802);if(i&&!["slim","stock"].includes(i))throw new d("BAD_REQUEST","Use slim or stock.");if(!Number.isInteger(n)||n<1||n>65535)throw new d("BAD_REQUEST","Use a port from 1 to 65535.")}}export{F as PROTOCOL_VERSION,fe as STATE_VERSION,Te as DEFAULT_SETTINGS,d as FarmError,Ve as ALWAYS_ENABLED,ie as SLIM_CATEGORIES,Xe as slimLabels,J as profileLabels,Ze as profileHash,$e as bootEnv,ge as findDataContainer,pt as readBuoyInstallId,mt as LoadMeter,ft as parseCpuTime,wt as BUILT_IN_PHONES,gt as DEFAULT_PHONE,xe as PHONE_OFF,Se as phoneDir,Z as loadPhones,St as savePhone,kt as defaultCapMB,bt as profileVars,Ue as joinInsertList,re as launchFilePath,ke as eventsFilePath,Mt as writeLaunchFile,be as removeLaunchFile,_t as readLaunchFile,je as simLaunchEnv,Et as parseEvents,Bt as summarize,Me as readSummary,It as buildDylib,Ot as LocalDylibBuilder,Rt as Engine,Nt as crashLoop,He as SimctlHost,G as farmHome,U as paths,Gt as Store,si as farmOwnedUdids,qt as startFarmd,zt as nodeLauncher,Kt as FarmClient,Qt as connectFarm,he as findRepoRoot,Ee as findExampleBuild,Jt as defaultSeedDir,pi as farmDefaults,gi as detectAgent,yi as agentLabel,es as measurePhone,Ae as farmHelp,Li as runFarmCommand};