@buoy-gg/mcp 7.0.72 → 7.0.73
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/{chunk-FJI4FST7.mjs → chunk-AHIKIVTB.mjs} +1 -1
- package/dist/chunk-DZRRLTOD.mjs +4 -0
- package/dist/chunk-MJDNVDJI.mjs +474 -0
- package/dist/{chunk-E3ECF6L6.mjs → chunk-OADIHE3T.mjs} +1 -1
- package/dist/{chunk-DPDIDM62.mjs → chunk-OUCQTYIW.mjs} +1 -1
- package/dist/{chunk-ZJAAYXQM.mjs → chunk-S4JHE46Q.mjs} +92 -92
- package/dist/cli.js +194 -192
- package/dist/cli.mjs +6 -6
- package/dist/{flowRun-BQKJKYSR.mjs → flowRun-GTYQQXHF.mjs} +1 -1
- package/dist/index.js +27 -27
- package/dist/index.mjs +1 -1
- package/dist/{init-FGX3CMMQ.mjs → init-FDDGVIXA.mjs} +1 -1
- package/dist/{main-3BG6EIXP.mjs → main-DJT43WTJ.mjs} +2 -2
- package/dist/{simFarm-EDOP6VEC.mjs → simFarm-5MWIXNER.mjs} +1 -1
- package/dist/src-ZFIIN4L2.mjs +1 -0
- package/package.json +4 -4
- package/skill/buoy-optimize/MEASURING.md +11 -2
- package/skill/buoy-optimize/SKILL.md +1 -1
- package/dist/chunk-GG4ZR76D.mjs +0 -4
- package/dist/chunk-SXYS37FL.mjs +0 -472
- package/dist/src-WMG32XDB.mjs +0 -1
package/dist/chunk-SXYS37FL.mjs
DELETED
|
@@ -1,472 +0,0 @@
|
|
|
1
|
-
import{createRequire as si}from"module";const fn=si(import.meta.url);var K=1;var Ie=1;var qe={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 ii}from"crypto";var It=["com.apple.sharingd"];var he=[{"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 $t(){const e=new Set(It);const t=new Set;for(const s of he)for(const i of s.labels)if(!e.has(i))t.add(i);return[...t].sort()}function ne(e){return e==="slim"?$t():[]}function Ot(e){return ii("sha256").update(e+"\n"+ne(e).join("\n")).digest("hex").slice(0,16)}import{promises as x,existsSync as At}from"fs";import L from"path";import{AsyncLocalStorage as ai}from"async_hooks";import{createHash as ni,randomBytes as $e}from"crypto";import{promises as oe}from"fs";import Ke from"path";import{randomBytes as oi}from"crypto";import{spawn as ri}from"child_process";var me=new Set;function Ye(){return me.size}function li(){for(const e of me){try{e.kill("SIGKILL")}catch{}}}function M(e,t,s={}){const{timeoutMs:i=3e4,maxBytes:a=4*1024*1024}=s;return new Promise(n=>{const o=ri(e,t,{env:s.env??process.env,stdio:[s.input==null?"ignore":"pipe","pipe","pipe"]});me.add(o);let r="";let l="";let c=false;o.stdout.on("data",u=>{if(r.length<a)r+=u.toString("utf8")});o.stderr.on("data",u=>{if(l.length<a)l+=u.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",u=>{me.delete(o);clearTimeout(p);n({code:null,stdout:r,stderr:l+String(u),timedOut:c})});o.on("close",u=>{me.delete(o);clearTimeout(p);n({code:u,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 Dt(){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 a of t.split("\n")){const n=/^\s*(\d+)\s+(.*)$/.exec(a);if(n)s.set(Number(n[1]),n[2])}const i=[];for(const a of e.split("\n")){const n=/^\s*(\d+)\s+(\d+)\s+(\w{3}\s+\w{3}\s+\d+\s+[\d:]+\s+\d{4})\s+(\S+)\s+(.*)$/.exec(a);if(!n)continue;const o=Number(n[1]);i.push({pid:o,ppid:Number(n[2]),start:n[3].replace(/\s+/g," "),stat:n[4],comm:n[5].trim(),command:s.get(o)??n[5].trim()})}return i}function Tt(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 a=[];const n=i.get(t);if(!n)return a;const o=[n];const r=new Set;while(o.length){const l=o.pop();if(r.has(l.pid))continue;r.add(l.pid);a.push(l);for(const c of s.get(l.pid)??[])o.push(c)}return a}async function re(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 C(e,t,s=false){if(!Number.isInteger(e)||e<=0)return false;try{process.kill(e,0)}catch(a){if(a.code!=="EPERM")return false}if(!t)return true;const i=await re(e);if(i===null)return s;return i===t}function Qe(e=process.env){return Object.fromEntries(Object.entries(e).filter(([t])=>!t.startsWith("SIMCTL_CHILD_")))}var I=e=>new Promise(t=>setTimeout(t,e));var le=process.env.BUOY_FARM_DISABLED_ROOT||"/private/var/tmp";function Rt(e,t=le){if(!/^[0-9A-F-]{36}$/i.test(e))throw new Error(`not a UDID: ${e}`);return Ke.join(t,`com.apple.CoreSimulator.SimDevice.${e}`)}function Pt(e,t=le){return Ke.join(Rt(e,t),"disabled.plist")}async function Nt(e,t=le){const s=Pt(e,t);let i;try{i=await oe.lstat(s)}catch{return{}}if(!i.isFile())throw new Error(`refusing ${s}: not a regular file`);const a=await P("plutil",["-convert","json","-o","-",s],{timeoutMs:1e4});const n=JSON.parse(a);const o={};for(const[r,l]of Object.entries(n))if(typeof l==="boolean")o[r]=l;return o}function ci(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function di(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>${ci(i)}</key>
|
|
2
|
-
<${e[i]?"true":"false"}/>
|
|
3
|
-
`;return s+"</dict>\n</plist>\n"}async function xt(e,t,s=le){const i=Rt(e,s);await oe.mkdir(i,{recursive:true});const a=await oe.lstat(i);if(!a.isDirectory())throw new Error(`refusing ${i}: not a directory`);const n=await Nt(e,s);const o=Ke.join(i,"buoy-farm-prior.json");let r={};try{r=JSON.parse(await oe.readFile(o,"utf8"))}catch{}const l={...n};for(const c of t){if(!(c in r))r[c]=c in n?n[c]:null;l[c]=true}await Lt(o,JSON.stringify(r,null,2)+"\n");await Lt(Pt(e,s),di(l))}async function pi(e,t,s=le){const i=await Nt(e,s);return t.every(a=>i[a]===true)}async function Lt(e,t){const s=`${e}.${oi(4).toString("hex")}.tmp`;const i=await oe.open(s,"w",420);try{await i.writeFile(t);await i.sync()}finally{await i.close()}await oe.rename(s,e)}import{promises as j,existsSync as X,readFileSync as En}from"fs";import E from"path";import{createHash as Ct}from"crypto";var jt=["@react_buoy_sync_device_id.json","@react_buoy_install.json"];var ui="@buoy~1floating-tool~1*";function fe(e){if(!X(E.join(e,"seed.json")))return`No seed at ${e}. Run: pnpm e2e:pool seed`;if(X(E.join(e,"Documents/buoy-license"))){for(const t of["buoy-gg-license.json","buoy-gg-device-fingerprint.json"]){if(!X(E.join(e,"Documents/buoy-license",t)))return`The seed lacks ${t}.`}}return null}async function hi(e){const t=Ct("sha256");async function s(i){let a;try{a=await j.readdir(i,{withFileTypes:true})}catch{return}a.sort((n,o)=>n.name.localeCompare(o.name));for(const n of a){const o=E.join(i,n.name);if(n.isDirectory())await s(o);else{const r=await j.stat(o);t.update(`${E.relative(e,o)}:${r.size}:${Math.floor(r.mtimeMs)}
|
|
4
|
-
`)}}}await s(e);return t.digest("hex").slice(0,16)}async function mi(e){const t=Ct("sha256");const s=E.join(e,"Info.plist");t.update(await j.readFile(s));const i=JSON.parse(await P("plutil",["-convert","json","-o","-",s],{timeoutMs:1e4}));const a=E.join(e,String(i.CFBundleExecutable??""));const n=await j.stat(a);t.update(`${n.size}:${Math.floor(n.mtimeMs)}`);return t.digest("hex").slice(0,16)}async function fi(e){const t=JSON.parse(await P("plutil",["-convert","json","-o","-",E.join(e,"Info.plist")],{timeoutMs:1e4}));if(!t.CFBundleIdentifier)throw new Error(`${e} has no CFBundleIdentifier`);return String(t.CFBundleIdentifier)}async function Oe(e,t){const s=E.join(e,"Containers/Data/Application");let i;try{i=await j.readdir(s)}catch{return null}for(const a of i){const n=E.join(s,a,".com.apple.mobile_container_manager.metadata.plist");if(!X(n))continue;const o=await M("plutil",["-extract","MCMMetadataIdentifier","raw","-o","-",n],{timeoutMs:5e3});if(o.code===0&&o.stdout.trim()===t)return E.join(s,a)}return null}function wi(e,t){return E.join(e,"Library/Application Support",t,"RCTAsyncLocalStorage_V1")}async function Ut(e,t,s,i){i();await j.mkdir(t,{recursive:true});const a=["-a","--delete"];for(const n of s)a.push("--exclude",n);a.push(e.replace(/\/?$/,"/"),t.replace(/\/?$/,"/"));i();await P("rsync",a,{timeoutMs:6e4})}async function Ft(e,t,s,i=()=>{}){i();const a=fe(s);if(a)throw new Error(a);const n=[...jt.map(l=>`react-buoy/${l}`),`react-buoy/${ui}`];if(X(E.join(s,"Documents")))await Ut(E.join(s,"Documents"),E.join(e,"Documents"),n,i);if(X(E.join(s,"AsyncStorage/manifest.json"))){await Ut(E.join(s,"AsyncStorage"),wi(e,t),[],i)}const o=E.join(s,"Preferences",`${t}.plist`);if(X(o)){i();await j.mkdir(E.join(e,"Library/Preferences"),{recursive:true});await j.copyFile(o,E.join(e,"Library/Preferences",`${t}.plist`))}const r=E.join(e,"Documents/react-buoy");try{for(const l of await j.readdir(r)){i();if(l.startsWith("@buoy~1floating-tool~1"))await j.rm(E.join(r,l),{force:true,recursive:true})}}catch{}}async function Ae(e,t=()=>{}){t();const s=[];const i=E.join(e,"Documents/react-buoy");let a=[];try{a=await j.readdir(i)}catch{return s}for(const n of a){if(jt.includes(n)||n.startsWith("@buoy~1floating-tool~1")){t();await j.rm(E.join(i,n),{force:true,recursive:true});s.push(n)}}return s}async function Gt(e){let t;try{t=await j.readFile(E.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 Wt=2*60*6e4;var gi=10;var yi=5;var vi=.8;var Z=e=>Math.round(e*10)/10;var Si=e=>{if(!e.length)return 0;const t=[...e].sort((i,a)=>i-a);const s=t.length>>1;return t.length%2?t[s]:(t[s-1]+t[s])/2};var Ht=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>=gi){const h=await Promise.all(e.udids.map(f=>this.host.simTree(f)));this.pids=h.flat().map(f=>f.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%yi===0);this.cpuCount=i.cpuCount;const a=this.now();const n=this.prev;this.prev={...i,at:a,leaseId:e.leaseId};const o=h=>(i.hostTotalMs-h)/Math.max(1,i.cpuCount);if(i.pidsCpuMs!==null&&i.graphicsCpuMs!==null){const h=this.lastProcs;const f=h?o(h.hostTotalMs):0;if(h&&f>0){this.rates.ours=Math.max(0,(i.pidsCpuMs-h.pidsCpuMs)/f);this.rates.graphics=Math.max(0,(i.graphicsCpuMs-h.graphicsCpuMs)/f)}this.rates.gpuPct=i.gpuPct;this.lastProcs={hostTotalMs:i.hostTotalMs,pidsCpuMs:i.pidsCpuMs,graphicsCpuMs:i.graphicsCpuMs}}if(!n||n.leaseId!==e.leaseId)return;const r=o(n.hostTotalMs);if(r<=0)return;const l=Math.max(0,(i.hostBusyMs-n.hostBusyMs)/r);const c=this.rates.ours;const p=this.rates.graphics;this.samples.push({at:Math.round((a+n.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 u=a-Wt;while(this.samples.length&&this.samples[0].at<u)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 a=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 n=Si(a.filter(o=>o.mine.length).map(o=>Ve(o.mine.map(r=>r.outsideCores))));return a.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()-Wt)){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*vi)){return{...p,reason:"No load record for all of this run. Hold perf-slot for the whole test."}}const u=l.map(w=>w.outsideCores);const h=l.map(w=>w.gpuPct).filter(w=>w!==null);const f=l.map(w=>w.thermal).filter(w=>w!==null);const S={...p,freeCoresMin:Math.min(...l.map(w=>w.freeCores)),outsideCoresAvg:Z(Ve(u)),outsideCoresMax:Math.max(...u),ourCoresAvg:Z(Ve(l.map(w=>w.ourCores))),graphicsCoresMax:Math.max(...l.map(w=>w.graphicsCores)),gpuMaxPct:h.length?Math.max(...h):null,swapGrowthMB:Math.round(Math.max(0,l[l.length-1].swapMB-(this.before(e,o.from)?.swapMB??l[0].swapMB))),thermalMax:f.length?Math.max(...f):null};if(S.thermalMax!=null&&S.thermalMax>s.maxThermalLevel){return{...S,reason:"The Mac got hot and slowed itself down. Let it cool, then run again."}}if(l.some(w=>w.memLevel>=4)){return{...S,reason:"The Mac ran low on memory. Close apps or stop sims you don't need."}}if(S.swapGrowthMB>s.maxSwapGrowthMB){return{...S,reason:`The Mac swapped ${S.swapGrowthMB} MB of memory to disk.`}}if(S.freeCoresMin<s.minFreeCores){return{...S,reason:`The Mac ran out of spare CPU (${S.freeCoresMin} cores free, needs ${s.minFreeCores}).`}}const b=Z(S.outsideCoresMax-n);if(b>s.maxSwingCores){return{...S,reason:`Other work on the Mac jumped by ${b} cores during this run.`}}return{...S,fair:true}})}};function Ve(e){return e.length?e.reduce((t,s)=>t+s,0)/e.length:0}function zt(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 ki}from"child_process";import{promises as O,readFileSync as bi}from"fs";import Je from"os";import U from"path";import{promisify as Mi}from"util";var _i=`// 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 Bi="499c4e3de0f8";var Ei='// 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 De=Mi(ki);var qt={"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 Kt="iphone-se-2nd-gen";var Xe="off";function W(){return process.env.BUOY_FARM_HOME||U.join(Je.homedir(),".buoy","farm")}function Te(e=W()){return U.join(e,"phone")}function Yt(e=W()){return U.join(Te(e),"phones.json")}function Qt(e){const t=e;const s=(i,a,n)=>typeof i==="number"&&Number.isInteger(i)&&i>=a&&i<=n;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 ce(e=W()){const t={...qt};try{const s=JSON.parse(bi(Yt(e),"utf8"));for(const[i,a]of Object.entries(s?.phones??{})){if(/^[a-z0-9][a-z0-9-]{0,63}$/.test(i)&&Qt(a))t[i]=a}}catch{}return t}async function Vt(e,t,s=W()){if(!/^[a-z0-9][a-z0-9-]{0,63}$/.test(e))throw new Error(`Bad phone id ${e}.`);if(!Qt(t))throw new Error(`Bad phone numbers for ${e}.`);const i=Yt(s);let a={phones:{}};try{a=JSON.parse(await O.readFile(i,"utf8"));if(!a||typeof a.phones!=="object")a={phones:{}}}catch{}a.phones[e]=t;await O.mkdir(U.dirname(i),{recursive:true});const n=`${i}.${process.pid}.tmp`;await O.writeFile(n,JSON.stringify(a,null,2)+"\n");await O.rename(n,i)}function Jt(e){return Math.max(3072,e.limitMB+1024)}function Xt(e,t,s){const i=t.capMB>e.limitMB?t.capMB:Jt(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 Ze(...e){const t=new Set;const s=[];for(const i of e){for(const a of(i??"").split(":")){const n=a.trim();if(n&&!t.has(n)){t.add(n);s.push(n)}}}return s.join(":")}function we(e,t=W()){if(!/^[0-9A-F-]{36}$/i.test(e))throw new Error(`not a UDID: ${e}`);return U.join(Te(t),`${e}.launch.json`)}function Re(e,t=W()){if(!/^[0-9A-F-]{36}$/i.test(e))throw new Error(`not a UDID: ${e}`);return U.join(Te(t),`${e}.events.jsonl`)}async function Zt(e,t=W()){const s=we(e.udid,t);await O.mkdir(U.dirname(s),{recursive:true});const i=`${s}.${process.pid}.tmp`;await O.writeFile(i,JSON.stringify(e,null,2)+"\n");await O.rename(i,s)}async function Pe(e,t=W()){await O.rm(we(e,t),{force:true})}async function es(e,t=W()){try{const s=JSON.parse(await O.readFile(we(e,t),"utf8"));if(s?.udid!==e||typeof s.dylib!=="string"||!s.vars||typeof s.vars!=="object")return null;await O.access(s.dylib);return s}catch{return null}}async function Ii(e){try{const{stdout:t}=await De("xcrun",["simctl","spawn",e,"launchctl","getenv","DYLD_INSERT_LIBRARIES"],{timeout:1e4});return t.trim()}catch{return""}}async function et(e,t,s,i=W(),a=Ii){const n=await es(e,i);if(!n||n.bundleId!==t){return s?{SIMCTL_CHILD_DYLD_INSERT_LIBRARIES:Ze(process.env.SIMCTL_CHILD_DYLD_INSERT_LIBRARIES,await a(e),s)}:{}}const o={};for(const[r,l]of Object.entries(n.vars))o[`SIMCTL_CHILD_${r}`]=l;o.SIMCTL_CHILD_DYLD_INSERT_LIBRARIES=Ze(process.env.SIMCTL_CHILD_DYLD_INSERT_LIBRARIES,await a(e),s,n.dylib);return o}function ts(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 ss(e){let t=-1;for(let n=e.length-1;n>=0;n--)if(e[n].event==="profile_loaded"){t=n;break}if(t<0)return{loaded:false,ignored:[],memoryWarnings:0,overLimit:false,peakMB:0};const s=e[t];const i=e.slice(t).filter(n=>n.pid===s.pid);const a={pid:s.pid,loaded:true,ignored:Array.isArray(s.ignored)?s.ignored:[],memoryWarnings:0,overLimit:false,peakMB:0};for(const n of i){a.peakMB=Math.max(a.peakMB,n.footprintMB??0,typeof n.peakMB==="number"?n.peakMB:0);a.lastFootprintMB=n.footprintMB;if(n.event==="memory_warning")a.memoryWarnings++;if(n.event==="over_limit")a.overLimit=true;if(n.event==="jetsam_kill"){a.overLimit=true;a.ended="limit"}if(n.event==="safety_kill"){a.overLimit=true;a.ended="safety"}}return a}async function Ne(e,t=W()){const s=Re(e,t);try{const i=await O.open(s,"r");try{const{size:a}=await i.stat();const n=Math.min(a,256*1024);const o=Buffer.alloc(n);await i.read(o,0,n,a-n);let r=o.toString("utf8");if(n<a)r=r.slice(r.indexOf("\n")+1);return ss(ts(r))}finally{await i.close()}}catch{return null}}async function $i(){try{const{stdout:e}=await De("xcodebuild",["-version"],{timeout:3e4});return e.trim().split("\n").pop().replace(/^Build version\s*/,"").replace(/[^\w.-]/g,"")||"unknown"}catch{return"unknown"}}async function is(e){const t=U.join(e,"BuoyPhoneProfile.dylib");try{await O.access(t);return t}catch{}const s=await O.mkdtemp(U.join(Je.tmpdir(),"buoy-phone-profile-"));try{const i=U.join(s,"BuoyPhoneProfile.m");await O.writeFile(i,_i);const a=U.join(s,"BuoyPhoneProfile.dylib");await De("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",a],{timeout:18e4,maxBuffer:8*1024*1024,env:{...process.env,TMPDIR:s}});await De("codesign",["-f","-s","-",a],{timeout:6e4});await O.mkdir(e,{recursive:true});const n=`${t}.${process.pid}`;await O.copyFile(a,n);await O.rename(n,t);return t}finally{await O.rm(s,{recursive:true,force:true}).catch(()=>void 0)}}var as=class{constructor(e=U.join(Je.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=$i().then(t=>is(U.join(this.root,`${t}-${Bi}`))).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 de=1024**3;var tt="Buoy Farm ";var st=".buoy-farm.json";var Oi=120;var Ai=180;var it=9e4;var ns=500;var os=200;var Di=3;var Q=["done","failed","stopped","interrupted"];var rs=["setting-up","working","waiting","passed","failed","needs-help"];var Ti={now:()=>performance.now()};var Ri=10*6e4;var ls=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 Pi=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 Ni=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 cs=class{constructor(e){this.phoneFailed=new Map;this.simLock=new ls;this.deadlines=new Map;this.reservations=new Map;this.busy=new Pi;this.ticking=false;this.hardDeadlines=new Map;this.acquiring=new Set;this.budgetLock=new ls;this.labels=new Map;this.inflight=new Map;this.workContext=new ai;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(...a)=>{this.store.assertActive();const n=await i.apply(t,a);this.store.assertActive();return n}}});this.store=e.store;this.clock=e.clock??Ti;this.log=e.log??(()=>{});this.pollMs=e.pollMs??1e3;this.readyTimeoutMs=e.readyTimeoutMs??12e4;this.phoneBuilder=e.phoneBuilder??new as;this.phoneLoadTimeoutMs=e.phoneLoadTimeoutMs??1e4;this.bootGate=new Ni(this.state.settings.maxConcurrentBoots);this.meter=new Ht(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,a,n){this.touch(this.liveLease(e,t,n));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,a,n))}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 I(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,a]of Object.entries(this.state.locks)){if(!this.state.leases[a.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 a=t.get(i.udid);if(!a){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(a.state==="Booted"){i.power=i.power==="frozen"?"frozen":"awake";if(i.power!=="frozen"){const n=this.state.templates[i.templateId];const o=await this.health(i.udid,n?ne(n.profile):[]);i.profile=o.profile;i.lastCheckAt=new Date().toISOString();if(!o.ok||n?.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=a.state==="Booted"?"awake":"cold"}for(const i of Object.values(this.state.templates)){const a=t.get(i.udid);if(!a){i.usable=false;i.note="Its sim was deleted outside the farm."}else if(!At(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 a=i.data?.name;const n=e.find(o=>o.name===a&&!this.state.sims[o.udid]);if(n){this.state.orphans[n.udid]={udid:n.udid,name:n.name,cloneIntentName:a};this.store.event({kind:"orphan",message:`Found ${n.name} with no record after a crash. Held for review. Use farm delete to remove it.`,udid:n.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:a,name:n,templateId:o}=i.data;if(Object.values(this.state.orphans).some(r=>r.name===n))continue;s.add(a);this.busy.add(a);this.background(`resume rebuild ${n}`,()=>this.work(void 0,async()=>{try{const r=Object.values(this.state.sims).find(l=>l.name===n&&l.udid!==a);if(!r){if(this.state.sims[a]){const l=this.state.sims[a];if(l.leaseId)this.dropFromLease(l.leaseId,a);l.leaseId=void 0;await this.deleteSim(a)}await this.cloneSim(o,n)}this.store.result(i.seq,"rebuild",{recovered:true})}finally{this.busy.delete(a)}}))}for(const i of Object.values(this.state.leases)){this.deadlines.set(i.id,this.clock.now()+it);const a=Date.parse(i.createdAt)+i.ttlMs-Date.now();this.hardDeadlines.set(i.id,this.clock.now()+Math.max(a,0));if(a<=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 x.readFile(L.join(s,st),"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 x.mkdir(s,{recursive:true});this.checkActive();await x.writeFile(L.join(s,st),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 a=0;for(const f of this.reservations.values()){i+=f.ramGB;a+=f.diskGB}const n=s.totalMemBytes/de;const o=Li(n)*(s.memPressure==="warn"?2:1);const r=s.availableMemBytes/de-i;const l=n-xi(n,t.reserveRamGB)-this.farmAwakeGB()-i;const c=s.freeDiskBytes/de-a-t.reserveDiskGB;const p=Math.max(0,Math.floor(Math.min(r-o,l,c/t.cloneDiskGB*t.slimSimGB)/t.slimSimGB));const u=(f,S)=>({ok:false,code:f,reason:S,stats:s,roomFor:0});if(s.memPressure==="critical")return u("RAM_LOW","This Mac is low on memory. New sims will wait.");if(e.diskGB>0&&c-e.diskGB<0){return u("DISK_LOW",`Need ${t.reserveDiskGB} GB free after this. This Mac has ${Math.floor(s.freeDiskBytes/de)} GB.`)}if(e.ramGB>0){if(r-e.ramGB<o||l-e.ramGB<0){return u("RAM_LOW",`Not enough free memory for another sim (${Math.max(0,Math.floor(r))} GB free).`)}}const h=this.state.locks["perf-slot"];if(h&&(!this.workContext.getStore()?.active||this.workContext.getStore()?.leaseId!==h.leaseId))return u("HOST_BUSY","A speed test is running. New sims will wait.");return{ok:true,stats:s,roomFor:p}}async withReservation(e,t){const s=$e(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 a=new Set(i.map(r=>r.comm.split("/").pop()));for(const r of["SpringBoard","backboardd"])if(!a.has(r))s.push(`${r} is not running`);const n=ds(await this.host.launchdLogTail(e));if(n)s.push(`${n} 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=L.join(this.store.shotsPath,`${e}.png`);await this.files(()=>x.mkdir(L.dirname(r),{recursive:true}));if(!await this.host.screenshot(e,r,1e4))s.push("screenshot did not come back")}let o=i.length<Oi?"slim":i.length>Ai?"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 I(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:fe(e.seedDir);if(t)throw new d("NO_SEED",t,"Run: pnpm e2e:pool seed");if(!At(L.join(e.appPath,"Info.plist"))){throw new d("BAD_REQUEST",`No app build at ${e.appPath}.`,"Build the app first.")}const s=await fi(e.appPath);const i=`t-${$e(3).toString("hex")}`;const a=e.name??`${tt}Template ${i.slice(2)}`;return this.withReservation({ramGB:this.state.settings.stockSimGB,diskGB:4},async()=>{const n=this.store.intent("create-template",{id:i,name:a});const o=await this.host.create(a,e.deviceType,e.runtime);const r={id:i,udid:o,name:a,bundleId:s,appPath:e.appPath,appHash:await mi(e.appPath),seedDir:e.seedDir??null,seedHash:e.seedDir?await hi(e.seedDir):null,launchUrl:e.launchUrl,deviceType:e.deviceType,runtime:e.runtime,xcodeBuild:await this.host.xcodeBuild(),profile:e.profile,profileHash:Ot(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(n,"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 ${a} 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=ne(e.profile);if(s.length)await this.files(()=>xt(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 a=await this.host.appContainer(e.udid,e.bundleId);if(!a)throw new Error("app installed but has no data container");if(e.seedDir)await this.files(()=>Ft(a,e.bundleId,e.seedDir,this.checkActive));else await this.files(()=>Ae(a,this.checkActive));await this.setPrefs(e.udid,e);if(t){await this.launchApp(e.udid,e,{phone:false});await I(Math.min(15e3,this.pollMs*15));await this.host.terminate(e.udid,e.bundleId)}await this.host.shutdown(e.udid);await this.files(()=>Ae(a,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 a=_=>{const v=this.state.sims[e];if(v)v.phone=_};const n=async _=>{const v=await this.host.spawn(_,["launchctl","getenv","DYLD_INSERT_LIBRARIES"],1e4).catch(()=>null);return v&&v.code===0?v.stdout.trim():""};const o=async _=>{await this.files(()=>Pe(e,s));const v=await et(e,t,void 0,s,n);await this.host.launch(e,t,v);a(_)};if(i.phoneProfile===Xe)return o({status:"off"});const r=ce(s);const l=r[i.phoneProfile]?i.phoneProfile:Kt;const c=r[l];const p=l!==i.phoneProfile?`No phone "${i.phoneProfile}" on this Mac, so it uses ${c.name}. `:"";const u=this.phoneFailed.get(t);if(u!==void 0&&performance.now()-u<Ri){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 h=await this.phoneBuilder.dylib();if(!h){const _=this.phoneBuilder.lastError()||"unknown error";this.log(`phone profile: could not build the library: ${_}`);return o({status:"fallback",phoneId:l,phoneName:c.name,note:`${p}The phone profile could not be built (${_}), so the app runs as a plain simulator app.`})}const f=Re(e,s);await this.files(async()=>{await x.mkdir(L.dirname(f),{recursive:true});await x.writeFile(f,"");await Zt({udid:e,bundleId:t,dylib:h,phoneId:l,vars:Xt(c,{phone:l,onLimit:i.phoneOnLimit,capMB:i.phoneCapMB},f),writtenAt:new Date().toISOString()},s)});const S=await et(e,t,void 0,s,n);await this.host.launch(e,t,S);const b=performance.now()+this.phoneLoadTimeoutMs;let w=null;for(;;){w=await Ne(e,s);if(w?.loaded||performance.now()>=b)break;await I(Math.min(250,Math.max(10,this.pollMs/4)))}if(w?.loaded){this.phoneFailed.delete(t);const _=w.ignored.length?` Ignored bad settings: ${w.ignored.join(", ")}.`:"";a({status:"on",phoneId:l,phoneName:c.name,pid:w.pid,note:(p+_).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(`${tt}${String(s).padStart(2,"0")}`))s++;this.state.nextIndex=s+1;return`${tt}${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 a=this.template(e);return this.withReservation({ramGB:0,diskGB:this.state.settings.cloneDiskGB},()=>this.simLock.run(`template:${a.id}`,async()=>{await this.assertOwned(a.udid);const n=this.store.intent("clone",{templateId:e,name:i});const o=await this.host.clone(a.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(n,"clone",{udid:o});await this.writeMarker(o,{template:a.id});const l=await Oe(await this.dataPath(o),a.bundleId);if(l)await this.files(()=>Ae(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 a=this.state.settings;const n={ramGB:i?.profile==="slim"?a.slimSimGB:a.stockSimGB,diskGB:0};return this.withReservation(n,()=>this.bootGate.use(()=>this.simLock.run(e,async()=>{this.assertLeaseState(s,t);if(s.power==="awake")return s;const o=i?ne(i.profile):[];if(o.length&&!await pi(e,o,this.host.disabledRoot)){await this.files(()=>xt(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:a.stockSimGB-a.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 a=(await this.host.listDevices()).find(r=>r.udid===e);if(!a)throw new d("NOT_FOUND","This sim is gone.");let n=false;try{const r=JSON.parse(await x.readFile(L.join(a.dataPath,st),"utf8"));n=r.farmId===this.state.farmId}catch(r){n=r.code==="ENOENT"&&a.name===s.cloneIntentName}if(!n)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(()=>x.rm(L.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 a=this.store.intent("delete",{udid:e});await this.host.shutdown(e).catch(()=>{});await this.host.delete(e);await this.files(()=>x.rm(L.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(a,"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:a}=s;await this.assertOwned(e);await this.simLock.run(e,async()=>{this.assertLeaseState(s,t);this.busy.add(e)});const n=this.store.intent("rebuild",{udid:e,name:i,templateId:a});try{await this.deleteSim(e,t);const o=await this.cloneSimWork(a,i,t?{udid:e,leaseId:t}:void 0);this.store.result(n,"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 a=await Oe(await this.dataPath(e),i.bundleId);if(!a)throw new Error("app container not found");if(i.seedDir)await this.files(()=>Ft(a,i.bundleId,i.seedDir,this.checkActive));else await this.files(()=>Ae(a,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(n=>n.templateId===e&&!n.leaseId&&s.includes(n.power)&&!this.busy.has(n.udid)).sort((n,o)=>s.indexOf(n.power)-s.indexOf(o.power));const a=[];for(const n of i.slice(0,t)){try{await this.deleteSim(n.udid);a.push(n.name)}catch(o){if(!(o instanceof d))throw o}}return a}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 a=[];for(const o of s){await this.deleteSim(o.udid);a.push(o.name)}const n=(await this.host.listDevices()).some(o=>o.udid===t.udid);if(n){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(()=>x.rm(L.join(this.host.disabledRoot,`com.apple.CoreSimulator.SimDevice.${t.udid}`),{recursive:true,force:true}));this.store.result(o,"delete",{})})}delete this.state.templates[e];a.push(t.name);this.store.event({kind:"delete",message:`Removed template ${t.name} and its ${s.length} sim(s).`});return{removed:a}})}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 a=Date.parse(i.deadlineAt)-Date.now();if(a<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 n={id:`l-${$e(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,a)};i.leases.push(n.id);i.lastActivityAt=n.createdAt;if(e.labels?.length)this.labels.set(n.id,e.labels);this.state.leases[n.id]=n;this.hardDeadlines.set(n.id,this.clock.now()+n.ttlMs);this.acquiring.add(n.id);const o=()=>this.deadlines.set(n.id,this.clock.now()+Math.min(n.ttlMs,it));o();const r=performance.now()+(e.waitMs??0);const l=()=>{if(!this.state.leases[n.id])throw new d("LEASE_EXPIRED","The lease ended while sims were being prepared.");if(this.leaseOverdue(n))throw new d("LEASE_EXPIRED","The lease ran out of time while sims were being prepared.")};try{while(n.sims.length<e.count){l();o();const c=await this.claimOne(n,t);l();if(c)continue;if(performance.now()>=r)break;if(!n.sims.length&&i.state==="active"&&!Object.keys(i.lanes).length)i.state="waiting";await I(Math.max(this.pollMs,2e3))}if(n.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 ${n.sims.length} of ${e.count} sims. ${c.reason??"Others are in use."}`,"Try again later or ask for fewer.",true)}if(n.sims.length===0)throw new d("HOST_BUSY","No sim is free right now.","Try again later.",true);if(e.launch)await this.work(n.id,async()=>{l();await Promise.all(n.sims.map(c=>this.launchApp(c,t)));o();await this.checkIdentities(n,6e4);l()});o();this.store.event({kind:"lease",message:`${e.owner.label} took ${n.sims.length} sim(s) for ${i.goal}.`,leaseId:n.id,runId:i.id});this.note(i,"farm",`Got ${n.sims.length} sim${n.sims.length===1?"":"s"}.`);this.store.save();return{lease:n,run:i,sims:n.sims.map(c=>this.state.sims[c])}}catch(c){if(this.state.leases[n.id])this.note(i,"farm",`Could not get sims: ${c.message}`);await this.endLease(n.id,"acquire failed","fast","acquire-failed").catch(()=>{});throw c}finally{this.acquiring.delete(n.id);this.labels.delete(n.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 a=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 a(i);let n=null;try{if(i){n=await a(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;n=await a(await this.cloneSim(t.id))}if(!n)return null;await this.bootSim(n.udid,e.id);return n}catch(o){if(n)this.unclaim(e,n.udid);if(o instanceof d&&(o.code==="RAM_LOW"||o.code==="DISK_LOW"||o.code==="HOST_BUSY"||o.code==="LEASE_EXPIRED")){return null}if(n&&this.state.sims[n.udid]?.health!=="ok"){const r=n.udid;this.background(`rebuild ${r}`,()=>this.rebuildSim(r))}throw o}}unclaim(e,t){e.sims=e.sims.filter(a=>a!==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 a=new Map;for(;;){for(const o of e.sims){if(a.has(o))continue;const r=await Oe(await this.dataPath(o),s.bundleId);const l=r?await Gt(r):null;if(!l)continue;const c=[...a.entries()].find(([,u])=>u===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(u=>u.udid!==o&&!e.sims.includes(u.udid)&&u.buoyDeviceId===l);if(p)throw new d("ID_CLASH",`${this.state.sims[o].name} and ${p.name} share one Buoy ID.`);a.set(o,l);this.state.sims[o].buoyDeviceId=l}if(a.size===e.sims.length||performance.now()>=i)break;await I(Math.max(this.pollMs,1e3))}const n=e.sims.filter(o=>!a.has(o));if(n.length){this.store.event({kind:"no-id",message:`No Buoy ID yet on ${n.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 a=this.runOfLease(e);if(a&&(a.endedBy==="user"||a.endedBy==="deadline"))this.assertRunOpen(a);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 a=this.overdueEnd(i);this.background(`expire ${i.id}`,()=>this.endLease(i.id,"expired","full",a));if(a==="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 a=Math.min(this.clock.now()+Math.min(i.ttlMs,it),this.hardDeadlines.get(i.id)??Infinity);this.deadlines.set(i.id,a);return{expiresInMs:Math.round(a-this.clock.now())}}async release(e,t,s="fast",i,a=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,a?null:"released")}async endLease(e,t,s,i="released"){const a=this.state.leases[e];if(!a)return{};a.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 n=new Set(a.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 a.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(()=>Pe(r,this.store.homeDir)).catch(()=>void 0)}this.store.event({kind:"lease-end",message:`${a.owner.label}'s ${a.purpose} ended (${t}).`,leaseId:e,runId:a.runId});this.settleRun(a,i);this.store.save();this.background(`reset after ${e}`,()=>this.work(void 0,async()=>{for(const r of a.sims){if(!this.state.sims[r])continue;try{const l=Date.parse(a.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"&&!n.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,a,n){const o=this.liveLease(e,t,n);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,n);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 u=L.join(this.store.shotsPath,`${l}.png`);r[l]=await this.host.screenshot(l,u)?u:null;break}case"open-url":if(!a)throw new d("BAD_REQUEST","open-url needs a url.");await this.host.openUrl(l,a);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(f=>f===l?p.udid:f);const u=o.runId?this.state.runs[o.runId]:void 0;const h=u?.lanes[l];if(u&&h){delete u.lanes[l];u.lanes[p.udid]={...h,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,a){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,a));if(this.state.locks[e]?.leaseId===t)return{held:true};const n=this.lockQueues.get(e)??[];this.lockQueues.set(e,n);const o={};n.push(o);const r=performance.now()+i;try{for(;;){this.store.assertActive();this.liveLease(t,s,a);const l=this.state.locks[e];const c=e==="perf-slot"&&(this.activeWork>0||this.busy.size>0||this.pendingBg>0);if(n[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 I(Math.max(1,Math.min(this.pollMs,r-performance.now())))}}finally{n.splice(n.indexOf(o),1);if(!n.length)this.lockQueues.delete(e)}}fairness(e,t,s,i){this.liveLease(e,t,i);const a=this.state.settings;const n=Ci(a,this.meter.cpuCount);const o=this.meter.verdicts(e,s,n);return{rules:n,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>=Di)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=L.join(this.store.shotsPath,`${e}.png`);await this.files(()=>x.mkdir(L.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 C(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>ns)for(const s of t.slice(0,t.length-ns))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 I(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 a=`${e}:${t}`;const n=ni("sha256").update(JSON.stringify(s)).digest("hex").slice(0,16);const o=this.state.requests[a];if(o){if(o.hash!==n)throw new d("REQUEST_REUSED",`Request ${t} was already used for a different call.`);return o.result}const r=this.inflight.get(a);if(r){if(r.hash!==n)throw new d("REQUEST_REUSED",`Request ${t} was already used for a different call.`);return r.promise}const l=i();this.inflight.set(a,{hash:n,promise:l});try{const c=await l;this.state.requests[a]={hash:n,result:c,at:new Date().toISOString()};this.store.save();return c}finally{this.inflight.delete(a)}}newRun(e,t,s){const i=Date.now();const a=e.owner.agent?this.state.settings.runCapMinutes*6e4:24*36e5;const n=(e.goal??"").trim()||e.purpose;const o={id:`r-${$e(4).toString("hex")}`,goal:n.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,a)).toISOString(),capAt:new Date(i+a).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(Q.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 x.rm(we(e,this.store.homeDir),{force:true});await x.rm(Re(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||Q.includes(s.state))continue;const i=await Ne(e.udid,this.store.homeDir);if(!i?.overLimit||!i.pid||e.phone.notedPid===i.pid)continue;e.phone.notedPid=i.pid;const a=s.lanes[e.udid]?.label??e.name;const n=e.phone.phoneName??"the phone";this.note(s,"farm",i.ended==="safety"?`${a}: the app used ${i.peakMB} MB and hit the farm's safety cap, so it was closed. ${n} would have closed it sooner.`:i.ended==="limit"?`${a}: the app went past ${n}'s memory limit (${i.peakMB} MB) and was closed, like on a real phone.`:`${a}: the app went past ${n}'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>os)e.notes.splice(0,e.notes.length-os)}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 a of e.sims)if(s.lanes[a])s.lanes[a].gone=true;if(Q.includes(s.state)||s.state==="stopping"||t===null)return;const i=s.leases.some(a=>this.state.leases[a]);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,a="full"){if(Q.includes(e.state))return;e.state="stopping";e.endedBy=s;if(i)this.note(e,s==="user"?"person":"farm",i);for(const n of e.leases){if(this.state.leases[n])void this.endLease(n,i??s,s==="finished"||s==="released"?a:"full",null)}for(const n of Object.values(e.lanes))n.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(a=>a.state==="passed").length;const i=t.filter(a=>a.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&&!rs.includes(e.state))throw new d("BAD_REQUEST",`state must be one of ${rs.join(", ")}.`);if(e.udid!==void 0){const a=s.lanes[e.udid];if(!a)throw new d("NOT_FOUND",`That sim is not in run ${s.id}.`,"Use a UDID from this run's sims.");if(e.state)a.state=e.state;if(e.state==="passed"||e.state==="failed")a.resultSource=e.resultSource==="test"?"test":"agent";if(e.note!==void 0)a.note=String(e.note).slice(0,200);a.at=i}if(e.counts!==void 0){const a=e.counts;const n=o=>o===void 0||Number.isInteger(o)&&o>=0;if(!a||typeof a!=="object"||!n(a.done)||!n(a.total)||!n(a.passed)||!n(a.failed)||a.done>a.total){throw new d("BAD_REQUEST","counts needs whole numbers, with done no more than total.")}s.counts={done:a.done,total:a.total,passed:a.passed,failed:a.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 a=Date.parse(i.deadlineAt);const n=Date.now()+t*6e4;const o=Math.min(n,Date.parse(i.capAt));if(o<=a){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<n,...this.timeLeft(i)}}finish(e,t,s,i){const a=this.state.runs[e];if(a?.endedBy==="finished"&&a.owner.clientId===i)return{state:a.state,outcome:a.outcome};const n=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.");n.outcome=t??this.outcomeOf(n);if(s)n.summary=s.slice(0,600);this.endRun(n,n.outcome==="failed"?"failed":"done","finished",void 0,"fast");this.store.save();return{state:n.state,outcome:n.outcome}}stopRun(e,t="you"){const s=this.state.runs[e];if(!s)throw new d("NOT_FOUND",`No run ${e}.`);if(Q.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=>!Q.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 a of Object.values(this.state.runs)){if(Q.includes(a.state))continue;if(e>=Date.parse(a.deadlineAt)){this.endRun(a,"stopped","deadline","Ran out of time. The sims were taken back.");this.store.save()}else if(!a.leases.some(n=>this.state.leases[n])&&!await C(a.owner.pid,a.owner.pidStart,true)){this.endRun(a,"interrupted","owner-exited","The chat closed.");this.store.save()}}const t=this.state.settings.keepRunsHours*36e5;const s=Object.values(this.state.runs).filter(a=>Q.includes(a.state)).sort((a,n)=>Date.parse(n.endedAt??n.createdAt)-Date.parse(a.endedAt??a.createdAt));let i=false;s.forEach((a,n)=>{if(n>=200||e-Date.parse(a.endedAt??a.createdAt)>t){delete this.state.runs[a.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 a=>{const n=a.leaseId?this.state.leases[a.leaseId]:void 0;const o=n?.runId?this.state.runs[n.runId]:void 0;const r=a.phone?.status==="on"?await Ne(a.udid,this.store.homeDir):null;const l=a.phone&&{...a.phone,notedPid:void 0,...r?.loaded?{pid:r.pid,peakMB:r.peakMB,memoryWarnings:r.memoryWarnings,overLimit:r.overLimit,ended:r.ended}:{}};return{...a,phone:l,owner:n?.owner.label,purpose:o?.goal??n?.purpose,runId:o?.id,lane:o?.lanes[a.udid]?.label,busy:this.busy.has(a.udid)}}));const i={farmId:this.state.farmId,counts:{pool:s.length,awake:s.filter(a=>a.power==="awake").length,leased:s.filter(a=>a.leaseId).length},budget:{roomForMoreSims:t.roomFor,freeDiskGB:Math.floor(t.stats.freeDiskBytes/de),availableMemGB:Math.floor(t.stats.availableMemBytes/de),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(a=>({...a,expiresInMs:Math.max(0,Math.round(this.leaseDeadline(a)-this.clock.now()))})),runs:Object.values(this.state.runs).sort((a,n)=>Date.parse(n.createdAt)-Date.parse(a.createdAt)).map(a=>({...a,notes:a.notes.slice(-50),secondsLeft:Q.includes(a.state)?0:Math.max(0,Math.round((Date.parse(a.deadlineAt)-Date.now())/1e3))})),locks:Object.values(this.state.locks),recentEvents:this.state.events.slice(-25),settings:this.state.settings};if(e.outside){const a=new Set([...Object.keys(this.state.sims),...Object.keys(this.state.orphans),...Object.values(this.state.templates).map(n=>n.udid)]);i.outsideSims=(await this.host.listDevices()).filter(n=>!a.has(n.udid)&&n.available).map(n=>({udid:n.udid,name:n.name,state:n.state,runtime:n.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 a=ce(this.store.homeDir);if(e.phoneProfile!==Xe&&!(typeof e.phoneProfile==="string"&&a[e.phoneProfile])){throw new d("BAD_REQUEST",`phoneProfile must be "off" or one of: ${Object.keys(a).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[a,n]of Object.entries(e)){if(!(a in t)||typeof n!==typeof t[a])throw new d("BAD_REQUEST",`Bad setting ${a}.`);const o=s[a];if(o&&(typeof n!=="number"||!Number.isFinite(n)||n<o[0]||n>o[1])){throw new d("BAD_REQUEST",`${a} must be ${o[0]} to ${o[1]}.`)}}const i=["phoneProfile","phoneOnLimit","phoneCapMB"].some(a=>a in e&&e[a]!==t[a]);for(const[a,n]of Object.entries(e))t[a]=n;this.store.save();if(i){for(const a of Object.keys(this.state.sims))void Pe(a,this.store.homeDir).catch(()=>void 0)}return t}};function xi(e,t){return Math.min(t,Math.max(4,Math.round(e*.375)))}function Li(e){return Math.min(4,Math.max(1.5,e*.1))}function Ci(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 ds(e,t=Date.now()-3*6e4){const s=new Map;for(const i of e.split("\n")){const a=/^(\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(!a||a[3]==="SIGKILL"||a[3]==="SIGTERM")continue;const n=Date.parse(a[1].replace(" ","T"));if(!(n>=t))continue;const o=s.get(a[2])??[];o.push(n);s.set(a[2],o)}for(const[i,a]of s){a.sort((n,o)=>n-o);for(let n=2;n<a.length;n++)if(a[n]-a[n-2]<=6e4)return i.replace(/^com\.apple\./,"")}return null}import{promises as ps}from"fs";import pe from"os";import ue from"path";var us=6e4;var at=class{constructor(){this.disabledRoot=le;this.devicesDir=ue.join(pe.homedir(),"Library/Developer/CoreSimulator/Devices");this.graphicsPids=[];this.loadCalls=0}simctl(e,t=us){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 a of i){t.push({udid:a.udid,name:a.name,state:a.state,runtime:s,deviceType:a.deviceTypeIdentifier,dataPath:a.dataPath??ue.join(this.devicesDir,a.udid,"data"),available:a.isAvailable!==false})}}return t}async dataPathOf(e){if(!/^[0-9A-F-]{36}$/i.test(e))return null;const t=ue.join(this.devicesDir,e);try{await ps.access(ue.join(t,"device.plist"));return ue.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:us,env:Qe()});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 Dt();const s=t.find(i=>/launchd_sim/.test(i.command)&&i.command.includes(e));return s?Tt(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=ue.join(this.disabledRoot,`com.apple.CoreSimulator.SimDevice.${e}`,"launchd.log");try{const i=await ps.open(s,"r");try{const{size:a}=await i.stat();const n=Math.max(0,a-t);const o=Buffer.alloc(a-n);await i.read(o,0,o.length,n);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",pe.homedir()],{timeoutMs:1e4})]);const a=Number(/page size of (\d+)/.exec(e)?.[1]??16384);const n=u=>Number(new RegExp(`${u}:\\s+(\\d+)`).exec(e)?.[1]??0);const o=n("Pages free")+n("Pages inactive")+n("Pages speculative")+n("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:pe.totalmem(),availableMemBytes:o*a,memPressure:r>=4?"critical":r>=2?"warn":"normal",swapUsedBytes:l?Number(l)*1024*1024:0,freeDiskBytes:p*1024,cpuCount:pe.cpus().length,loadAvg1:pe.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 b=await M("pgrep",["-x","SimMetalHost"],{timeoutMs:5e3});this.graphicsPids=b.stdout.split("\n").map(Number).filter(w=>w>0)}const s=pe.cpus();let i=0;let a=0;for(const b of s){const w=b.times;const _=w.user+w.nice+w.sys+w.idle+w.irq;a+=_;i+=_-w.idle}const n=[...e,...this.graphicsPids];const[o,r,l,c]=await Promise.all([t&&n.length?M("ps",["-o","pid=,time=","-p",n.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 u=0;let h=0;for(const b of o?.stdout.split("\n")??[]){const w=/^\s*(\d+)\s+(\S+)/.exec(b);if(!w)continue;const _=zt(w[2]);if(p.has(Number(w[1])))h+=_;else u+=_}const f=r&&/"Device Utilization %"=(\d+)/.exec(r.stdout);const S=/thermalpressurelevel\s+(\d+)/.exec(c.stdout);return{hostBusyMs:i,hostTotalMs:a,cpuCount:s.length,pidsCpuMs:t?u:null,graphicsCpuMs:t?h:null,gpuPct:f?Number(f[1]):null,memPressureLevel:Number(l.stdout.trim().split("\n")[0])||1,swapUsedMB:Number(/used = ([\d.]+)M/.exec(l.stdout)?.[1]??0),thermalLevel:S?Number(S[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 Dt();const s=new Set((await this.simTree(e)).map(a=>a.pid));const i=new Set(Tt(t,process.pid).map(a=>a.pid));return t.filter(a=>!i.has(a.pid)&&!s.has(a.pid)&&a.command.includes(e)&&!/launchd_sim|CoreSimulator/.test(a.command))}async kill(e,t){if(!await C(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 C(e,t))return}if(await C(e,t)){try{process.kill(e,"SIGKILL")}catch{}}}};import ji from"net";import{chmodSync as Ui,rmSync as Fi,appendFileSync as hs,mkdirSync as Gi}from"fs";import{timingSafeEqual as Wi}from"crypto";import{promises as Hi,existsSync as nt,mkdirSync as ot,readFileSync as ee,renameSync as rt,writeFileSync as xe,rmSync as ge,openSync as zi,fsyncSync as qi,closeSync as Ki,chmodSync as Yi,readdirSync as Qi,statSync as ms}from"fs";import Vi from"os";import R from"path";import{createHash as Ji,randomBytes as ye}from"crypto";function H(){return process.env.BUOY_FARM_HOME||R.join(Vi.homedir(),".buoy","farm")}var z=(e=H())=>({home:e,lock:R.join(e,"owner.lock"),lockOwner:R.join(e,"owner.lock","owner.json"),socket:R.join(e,"farmd.sock"),token:R.join(e,"token"),state:R.join(e,"state.json"),journal:R.join(e,"journal.ndjson"),log:R.join(e,"farmd.log"),shots:R.join(e,"shots")});function lt(e=H()){ot(e,{recursive:true,mode:448});try{Yi(e,448)}catch{}}function fs(e=H()){const t=z(e).token;try{const s=ee(t,"utf8").trim();if(s)return s}catch{}lt(e);try{xe(t,ye(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=ee(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 ve(e=H()){try{return JSON.parse(await Hi.readFile(z(e).lockOwner,"utf8"))}catch{return null}}async function Se(e){return!!e&&await C(e.pid,e.start,true)}async function Xi(e,t){const s=R.join(e,"owner.claim");for(let i=0;i<20;i++){try{ot(s,{mode:448});xe(R.join(s,"pid"),`${process.pid}
|
|
364
|
-
${await re(process.pid)??""}`);try{return await t()}finally{ge(s,{recursive:true,force:true})}}catch(a){if(a.code!=="EEXIST")throw a;const n=ms(s,{throwIfNoEntry:false});if(n&&Date.now()-n.mtimeMs>3e4){let o=true;try{const[r,l]=ee(R.join(s,"pid"),"utf8").split("\n");o=!await C(Number(r),l||void 0)}catch{}if(o){try{rt(s,R.join(e,`owner.claim-dead-${ye(4).toString("hex")}`))}catch{}}}await new Promise(o=>setTimeout(o,100))}}return null}async function Zi(e,t,s=H()){lt(s);const i=z(s);const a=await re(process.pid)??"";for(let n=0;n<3;n++){try{ot(i.lock,{mode:448})}catch(r){if(r.code!=="EEXIST")throw r;const l=await ve(s);if(l&&await Se(l))return null;if(!l){await new Promise(u=>setTimeout(u,300));const p=await ve(s);if(p&&await Se(p))return null}const c=await Xi(s,async()=>{const p=await ve(s);if(p&&await Se(p))return false;if(!nt(i.lock))return true;rt(i.lock,R.join(s,`owner.stale-${ye(4).toString("hex")}`));return true});if(c===false)return null;continue}const o={pid:process.pid,start:a,version:e,host:t,since:new Date().toISOString()};xe(i.lockOwner,JSON.stringify(o),{mode:384});ea(s);return{info:o,release(){try{const r=JSON.parse(ee(i.lockOwner,"utf8"));if(r.pid!==process.pid)return}catch{return}try{ge(i.socket,{force:true})}catch{}ge(i.lock,{recursive:true,force:true})}}}return null}function ea(e){try{for(const t of Qi(e)){if(t.startsWith("owner.stale-")||t.startsWith("owner.claim-dead-"))ge(R.join(e,t),{recursive:true,force:true})}}catch{}}function ws(){return{version:Ie,seq:0,farmId:ye(6).toString("hex"),nextIndex:1,templates:{},sims:{},orphans:{},leases:{},runs:{},locks:{},requests:{},events:[],settings:{...qe}}}var gs=e=>Ji("sha256").update(JSON.stringify(e)).digest("hex").slice(0,12);function ys(e,t,s){const i=zi(e,s,384);try{xe(i,t);qi(i)}finally{Ki(i)}}var vs=class{constructor(e=H()){this.fenced=false;this.pending=[];this.open=new Map;this.p=z(e);lt(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=ws();if(nt(this.p.state)){const a=JSON.parse(ee(this.p.state,"utf8"));if(a.version>Ie){throw new Error(`farm state is version ${a.version}; this farmd understands ${Ie}. Update Buoy.`)}e={...ws(),...a,settings:{...qe,...a.settings}}}delete e.settings.activeSlots;const t=new Map;const s=new Set;let i=e.seq;if(nt(this.p.journal)){for(const a of ee(this.p.journal,"utf8").split("\n")){if(!a.trim())continue;let n;try{n=JSON.parse(a)}catch{continue}const{sum:o,...r}=n;if(gs(r)!==o||n.seq<=e.seq)continue;i=Math.max(i,n.seq);if(n.type==="intent")t.set(n.seq,n);else{t.delete(n.seq);s.add(n.seq)}}}for(const a of e.openIntents??[]){if(!s.has(a.seq)&&!t.has(a.seq))t.set(a.seq,{...a,type:"intent",sum:""})}this.pending=[...t.values()].sort((a,n)=>a.seq-n.seq);for(const a of this.pending)this.open.set(a.seq,a);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();ys(this.p.journal,JSON.stringify({...e,sum:gs(e)})+"\n","a")}save(){this.assertActive();const e=`${this.p.state}.${ye(4).toString("hex")}.tmp`;this.state.openIntents=[...this.open.values()].map(({seq:t,at:s,op:i,data:a})=>({seq:t,at:s,op:i,data:a}));ys(e,JSON.stringify(this.state,null,1),"w");rt(e,this.p.state);try{if(ms(this.p.journal).size>2*1024*1024)ge(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 ta(e=H()){try{const t=JSON.parse(ee(z(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 Ss=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 ks(e={}){const t=e.home??H();const s=z(t);if(Buffer.byteLength(s.socket)>103){const n=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{Gi(t,{recursive:true});hs(s.log,`${new Date().toISOString()} ${n.message} ${n.next}
|
|
365
|
-
`)}catch{}throw n}const i=await Zi(K,e.hostLabel??"node",t);if(!i)return null;const a=n=>{try{hs(s.log,`${new Date().toISOString()} ${n}
|
|
366
|
-
`)}catch{}e.log?.(n)};try{return await sa(e,t,i,a)}catch(n){i.release();throw n}}async function sa(e,t,s,i){const a=z(t);const n=fs(t);const o=new vs(t);const r=new cs({host:e.host??new at,store:o,log:i,pollMs:e.pollMs,readyTimeoutMs:e.readyTimeoutMs,phoneBuilder:e.phoneBuilder});await r.recover();Fi(a.socket,{force:true});const l=new Set;let c=Date.now();let p=false;let u=0;const h=ji.createServer(k=>{l.add(k);k.on("close",()=>l.delete(k));k.on("error",()=>{});let m="";k.on("data",g=>{m+=g.toString("utf8");if(m.length>1024*1024)return k.destroy();let y;while((y=m.indexOf("\n"))>=0){const B=m.slice(0,y);m=m.slice(y+1);if(B.trim())void S(k,B)}})});const f=(k,m,g)=>{if(!k.destroyed)k.write(JSON.stringify({id:m,...g})+"\n")};async function S(k,m){c=Date.now();let g;try{g=JSON.parse(m)}catch{return f(k,-1,{ok:false,error:{code:"BAD_REQUEST",message:"Not JSON."}})}u++;try{if(!g||typeof g!=="object")throw new d("BAD_REQUEST","Use a request object.");if(!ia(g.token,n))throw new d("UNAUTHORIZED","Bad farm token.");if(!g.client||typeof g.client.clientId!=="string"||!g.client.clientId.trim())throw new d("BAD_REQUEST","Each call needs a clientId.");if(p&&!["hello","status"].includes(g.method)){throw new d("HOST_BUSY","The farm is stopping.","Try again in a few seconds.",true)}if(g.v>K&&Ss.has(g.method)){throw new d("FARMD_VERSION",`This farm runs protocol ${K}; the client speaks ${g.v}.`,"Ask it to stop when idle (method shutdown), then start a newer farm.")}if(g.v<K&&Ss.has(g.method)){throw new d("READ_ONLY",`This client speaks farm protocol ${g.v}; the farm runs ${K}.`,"Update Buoy to change the farm.")}aa(g);const y=await b(g);f(k,g.id,{ok:true,result:y})}catch(y){const B=y instanceof d?y.toJSON():{code:"HOST_ERROR",message:y.message,retryable:false};f(k,g?.id??-1,{ok:false,error:B})}finally{u--}}async function b(k){const m=k.params??{};const g=k.client;const y=B=>r.once(g.clientId,k.requestId,{m:k.method,q:m},B);switch(k.method){case"hello":return{protocol:K,pid:process.pid,host:s.info.host,farmId:r.state.farmId};case"status":return r.status({outside:m.outside});case"budget":return r.budget({ramGB:m.ramGB??0,diskGB:m.diskGB??0});case"setup":return y(()=>r.createTemplate(m));case"grow":return y(async()=>(await r.grow(m.templateId,m.count)).map(B=>B.name));case"shrink":return y(()=>r.shrink(m.templateId,m.count));case"removeTemplate":return y(()=>r.removeTemplate(m.templateId));case"acquire":return y(async()=>{const{lease:B,run:G,sims:ze}=await r.acquire({...m,owner:g});return{runId:G.id,leaseId:B.id,epoch:B.epoch,deadlineAt:G.deadlineAt,capAt:G.capAt,sims:ze.map(Ee=>({udid:Ee.udid,name:Ee.name,buoyDeviceId:Ee.buoyDeviceId,profile:Ee.profile}))}});case"renew":return r.renew(m.leaseId,m.epoch,g.clientId);case"release":return y(()=>r.release(m.leaseId,m.epoch,m.reset,g.clientId,m.keepRun===true));case"action":return y(()=>r.action(m.leaseId,m.epoch,m.udids,m.action,m.arg,g.clientId));case"lock":return r.lock(m.name,m.leaseId,m.epoch,m.waitMs??0,g.clientId);case"unlock":return r.unlock(m.name,m.leaseId,m.epoch,g.clientId);case"fairness":return r.fairness(m.leaseId,m.epoch,m.windows,g.clientId);case"park":return y(async()=>(await r.parkSim(m.udid,"asked"),"parked"));case"wake":return y(async()=>(await r.bootSim(m.udid)).power);case"reset":return y(async()=>(await r.fastReset(m.udid),"reset"));case"rebuild":return y(async()=>(await r.rebuildSim(m.udid)).udid);case"delete":return y(async()=>(await r.deleteSim(m.udid),"deleted"));case"endLease":{const B=r.state.leases[m.leaseId];if(!B)return{};if(B.owner.clientId!==g.clientId&&m.force!==true){throw new d("NOT_OWNED",`Lease ${m.leaseId} belongs to ${B.owner.label}.`,"Pass force: true only after a person confirms.")}return y(()=>r.endLease(m.leaseId,`ended by ${g.label}`,"full",B.owner.clientId===g.clientId?"released":"user"))}case"report":return y(async()=>r.report(m,g.clientId));case"extend":return y(async()=>r.extend(m.runId,m.minutes,g.clientId));case"finish":return y(async()=>r.finish(m.runId,m.outcome,m.summary,g.clientId));case"stopRun":{const B=r.state.runs[m.runId];if(B&&B.owner.clientId!==g.clientId&&m.force!==true){throw new d("NOT_OWNED",`Run ${m.runId} belongs to ${B.owner.label}.`,"Pass force: true only after a person confirms.")}return y(async()=>r.stopRun(m.runId))}case"stopAll":if(m.force!==true)throw new d("BAD_REQUEST","stopAll needs force: true, after a person confirms.");return y(async()=>r.stopAll());case"settings":return r.setSettings(m);case"shot":return r.shot(m.udid);case"show":return r.show(m.udid);case"shutdown":if(m.ifIdle!==false&&(!r.idle()||u>1))return{stopping:false,reason:"busy"};void A("asked to stop");return{stopping:true};default:throw new d("BAD_REQUEST",`Unknown method ${k.method}.`)}}await new Promise((k,m)=>{h.once("error",m);h.listen(a.socket,()=>k())});Ui(a.socket,384);i(`farmd ${K} up, pid ${process.pid}, host ${e.hostLabel??"node"}`);const w=setInterval(()=>{void r.tick().catch(m=>i(`tick: ${m.message}`));const k=Date.now()-c;if(e.idleExitMs&&l.size===0&&k>e.idleExitMs){void(async()=>{await r.parkAllIdle();if(r.idle()&&l.size===0&&u===0&&Date.now()-c>e.idleExitMs)await A("idle")})()}},e.tickMs??5e3);w.unref?.();const _=setInterval(()=>void r.meter.tick().catch(k=>i(`meter: ${k.message}`)),1e3);_.unref?.();let v=null;function A(k,m=10*6e4){if(!v)v=ae(k,m);return v}async function ae(k,m){if(p)return;p=true;clearInterval(w);clearInterval(_);i(`farmd stopping: ${k}`);const g=Date.now()+m;while(u>0&&Date.now()<g)await new Promise(G=>setTimeout(G,200));const y=await r.drain(Math.max(0,g-Date.now()));let B=false;if(u>0||!y||Ye()>0){o.save();r.fence();B=true;i(`farmd stopping with ${u} call(s) and ${Ye()} child process(es) still running; killing them`);li();const G=Date.now()+5e3;while(Ye()>0&&Date.now()<G)await new Promise(ze=>setTimeout(ze,100))}await r.settleFiles();if(!B&&u===0){try{await r.parkAllIdle()}catch{}}for(const G of l)G.destroy();await new Promise(G=>h.close(()=>G()));if(!B){o.save();r.fence()}s.release();e.onExit?.(k)}return{engine:r,owner:s,stop:A}}function ia(e,t){if(typeof e!=="string"||e.length!==t.length)return false;return Wi(Buffer.from(e),Buffer.from(t))}function aa(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 a=o=>{if(s[o]!==void 0&&typeof s[o]!=="boolean")t(`${o} must be true or false.`)};const n=(o,r,l,c=false,p=false)=>{const u=s[o];if(p&&u===void 0)return;if(typeof u!=="number"||!Number.isFinite(u)||u<r||u>l||c&&!Number.isInteger(u))t(`${o} must be a number from ${r} to ${l}.`)};switch(e.method){case"status":a("outside");break;case"budget":n("ramGB",0,Number.MAX_VALUE,false,true);n("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);a("warmLaunch");if(!["slim","stock"].includes(s.profile))t("Use slim or stock.");n("metroPort",1,65535,true);break;case"removeTemplate":i("templateId");break;case"grow":case"shrink":case"acquire":i("templateId");n("count",1,64,true);if(e.method==="acquire"){i("purpose");n("ttlMs",1,Number.MAX_VALUE,false,true);n("waitMs",0,Number.MAX_SAFE_INTEGER,false,true);a("launch");a("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.");n("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);n("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");n("minutes",1,24*60);break;case"finish":i("runId");i("summary",true);i("outcome",true);break;case"stopRun":i("runId");a("force");break;case"stopAll":a("force");break;case"shutdown":a("ifIdle");break}if(["renew","release","action","lock","unlock","fairness"].includes(e.method))i("leaseId")}import na from"net";import{existsSync as oa}from"fs";import{spawn as ra}from"child_process";import{randomBytes as bs}from"crypto";function Ms(e,t=["farmd"]){return()=>{const s=ra(process.execPath,[...process.execArgv,e,...t],{detached:true,stdio:"ignore",env:Qe()});s.unref()}}var _s=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??H();this.clientIdValue=`c-${bs(5).toString("hex")}`}get clientId(){return this.owner?.clientId}async connect(){this.token=fs(this.home);this.owner={clientId:this.clientIdValue,pid:process.pid,pidStart:await re(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 ve(this.home);if(!await Se(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 I(250);if(await this.tryOpen())return this.checkVersion()}throw new d("HOST_ERROR","The farm did not start in time.",`Check ${z(this.home).log}.`)}async checkVersion(){const e=await this.send("hello",void 0,{});if(e.protocol<K&&this.opts.launcher){const t=await this.send("shutdown",{ifIdle:true},{});if(t.stopping){this.close();await I(500);return this.connect()}}return this}tryOpen(){const e=z(this.home).socket;if(!oa(e))return Promise.resolve(false);return new Promise(t=>{const s=na.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 a=this.pending.get(i.id);if(!a)continue;this.pending.delete(i.id);clearTimeout(a.timer);if(i.ok)a.resolve(i.result);else{const n=i.error??{};a.reject(new d(n.code??"HOST_ERROR",n.message??"farm error",n.next,n.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 a={id:i,v:K,token:this.token,client:this.owner,method:e,params:t,requestId:s.requestId};return new Promise((n,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:n,reject:o,timer:r});this.sock.write(JSON.stringify(a)+"\n")})}async acquire(e){const{requestId:t,...s}=e;const i=t??`acq-${bs(4).toString("hex")}`;const a=await this.call("acquire",s,{timeoutMs:15*6e4+(e.waitMs??0),requestId:i});if(this.renewals.has(a.leaseId))return a;const n=setInterval(()=>{this.call("renew",{leaseId:a.leaseId,epoch:a.epoch}).catch(o=>{if(["LEASE_EXPIRED","STALE_EPOCH","RUN_STOPPED","RUN_ENDED"].includes(o.code))this.stopRenew(a.leaseId)})},15e3);n.unref?.();this.renewals.set(a.leaseId,n);return a}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 Bs(e){return new _s(e).connect()}import ke from"path";import la from"os";import{existsSync as ct,readdirSync as ca,statSync as da}from"fs";function be(e=process.cwd()){let t=e;for(;;){if(ct(ke.join(t,"buoy.tools.json")))return t;const s=ke.dirname(t);if(s===t)return null;t=s}}function Le(){const e=ke.join(la.homedir(),"Library/Developer/Xcode/DerivedData");let t=null;try{for(const s of ca(e)){if(!s.startsWith("exampledevbuild-"))continue;const i=ke.join(e,s,"Build/Products/Debug-iphonesimulator/exampledevbuild.app");if(!ct(i))continue;const a=da(i).mtimeMs;if(!t||a>t.t)t={p:i,t:a}}}catch{}return t?.p??null}function Es(e=be()){return e?ke.join(e,"example-dev-build/artifacts/pool-seed"):null}async function pa(e=be()){const t=Es(e);let s=[];let i=[];try{const a=JSON.parse(await P("xcrun",["simctl","list","runtimes","--json"],{timeoutMs:3e4}));s=(a.runtimes??[]).filter(o=>o.isAvailable!==false&&/^iOS/.test(o.name??"")).map(o=>({id:o.identifier,name:o.name}));const n=JSON.parse(await P("xcrun",["simctl","list","devicetypes","--json"],{timeoutMs:3e4}));i=(n.devicetypes??[]).filter(o=>/iPhone|iPad/.test(o.name??"")).map(o=>({id:o.identifier,name:o.name}))}catch{}return{appPath:Le(),seedDir:t&&ct(t)?t:null,seedProblem:t?fe(t):"Could not find the repo's seed folder.",runtimes:s,deviceTypes:i,slimTurnsOff:he.map(a=>({name:a.name,downside:a.downside}))}}import ua from"path";var Is=[{app:"claude",name:"Claude",match:/(^|\/)claude$/i},{app:"codex",name:"Codex",match:/(^|\/)codex$/i},{app:"cursor",name:"Cursor",match:/cursor/i}];async function ha(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 ma(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 fa(e){if(!e)return void 0;return Is.find(t=>e.toLowerCase().includes(t.app))}async function wa(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 u=await ha(s).catch(()=>null);if(!u)break;const h=Is.find(f=>f.match.test(u.comm));if(p>0&&h){i={app:h,pid:s};break}s=u.ppid}const a=i?.app??fa(e.clientName);const n=(i?await ma(i.pid).catch(()=>null):null)??process.cwd();const o=(await M("git",["-C",n,"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&&(a?.app??"claude")==="claude"){l=`claude:${r}`;c="claude-session"}else if(i){l=`${i.app.app}:${i.pid}:${await re(i.pid)??""}`;c="parent-process"}return{app:a?.app??"other",appName:a?.name??(e.clientName||"Agent"),chatKey:l,chatKeySource:c,project:ua.basename(n)||void 0,projectPath:n,branch:o&&o!=="HEAD"?o:void 0,clientName:e.clientName}}function ga(e){return e.project?`${e.appName} \xB7 ${e.project}`:e.appName}import $s from"path";import{existsSync as ya}from"fs";import va from"os";import{execFile as Sa,spawn as ka}from"child_process";import{createHash as ba}from"crypto";import{promises as q}from"fs";import Ce from"os";import F from"path";import{promisify as Ma}from"util";var te=Ma(Sa);var je="gg.buoy.phoneprobe";var Ue=1024*1024;function _a(e){const t=e.match(/BUOY_PROBE physicalMemory=(\d+) cpus=(\d+) footprint=(\d+) available=(\d+)/);if(!t)return null;const[s,i,a,n]=t.slice(1).map(Number);const o=a+n;if(!s||!i||n<=0||o>s)return null;return{ramMB:Math.floor(s/Ue),cpus:i,limitMB:Math.floor(o/Ue)}}function Os(e,t){return e.match(new RegExp(`<key>${t}</key>\\s*<string>([^<]*)</string>`))?.[1]}function dt(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(a=>a[1].replace(/\s+/g,""))}function Ba(e,t){const s=t.match(/<key>Entitlements<\/key>\s*<dict>([\s\S]*?)<\/dict>/)?.[1]??"";const i=Os(s,"application-identifier");const a=dt(t,"TeamIdentifier","string")[0];const n=t.match(/<key>ExpirationDate<\/key>\s*<date>([^<]+)<\/date>/)?.[1];if(!i||!a||!n)return null;return{file:e,name:Os(t,"Name")??F.basename(e),team:a,appId:i,expires:new Date(n),devices:dt(t,"ProvisionedDevices","string"),allDevices:/<key>ProvisionsAllDevices<\/key>\s*<true\/>/.test(t),getTaskAllow:/<key>get-task-allow<\/key>\s*<true\/>/.test(s),certSha1s:dt(t,"DeveloperCertificates","data").map(o=>ba("sha1").update(Buffer.from(o,"base64")).digest("hex").toUpperCase())}}function Ea(e,t,s,i=new Date){const a=e.filter(o=>o.getTaskAllow&&o.expires>i&&(o.allDevices||o.devices.includes(t))&&(o.appId===`${o.team}.*`||o.appId===`${o.team}.${je}`)&&o.certSha1s.some(r=>s.has(r)));a.sort((o,r)=>Number(r.appId.endsWith(".*"))-Number(o.appId.endsWith(".*"))||r.expires.getTime()-o.expires.getTime());const n=a[0];return n?{profile:n,identity:n.certSha1s.find(o=>s.has(o))}:null}async function Ia(){const e=[F.join(Ce.homedir(),"Library/Developer/Xcode/UserData/Provisioning Profiles"),F.join(Ce.homedir(),"Library/MobileDevice/Provisioning Profiles")];const t=[];for(const s of e){let i=[];try{i=(await q.readdir(s)).filter(a=>a.endsWith(".mobileprovision"))}catch{continue}for(const a of i){const n=F.join(s,a);try{const{stdout:o}=await te("security",["cms","-D","-i",n],{timeout:15e3,maxBuffer:16*Ue});const r=Ba(n,o);if(r)t.push(r)}catch{}}}return t}async function $a(){const{stdout:e}=await te("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 Oa(){const e=await q.mkdtemp(F.join(Ce.tmpdir(),"buoy-phones-"));try{const t=F.join(e,"devices.json");await te("xcrun",["devicectl","list","devices","--json-output",t],{timeout:3e4});const s=JSON.parse(await q.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 q.rm(e,{recursive:true,force:true}).catch(()=>void 0)}}function Aa(e,t,s){const i=Object.keys(e).find(n=>e[n].productType===t);if(i)return i;const a=n=>n.toLowerCase().replace(/[()]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");return`${a(s)}-${a(t)}`.slice(0,64).replace(/-$/,"")}async function Da(e,t,s,i){const a=F.join(e,"PhoneProbe.app");await q.mkdir(a,{recursive:true});const n=F.join(e,"PhoneProbe.m");await q.writeFile(n,Ei);await te("xcrun",["--sdk","iphoneos","clang","-arch","arm64","-miphoneos-version-min=13.0","-fobjc-arc","-O2","-framework","Foundation","-framework","UIKit",n,"-o",F.join(a,"PhoneProbe")],{timeout:18e4,maxBuffer:8*Ue,env:{...process.env,TMPDIR:e}});const o=je;await q.writeFile(F.join(a,"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 q.copyFile(s,F.join(a,"embedded.mobileprovision"));const r=F.join(e,"probe.entitlements");await q.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 te("codesign",["-f","-s",i,"--entitlements",r,a],{timeout:6e4});return a}function Ta(e,t=45e3){return new Promise(s=>{const i=ka("xcrun",["devicectl","device","process","launch","--device",e,"--terminate-existing","--console",je]);let a="";let n=false;const o=()=>{if(n)return;n=true;clearTimeout(r);i.kill("SIGTERM");s(a)};const r=setTimeout(o,t);const l=c=>{a+=c.toString();if(/BUOY_PROBE .*available=\d+/.test(a))setTimeout(o,300)};i.stdout.on("data",l);i.stderr.on("data",l);i.on("close",o);i.on("error",o)})}async function As(e={}){const t=e.log??(()=>{});const s=(await Oa()).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 a=Ea(await Ia(),i.udid,await $a());if(!a){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 n=await q.mkdtemp(F.join(Ce.tmpdir(),"buoy-probe-"));try{const o=await Da(n,a.profile.team,a.profile.file,a.identity);await te("xcrun",["devicectl","device","install","app","--device",i.udid,o],{timeout:12e4});let r=null;try{const f=await Ta(i.udid);r=_a(f);if(!r){const S=/locked/i.test(f)?" The phone looks locked: unlock it and try again.":"";throw new Error(`Could not read the phone.${S} Output: ${f.trim().slice(-300)}`)}}finally{await te("xcrun",["devicectl","device","uninstall","app","--device",i.udid,je],{timeout:6e4}).catch(()=>void 0)}const l=ce();const c=Aa(l,i.productType,i.name);const p=l[c];const u=p?.warnSource?.startsWith("measured")&&p.warnMB<r.limitMB;const h={name:p?.name??i.name,productType:i.productType,ramMB:r.ramMB,cpus:r.cpus,limitMB:r.limitMB,warnMB:u?p.warnMB:Math.round(r.limitMB*.8),warnSource:u?p.warnSource:"80% of the limit (not measured)",ios:i.ios,measuredAt:new Date().toISOString().slice(0,10)};await Vt(c,h);return{id:c,phone:h,previous:p}}finally{await q.rm(n,{recursive:true,force:true}).catch(()=>void 0)}}import Ra from"os";import Ds from"path";import{spawn as Ts}from"child_process";import{randomBytes as Pa}from"crypto";import{existsSync as pt,mkdirSync as ut,openSync as Rs,closeSync as Ps,promises as se,readFileSync as Ns,rmSync as xs,writeFileSync as Fe,renameSync as Na}from"fs";import xa from"net";import ht from"os";import D from"path";import{createHash as La}from"crypto";import{createReadStream as Ca,createWriteStream as ja,existsSync as Me,promises as Y,readFileSync as Ua}from"fs";import mt from"os";import T from"path";import{Readable as Fa}from"stream";import{pipeline as Ls}from"stream/promises";var _e="https://dl.google.com/android/repository/";var Ga="channel-0";var ie={api:36,tag:"aosp_atd",abi:Wa()};function Wa(){return mt.arch()==="arm64"?"arm64-v8a":"x86_64"}function Ge(e){return`system-images/android-${e.api}/${e.tag}/${e.abi}/`}function Cs(e){return T.join(e,"sdk")}function ft(e=process.env){const t=mt.homedir();const s=[e.ANDROID_HOME,e.ANDROID_SDK_ROOT,T.join(t,"Library/Android/sdk"),T.join(t,"Android/Sdk")];return[...new Set(s.filter(i=>!!i))]}function js(e){try{const t=/Pkg\.Revision=([\d.]+)/.exec(Ua(T.join(e,"emulator/source.properties"),"utf8"));return t?.[1]??null}catch{return null}}function wt(e,t){const s=e.split(".").map(Number);const i=t.split(".").map(Number);for(let a=0;a<Math.max(s.length,i.length);a++){const n=(s[a]??0)-(i[a]??0);if(n)return n}return 0}var Us="35.4.9";function Be(e,t,s=ie){const i=T.join(e,"emulator",process.platform==="win32"?"emulator.exe":"emulator");const a=T.join(e,"platform-tools",process.platform==="win32"?"adb.exe":"adb");const n=js(e);if(!Me(i)||!Me(a)||!n)return null;return{root:e,source:t,emulator:i,emulatorVersion:n,adb:a,hasImage:Me(T.join(e,Ge(s),"system.img"))}}function gt(e,t=ie,s="auto"){const i=Be(Cs(e),"buoy",t);if(s!=="system"&&i?.hasImage&&wt(i.emulatorVersion,Us)>=0)return i;if(s==="buoy")return i;for(const a of ft()){const n=Be(a,"system",t);if(n?.hasImage&&wt(n.emulatorVersion,Us)>=0)return n}return s==="system"?null:i}function Ha(e){return[...e.matchAll(/<remotePackage path="([^"]+)">([\s\S]*?)<\/remotePackage>/g)].map(t=>({path:t[1],body:t[2]}))}function za(e){const t=/<revision>([\s\S]*?)<\/revision>/.exec(e)?.[1]??"";return["major","minor","micro"].map(s=>new RegExp(`<${s}>(\\d+)</${s}>`).exec(t)?.[1]).filter(Boolean).join(".")}function qa(){return process.platform==="darwin"?"macosx":process.platform==="win32"?"windows":"linux"}function Ka(){return mt.arch()==="arm64"?"aarch64":"x64"}function yt(e,t,s,i,a={}){const n=a.os??qa();const o=a.arch??Ka();let r=null;for(const l of Ha(e)){if(l.path!==t)continue;if(!l.body.includes(`<channelRef ref="${Ga}"/>`))continue;const c=za(l.body);const p=/<uses-license ref="([^"]+)"/.exec(l.body)?.[1]??"";for(const u of l.body.matchAll(/<archive>([\s\S]*?)<\/archive>/g)){const h=u[1];const f=/<host-os>([^<]+)<\/host-os>/.exec(h)?.[1];const S=/<host-arch>([^<]+)<\/host-arch>/.exec(h)?.[1];if(f&&f!==n)continue;if(S&&S!==o)continue;const b=/<url>([^<]+)<\/url>/.exec(h)?.[1];const w=/<checksum type="sha1">([0-9a-f]+)<\/checksum>/.exec(h)?.[1];const _=Number(/<size>(\d+)<\/size>/.exec(h)?.[1]??0);if(!b||!w)continue;const v=/<display-name>([^<]+)<\/display-name>/.exec(l.body)?.[1]??t;if(!r||wt(c,r.rev)>0){r={rev:c,a:{name:`${v} ${c}`,url:s+b,sha1:w,size:_,license:p,dest:i}}}}}return r?.a??null}function Fs(e,t){const s=new RegExp(`<license id="${t}" type="text">([\\s\\S]*?)</license>`).exec(e);return s?s[1].replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").trim():null}async function Gs(e){const t=await fetch(e);if(!t.ok)throw new Error(`GET ${e} failed: ${t.status}`);return t.text()}async function Ya(e=ie){const t=await Gs(`${_e}repository2-3.xml`);const s=`${_e}sys-img/${e.tag}/`;const i=await Gs(`${s}sys-img2-3.xml`);const a=yt(t,"emulator",_e,"emulator");const n=yt(t,"platform-tools",_e,"platform-tools");const o=yt(i,`system-images;android-${e.api};${e.tag};${e.abi}`,s,Ge(e));const r=[!a&&"emulator",!n&&"platform-tools",!o&&`${e.tag} image for Android ${e.api}`].filter(Boolean);if(r.length)throw new Error(`Google's list has no stable ${r.join(", ")} for this computer.`);const l=[a,n,o];const c={};for(const p of l){if(c[p.license])continue;c[p.license]=Fs(t,p.license)??Fs(i,p.license)??`(See ${_e} for license ${p.license}.)`}return{archives:l,licenses:c}}async function Ws(e){const t=La("sha1");await Ls(Ca(e),t);return t.digest("hex")}async function Qa(e,t,s=()=>{}){if(process.platform==="win32")throw new Error("The Android farm can't set up its own SDK on Windows yet.");const i=Cs(e);const a=T.join(e,"download");await Y.mkdir(a,{recursive:true});await Promise.all(t.archives.map(async o=>{const r=T.join(i,o.dest);if(o.dest==="emulator"?js(i):Me(T.join(r,o.dest==="platform-tools"?"adb":"system.img"))){s(`${o.name}: already here.`);return}const l=T.join(a,T.basename(o.url));if(!Me(l)||await Ws(l)!==o.sha1){s(`Downloading ${o.name} (${Math.round(o.size/1024**2)} MB)\u2026`);const u=await fetch(o.url);if(!u.ok||!u.body)throw new Error(`GET ${o.url} failed: ${u.status}`);await Ls(Fa.fromWeb(u.body),ja(l));const h=await Ws(l);if(h!==o.sha1)throw new Error(`${o.name} failed its checksum (${h}).`)}const c=T.join(a,`unzip-${T.basename(o.url)}`);await Y.rm(c,{recursive:true,force:true});await Y.mkdir(c,{recursive:true});await P("unzip",["-q",l,"-d",c],{timeoutMs:15*6e4});const[p]=await Y.readdir(c);await Y.mkdir(T.dirname(r),{recursive:true});await Y.rm(r,{recursive:true,force:true});await Y.rename(T.join(c,p),r);await Y.rm(c,{recursive:true,force:true});await Y.rm(l,{force:true});s(`${o.name}: ready.`)}));await Y.rm(a,{recursive:true,force:true});const n=Be(i,"buoy");if(!n)throw new Error(`The SDK at ${i} is not complete after the download.`);return n}import{existsSync as Va,promises as vt,readFileSync as Ja}from"fs";import Xa from"path";var St="android-3gb";var Hs={"android-3gb":{name:"Low-end Android (3 GB)",ramMB:3072,cores:4,width:720,height:1600,density:320,heapGrowthMB:192,heapMB:512,source:"built in"},"pixel-4a":{name:"Pixel 4a",ramMB:6144,cores:8,width:1080,height:2340,density:440,heapGrowthMB:256,heapMB:512,source:"built in"}};function zs(e){return Xa.join(e,"phones.json")}function kt(e){const t={...Hs};const s=zs(e);if(Va(s)){try{Object.assign(t,JSON.parse(Ja(s,"utf8")))}catch{}}return t}async function Za(e,t,s){const i=zs(e);let a={};try{a=JSON.parse(await vt.readFile(i,"utf8"))}catch{}a[t]=s;await vt.mkdir(e,{recursive:true});await vt.writeFile(i,JSON.stringify(a,null,2)+"\n")}var en=[1024,1536,2048,3072,4096,6144,8192,12288,16384,24576];function tn(e,t){const s=u=>new RegExp(`\\[${u.replace(/\./g,"\\.")}\\]: \\[([^\\]]*)\\]`).exec(e.props)?.[1]??"";const i=Number(/MemTotal:\s+(\d+)/.exec(e.meminfo)?.[1]??0);const a=i?en.find(u=>u>=i/1024)??Math.ceil(i/1024/1024)*1024:0;const n=/Override size: (\d+)x(\d+)/.exec(e.wmSize)??/Physical size: (\d+)x(\d+)/.exec(e.wmSize);const o=/Override density: (\d+)/.exec(e.wmDensity)??/Physical density: (\d+)/.exec(e.wmDensity);const r=u=>Number(/^(\d+)m$/i.exec(u)?.[1]??0);const l=s("ro.product.model")||"Android phone";const c={name:l,ramMB:a||3072,cores:Number(e.nproc.trim())||4,width:n?Number(n[1]):1080,height:n?Number(n[2]):2400,density:o?Number(o[1]):420,heapGrowthMB:r(s("dalvik.vm.heapgrowthlimit"))||256,heapMB:r(s("dalvik.vm.heapsize"))||512,source:t};const p=l.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"android-phone";return{id:p,phone:c}}var We=Number(process.env.BUOY_FARM_ADB_PORT)||5137;var qs=5800;var Ks=5998;var sn="BuoyFarm_";var an=1.3;function Ys(e=H()){return D.join(e,"android")}var Qs=class{constructor(e={}){this.dir=Ys(e.home);this.avdHome=D.join(this.dir,"avd");this.adbPort=e.adbPort??We;this.log=e.log??(()=>{});this.sdkPref=e.sdk??"auto"}get stateFile(){return D.join(this.dir,"state.json")}read(){try{return JSON.parse(Ns(this.stateFile,"utf8"))}catch{return{version:1,templates:{},copies:{}}}}write(e){ut(this.dir,{recursive:true});const t=`${this.stateFile}.${process.pid}.tmp`;Fe(t,JSON.stringify(e,null,2)+"\n");Na(t,this.stateFile)}async locked(e){ut(this.dir,{recursive:true});const t=D.join(this.dir,"state.lock");for(let s=0;;s++){try{const i=Rs(t,"wx");Fe(i,String(process.pid));Ps(i);break}catch{const i=Number(Ns(t,"utf8").trim()||0);if(!i||!await C(i)){xs(t,{force:true});continue}if(s>600)throw new Error("Another farm command holds the Android state lock.");await I(100)}}try{const s=this.read();const i=await e(s);this.write(s);return i}finally{xs(t,{force:true})}}sdk(e=ie){const t=gt(this.dir,e,this.sdkPref);if(!t)throw new Error("No Android SDK with an emulator and the slim image yet. Run: farm android setup");if(!t.hasImage)throw new Error(`The SDK at ${t.root} has no ${Ge(e)} image. Run: farm android setup`);return t}env(e){return{...process.env,ANDROID_HOME:e.root,ANDROID_SDK_ROOT:e.root,ANDROID_AVD_HOME:this.avdHome,ANDROID_ADB_SERVER_PORT:String(this.adbPort)}}adb(e,t,s=3e4){return M(e.adb,t,{timeoutMs:s,env:this.env(e)})}async shell(e,t,s,i=3e4){const a=await this.adb(e,["-s",t,"shell",s],i);if(a.timedOut)throw new Error(`adb shell on ${t} timed out: ${s}`);if(a.code!==0)throw new Error(`adb shell on ${t} failed: ${s}: ${(a.stderr||a.stdout).trim().slice(0,300)}`);return a.stdout}async freePort(e){const t=s=>new Promise(i=>{const a=xa.createServer();a.once("error",()=>i(false));a.listen(s,"127.0.0.1",()=>a.close(()=>i(true)))});for(let s=qs;s<=Ks;s+=2){if(e.has(s))continue;if(await t(s)&&await t(s+1))return s}throw new Error(`No free emulator port from ${qs} to ${Ks}.`)}async launch(e,t,s,i,a){const n=D.join(this.dir,"logs");await se.mkdir(n,{recursive:true});const o=D.join(n,a);const r=Rs(o,"w");const l=["-avd",t,"-port",String(s),"-gpu","host","-no-audio","-no-boot-anim","-camera-back","none","-camera-front","none",...i];const c=Ts(e.emulator,l,{detached:true,stdio:["ignore",r,r],env:this.env(e)});Ps(r);c.unref();if(!c.pid)throw new Error("The emulator did not start.");const p=await re(c.pid)??"";return{pid:c.pid,pidStart:p,log:o}}async waitBooted(e,t,s,i){const a=Date.now()+i;while(Date.now()<a){if(!await C(s))throw new Error(`The emulator for ${t} stopped while booting.`);const n=await this.adb(e,["-s",t,"shell","getprop","sys.boot_completed"],5e3);if(n.code===0&&n.stdout.trim()==="1")return;await I(250)}throw new Error(`${t} did not finish booting in ${Math.round(i/1e3)} s.`)}async stopEmulator(e,t,s,i){await this.adb(e,["-s",t,"emu","kill"],1e4);for(let a=0;a<300;a++){if(!await C(s,i))return;await I(100)}if(await C(s,i)){try{process.kill(s,"SIGKILL")}catch{}}}writeAvd(e,t,s,i){const a=D.join(this.avdHome,`${t}.avd`);ut(a,{recursive:true});const n={AvdId:t,"avd.ini.displayname":t.replace(/_/g," "),"avd.ini.encoding":"UTF-8","abi.type":i.abi,"hw.cpu.arch":i.abi==="arm64-v8a"?"arm64":"x86_64","image.sysdir.1":Ge(i),"tag.id":i.tag,"tag.display":i.tag==="aosp_atd"?"AOSP ATD":"Google ATD",target:`android-${i.api}`,"hw.ramSize":s.ramMB,"hw.cpu.ncore":s.cores,"hw.lcd.width":s.width,"hw.lcd.height":s.height,"hw.lcd.density":s.density,"disk.dataPartition.size":"6G","hw.gpu.enabled":"yes","hw.gpu.mode":"host","hw.keyboard":"yes","hw.audioInput":"no","hw.audioOutput":"no","hw.camera.back":"none","hw.camera.front":"none","fastboot.forceColdBoot":"no","fastboot.forceFastBoot":"yes",showDeviceFrame:"no"};Fe(D.join(a,"config.ini"),Object.entries(n).map(([o,r])=>`${o}=${r}`).join("\n")+"\n");Fe(D.join(this.avdHome,`${t}.ini`),`avd.ini.encoding=UTF-8
|
|
391
|
-
path=${a}
|
|
392
|
-
path.rel=avd/${t}.avd
|
|
393
|
-
target=android-${i.api}
|
|
394
|
-
`);return a}async createTemplate(e){const t=D.resolve(e.apk);if(!pt(t)||!t.endsWith(".apk"))throw new Error(`No APK at ${t}.`);const s=e.image??ie;const i=this.sdk(s);const a=kt(this.dir);const n=e.phoneId??St;const o=a[n];if(!o)throw new Error(`No phone "${n}". Try: farm android phone list`);await this.budget(o,1);const r=Pa(3).toString("hex");const l=`${sn}${r}`;const c=await se.stat(t);const p={id:r,avd:l,apk:t,apkSize:c.size,apkMtimeMs:c.mtimeMs,packageName:"",activity:"",phoneId:n,phone:o,image:s,sdkRoot:i.root,emulatorVersion:i.emulatorVersion,createdAt:new Date().toISOString(),usable:false,note:"Being built."};const u=this.writeAvd(i,l,o,s);await this.adb(i,["start-server"],2e4);const h=await this.locked(async v=>{v.templates[r]=p;return this.freePort(new Set(Object.values(v.copies).map(A=>A.port)))});const f=`emulator-${h}`;const S=Date.now();this.log(`Template ${r}: first boot of ${o.name} (${s.tag}, Android ${s.api})\u2026`);const b=await this.launch(i,l,h,["-no-window","-no-snapshot-load","-no-snapshot-save"],`template-${r}.log`);try{await this.waitBooted(i,f,b.pid,e.bootTimeoutMs??10*6e4);this.log(`Booted in ${((Date.now()-S)/1e3).toFixed(1)} s. Setting up\u2026`);const v=(y,B)=>this.shell(i,f,y,B);await v("setprop debug.hwui.drawing_enabled 1");await this.setHeap(i,f,o);await v("settings put global package_verifier_enable 0; settings put system screen_off_timeout 2147483647; svc power stayon true; input keyevent 82");const A=new Set((await v("pm list packages -3")).split("\n").map(y=>y.trim()).filter(Boolean));this.log("Installing the app\u2026");const ae=await this.adb(i,["-s",f,"install","-r","-g",t],10*6e4);if(ae.code!==0||!/Success/.test(ae.stdout))throw new Error(`Install failed: ${(ae.stderr||ae.stdout).trim().slice(0,400)}`);const k=(await v("pm list packages -3")).split("\n").map(y=>y.trim()).filter(Boolean);const m=k.filter(y=>!A.has(y)).map(y=>y.replace(/^package:/,""));if(m.length!==1)throw new Error(`Could not tell which package the APK installed (${m.join(", ")||"none"}).`);p.packageName=m[0];p.activity=(await v(`cmd package resolve-activity --brief -c android.intent.category.LAUNCHER ${p.packageName}`)).trim().split("\n").pop().trim();if(!p.activity.includes("/"))throw new Error(`${p.packageName} has no launcher screen.`);this.log("Compiling the app ahead of time, so every copy times the same code\u2026");await v(`cmd package compile -m speed -f ${p.packageName}`,10*6e4);await v(`am start -W -n ${p.activity}`,12e4);await I(8e3);await v(`am force-stop ${p.packageName}`);this.log("Saving the snapshot\u2026");const g=await this.adb(i,["-s",f,"emu","avd","snapshot","save","default_boot"],5*6e4);if(g.code!==0||/KO/.test(g.stdout))throw new Error(`Snapshot save failed: ${(g.stdout+g.stderr).trim().slice(0,300)}`)}catch(v){await this.stopEmulator(i,f,b.pid,b.pidStart);await this.locked(A=>{A.templates[r].note=`Build failed: ${v.message}`});throw v}await this.stopEmulator(i,f,b.pid,b.pidStart);if(!pt(D.join(u,"snapshots","default_boot","ram.bin"))){await this.locked(v=>{v.templates[r].note="Build failed: no snapshot was saved."});throw new Error("No snapshot was saved.")}await this.locked(v=>{Object.assign(v.templates[r],{packageName:p.packageName,activity:p.activity,usable:true,note:void 0})});this.log("Checking that a copy starts from the snapshot\u2026");const[w]=await this.up(r,1,{label:"template check"});await this.down([w.serial]);const _=await this.locked(v=>{const A=v.templates[r];A.copyReadyMs=w.readyMs;if(w.bootedFrom==="cold"){A.usable=false;A.note="Copies cold boot instead of loading the snapshot."}return A});if(!_.usable)throw new Error(_.note);return _}async setHeap(e,t,s){const i=(r,l)=>this.shell(e,t,r,l);const a=(await i("getprop dalvik.vm.heapgrowthlimit; getprop dalvik.vm.heapsize")).split("\n").map(r=>r.trim());if(a[0]===`${s.heapGrowthMB}m`&&a[1]===`${s.heapMB}m`)return;const n=await this.adb(e,["-s",t,"root"],3e4);if(n.code!==0||/cannot run as root/i.test(n.stdout+n.stderr)){this.log(`Could not set the heap limit on this image (${(n.stdout+n.stderr).trim()}). Apps keep ${a[0]}.`);return}await I(1500);await this.adb(e,["-s",t,"wait-for-device"],6e4);await i(`setprop dalvik.vm.heapgrowthlimit ${s.heapGrowthMB}m && setprop dalvik.vm.heapsize ${s.heapMB}m && stop && start`);const o=Date.now()+3*6e4;for(;;){const r=await this.adb(e,["-s",t,"shell","service check package; pidof system_server"],5e3);if(/Service package: found/.test(r.stdout)&&/\d/.test(r.stdout.split("\n")[1]??""))break;if(Date.now()>o)throw new Error("Android's framework did not come back after setting the heap limit.");await I(500)}await I(5e3);await this.adb(e,["-s",t,"unroot"],3e4);await I(1500);await this.adb(e,["-s",t,"wait-for-device"],6e4)}staleReason(e,t){if(!e.usable)return e.note??"not ready";if(t.root!==e.sdkRoot||t.emulatorVersion!==e.emulatorVersion){return`It was saved with emulator ${e.emulatorVersion}; this SDK has ${t.emulatorVersion}. Snapshots don't load across versions.`}if(!pt(D.join(this.avdHome,`${e.avd}.avd`,"snapshots","default_boot","ram.bin")))return"Its snapshot is gone.";return null}async budget(e,t){const{availableGB:s,totalGB:i,freeDiskGB:a}=await Xs();const n=Math.round((e.ramMB/1024+an)*10)/10;const o=Math.min(24,Math.max(4,Math.round(i*.25)));const r=Math.max(0,Math.floor((s-o)/n));if(t>r){throw new Error(`Not enough free memory for ${t} more ${e.name} cop${t===1?"y":"ies"} (${n} GB each, ${s.toFixed(1)} GB free, ${o} GB kept for the Mac). Room for ${r}.`)}if(a<10)throw new Error(`Only ${a.toFixed(0)} GB of disk is free. Copies need at least 10 GB.`);return{perCopyGB:n,availableGB:s,reserveGB:o,roomFor:r}}async up(e,t,s={}){const i=this.read();const a=e?i.templates[e]:on(i);if(!a)throw new Error(e?`No template ${e}.`:"No Android template yet. Run: farm android template --apk <app.apk>");const n=this.sdk(a.image);const o=this.staleReason(a,n);if(o)throw new Error(`Template ${a.id} can't be used: ${o} Make a new one with: farm android template --apk ${a.apk}`);await this.budget(a.phone,t);await this.adb(n,["start-server"],2e4);const r=await this.locked(async u=>{const h=new Set(Object.values(u.copies).map(S=>S.port));const f=[];for(let S=0;S<t;S++){const b=await this.freePort(h);h.add(b);const w=`emulator-${b}`;const _=["-read-only","-no-snapshot-save",...s.window?[]:["-no-window"]];const v=await this.launch(n,a.avd,b,_,`${w}.log`);const A={serial:w,port:b,pid:v.pid,pidStart:v.pidStart,templateId:a.id,startedAt:new Date().toISOString(),log:v.log,window:!!s.window,label:s.label};u.copies[w]=A;f.push(A)}return f});const l=Date.now();const c=await Promise.allSettled(r.map(async u=>{await this.waitBooted(n,u.serial,u.pid,s.bootTimeoutMs??5*6e4);u.readyMs=Date.now()-l;u.bootedFrom=await rn(u.log);for(const h of s.reverse??[]){const[f,S]=h.split(":");await this.adb(n,["-s",u.serial,"reverse",`tcp:${f}`,`tcp:${S??f}`],1e4)}return u}));await this.locked(u=>{for(const h of r)if(u.copies[h.serial])Object.assign(u.copies[h.serial],{readyMs:h.readyMs,bootedFrom:h.bootedFrom})});const p=c.flatMap((u,h)=>u.status==="rejected"?[`${r[h].serial}: ${u.reason.message}`]:[]);if(p.length){await this.down(r.filter((u,h)=>c[h].status==="rejected").map(u=>u.serial));throw new Error(`Some copies did not start:
|
|
395
|
-
${p.join("\n")}`)}return r}async list(){return this.locked(async e=>{for(const t of Object.values(e.copies)){if(!await C(t.pid,t.pidStart,true))delete e.copies[t.serial]}return{templates:Object.values(e.templates),copies:Object.values(e.copies)}})}async down(e){const t=this.read();const s=e==="all"?Object.values(t.copies):e.map(a=>{const n=t.copies[a];if(!n)throw new Error(`${a} is not a farm copy.`);return n});const i=s.length?this.sdk(t.templates[s[0].templateId]?.image):null;await Promise.all(s.map(async a=>{if(await C(a.pid,a.pidStart))await this.stopEmulator(i,a.serial,a.pid,a.pidStart)}));await this.locked(a=>{for(const n of s)delete a.copies[n.serial]});return s.map(a=>a.serial)}async removeTemplate(e){await this.locked(async t=>{const s=t.templates[e];if(!s)throw new Error(`No template ${e}.`);const i=Object.values(t.copies).filter(a=>a.templateId===e);if(i.length)throw new Error(`Template ${e} still has copies running: ${i.map(a=>a.serial).join(", ")}. Close them first.`);await se.rm(D.join(this.avdHome,`${s.avd}.avd`),{recursive:true,force:true});await se.rm(D.join(this.avdHome,`${s.avd}.ini`),{force:true});delete t.templates[e]})}copy(e){const t=this.read();const s=t.copies[e];if(!s)throw new Error(`${e} is not a farm copy.`);const i=t.templates[s.templateId];return{c:s,t:i,sdk:this.sdk(i.image)}}async launchApp(e,t){const{t:s,sdk:i}=this.copy(e);await this.shell(i,e,`am force-stop ${s.packageName}`);const a=t?`am start -W -a android.intent.action.VIEW -d '${t.replace(/'/g,"'\\''")}' ${s.packageName}`:`am start -W -n ${s.activity}`;const n=await this.shell(i,e,a,12e4);const o=/TotalTime: (\d+)/.exec(n);return{totalMs:o?Number(o[1]):null,output:n.trim()}}async install(e,t){await Promise.all(e.map(async s=>{const{t:i,sdk:a}=this.copy(s);const n=await this.adb(a,["-s",s,"install","-r","-g",D.resolve(t)],10*6e4);if(n.code!==0||!/Success/.test(n.stdout))throw new Error(`${s}: install failed: ${(n.stderr||n.stdout).trim().slice(0,300)}`);await this.shell(a,s,`cmd package compile -m speed -f ${i.packageName}`,10*6e4)}))}async screenshot(e,t){const{sdk:s}=this.copy(e);const i=await new Promise(a=>{const n=Ts(s.adb,["-s",e,"exec-out","screencap","-p"],{env:this.env(s)});const o=[];n.stdout.on("data",l=>o.push(l));const r=setTimeout(()=>n.kill("SIGKILL"),2e4);n.on("close",l=>{clearTimeout(r);a({code:l,buf:Buffer.concat(o)})})});if(i.code!==0||i.buf.length<100)throw new Error(`No screenshot from ${e}.`);await se.mkdir(D.dirname(D.resolve(t)),{recursive:true});await se.writeFile(t,i.buf)}async bench(e,t={}){const{c:s,t:i,sdk:a}=this.copy(e);const n=[];for(let h=0;h<(t.launches??3);h++){const f=await this.launchApp(e);if(f.totalMs!=null)n.push(f.totalMs)}await I(2e3);await this.shell(a,e,`dumpsys gfxinfo ${i.packageName} reset`);const o=await Zs(s.pid);const r=Date.now();await I((t.seconds??15)*1e3);const l=await Zs(s.pid);const c=Vs(await this.shell(a,e,`dumpsys gfxinfo ${i.packageName}`));const p=await this.shell(a,e,`dumpsys meminfo ${i.packageName}`);const u=Number(/TOTAL PSS:\s+(\d+)/.exec(p)?.[1]??/TOTAL\s+(\d+)/.exec(p)?.[1]??0);return{serial:e,appStartMs:nn(n),appStarts:n,frames:c,appMemoryMB:Math.round(u/1024),macMemoryMB:await ln(s.pid),macCpuPct:o!=null&&l!=null?Math.round((l-o)/(Date.now()-r)*100):null}}};function Vs(e){const t=s=>{const i=s.exec(e);return i?Number(i[1]):null};return{frames:t(/Total frames rendered: (\d+)/)??0,jankyPct:t(/Janky frames: \d+ \(([\d.]+)%\)/),p50:t(/50th percentile: (\d+)ms/),p90:t(/90th percentile: (\d+)ms/),p99:t(/99th percentile: (\d+)ms/)}}function nn(e){if(!e.length)return null;const t=[...e].sort((i,a)=>i-a);const s=Math.floor(t.length/2);return t.length%2?t[s]:Math.round((t[s-1]+t[s])/2)}function on(e){return Object.values(e.templates).filter(t=>t.usable).sort((t,s)=>t.createdAt.localeCompare(s.createdAt)).pop()}async function rn(e){let t="";try{t=await se.readFile(e,"utf8")}catch{return"unknown"}return Js(t)}function Js(e){if(/Successfully loaded snapshot|Loading snapshot '?default_boot'? .*(done|succeeded)|snapshot.*loaded/i.test(e))return"snapshot";if(/Cold boot|failed to load snapshot|Snapshot load failed|could not load snapshot/i.test(e))return"cold";return"unknown"}async function Xs(){const e=ht.totalmem()/1024**3;let t=ht.freemem()/1024**3;if(process.platform==="darwin"){const a=await M("vm_stat",[],{timeoutMs:1e4});const n=Number(/page size of (\d+)/.exec(a.stdout)?.[1]??16384);const o=r=>Number(new RegExp(`${r}:\\s+(\\d+)`).exec(a.stdout)?.[1]??0);t=(o("Pages free")+o("Pages inactive")+o("Pages speculative")+o("Pages purgeable"))*n/1024**3}const s=await M("df",["-k",ht.homedir()],{timeoutMs:1e4});const i=Number((s.stdout.trim().split("\n").pop()??"").split(/\s+/)[3]??0);return{availableGB:t,totalGB:e,freeDiskGB:i/1024**2}}async function ln(e){if(process.platform==="darwin"){const i=await M("footprint",[String(e)],{timeoutMs:3e4});const a=/Footprint: ([\d.]+) (MB|GB|KB)/.exec(i.stdout);if(a)return Math.round(Number(a[1])*(a[2]==="GB"?1024:a[2]==="KB"?1/1024:1))}const t=await M("ps",["-o","rss=","-p",String(e)],{timeoutMs:5e3});const s=Number(t.stdout.trim());return s?Math.round(s/1024):null}async function Zs(e){const t=await M("ps",["-o","time=","-p",String(e)],{timeoutMs:5e3});const s=/(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+(?:\.\d+)?)/.exec(t.stdout.trim());if(!s)return null;const[,i,a,n,o]=s;return((Number(i??0)*24+Number(a??0))*60+Number(n))*6e4+Number(o)*1e3}var bt=e=>`Usage: ${e} android <command>
|
|
396
|
-
|
|
397
|
-
Many slim Android phones on one computer. Each copy starts from a saved
|
|
398
|
-
snapshot in seconds and draws with your Mac's GPU.
|
|
399
|
-
|
|
400
|
-
setup [--accept-license] [--sdk auto|buoy|system] [--image aosp_atd|google_atd]
|
|
401
|
-
Get the emulator, adb and the slim image.
|
|
402
|
-
Uses your Android SDK when it already has them.
|
|
403
|
-
--sdk buoy downloads a pinned copy (about 1.2 GB)
|
|
404
|
-
template --apk <app.apk> [--phone <id>] [--image aosp_atd|google_atd]
|
|
405
|
-
Make a template: boot once, install and compile
|
|
406
|
-
the app, save the snapshot copies start from
|
|
407
|
-
up [n] [--template <id>] [--show] [--reverse 8081[:8810]]
|
|
408
|
-
Start n copies (default 1). --show opens windows.
|
|
409
|
-
--reverse maps a copy's port to your computer's
|
|
410
|
-
(for Metro). Repeat it for more ports
|
|
411
|
-
list Templates and running copies
|
|
412
|
-
down <serial ...> | --all Close copies (only the farm's own)
|
|
413
|
-
launch <serial> [--url <link>]
|
|
414
|
-
Open the app cold and print its start time
|
|
415
|
-
install <apk> <serial ...> | --all
|
|
416
|
-
Put a new build on running copies
|
|
417
|
-
shot <serial> <file.png> Save a screenshot
|
|
418
|
-
bench <serial> [--seconds 15]
|
|
419
|
-
App start time, frame times and memory
|
|
420
|
-
adb <serial> <args...> Run adb on the farm's own adb server
|
|
421
|
-
share <serial> Also show a copy on your normal adb server, so
|
|
422
|
-
Android Studio, Detox or Buoy's MCP see it
|
|
423
|
-
remove-template <id> Delete a template (no copies may run)
|
|
424
|
-
phone list Phones a copy can act like
|
|
425
|
-
phone measure [--serial <usb serial>]
|
|
426
|
-
Read the Android phone plugged in and save it
|
|
427
|
-
doctor Check the SDK, GPU mode, memory and disk
|
|
428
|
-
|
|
429
|
-
The farm runs its own adb server on port ${We}, so other tools
|
|
430
|
-
can't drop its copies. To use plain adb with them:
|
|
431
|
-
ANDROID_ADB_SERVER_PORT=${We} adb devices
|
|
432
|
-
`;function J(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}function cn(e,t){const s=[];e.forEach((i,a)=>{if(i===`--${t}`){const n=e[a+1];if(!n||n.startsWith("--"))throw new d("BAD_REQUEST",`--${t} needs a value.`);s.push(n)}});return s}function V(e,t){const s=[];for(let i=0;i<e.length;i++){if(e[i].startsWith("--")){if(t.includes(e[i].slice(2)))i++;continue}s.push(e[i])}return s}function Mt(e){const t=J(e,"image")??ie.tag;if(t!=="aosp_atd"&&t!=="google_atd")throw new d("BAD_REQUEST","Use --image aosp_atd or google_atd.");return{...ie,tag:t}}function _t(e){const t=J(e,"sdk")??"auto";if(t!=="auto"&&t!=="buoy"&&t!=="system")throw new d("BAD_REQUEST","Use --sdk auto, buoy or system.");return t}function Bt(e){const t=e.usable?"ready":e.note??"not ready";const s=e.copyReadyMs?`, copies ready in ${(e.copyReadyMs/1e3).toFixed(1)} s`:"";return`Template ${e.id}: ${e.packageName||Ds.basename(e.apk)} as ${e.phone.name} (${e.image.tag}, Android ${e.image.api}): ${t}${s}`}async function ei(e,t){const[s,...i]=e;const a=o=>console.log(o);const n=new Qs({log:o=>console.error(o),sdk:_t(i)});switch(s){case void 0:case"help":case"--help":return a(bt(t));case"setup":{const o=Mt(i);const r=_t(i);const l=gt(n.dir,o,r);if(l?.hasImage&&r!=="buoy"){a(`Ready. Using the ${l.source==="buoy"?"farm's own":"existing"} Android SDK at ${l.root} (emulator ${l.emulatorVersion}).`);return a(`Next: ${t} android template --apk <your app.apk>`)}if(l?.hasImage){return a(`Ready. The farm's own SDK is at ${l.root} (emulator ${l.emulatorVersion}).`)}const c=await Ya(o);if(!i.includes("--accept-license")){for(const[h,f]of Object.entries(c.licenses))a(`---- ${h} ----
|
|
433
|
-
${f}
|
|
434
|
-
`);a(`The farm will download:
|
|
435
|
-
${c.archives.map(h=>` ${h.name} (${Math.round(h.size/1024**2)} MB)`).join("\n")}`);return a(`
|
|
436
|
-
These come from Google under the licenses above. To accept them and download, run:
|
|
437
|
-
${t} android setup --sdk buoy --accept-license`)}const p=Date.now();const u=await Qa(n.dir,c,h=>console.error(h));a(`Ready in ${((Date.now()-p)/1e3).toFixed(1)} s. Emulator ${u.emulatorVersion} at ${u.root}.`);return a(`Next: ${t} android template --apk <your app.apk>`)}case"template":{const o=J(i,"apk");if(!o)throw new d("BAD_REQUEST","template needs --apk <app.apk>.");const r=Date.now();const l=await n.createTemplate({apk:o,phoneId:J(i,"phone"),image:Mt(i)});a(Bt(l));a(`Built in ${((Date.now()-r)/1e3).toFixed(0)} s. Start copies with: ${t} android up 2`);return}case"up":{const[o]=V(i,["template","reverse","sdk"]);const r=Number(o??1);if(!Number.isInteger(r)||r<1)throw new d("BAD_REQUEST","up needs a count of 1 or more.");const l=Date.now();const c=await n.up(J(i,"template"),r,{window:i.includes("--show"),reverse:cn(i,"reverse")});for(const p of c)a(`${p.serial} ready in ${((p.readyMs??0)/1e3).toFixed(1)} s (${p.bootedFrom})`);return a(`${c.length} cop${c.length===1?"y":"ies"} up in ${((Date.now()-l)/1e3).toFixed(1)} s.`)}case"list":{const{templates:o,copies:r}=await n.list();if(i.includes("--json"))return a(JSON.stringify({adbPort:n.adbPort,templates:o,copies:r},null,2));if(!o.length)a(`No templates. Make one with: ${t} android template --apk <app.apk>`);for(const l of o)a(Bt(l));for(const l of r)a(` ${l.serial} ${l.window?"window":"no window"} up since ${new Date(l.startedAt).toLocaleTimeString(void 0,{hour12:false})} template ${l.templateId}`);return a(`adb server: ANDROID_ADB_SERVER_PORT=${n.adbPort}`)}case"down":{const o=i.includes("--all")?"all":V(i,["sdk"]);if(o!=="all"&&!o.length)throw new d("BAD_REQUEST","down needs serials or --all.");const r=new Map((await n.list()).copies.map(c=>[c.serial,c.port]));const l=await n.down(o);await Promise.all(l.map(c=>r.has(c)&&M(Et(),["disconnect",`127.0.0.1:${r.get(c)+1}`],{timeoutMs:1e4})));return a(l.length?`Closed ${l.join(", ")}.`:"No copies were running.")}case"launch":{const[o]=V(i,["url","sdk"]);if(!o)throw new d("BAD_REQUEST","launch needs a serial.");const r=await n.launchApp(o,J(i,"url"));return a(r.totalMs!=null?`Started in ${r.totalMs} ms.`:r.output)}case"install":{const[o,...r]=V(i,["sdk"]);if(!o)throw new d("BAD_REQUEST","install needs an APK.");const l=i.includes("--all")?(await n.list()).copies.map(p=>p.serial):r;if(!l.length)throw new d("BAD_REQUEST","install needs serials or --all.");const c=Date.now();await n.install(l,o);return a(`Installed on ${l.length} cop${l.length===1?"y":"ies"} in ${((Date.now()-c)/1e3).toFixed(1)} s.`)}case"shot":{const[o,r]=V(i,["sdk"]);if(!o||!r)throw new d("BAD_REQUEST","shot needs a serial and a file.");await n.screenshot(o,r);return a(`Saved ${Ds.resolve(r)}.`)}case"bench":{const[o]=V(i,["seconds","sdk"]);if(!o)throw new d("BAD_REQUEST","bench needs a serial.");const r=await n.bench(o,{seconds:Number(J(i,"seconds")??15)});if(i.includes("--json"))return a(JSON.stringify(r,null,2));a(`App start: ${r.appStartMs??"?"} ms (runs: ${r.appStarts.join(", ")})`);a(`Frames: ${r.frames.frames}, median ${r.frames.p50??"?"} ms, 90% ${r.frames.p90??"?"} ms, 99% ${r.frames.p99??"?"} ms, janky ${r.frames.jankyPct??"?"}%`);a(`App memory: ${r.appMemoryMB} MB. Mac memory for this copy: ${r.macMemoryMB??"?"} MB. Mac CPU: ${r.macCpuPct??"?"}%`);return}case"adb":{const[o,...r]=i;if(!o)throw new d("BAD_REQUEST","adb needs a serial.");const l=n.sdk();const c=await n.adb(l,["-s",o,...r],10*6e4);process.stdout.write(c.stdout);process.stderr.write(c.stderr);if(c.code)process.exitCode=c.code;return}case"share":{const[o]=V(i,["sdk"]);const r=(await n.list()).copies.find(c=>c.serial===o);if(!r)throw new d("BAD_REQUEST",`${o??"That"} is not a running farm copy.`);const l=await M(Et(),["connect",`127.0.0.1:${r.port+1}`],{timeoutMs:2e4});if(!/connected to/.test(l.stdout))throw new d("HOST_ERROR",`adb connect failed: ${(l.stdout+l.stderr).trim()}`);return a(`${o} is now also 127.0.0.1:${r.port+1} on your normal adb server.`)}case"remove-template":{const[o]=V(i,["sdk"]);if(!o)throw new d("BAD_REQUEST","remove-template needs a template id.");await n.removeTemplate(o);return a(`Removed template ${o}.`)}case"phone":{const[o]=V(i,["serial","sdk"]);if(!o||o==="list"){for(const[r,l]of Object.entries(kt(n.dir))){a(`${r}${r===St?" (default)":""}: ${l.name}, ${l.ramMB} MB RAM, ${l.cores} cores, ${l.width}x${l.height} at ${l.density} dpi, heap ${l.heapGrowthMB} MB (large ${l.heapMB} MB), ${l.source}`)}return}if(o==="measure"){const r=Et();const l=J(i,"serial");const c=l?["-s",l]:["-d"];const p=async S=>{const b=await M(r,[...c,"shell",S],{timeoutMs:2e4});if(b.code!==0)throw new d("HOST_ERROR",`Could not read the phone: ${(b.stderr||b.stdout).trim().slice(0,200)}`,"Plug in one Android phone with USB debugging on, or pass --serial.");return b.stdout};const u={props:await p("getprop"),meminfo:await p("cat /proc/meminfo"),nproc:await p("nproc"),wmSize:await p("wm size"),wmDensity:await p("wm density")};const{id:h,phone:f}=tn(u,`measured ${new Date().toISOString().slice(0,10)}`);await Za(n.dir,h,f);return a(`Saved "${h}": ${f.ramMB} MB RAM, ${f.cores} cores, ${f.width}x${f.height} at ${f.density} dpi, heap ${f.heapGrowthMB} MB (large ${f.heapMB} MB).
|
|
438
|
-
Use it with: ${t} android template --apk <app.apk> --phone ${h}`)}throw new d("BAD_REQUEST",`Unknown phone command ${o}.`,"Try: phone list, phone measure")}case"doctor":{const o=Mt(i);const r=gt(n.dir,o,_t(i));const l=await Xs();const c=ft().map(h=>Be(h,"system",o)).filter(Boolean);const{templates:p,copies:u}=await n.list().catch(()=>({templates:[],copies:[]}));a(JSON.stringify({sdk:r?{root:r.root,source:r.source,emulator:r.emulatorVersion,slimImage:r.hasImage}:"none yet: run android setup",otherSdks:c.map(h=>({root:h.root,emulator:h.emulatorVersion,slimImage:h.hasImage})),adbServerPort:n.adbPort,avdFolder:n.avdHome,gpu:"host (Metal on a Mac); copies never fall back to software drawing",freeMemoryGB:Number(l.availableGB.toFixed(1)),freeDiskGB:Math.floor(l.freeDiskGB),cpuCores:Ra.cpus().length,templates:p.map(Bt),copies:u.map(h=>h.serial)},null,2));return}default:a(bt(t));process.exitCode=2}}function Et(){for(const e of ft()){const t=Be(e,"system");if(t)return t.adb}return"adb"}var He=e=>`Usage: ${e} <command>
|
|
439
|
-
|
|
440
|
-
status [--outside] Pool, budgets, sims, leases, recent events
|
|
441
|
-
setup [options] Make a template (the sim clones are made from)
|
|
442
|
-
--app <path.app> App build (default: example-dev-build Debug build)
|
|
443
|
-
--no-seed Skip the seed
|
|
444
|
-
--launch-url <url> Open this URL after each app launch. iOS asks
|
|
445
|
-
"Open in \u2026?" for a custom scheme, so a dev-client
|
|
446
|
-
app is better seeded with Preferences/ (it reopens
|
|
447
|
-
its last Metro URL by itself)
|
|
448
|
-
--seed <dir> Seed folder (default: example-dev-build/artifacts/pool-seed)
|
|
449
|
-
--device <type id> Default: iPhone 17 Pro
|
|
450
|
-
--runtime <runtime id> Default: iOS 26.3
|
|
451
|
-
--profile slim|stock Default: slim
|
|
452
|
-
--metro <port> Default: 8802
|
|
453
|
-
--dry-run Show what it would do and what it costs
|
|
454
|
-
grow <n> [--template id] Add n sims
|
|
455
|
-
shrink <n> [--template id] Remove n idle sims
|
|
456
|
-
remove-template <id> Delete a template and all its sims (none may be in use)
|
|
457
|
-
acquire <n> [--template id] [--purpose text] [--launch]
|
|
458
|
-
Take n sims and hold them until Ctrl-C
|
|
459
|
-
park|wake|reset|rebuild|delete <udid>
|
|
460
|
-
end-lease <leaseId> Force-end a lease (its sims are rebuilt)
|
|
461
|
-
settings [key=value ...] Show or change settings
|
|
462
|
-
phone list Phones a sim can act like (RAM, CPUs, memory limit)
|
|
463
|
-
phone use <id|off> Launch apps as this phone (default: iphone-se-2nd-gen)
|
|
464
|
-
phone measure [--device <udid>]
|
|
465
|
-
Read the iPhone plugged into this Mac and add it
|
|
466
|
-
doctor Check Xcode, disk, memory, the farm service
|
|
467
|
-
android <command> Slim Android phones from one snapshot
|
|
468
|
-
(see: android help)
|
|
469
|
-
stop [--now] Stop the farm service and park free sims
|
|
470
|
-
--now Stop even if leases are still held
|
|
471
|
-
farmd Run the farm service in this process
|
|
472
|
-
`;var _o=He("pnpm farm");function N(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 dn(e){return Bs({label:`CLI (${va.userInfo().username})`,launcher:Ms(e,["farmd"])})}function $(e){console.log(typeof e==="string"?e:JSON.stringify(e,null,2))}async function ti(e,t,s){if(s)return s;const i=await e.call("status");const a=i.templates.filter(n=>n.usable);if(a.length===0)throw new d("NO_TEMPLATE","No template yet.",`Run: ${t} setup`);return a[a.length-1].id}function pn(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 un(e,{prog:t,entry:s}){const[i,...a]=e;if(!i||i==="help"||i==="--help")return $(He(t));if(i==="android")return ei(a,t);hn(i,a);if(i==="farmd"){const o=await ks({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"&&a[0]!=="use"){const o=a[0];if(o==="list"||!o){const r=ce();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 As({device:N(a,"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 at;const r=await o.hostStats();const l=await ve();const c=await o.listDevices().catch(()=>[]);const p=be();const u=p?$s.join(p,"example-dev-build/artifacts/pool-seed"):null;const h=p?{exampleBuild:Le(),seed:u?fe(u)??"ok":"none"}:{};$({xcode:await o.xcodeBuild(),runtimes:[...new Set(c.map(f=>f.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 Se(l)}:"not running",socket:ya(z().socket),...h,slimLabels:ne("slim").length,slimTurnsOff:he.map(f=>f.name)});return}const n=await dn(s);try{switch(i){case"status":{const o=await n.call("status",{outside:a.includes("--outside")});return $(a.includes("--json")?o:pn(o))}case"setup":{const o=be();const r={appPath:N(a,"app")??Le(),seedDir:a.includes("--no-seed")?null:N(a,"seed")??(o?$s.join(o,"example-dev-build/artifacts/pool-seed"):void 0),launchUrl:N(a,"launch-url"),deviceType:N(a,"device")??"com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",runtime:N(a,"runtime")??"com.apple.CoreSimulator.SimRuntime.iOS-26-3",profile:N(a,"profile")??"slim",metroPort:Number(N(a,"metro")??8802)};if(!r.appPath)throw new d("BAD_REQUEST","No app build found.","Pass --app <path.app>.");if(!r.seedDir&&!a.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(a.includes("--dry-run")){const l=await n.call("budget",{ramGB:6,diskGB:4});return $({wouldCreateTemplate:r,seed:r.seedDir?fe(r.seedDir)??"ok":"none",slimTurnsOff:r.profile==="slim"?he.map(c=>`${c.name}: ${c.downside}`):[],budget:l.ok?"ok":l.reason,roomForSims:l.roomFor})}return $(await n.call("setup",r,{timeoutMs:15*6e4,requestId:`setup-${Date.now()}`}))}case"grow":case"shrink":{const o=await ti(n,t,N(a,"template"));return $(await n.call(i,{templateId:o,count:Number(a[0]??1)},{timeoutMs:30*6e4,requestId:`${i}-${Date.now()}`}))}case"acquire":{const o=await ti(n,t,N(a,"template"));const r=await n.acquire({templateId:o,count:Number(a[0]??1),purpose:N(a,"purpose")??"CLI",launch:a.includes("--launch")});$(r);console.error("Holding these sims. Press Ctrl-C to release them.");await new Promise(l=>process.once("SIGINT",()=>l()));await n.release(r.leaseId,r.epoch);return $("Released.")}case"remove-template":if(!a[0])throw new d("BAD_REQUEST",`Usage: ${t} remove-template <id>`);return $(await n.call("removeTemplate",{templateId:a[0]},{timeoutMs:30*6e4,requestId:`rmt-${a[0]}-${Date.now()}`}));case"park":case"wake":case"reset":case"rebuild":case"delete":if(!a[0])throw new d("BAD_REQUEST",`Usage: ${t} ${i} <udid>`);return $(await n.call(i,{udid:a[0]},{timeoutMs:5*6e4,requestId:`${i}-${a[0]}-${Date.now()}`}));case"stop":return $(await n.call("shutdown",{ifIdle:!a.includes("--now")}));case"end-lease":return $(await n.call("endLease",{leaseId:a[0],force:true},{requestId:`end-${a[0]}`}));case"phone":{if(!a[1])throw new d("BAD_REQUEST","phone use needs a phone id or off.",`See: ${t} phone list`);const o=await n.call("settings",{phoneProfile:a[1]});return $(o.phoneProfile==="off"?"Apps now launch as plain simulator apps.":`Apps now launch as ${ce()[o.phoneProfile]?.name??o.phoneProfile}. Apps that are already open keep their old setting until the farm launches them again.`)}case"settings":{if(a.length===0)return $((await n.call("status")).settings);const o={};for(const r of a){const[l,c]=r.split("=");o[l]=c==="true"?true:c==="false"?false:Number.isNaN(Number(c))?c:Number(c)}return $(await n.call("settings",o))}default:$(He(t));process.exitCode=2}}finally{n.close()}}function hn(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]??[])N(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=N(t,"profile");const a=Number(N(t,"metro")??8802);if(i&&!["slim","stock"].includes(i))throw new d("BAD_REQUEST","Use slim or stock.");if(!Number.isInteger(a)||a<1||a>65535)throw new d("BAD_REQUEST","Use a port from 1 to 65535.")}}export{K as PROTOCOL_VERSION,Ie as STATE_VERSION,qe as DEFAULT_SETTINGS,d as FarmError,It as ALWAYS_ENABLED,he as SLIM_CATEGORIES,$t as slimLabels,ne as profileLabels,Ot as profileHash,Qe as bootEnv,Oe as findDataContainer,Gt as readBuoyInstallId,Ht as LoadMeter,zt as parseCpuTime,qt as BUILT_IN_PHONES,Kt as DEFAULT_PHONE,Xe as PHONE_OFF,Te as phoneDir,ce as loadPhones,Vt as savePhone,Jt as defaultCapMB,Xt as profileVars,Ze as joinInsertList,we as launchFilePath,Re as eventsFilePath,Zt as writeLaunchFile,Pe as removeLaunchFile,es as readLaunchFile,et as simLaunchEnv,ts as parseEvents,ss as summarize,Ne as readSummary,is as buildDylib,as as LocalDylibBuilder,cs as Engine,ds as crashLoop,at as SimctlHost,H as farmHome,z as paths,vs as Store,ta as farmOwnedUdids,ks as startFarmd,Ms as nodeLauncher,_s as FarmClient,Bs as connectFarm,be as findRepoRoot,Le as findExampleBuild,Es as defaultSeedDir,pa as farmDefaults,wa as detectAgent,ga as agentLabel,As as measurePhone,St as DEFAULT_ANDROID_PHONE,Hs as BUILT_IN_ANDROID_PHONES,kt as loadAndroidPhones,We as ANDROID_ADB_PORT,Ys as androidHome,Qs as AndroidFarm,Vs as parseGfxinfo,Js as classifyBootLog,bt as androidHelp,ei as runAndroidCommand,He as farmHelp,un as runFarmCommand};
|