@buoy-gg/mcp 7.0.66 → 7.0.67
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-2MSKDRYW.mjs +2 -0
- package/dist/{chunk-OCWGZASK.mjs → chunk-7XCEVM3W.mjs} +1 -1
- package/dist/chunk-AMU2EOGE.mjs +6 -0
- package/dist/{chunk-EPYLVJ7F.mjs → chunk-LDULNQCZ.mjs} +105 -101
- package/dist/cli.js +167 -163
- package/dist/cli.mjs +3 -3
- package/dist/{flowRun-OP4UJXKS.mjs → flowRun-WBOCHITQ.mjs} +1 -1
- package/dist/index.d.mts +88 -88
- package/dist/index.d.ts +88 -88
- package/dist/index.js +103 -99
- package/dist/index.mjs +1 -1
- package/dist/simFarm-OFT42BGC.mjs +1 -0
- package/dist/src-DPWEFWQY.mjs +1 -0
- package/package.json +4 -4
- package/skill/buoy-optimize/MEASURING.md +19 -0
- package/skill/buoy-optimize/SKILL.md +1 -1
- package/dist/chunk-MHL43LJN.mjs +0 -2
- package/dist/chunk-Y7SNXKA2.mjs +0 -6
- package/dist/simFarm-EY4R3A4O.mjs +0 -1
- package/dist/src-XCBUDSR7.mjs +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as R}from"module";const Y=R(import.meta.url);import{proRequired as F,readEntitlement as M}from"./chunk-VKWX4XAY.mjs";import{FarmError as I,agentLabel as q,connectFarm as U,detectAgent as A,findDataContainer as B,nodeLauncher as E,readBuoyInstallId as O}from"./chunk-AMU2EOGE.mjs";import $ from"os";import C from"path";import{z as t}from"zod";var G=s=>({content:[{type:"text",text:s}]});var w=s=>({isError:true,content:[{type:"text",text:s}]});var c=s=>G(JSON.stringify(s,null,2));var k=s=>M().isPro?null:w(F(s));var _=null;var x=()=>void 0;function v(){if(!_){_=A({clientName:x()}).catch(()=>void 0).then(s=>U({label:process.env.BUOY_AGENT_LABEL||(s?q(s):"Buoy MCP"),agent:s,launcher:E(process.argv[1],["farmd"])})).catch(s=>{_=null;throw s})}return _}async function d(s,i,e,o){return(await v()).call(s,i,{timeoutMs:e,requestId:o})}var h=[];function P(s){for(let i=h.length-1;i>=0;i--)if(s(h[i]))h.splice(i,1)}async function L(s,i){const e=()=>h.find(r=>r.buoyDeviceId&&s.endsWith(r.buoyDeviceId));let o=e();if(!o&&h.length){await N().catch(()=>void 0);o=e()}if(!o)return null;try{return{checked:true,...await d("fairness",{leaseId:o.leaseId,epoch:o.epoch,windows:i},3e4)}}catch(r){if(r instanceof I&&r.code==="BAD_REQUEST"&&/Unknown method/.test(r.message)){return{checked:false,why:"This farm is too old to check fairness. Restart Buoy Desktop when the farm is idle."}}return{checked:false,why:r instanceof I?`${r.code}: ${r.message}`:String(r?.message??r)}}}async function N(){const s=await d("status");const i=new Set(h.map(e=>e.leaseId));for(const e of s.sims){if(!e.leaseId||!i.has(e.leaseId))continue;let o=h.find(p=>p.udid===e.udid);if(!o){const p=h.find(g=>g.leaseId===e.leaseId);o={...p,udid:e.udid,buoyDeviceId:void 0};h.push(o)}if(e.buoyDeviceId){o.buoyDeviceId=e.buoyDeviceId;continue}const r=s.templates.find(p=>p.id===e.templateId)?.bundleId;const n=C.join($.homedir(),"Library/Developer/CoreSimulator/Devices",e.udid,"data");const a=r?await B(n,r):null;const l=a?await O(a):null;if(l)o.buoyDeviceId=l}}function y(s){if(s instanceof I&&s.code==="RUN_STOPPED"){return w('RUN_STOPPED: The person stopped this run in Buoy Desktop (reason=user). Stop work on it. Tell them: "You stopped this run in Sims." Start a new run only if they ask.')}if(s instanceof I)return w(`${s.code}: ${s.message}${s.next?`
|
|
2
|
+
Next: ${s.next}`:""}`);return w(`Sim Farm error: ${s?.message??s}`)}var D={leaseId:t.string().describe("The lease id from sim_farm_acquire."),epoch:t.number().int().describe("The epoch from sim_farm_acquire. A stale epoch is refused.")};var S=t.string().optional().describe("Any unique string for this call. Repeating the same call with the same requestId returns the first result instead of acting twice.");var T=t.string().describe("The runId from sim_farm_acquire.");async function j(s,i,e){const o=new Map;const r=Date.now()+e;for(;;){for(const n of i){if(o.has(n))continue;const a=s.connectedDevices().find(l=>l.deviceId.endsWith(n)&&l.tier!=="checking");if(a)o.set(n,a.deviceId)}if(o.size===i.length||Date.now()>=r)return o;await new Promise(n=>setTimeout(n,500))}}function z(s,i){x=()=>s.server.getClientVersion()?.name;s.registerTool("sim_farm_status",{description:"Show the Sim Farm: how many farm simulators exist, which are awake or in use and by whom, free memory and disk, how many more sims fit, templates, leases, and recent events. Farm sims are slim iOS simulators (about 1.5 GB each instead of 5) that the farm makes from a template. Start here before sim_farm_acquire. Set `outside` to also list this Mac's other simulators, which the farm never touches.",inputSchema:{outside:t.boolean().optional().describe("Also list simulators the farm does not own.")}},async({outside:e})=>{try{return c(await d("status",{outside:!!e}))}catch(o){return y(o)}});s.registerTool("sim_farm_setup",{description:"Create or resize the Sim Farm. `create` makes a template sim from an app build and, optionally, a seed folder (signed-in app data); clones are made from it in about 4 s each. Dev-client apps (Expo) need `launchUrl` so they open on Metro instead of the launcher. `grow` / `shrink` change how many sims exist. Use `dryRun` first: it returns the plan, what slim mode turns off (push, StoreKit, app links, widgets, Spotlight\u2026) and whether the Mac has room. You own the pool: Buoy Desktop has no size control. sim_farm_acquire makes sims as needed; `shrink` the ones you no longer need so they stop using disk space.",inputSchema:{mode:t.enum(["create","grow","shrink"]).describe("create = new template; grow/shrink = pool size."),templateId:t.string().optional().describe("For grow/shrink. Defaults to the newest usable template."),count:t.number().int().min(1).max(64).optional().describe("For grow/shrink: how many sims to add or remove."),appPath:t.string().optional().describe("For create: path to a simulator .app build."),seedDir:t.string().nullable().optional().describe("For create: seed folder (Documents/, AsyncStorage/, Preferences/, seed.json). null = no seed."),launchUrl:t.string().optional().describe("For create: URL opened after each launch, e.g. exp+my-app://expo-development-client/?url=http%3A%2F%2Flocalhost%3A8081."),deviceType:t.string().optional().describe("For create: a simctl device type id. Default iPhone 17 Pro."),runtime:t.string().optional().describe("For create: a simctl runtime id. Default iOS 26.3."),profile:t.enum(["slim","stock"]).optional().describe("For create: slim (default) or stock."),metroPort:t.number().int().min(1).max(65535).optional().describe("For create: the Metro port the app loads from. Default 8802."),dryRun:t.boolean().optional().describe("Return the plan and its cost without changing anything."),requestId:S}},async e=>{const o=k("sim_farm_setup");if(o)return o;try{if(e.mode==="create"){const a={appPath:e.appPath,seedDir:e.seedDir,deviceType:e.deviceType??"com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",runtime:e.runtime??"com.apple.CoreSimulator.SimRuntime.iOS-26-3",profile:e.profile??"slim",metroPort:e.metroPort??8802,...e.launchUrl?{launchUrl:e.launchUrl}:{}};if(!a.appPath)return w("create needs appPath.");if(a.seedDir===void 0)return w("create needs seedDir, or seedDir: null for an app with no seed.");if(e.dryRun)return c({wouldCreateTemplate:a,budget:await d("budget",{ramGB:6,diskGB:4})});return c(await d("setup",a,15*6e4,e.requestId))}let r=e.templateId;if(!r){const a=await d("status");r=a.templates.filter(l=>l.usable).pop()?.id;if(!r)return w("No usable template yet. Run sim_farm_setup with mode create first.")}const n=e.count??1;if(e.dryRun){const a=await d("budget",{ramGB:0,diskGB:e.mode==="grow"?2*n:0});return c({mode:e.mode,templateId:r,count:n,roomForMoreSims:a.roomFor,ok:a.ok,reason:a.reason})}return c(await d(e.mode,{templateId:r,count:n},30*6e4,e.requestId))}catch(r){return y(r)}});s.registerTool("sim_farm_acquire",{description:"Take farm simulators for your work. The person watches your work live in Buoy Desktop, so give a clear `goal` and a `labels` entry per sim. Returns a run (runId, deadlineAt), a lease (leaseId + epoch) and exact sims (UDID, name, and buoyDeviceId once the app ran: the 8-character tail that its list_devices id ends with; with launch, also deviceId, the full id to pass to other tools). Parked sims are booted and new ones cloned as needed, within the Mac's memory and disk limits. This MCP keeps the lease alive while it runs; release it with sim_farm_finish when done. Only ever target the returned UDIDs: never `booted`, which picks a random simulator when many run. While working, send sim_farm_report when a sim starts, passes or fails. The run stops at deadlineAt unless you ask for more time with sim_farm_extend. If any call returns RUN_STOPPED, the person stopped you: stop and tell them.",inputSchema:{count:t.number().int().min(1).max(64).describe("How many sims. There is no fixed cap: the farm gives as many as this Mac's memory and disk allow. Use allowPartial to take what fits."),goal:t.string().max(200).optional().describe("One short sentence the person sees on the run card, e.g. 'Make the menu list scroll faster'. With runId, the run's goal is used if you leave this out."),labels:t.array(t.string().max(80)).optional().describe("One label per sim, in order, e.g. ['Idea 1: memo rows', 'Idea 2: flat list']."),kind:t.enum(["try-ideas","run-tests","reproduce-bug","explore"]).optional().describe("What sort of work this is."),runId:t.string().optional().describe("Add these sims to a run you already have, instead of starting a new one."),purpose:t.string().optional().describe("Old name for goal. Use goal."),templateId:t.string().optional().describe("Defaults to the newest usable template."),launch:t.boolean().optional().describe("Launch the app on each sim and wait (up to about 30 s) until it joins Buoy. Each sim then has deviceId for other tools."),allowPartial:t.boolean().optional().describe("Return fewer sims than asked instead of failing."),waitSeconds:t.number().int().min(0).max(1800).optional().describe("Wait this long for sims to free up."),ttlMinutes:t.number().int().min(1).max(1440).optional().describe("How long the run may go. Default 15. Agents are capped (1 hour by default); ask for more later with sim_farm_extend."),requestId:S}},async e=>{const o=k("sim_farm_acquire");if(o)return o;try{let r=e.templateId;if(!r){const u=await d("status");r=u.templates.filter(f=>f.usable).pop()?.id;if(!r)return w("No usable template yet. Run sim_farm_setup with mode create first.")}let n=(e.goal??e.purpose??"").trim();if(!n&&e.runId)n=((await d("status")).runs??[]).find(u=>u.id===e.runId)?.goal??"";if(!n)return w("Give a goal: one short sentence about what you are doing.");const a=await v();const l=await a.acquire({templateId:r,count:e.count,purpose:n,goal:n,labels:e.labels,kind:e.kind,runId:e.runId,launch:e.launch,allowPartial:e.allowPartial,waitMs:(e.waitSeconds??0)*1e3,ttlMs:(e.ttlMinutes??15)*6e4,requestId:e.requestId});for(const u of l.sims){const f=h.findIndex(b=>b.udid===u.udid);if(f>=0)h.splice(f,1);h.push({leaseId:l.leaseId,epoch:l.epoch,runId:l.runId,udid:u.udid,buoyDeviceId:u.buoyDeviceId??void 0})}let p=l;if(e.launch&&i){const u=l.sims.map(m=>m.buoyDeviceId).filter(m=>!!m);const f=u.length?await j(i,u,3e4):new Map;p={...l,sims:l.sims.map(m=>({...m,deviceId:m.buoyDeviceId&&f.get(m.buoyDeviceId)||null}))};const b=l.sims.filter(m=>m.buoyDeviceId&&!f.has(m.buoyDeviceId));if(b.length){p.warning=`The app started on ${b.map(m=>m.name).join(", ")} but has not joined Buoy after 30 s. Run list_devices again in a moment, or take a screenshot with sim_farm_action to see the screen.`}}const g=e.launch?l.sims.filter(u=>!u.buoyDeviceId):[];if(g.length){const u=(await d("status").catch(()=>null))?.templates?.find(b=>b.id===r);const f=u?.metroPort?` on port ${u.metroPort}`:"";return c({...p,warning:`The app did not report a Buoy id on ${g.map(b=>b.name).join(", ")}. It may still be loading, or Metro${f} may be down or broken. Check Metro${f}, then take a screenshot with sim_farm_action to see the screen.`})}return c(p)}catch(r){return y(r)}});s.registerTool("sim_farm_release",{description:"Give one lease's sims back. `fast` (default) stops the app and restores its seeded data in about 2 s; `full` rebuilds each sim from the template. Use `full` after anything changed OS settings (permissions, keychain, location) or after a crash. Releasing your last lease ends the run, unless `keepRun` is true. To end a run with a result, use sim_farm_finish instead.",inputSchema:{...D,reset:t.enum(["fast","full"]).optional(),keepRun:t.boolean().optional().describe("Keep the run open to take more sims into it later.")}},async e=>{try{const o=await v();const r=await o.release(e.leaseId,e.epoch,e.reset??"fast",e.keepRun===true);P(n=>n.leaseId===e.leaseId);return c(r)}catch(o){return y(o)}});s.registerTool("sim_farm_action",{description:"Act on sims in your lease: `screenshot` (returns file paths), `open-url` (deep link, pass `url`), `launch` the app, `reset` (restore seeded app data), or `rebuild` (fresh clone; the UDID changes, the result maps old to new).",inputSchema:{...D,udids:t.array(t.string()).min(1).describe("UDIDs from your lease."),action:t.enum(["screenshot","open-url","launch","reset","rebuild"]),url:t.string().optional().describe("For open-url."),requestId:S}},async e=>{const o=k("sim_farm_action");if(o)return o;try{return c(await d("action",{leaseId:e.leaseId,epoch:e.epoch,udids:e.udids,action:e.action,arg:e.url},10*6e4,e.requestId))}catch(r){return y(r)}});s.registerTool("sim_farm_lock",{description:"Hold or free a Mac-wide lock tied to your lease. `perf-slot` is for fair speed tests: while you hold it the farm boots, clones and screenshots nothing else, and it records how busy the Mac is every second. It waits only for farm work in flight, not for other runs to end, so other sims and other apps may still use the Mac. run_benchmark_batch on your farm sim then marks each run fair or unfair from that record; run the unfair cases again. Measure only while you hold it. Other names guard shared test fixtures (e.g. `ask-buoy-gateway`, `shop`). Locks end with the lease.",inputSchema:{...D,name:t.string().regex(/^[a-z0-9-]{1,40}$/).describe("Lock name, e.g. perf-slot."),hold:t.boolean().describe("true = take it, false = free it."),waitSeconds:t.number().int().min(0).max(1800).optional()}},async e=>{const o=k("sim_farm_lock");if(o)return o;try{const r={leaseId:e.leaseId,epoch:e.epoch,name:e.name,waitMs:(e.waitSeconds??0)*1e3};return c(await d(e.hold?"lock":"unlock",r,(e.waitSeconds??0)*1e3+3e4))}catch(r){return y(r)}});s.registerTool("sim_farm_report",{description:"Tell the person how your run is going. They watch it live in Buoy Desktop. Send one when a sim starts work, passes, fails or needs help, with a short note. `counts` only when you know the full task list. Reports never add time. Pass an increasing `sequence` so a retry is never counted twice.",inputSchema:{runId:T,udid:t.string().optional().describe("The sim this is about. Leave out for the whole run."),state:t.enum(["setting-up","working","waiting","passed","failed","needs-help"]).optional(),note:t.string().max(200).optional().describe("Short and plain, e.g. 'Idea 3: 58 fps, best so far'."),counts:t.object({done:t.number().int().min(0),total:t.number().int().min(0),passed:t.number().int().min(0).optional(),failed:t.number().int().min(0).optional()}).optional(),resultSource:t.enum(["agent","test"]).optional().describe("'test' when a test runner decided pass or fail, 'agent' when you judged it. Default agent."),sequence:t.number().int().min(0).optional()}},async e=>{try{return c(await d("report",e,3e4))}catch(o){return y(o)}});s.registerTool("sim_farm_extend",{description:"Ask for more time on your run before deadlineAt. The farm never goes past the run's cap (capAt). It says how much you got.",inputSchema:{runId:T,minutes:t.number().int().min(1).max(1440).describe("Minutes from now.")}},async e=>{try{return c(await d("extend",e))}catch(o){return y(o)}});s.registerTool("sim_farm_finish",{description:"End your run with a result. Gives back every sim it still holds. The person sees the summary in Buoy Desktop, so make it one or two plain sentences, e.g. 'Idea 3 won: 52 \u2192 58 fps.'",inputSchema:{runId:T,outcome:t.enum(["passed","failed","mixed","unknown"]).optional(),summary:t.string().max(600).optional()}},async e=>{try{const o=await d("finish",e,6e4,`fin-${e.runId}`);P(r=>r.runId===e.runId);return c(o)}catch(o){return y(o)}})}async function W(){const{startFarmd:s}=await import("./src-DPWEFWQY.mjs");const i=await s({hostLabel:"buoy-mcp",idleExitMs:10*6e4,onExit:()=>process.exit(0)});if(!i)process.exit(0);for(const e of["SIGTERM","SIGINT"])process.on(e,()=>void i.stop(e))}export{L as farmFairness,z as registerSimFarmTools,W as runFarmd};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as x}from"module";const B=x(import.meta.url);import{PACKAGE_NAME as l,VERSION as y}from"./chunk-
|
|
1
|
+
import{createRequire as x}from"module";const B=x(import.meta.url);import{PACKAGE_NAME as l,VERSION as y}from"./chunk-LDULNQCZ.mjs";import{spawnSync as p}from"child_process";import i from"fs";import _ from"os";import a from"path";function h(){return{BUOY_VERIFY:"auto"}}var v="https://registry.npmjs.org";var m=3e3;function j(e={}){const t=e.cwd??process.cwd();const r=e.skillSrcDir??a.resolve(__dirname,"../skill");const n=e.log??(c=>process.stdout.write(c+"\n"));const o=A(e,n);const s=[];f(a.join(t,".mcp.json"),"mcpServers",o,t,s);i.mkdirSync(a.join(t,".cursor"),{recursive:true});f(a.join(t,".cursor","mcp.json"),"mcpServers",o,t,s);if(i.existsSync(a.join(t,".vscode"))){f(a.join(t,".vscode","mcp.json"),"servers",o,t,s)}F(r,t,s);k(a.join(t,"CLAUDE.md"),t,s);k(a.join(t,"AGENTS.md"),t,s);n("Buoy MCP configuration written:");for(const c of s)n(" \u2022 "+c);n("");n("Next steps:");n(" 1. Restart your editor (or reconnect the MCP server) to load `buoy`.");n(" 2. Complete account setup, then open an app with the required Buoy tools and sync integration.");n(" 3. Confirm the device and tools are available. Free accounts get the basic MCP tools; Pro adds the rest.");if(o.command==="npx"){n("");n(`The editor launches the server with \`npx -y ${l}@latest\`, so it stays`);n(`Registry access may be needed. Re-run \`npx -y ${l}@latest init\` to refresh configuration.`)}else if(!e.cliPath){n("");n(`This uses a pinned local install (no network on startup). To update it later,`);n(`To update the local package, run: npx -y ${o.args[0]?.replace(/dist[/\\]cli\.js$/,"")??""}@latest init --local`)}}function A(e,t){if(e.cliPath){return{type:"stdio",command:"node",args:[e.cliPath],env:h()}}const r=e.mode??"auto";if(r==="npx"){return g()}if(r==="local"){return b(e,t)}const n=C();if(n.reachable){return g()}t(`\u26A0 npm registry ${n.registry?`(${n.registry}) `:""}looks unreachable \u2014 \`npx @latest\` would hang your editor at startup. Falling back to a pinned local install.`);return b(e,t)}function g(){return{type:"stdio",command:"npx",args:["-y",`${l}@latest`],env:h()}}function b(e,t){const r=e.installDir??process.env.BUOY_MCP_HOME??a.join(_.homedir(),".buoy-mcp");const n=e.registry??v;const o=E(r,n,t);if(o){return{type:"stdio",command:"node",args:[o],env:h()}}t("\u26A0 local install failed \u2014 writing the npx entry instead (see the error above).");return g()}function E(e,t,r){const n=`${l}@${y==="0.0.0-dev"?"latest":y}`;i.mkdirSync(e,{recursive:true});const o=process.platform==="win32"?"npm.cmd":"npm";r(`Installing ${n} into ${e} from ${t} \u2026`);const s=p(o,["install",n,"--prefix",e,"--registry",t,`--@buoy-gg:registry=${t}`,"--no-audit","--no-fund","--loglevel=error"],{stdio:["ignore","ignore","inherit"],encoding:"utf8"});if(s.status!==0){r(`\u26A0 npm install exited with code ${s.status??"?"}${s.error?` (${s.error.message})`:""}.`);return null}const c=a.join(e,"node_modules",l,"dist","cli.js");if(!i.existsSync(c)){r(`\u26A0 install finished but ${c} is missing.`);return null}return c}function C(){const e=R();if(!e)return{reachable:false,registry:null};if(/^https?:\/\/registry\.npmjs\.org\/?$/i.test(e)){return{reachable:true,registry:e}}return{reachable:I(e),registry:e}}function R(){const e=w("@buoy-gg:registry");if(e)return e;const t=w("registry");return t??v}function w(e){const t=process.platform==="win32"?"npm.cmd":"npm";const r=p(t,["config","get",e],{encoding:"utf8",timeout:m});if(r.status!==0||typeof r.stdout!=="string")return null;const n=r.stdout.trim();if(!n||n==="undefined"||n==="null")return null;return n}function I(e){const t=p(process.execPath,["-e",P,e,String(m)],{encoding:"utf8",timeout:m+2e3});return t.status===0}var P=`
|
|
2
2
|
const url = process.argv[1];
|
|
3
3
|
const ms = Number(process.argv[2]) || 3000;
|
|
4
4
|
const c = new AbortController();
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{createRequire as dt}from"module";const bs=dt(import.meta.url);var $=1;var V=1;var le={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};var c=class extends Error{constructor(e,s,t,i=false){super(s);this.code=e;this.next=t;this.retryable=i;this.name="FarmError"}toJSON(){return{code:this.code,message:this.message,next:this.next,retryable:this.retryable}}};import{createHash as ht}from"crypto";var Ie=["com.apple.sharingd"];var ce=[{"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 Ee(){const e=new Set(Ie);const s=new Set;for(const t of ce)for(const i of t.labels)if(!e.has(i))s.add(i);return[...s].sort()}function H(e){return e==="slim"?Ee():[]}function Oe(e){return ht("sha256").update(e+"\n"+H(e).join("\n")).digest("hex").slice(0,16)}import{promises as R,existsSync as De}from"fs";import O from"path";import{AsyncLocalStorage as ut}from"async_hooks";import{createHash as pt,randomBytes as Z}from"crypto";import{promises as G}from"fs";import de from"path";import{randomBytes as mt}from"crypto";import{spawn as ft}from"child_process";var Q=new Set;function he(){return Q.size}function wt(){for(const e of Q){try{e.kill("SIGKILL")}catch{}}}function b(e,s,t={}){const{timeoutMs:i=3e4,maxBytes:a=4*1024*1024}=t;return new Promise(n=>{const o=ft(e,s,{env:t.env??process.env,stdio:[t.input==null?"ignore":"pipe","pipe","pipe"]});Q.add(o);let r="";let l="";let d=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(t.input!=null)o.stdin.end(t.input);const p=setTimeout(()=>{d=true;o.kill("SIGTERM");setTimeout(()=>o.kill("SIGKILL"),2e3).unref?.()},i);o.on("error",u=>{Q.delete(o);clearTimeout(p);n({code:null,stdout:r,stderr:l+String(u),timedOut:d})});o.on("close",u=>{Q.delete(o);clearTimeout(p);n({code:u,stdout:r,stderr:l,timedOut:d})})})}async function D(e,s,t={}){const i=await b(e,s,t);if(i.timedOut)throw new Error(`${e} ${s.slice(0,3).join(" ")} timed out after ${t.timeoutMs??3e4} ms`);if(i.code!==0)throw new Error(`${e} ${s.slice(0,3).join(" ")} failed (${i.code}): ${(i.stderr||i.stdout).trim().slice(0,500)}`);return i.stdout}async function Ae(){const e=await D("ps",["-axww","-o","pid=,ppid=,lstart=,stat=,comm="],{timeoutMs:15e3});const s=await D("ps",["-axww","-o","pid=,command="],{timeoutMs:15e3});const t=new Map;for(const a of s.split("\n")){const n=/^\s*(\d+)\s+(.*)$/.exec(a);if(n)t.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:t.get(o)??n[5].trim()})}return i}function Te(e,s){const t=new Map;const i=new Map;for(const l of e){i.set(l.pid,l);const d=t.get(l.ppid)??[];d.push(l);t.set(l.ppid,d)}const a=[];const n=i.get(s);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 d of t.get(l.pid)??[])o.push(d)}return a}async function z(e){const s=await b("ps",["-o","lstart=","-p",String(e)],{timeoutMs:5e3});const t=s.stdout.trim().replace(/\s+/g," ");return s.code===0&&t?t:null}async function P(e,s){if(!Number.isInteger(e)||e<=0)return false;try{process.kill(e,0)}catch(t){if(t.code!=="EPERM")return false}if(!s)return true;return await z(e)===s}var _=e=>new Promise(s=>setTimeout(s,e));var F=process.env.BUOY_FARM_DISABLED_ROOT||"/private/var/tmp";function $e(e,s=F){if(!/^[0-9A-F-]{36}$/i.test(e))throw new Error(`not a UDID: ${e}`);return de.join(s,`com.apple.CoreSimulator.SimDevice.${e}`)}function Be(e,s=F){return de.join($e(e,s),"disabled.plist")}async function xe(e,s=F){const t=Be(e,s);let i;try{i=await G.lstat(t)}catch{return{}}if(!i.isFile())throw new Error(`refusing ${t}: not a regular file`);const a=await D("plutil",["-convert","json","-o","-",t],{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 gt(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function yt(e){const s=Object.keys(e).sort();let t='<?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 s)t+=` <key>${gt(i)}</key>
|
|
2
|
+
<${e[i]?"true":"false"}/>
|
|
3
|
+
`;return t+"</dict>\n</plist>\n"}async function Re(e,s,t=F){const i=$e(e,t);await G.mkdir(i,{recursive:true});const a=await G.lstat(i);if(!a.isDirectory())throw new Error(`refusing ${i}: not a directory`);const n=await xe(e,t);const o=de.join(i,"buoy-farm-prior.json");let r={};try{r=JSON.parse(await G.readFile(o,"utf8"))}catch{}const l={...n};for(const d of s){if(!(d in r))r[d]=d in n?n[d]:null;l[d]=true}await _e(o,JSON.stringify(r,null,2)+"\n");await _e(Be(e,t),yt(l))}async function kt(e,s,t=F){const i=await xe(e,t);return s.every(a=>i[a]===true)}async function _e(e,s){const t=`${e}.${mt(4).toString("hex")}.tmp`;const i=await G.open(t,"w",420);try{await i.writeFile(s);await i.sync()}finally{await i.close()}await G.rename(t,e)}import{promises as E,existsSync as C,readFileSync as Rs}from"fs";import v from"path";import{createHash as Ne}from"crypto";var je=["@react_buoy_sync_device_id.json","@react_buoy_install.json"];var vt="@buoy~1floating-tool~1*";function ue(e){if(!C(v.join(e,"seed.json")))return`No seed at ${e}. Run: pnpm e2e:pool seed`;if(C(v.join(e,"Documents/buoy-license"))){for(const s of["buoy-gg-license.json","buoy-gg-device-fingerprint.json"]){if(!C(v.join(e,"Documents/buoy-license",s)))return`The seed lacks ${s}.`}}return null}async function St(e){const s=Ne("sha256");async function t(i){let a;try{a=await E.readdir(i,{withFileTypes:true})}catch{return}a.sort((n,o)=>n.name.localeCompare(o.name));for(const n of a){const o=v.join(i,n.name);if(n.isDirectory())await t(o);else{const r=await E.stat(o);s.update(`${v.relative(e,o)}:${r.size}:${Math.floor(r.mtimeMs)}
|
|
4
|
+
`)}}}await t(e);return s.digest("hex").slice(0,16)}async function bt(e){const s=Ne("sha256");const t=v.join(e,"Info.plist");s.update(await E.readFile(t));const i=JSON.parse(await D("plutil",["-convert","json","-o","-",t],{timeoutMs:1e4}));const a=v.join(e,String(i.CFBundleExecutable??""));const n=await E.stat(a);s.update(`${n.size}:${Math.floor(n.mtimeMs)}`);return s.digest("hex").slice(0,16)}async function Mt(e){const s=JSON.parse(await D("plutil",["-convert","json","-o","-",v.join(e,"Info.plist")],{timeoutMs:1e4}));if(!s.CFBundleIdentifier)throw new Error(`${e} has no CFBundleIdentifier`);return String(s.CFBundleIdentifier)}async function ee(e,s){const t=v.join(e,"Containers/Data/Application");let i;try{i=await E.readdir(t)}catch{return null}for(const a of i){const n=v.join(t,a,".com.apple.mobile_container_manager.metadata.plist");if(!C(n))continue;const o=await b("plutil",["-extract","MCMMetadataIdentifier","raw","-o","-",n],{timeoutMs:5e3});if(o.code===0&&o.stdout.trim()===s)return v.join(t,a)}return null}function It(e,s){return v.join(e,"Library/Application Support",s,"RCTAsyncLocalStorage_V1")}async function Pe(e,s,t,i){i();await E.mkdir(s,{recursive:true});const a=["-a","--delete"];for(const n of t)a.push("--exclude",n);a.push(e.replace(/\/?$/,"/"),s.replace(/\/?$/,"/"));i();await D("rsync",a,{timeoutMs:6e4})}async function Ce(e,s,t,i=()=>{}){i();const a=ue(t);if(a)throw new Error(a);const n=[...je.map(l=>`react-buoy/${l}`),`react-buoy/${vt}`];if(C(v.join(t,"Documents")))await Pe(v.join(t,"Documents"),v.join(e,"Documents"),n,i);if(C(v.join(t,"AsyncStorage/manifest.json"))){await Pe(v.join(t,"AsyncStorage"),It(e,s),[],i)}const o=v.join(t,"Preferences",`${s}.plist`);if(C(o)){i();await E.mkdir(v.join(e,"Library/Preferences"),{recursive:true});await E.copyFile(o,v.join(e,"Library/Preferences",`${s}.plist`))}const r=v.join(e,"Documents/react-buoy");try{for(const l of await E.readdir(r)){i();if(l.startsWith("@buoy~1floating-tool~1"))await E.rm(v.join(r,l),{force:true,recursive:true})}}catch{}}async function te(e,s=()=>{}){s();const t=[];const i=v.join(e,"Documents/react-buoy");let a=[];try{a=await E.readdir(i)}catch{return t}for(const n of a){if(je.includes(n)||n.startsWith("@buoy~1floating-tool~1")){s();await E.rm(v.join(i,n),{force:true,recursive:true});t.push(n)}}return t}async function Le(e){let s;try{s=await E.readFile(v.join(e,"Documents/react-buoy/@react_buoy_sync_device_id.json"),"utf8")}catch{return null}try{const t=JSON.parse(s);if(typeof t==="string")return t||null;if(typeof t?.value==="string")return t.value||null}catch{}return s.trim()||null}var Ue=2*60*6e4;var Et=10;var Ot=5;var Dt=.8;var L=e=>Math.round(e*10)/10;var At=e=>{if(!e.length)return 0;const s=[...e].sort((i,a)=>i-a);const t=s.length>>1;return s.length%2?s[t]:(s[t-1]+s[t])/2};var Ge=class{constructor(e,s,t=1e3,i=Date.now){this.host=e;this.target=s;this.periodMs=t;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 s=`${e.leaseId}:${e.udids.join(",")}`;if(s!==this.treeKey||++this.treeAge>=Et){const y=await Promise.all(e.udids.map(k=>this.host.simTree(k)));this.pids=y.flat().map(k=>k.pid);this.treeAge=0;if(s!==this.treeKey){this.prev=null;this.lastProcs=null;this.ticks=0;this.rates={ours:0,graphics:0,gpuPct:null}}this.treeKey=s}const t=this.ticks++;const i=await this.host.loadCounters(this.pids,t<2||t%Ot===0);this.cpuCount=i.cpuCount;const a=this.now();const n=this.prev;this.prev={...i,at:a,leaseId:e.leaseId};const o=y=>(i.hostTotalMs-y)/Math.max(1,i.cpuCount);if(i.pidsCpuMs!==null&&i.graphicsCpuMs!==null){const y=this.lastProcs;const k=y?o(y.hostTotalMs):0;if(y&&k>0){this.rates.ours=Math.max(0,(i.pidsCpuMs-y.pidsCpuMs)/k);this.rates.graphics=Math.max(0,(i.graphicsCpuMs-y.graphicsCpuMs)/k)}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 d=this.rates.ours;const p=this.rates.graphics;this.samples.push({at:Math.round((a+n.at)/2),leaseId:e.leaseId,freeCores:L(Math.max(0,i.cpuCount-l)),ourCores:L(d),graphicsCores:L(p),outsideCores:L(Math.max(0,l-d-p)),gpuPct:this.rates.gpuPct,memLevel:i.memPressureLevel,swapMB:i.swapUsedMB,thermal:i.thermalLevel});const u=a-Ue;while(this.samples.length&&this.samples[0].at<u)this.samples.shift()}finally{this.sampling=false}}before(e,s){for(let t=this.samples.length-1;t>=0;t--){const i=this.samples[t];if(i.at<s)return i.leaseId===e?i:void 0}return void 0}latest(){return this.samples[this.samples.length-1]}verdicts(e,s,t){const i=this.periodMs/2;const a=s.map(o=>{const r=this.samples.filter(d=>d.at>=o.from-i&&d.at<=o.to+i);const l=r.filter(d=>d.leaseId===e);return{w:o,all:r,mine:l}});const n=At(a.filter(o=>o.mine.length).map(o=>pe(o.mine.map(r=>r.outsideCores))));return a.map(({w:o,all:r,mine:l})=>{const d=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()-Ue)){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(d*Dt)){return{...p,reason:"No load record for all of this run. Hold perf-slot for the whole test."}}const u=l.map(f=>f.outsideCores);const y=l.map(f=>f.gpuPct).filter(f=>f!==null);const k=l.map(f=>f.thermal).filter(f=>f!==null);const M={...p,freeCoresMin:Math.min(...l.map(f=>f.freeCores)),outsideCoresAvg:L(pe(u)),outsideCoresMax:Math.max(...u),ourCoresAvg:L(pe(l.map(f=>f.ourCores))),graphicsCoresMax:Math.max(...l.map(f=>f.graphicsCores)),gpuMaxPct:y.length?Math.max(...y):null,swapGrowthMB:Math.round(Math.max(0,l[l.length-1].swapMB-(this.before(e,o.from)?.swapMB??l[0].swapMB))),thermalMax:k.length?Math.max(...k):null};if(M.thermalMax!=null&&M.thermalMax>t.maxThermalLevel){return{...M,reason:"The Mac got hot and slowed itself down. Let it cool, then run again."}}if(l.some(f=>f.memLevel>=4)){return{...M,reason:"The Mac ran low on memory. Close apps or stop sims you don't need."}}if(M.swapGrowthMB>t.maxSwapGrowthMB){return{...M,reason:`The Mac swapped ${M.swapGrowthMB} MB of memory to disk.`}}if(M.freeCoresMin<t.minFreeCores){return{...M,reason:`The Mac ran out of spare CPU (${M.freeCoresMin} cores free, needs ${t.minFreeCores}).`}}const T=L(M.outsideCoresMax-n);if(T>t.maxSwingCores){return{...M,reason:`Other work on the Mac jumped by ${T} cores during this run.`}}return{...M,fair:true}})}};function pe(e){return e.length?e.reduce((s,t)=>s+t,0)/e.length:0}function Fe(e){const s=e.trim().split(":").map(Number);if(!s.length||s.some(t=>!Number.isFinite(t)))return 0;return Math.round(s.reduce((t,i)=>t*60+i,0)*1e3)}var W=1024**3;var me="Buoy Farm ";var fe=".buoy-farm.json";var Tt=120;var $t=180;var we=9e4;var We=500;var qe=200;var Bt=3;var j=["done","failed","stopped","interrupted"];var He=["setting-up","working","waiting","passed","failed","needs-help"];var xt={now:()=>performance.now()};var Qe=class{constructor(){this.tails=new Map}run(e,s){const t=this.tails.get(e)??Promise.resolve();const i=t.catch(()=>{}).then(s);this.tails.set(e,i);i.finally(()=>{if(this.tails.get(e)===i)this.tails.delete(e)}).catch(()=>{});return i}};var Rt=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 s=(this.counts.get(e)??0)-1;if(s>0)this.counts.set(e,s);else this.counts.delete(e)}};var _t=class{constructor(e){this.free=e;this.waiting=[]}async use(e){if(this.free>0)this.free--;else await new Promise(s=>this.waiting.push(s));try{return await e()}finally{const s=this.waiting.shift();if(s)s();else this.free++}}};var ze=class{constructor(e){this.simLock=new Qe;this.deadlines=new Map;this.reservations=new Map;this.busy=new Rt;this.ticking=false;this.hardDeadlines=new Map;this.acquiring=new Set;this.budgetLock=new Qe;this.labels=new Map;this.inflight=new Map;this.workContext=new ut;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:(s,t)=>{const i=Reflect.get(s,t);if(typeof i!=="function")return i;return async(...a)=>{this.store.assertActive();const n=await i.apply(s,a);this.store.assertActive();return n}}});this.store=e.store;this.clock=e.clock??xt;this.log=e.log??(()=>{});this.pollMs=e.pollMs??1e3;this.readyTimeoutMs=e.readyTimeoutMs??12e4;this.bootGate=new _t(this.state.settings.maxConcurrentBoots);this.meter=new Ge(this.host,()=>{const s=this.state.locks["perf-slot"];const t=s&&this.state.leases[s.leaseId];return t?{leaseId:t.id,udids:t.sims}:null})}async createTemplate(e){return this.work(void 0,()=>this.createTemplateWork(e))}async cloneSim(e,s){return this.work(void 0,()=>this.cloneSimWork(e,s))}async bootSim(e,s){return this.work(s,()=>this.bootSimWork(e,s))}async parkSim(e,s="idle"){return this.work(void 0,()=>this.parkSimWork(e,s))}async deleteSim(e,s){return this.work(s,()=>this.deleteSimWork(e,s))}async rebuildSim(e,s){return this.work(void 0,()=>this.simLock.run(`rebuild:${e}`,()=>this.rebuildSimWork(e,s)))}async fastReset(e,s){return this.work(void 0,()=>this.fastResetWork(e,s))}async claimOne(e,s){return this.work(e.id,()=>this.claimOneWork(e,s))}async action(e,s,t,i,a,n){this.touch(this.liveLease(e,s,n));const o=this.state.locks["perf-slot"];if(i==="screenshot"&&o&&o.leaseId!==e)throw new c("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,s,t,i,a,n))}async work(e,s){this.store.assertActive();if(this.workContext.getStore()?.active)return s();while(this.state.locks["perf-slot"]&&this.state.locks["perf-slot"].leaseId!==e){await _(this.pollMs);this.store.assertActive()}const t={active:true,leaseId:e};this.activeWork++;try{return await this.workContext.run(t,s)}finally{t.active=false;this.activeWork--}}async files(e){this.checkActive();const s=e();this.fileTasks.add(s);try{const t=await s;this.checkActive();return t}finally{this.fileTasks.delete(s)}}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 s=new Map(e.map(i=>[i.udid,i]));for(const i of Object.values(this.state.sims)){const a=s.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);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?H(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=s.get(i.udid);if(!a){i.usable=false;i.note="Its sim was deleted outside the farm."}else if(!De(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(!s.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 t=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;t.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()+we);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&&!t.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 s=(await this.host.listDevices()).find(t=>t.udid===e);if(!s)throw new c("NOT_FOUND",`No sim ${e} on this Mac.`);return s.dataPath}async isOwned(e){const s=this.state.sims[e]??Object.values(this.state.templates).find(t=>t.udid===e);if(!s)return false;try{const t=JSON.parse(await R.readFile(O.join(await this.dataPath(e),fe),"utf8"));return t.farmId===this.state.farmId}catch{return false}}async assertOwned(e){if(!await this.isOwned(e)){throw new c("NOT_OWNED",`Sim ${e} is not a farm sim. The farm never changes sims it did not make.`)}}async writeMarker(e,s){const t=await this.dataPath(e);await this.files(async()=>{await R.mkdir(t,{recursive:true});this.checkActive();await R.writeFile(O.join(t,fe),JSON.stringify({farmId:this.state.farmId,...s})+"\n")})}farmAwakeGB(){const e=this.state.settings;let s=0;for(const t of Object.values(this.state.sims)){if(["awake","booting","frozen","thawing"].includes(t.power))s+=t.profile==="slim"?e.slimSimGB:e.stockSimGB}return s}async budget(e={ramGB:0,diskGB:0}){const s=this.state.settings;const t=await this.host.hostStats();let i=0;let a=0;for(const k of this.reservations.values()){i+=k.ramGB;a+=k.diskGB}const n=t.totalMemBytes/W;const o=jt(n)*(t.memPressure==="warn"?2:1);const r=t.availableMemBytes/W-i;const l=n-Nt(n,s.reserveRamGB)-this.farmAwakeGB()-i;const d=t.freeDiskBytes/W-a-s.reserveDiskGB;const p=Math.max(0,Math.floor(Math.min(r-o,l,d/s.cloneDiskGB*s.slimSimGB)/s.slimSimGB));const u=(k,M)=>({ok:false,code:k,reason:M,stats:t,roomFor:0});if(t.memPressure==="critical")return u("RAM_LOW","This Mac is low on memory. New sims will wait.");if(e.diskGB>0&&d-e.diskGB<0){return u("DISK_LOW",`Need ${s.reserveDiskGB} GB free after this. This Mac has ${Math.floor(t.freeDiskBytes/W)} 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 y=this.state.locks["perf-slot"];if(y&&(!this.workContext.getStore()?.active||this.workContext.getStore()?.leaseId!==y.leaseId))return u("HOST_BUSY","A speed test is running. New sims will wait.");return{ok:true,stats:t,roomFor:p}}async withReservation(e,s){const t=Z(4).toString("hex");await this.budgetLock.run("budget",async()=>{const i=await this.budget(e);if(!i.ok)throw new c(i.code,i.reason,void 0,true);this.reservations.set(t,e)});try{return await s()}finally{this.reservations.delete(t)}}async health(e,s=[]){const t=[];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))t.push(`${r} is not running`);const n=Je(await this.host.launchdLogTail(e));if(n)t.push(`${n} keeps crashing`);if(t.length===0){const r=O.join(this.store.shotsPath,`${e}.png`);await this.files(()=>R.mkdir(O.dirname(r),{recursive:true}));if(!await this.host.screenshot(e,r,1e4))t.push("screenshot did not come back")}let o=i.length<Tt?"slim":i.length>$t?"stock":"unknown";if(t.length===0&&s.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 d=s.filter(p=>!l.has(p)).length;o=d===0?"slim":d===s.length?"stock":"unknown"}else{o="unknown"}}return{ok:t.length===0,profile:o,faults:t,procs:i.length}}async waitHealthy(e,s=[]){const t=performance.now()+this.readyTimeoutMs;let i=await this.health(e,s);while(!i.ok&&performance.now()<t){await _(this.pollMs);i=await this.health(e,s)}return i}async createTemplateWork(e){if(!["slim","stock"].includes(e.profile)||!Number.isInteger(e.metroPort)||e.metroPort<1||e.metroPort>65535){throw new c("BAD_REQUEST","Use slim or stock and a port from 1 to 65535.")}const s=e.seedDir==null?null:ue(e.seedDir);if(s)throw new c("NO_SEED",s,"Run: pnpm e2e:pool seed");if(!De(O.join(e.appPath,"Info.plist"))){throw new c("BAD_REQUEST",`No app build at ${e.appPath}.`,"Build the app first.")}const t=await Mt(e.appPath);const i=`t-${Z(3).toString("hex")}`;const a=e.name??`${me}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:t,appPath:e.appPath,appHash:await bt(e.appPath),seedDir:e.seedDir??null,seedHash:e.seedDir?await St(e.seedDir):null,launchUrl:e.launchUrl,deviceType:e.deviceType,runtime:e.runtime,xcodeBuild:await this.host.xcodeBuild(),profile:e.profile,profileHash:Oe(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,s){const t=H(e.profile);if(t.length)await this.files(()=>Re(e.udid,t,this.host.disabledRoot));await this.host.boot(e.udid);const i=await this.waitHealthy(e.udid,t);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(()=>Ce(a,e.bundleId,e.seedDir,this.checkActive));else await this.files(()=>te(a,this.checkActive));await this.setPrefs(e.udid,e);if(s){await this.launchApp(e.udid,e);await _(Math.min(15e3,this.pollMs*15));await this.host.terminate(e.udid,e.bundleId)}await this.host.shutdown(e.udid);await this.files(()=>te(a,this.checkActive))}async launchApp(e,s){await this.host.launch(e,s.bundleId);if(s.launchUrl)await this.host.openUrl(e,s.launchUrl)}async setPrefs(e,s){const t=["defaults","write","com.apple.keyboard.preferences"];await this.host.spawn(e,[...t,"AutomaticMinimizationEnabled","-bool","true"]);await this.host.spawn(e,[...t,"DidShowContinuousPathIntroduction","-bool","true"]);await this.host.spawn(e,["defaults","write",s.bundleId,"RCT_jsLocation",`localhost:${s.metroPort}`])}async nextName(){const e=await this.host.listDevices();const s=new Set([...e.map(i=>i.name),...Object.values(this.state.sims).map(i=>i.name)]);let t=this.state.nextIndex;while(s.has(`${me}${String(t).padStart(2,"0")}`))t++;this.state.nextIndex=t+1;return`${me}${String(t).padStart(2,"0")}`}template(e){const s=this.state.templates[e];if(!s)throw new c("NO_TEMPLATE",`No template ${e}.`,"Run sim_farm_setup to make one.");if(!s.usable)throw new c("NO_TEMPLATE",`Template ${s.name} can't be used: ${s.note??"not ready"}.`);return s}async cloneSimWork(e,s,t){s??=await this.nextName();const i=s;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 ee(await this.dataPath(o),a.bundleId);if(l)await this.files(()=>te(l,this.checkActive));const d=t?this.state.leases[t.leaseId]:void 0;if(d&&!this.leaseOverdue(d)){r.leaseId=d.id;d.sims=d.sims.map(p=>p===t.udid?o:p)}r.power="cold";this.store.event({kind:"clone",message:`Made ${s}.`,udid:o});this.store.save();return r}))}async bootSimWork(e,s){await this.assertOwned(e);const t=this.sim(e);if(t.power==="frozen"||t.power==="thawing"){throw new c("BAD_REQUEST",`${t.name} is frozen. Thaw it first.`)}const i=this.state.templates[t.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(t,s);if(t.power==="awake")return t;const o=i?H(i.profile):[];if(o.length&&!await kt(e,o,this.host.disabledRoot)){await this.files(()=>Re(e,o,this.host.disabledRoot))}t.power="booting";t.bootEpoch++;this.store.save();await this.host.boot(e);const r=await this.waitHealthy(e,i?.profile==="slim"?o:[]);t.lastCheckAt=new Date().toISOString();t.profile=r.profile;t.power="awake";if(!r.ok){t.failures++;t.health=t.failures>=2?"broken":"suspect";t.lastError=r.faults.join("; ");this.store.event({kind:"unhealthy",message:`${t.name}: ${t.lastError}`,udid:e});this.store.save();throw new c("HOST_ERROR",`${t.name} did not come up: ${t.lastError}`,"The farm will rebuild it.",true)}t.failures=0;if(t.health==="suspect")t.health="ok";t.idleSince=new Date().toISOString();if(i?.profile==="slim"&&r.profile==="unknown"){t.health="suspect";t.lastError="can't tell if slim applied";this.store.event({kind:"unknown-profile",message:`${t.name}: can't tell if slim worked. Held for now.`,udid:e});this.store.save();throw new c("HOST_ERROR",`${t.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:`${t.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){t.health="suspect";t.lastError="slim did not apply and there is no RAM for a full sim";await this.host.shutdown(e).catch(()=>{});t.power="parked";this.store.save();throw new c("RAM_LOW",`${t.name}: slim didn't apply and there's no room for a full sim.`,void 0,true)}}this.store.save();return t})))}assertLeaseState(e,s){if(!this.state.sims[e.udid])throw new c("NOT_FOUND",`${e.name} is gone.`);if(s){const t=this.state.leases[s];if(e.leaseId!==s||!t||this.leaseOverdue(t)){throw new c("LEASE_EXPIRED",`${e.name} is no longer in lease ${s}.`)}}else if(e.leaseId){throw new c("BAD_REQUEST",`${e.name} is in use. End its lease first.`)}}async parkSimWork(e,s="idle"){await this.assertOwned(e);const t=this.sim(e);await this.simLock.run(e,async()=>{this.assertLeaseState(t);if(this.busy.has(e))throw new c("BAD_REQUEST",`${t.name} is being reset.`);if(t.power==="frozen"||t.power==="thawing")throw new c("BAD_REQUEST",`${t.name} is frozen. Wake it before parking.`);if(t.power!=="awake")return;this.busy.add(e);try{await this.host.shutdown(e);t.power="parked"}finally{this.busy.delete(e)}this.store.event({kind:"park",message:`Parked ${t.name} (${s}).`,udid:e});this.store.save()})}sim(e){const s=this.state.sims[e];if(!s)throw new c("NOT_OWNED",`Sim ${e} is not a farm sim.`);return s}async deleteSimWork(e,s){const t=this.state.orphans[e];if(t){await this.simLock.run(e,async()=>{const a=(await this.host.listDevices()).find(r=>r.udid===e);if(!a)throw new c("NOT_FOUND","This sim is gone.");let n=false;try{const r=JSON.parse(await R.readFile(O.join(a.dataPath,fe),"utf8"));n=r.farmId===this.state.farmId}catch(r){n=r.code==="ENOENT"&&a.name===t.cloneIntentName}if(!n)throw new c("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(()=>R.rm(O.join(this.host.disabledRoot,`com.apple.CoreSimulator.SimDevice.${e}`),{recursive:true,force:true}));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,s);if(i.power==="frozen"||i.power==="thawing")throw new c("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(()=>R.rm(O.join(this.host.disabledRoot,`com.apple.CoreSimulator.SimDevice.${e}`),{recursive:true,force:true}));delete this.state.sims[e];this.store.result(a,"delete",{});this.store.event({kind:"delete",message:`Deleted ${i.name}.`,udid:e})})}async rebuildSimWork(e,s){const t=this.sim(e);const{name:i,templateId:a}=t;await this.assertOwned(e);await this.simLock.run(e,async()=>{this.assertLeaseState(t,s);this.busy.add(e)});const n=this.store.intent("rebuild",{udid:e,name:i,templateId:a});try{await this.deleteSim(e,s);const o=await this.cloneSimWork(a,i,s?{udid:e,leaseId:s}:void 0);this.store.result(n,"rebuild",{udid:o.udid});return o}finally{this.busy.delete(e)}}async fastResetWork(e,s){await this.assertOwned(e);const t=this.sim(e);const i=this.template(t.templateId);await this.simLock.run(e,async()=>{this.assertLeaseState(t,s);if(t.power==="frozen"||t.power==="thawing")throw new c("BAD_REQUEST",`${t.name} is frozen. Wake it first.`);this.busy.add(e);try{if(t.power==="awake")await this.host.terminate(e,i.bundleId);const a=await ee(await this.dataPath(e),i.bundleId);if(!a)throw new Error("app container not found");if(i.seedDir)await this.files(()=>Ce(a,i.bundleId,i.seedDir,this.checkActive));else await this.files(()=>te(a,this.checkActive));t.health="ok";this.store.save()}finally{this.busy.delete(e)}})}async grow(e,s){if(!Number.isInteger(s)||s<1||s>64)throw new c("BAD_REQUEST","count must be 1 to 64.");const t=[];for(let i=0;i<s;i++)t.push(await this.cloneSim(e));return t}async shrink(e,s){if(!Number.isInteger(s)||s<1||s>64)throw new c("BAD_REQUEST","count must be 1 to 64.");const t=["cold","parked","awake"];const i=Object.values(this.state.sims).filter(n=>n.templateId===e&&!n.leaseId&&t.includes(n.power)&&!this.busy.has(n.udid)).sort((n,o)=>t.indexOf(n.power)-t.indexOf(o.power));const a=[];for(const n of i.slice(0,s)){try{await this.deleteSim(n.udid);a.push(n.name)}catch(o){if(!(o instanceof c))throw o}}return a}async removeTemplate(e){return this.work(void 0,async()=>{const s=this.state.templates[e];if(!s)throw new c("NO_TEMPLATE",`No template ${e}.`);const t=Object.values(this.state.sims).filter(o=>o.templateId===e);const i=t.filter(o=>o.leaseId||this.busy.has(o.udid));if(i.length){throw new c("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 t){await this.deleteSim(o.udid);a.push(o.name)}const n=(await this.host.listDevices()).some(o=>o.udid===s.udid);if(n){await this.assertOwned(s.udid);await this.simLock.run(s.udid,async()=>{const o=this.store.intent("delete",{udid:s.udid});await this.host.shutdown(s.udid).catch(()=>{});await this.host.delete(s.udid);await this.files(()=>R.rm(O.join(this.host.disabledRoot,`com.apple.CoreSimulator.SimDevice.${s.udid}`),{recursive:true,force:true}));this.store.result(o,"delete",{})})}delete this.state.templates[e];a.push(s.name);this.store.event({kind:"delete",message:`Removed template ${s.name} and its ${t.length} sim(s).`});return{removed:a}})}leaseOverdue(e){const s=this.clock.now();if(s>(this.hardDeadlines.get(e.id)??Infinity))return true;return!this.acquiring.has(e.id)&&s>(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 c("BAD_REQUEST","ttlMs must be a finite number above zero.")}const s=this.template(e.templateId);if(!Number.isInteger(e.count)||e.count<1||e.count>64)throw new c("BAD_REQUEST","count must be 1 to 64.");const t=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,s.id,t);const a=Date.parse(i.deadlineAt)-Date.now();if(a<3e4)throw new c("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-${Z(4).toString("hex")}`,epoch:1,owner:e.owner,purpose:e.purpose,runId:i.id,templateId:s.id,sims:[],createdAt:new Date().toISOString(),ttlMs:Math.min(t,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,we));o();const r=performance.now()+(e.waitMs??0);const l=()=>{if(!this.state.leases[n.id])throw new c("LEASE_EXPIRED","The lease ended while sims were being prepared.");if(this.leaseOverdue(n))throw new c("LEASE_EXPIRED","The lease ran out of time while sims were being prepared.")};try{while(n.sims.length<e.count){l();o();const d=await this.claimOne(n,s);l();if(d)continue;if(performance.now()>=r)break;if(!n.sims.length&&i.state==="active"&&!Object.keys(i.lanes).length)i.state="waiting";await _(Math.max(this.pollMs,2e3))}if(n.sims.length<e.count&&!e.allowPartial){const d=await this.budget({ramGB:this.state.settings.slimSimGB,diskGB:0});throw new c(d.code??"HOST_BUSY",`Got ${n.sims.length} of ${e.count} sims. ${d.reason??"Others are in use."}`,"Try again later or ask for fewer.",true)}if(n.sims.length===0)throw new c("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(d=>this.launchApp(d,s)));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(d=>this.state.sims[d])}}catch(d){if(this.state.leases[n.id])this.note(i,"farm",`Could not get sims: ${d.message}`);await this.endLease(n.id,"acquire failed","fast","acquire-failed").catch(()=>{});throw d}finally{this.acquiring.delete(n.id);this.labels.delete(n.id)}}async claimOneWork(e,s){const t=Object.values(this.state.sims).filter(o=>o.templateId===s.id&&!o.leaseId&&o.health==="ok"&&!this.busy.has(o.udid));const i=t.find(o=>o.power==="awake")??t.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:s.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(s.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 c&&(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,s){e.sims=e.sims.filter(a=>a!==s);const t=e.runId?this.state.runs[e.runId]:void 0;if(t?.lanes[s])delete t.lanes[s];const i=this.state.sims[s];if(i&&i.leaseId===e.id)i.leaseId=void 0;this.store.save()}async checkIdentities(e,s=6e4){const t=this.template(e.templateId);const i=performance.now()+s;const a=new Map;for(;;){for(const o of e.sims){if(a.has(o))continue;const r=await ee(await this.dataPath(o),t.bundleId);const l=r?await Le(r):null;if(!l)continue;const d=[...a.entries()].find(([,u])=>u===l);if(d)throw new c("ID_CLASH",`${this.state.sims[o].name} and ${this.state.sims[d[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 c("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 _(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,s,t){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 c("LEASE_EXPIRED",`Lease ${e} has ended.`,"Acquire new sims.")}if(i.epoch!==s)throw new c("STALE_EPOCH",`Lease ${e} is at epoch ${i.epoch}, not ${s}.`);if(t&&i.owner.clientId!==t)throw new c("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 c("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 c("LEASE_EXPIRED",`Lease ${e} has expired.`,"Acquire new sims.")}return i}renew(e,s,t){const i=this.liveLease(e,s,t);const a=Math.min(this.clock.now()+Math.min(i.ttlMs,we),this.hardDeadlines.get(i.id)??Infinity);this.deadlines.set(i.id,a);return{expiresInMs:Math.round(a-this.clock.now())}}async release(e,s,t="fast",i,a=false){if(t!=="fast"&&t!=="full")throw new c("BAD_REQUEST","Use fast or full reset.");this.liveLease(e,s,i);return this.endLease(e,"released",t,a?null:"released")}async endLease(e,s,t,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"}this.store.event({kind:"lease-end",message:`${a.owner.label}'s ${a.purpose} ended (${s}).`,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 d of await this.host.clientsOf(r)){if(Date.parse(d.start)>=l)await this.host.kill(d.pid,d.start)}if(t==="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,s){const t=this.state.leases[e];if(t)t.sims=t.sims.filter(i=>i!==s)}async actionWork(e,s,t,i,a,n){const o=this.liveLease(e,s,n);const r={};for(const l of t){if(!o.sims.includes(l))throw new c("NOT_OWNED",`${l} is not in lease ${e}.`);await this.assertOwned(l);this.liveLease(e,s,n);const d=this.template(o.templateId);switch(i){case"screenshot":{const p=this.state.locks["perf-slot"];if(p&&p.leaseId!==o.id)throw new c("HOST_BUSY","A speed test is running. No screenshots right now.",void 0,true);const u=O.join(this.store.shotsPath,`${l}.png`);r[l]=await this.host.screenshot(l,u)?u:null;break}case"open-url":if(!a)throw new c("BAD_REQUEST","open-url needs a url.");await this.host.openUrl(l,a);r[l]="opened";break;case"launch":await this.launchApp(l,d);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 c("LEASE_EXPIRED",`Lease ${e} ended during the rebuild.`);p.leaseId=o.id;o.sims=o.sims.map(k=>k===l?p.udid:k);const u=o.runId?this.state.runs[o.runId]:void 0;const y=u?.lanes[l];if(u&&y){delete u.lanes[l];u.lanes[p.udid]={...y,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 c("BAD_REQUEST",`Unknown action ${i}.`)}}this.store.save();return r}async lock(e,s,t,i=0,a){if(typeof e!=="string"||!/^[a-z0-9-]{1,40}$/.test(e))throw new c("BAD_REQUEST","Lock names are short lowercase words.");this.touch(this.liveLease(s,t,a));if(this.state.locks[e]?.leaseId===s)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(s,t,a);const l=this.state.locks[e];const d=e==="perf-slot"&&(this.activeWork>0||this.busy.size>0||this.pendingBg>0);if(n[0]===o&&!l&&!d){this.state.locks[e]={name:e,leaseId:s,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 _(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,s,t,i){this.liveLease(e,s,i);const a=this.state.settings;const n=Pt(a,this.meter.cpuCount);const o=this.meter.verdicts(e,t,n);return{rules:n,fair:o.filter(r=>r.fair).length,unfair:o.filter(r=>!r.fair).length,runs:o}}unlock(e,s,t,i){this.liveLease(s,t,i);if(this.state.locks[e]?.leaseId===s)delete this.state.locks[e];this.store.save();return{held:false}}async shot(e){if(this.state.locks["perf-slot"])throw new c("HOST_BUSY","A speed test is running. No stills right now.",void 0,true);if(this.shotsInFlight>=Bt)throw new c("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 s=this.sim(e);if(this.state.locks["perf-slot"])throw new c("HOST_BUSY","A speed test is running. No stills right now.",void 0,true);if(s.power!=="awake")throw new c("BAD_REQUEST",`${s.name} is ${s.power}.`);const t=O.join(this.store.shotsPath,`${e}.png`);await this.files(()=>R.mkdir(O.dirname(t),{recursive:true}));if(!await this.host.screenshot(e,t,8e3))throw new c("HOST_ERROR",`No still from ${s.name} in time.`,void 0,true);return{file:t,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 s=this.sim(e);if(s.power==="frozen"||s.power==="thawing")throw new c("BAD_REQUEST",`${s.name} is paused. Wake it first.`);if(s.power!=="awake")await this.bootSim(e,s.leaseId);await this.host.showWindow(e);return"shown"}async tick(){if(this.ticking)return;this.ticking=true;try{for(const t of Object.values(this.state.leases)){const i=!await P(t.owner.pid,t.owner.pidStart);if(i)await this.endLease(t.id,"its owner exited","full","owner-exited");else if(this.leaseOverdue(t))await this.endLease(t.id,"no renewal","full",this.overdueEnd(t))}await this.tickRuns();const e=this.state.settings.parkAfterMinutes;if(e>0){for(const t of Object.values(this.state.sims)){if(t.power!=="awake"||t.leaseId||this.busy.has(t.udid)||!t.idleSince)continue;if(Date.now()-Date.parse(t.idleSince)>e*6e4){await this.parkSim(t.udid).catch(i=>this.log(`park ${t.name}: ${i.message}`))}}}const s=Object.keys(this.state.requests);if(s.length>We)for(const t of s.slice(0,s.length-We))delete this.state.requests[t]}finally{this.ticking=false}}async drain(e=10*6e4){const s=performance.now()+e;while((this.busy.size>0||this.pendingBg>0||this.activeWork>0)&&performance.now()<s)await _(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,s){this.pendingBg++;this.workContext.exit(s).catch(t=>{this.log(`${e}: ${t.message}`);try{this.store.event({kind:"error",message:`${e}: ${t.message}`})}catch{}}).finally(()=>this.pendingBg--)}async once(e,s,t,i){if(!s)return i();const a=`${e}:${s}`;const n=pt("sha256").update(JSON.stringify(t)).digest("hex").slice(0,16);const o=this.state.requests[a];if(o){if(o.hash!==n)throw new c("REQUEST_REUSED",`Request ${s} was already used for a different call.`);return o.result}const r=this.inflight.get(a);if(r){if(r.hash!==n)throw new c("REQUEST_REUSED",`Request ${s} was already used for a different call.`);return r.promise}const l=i();this.inflight.set(a,{hash:n,promise:l});try{const d=await l;this.state.requests[a]={hash:n,result:d,at:new Date().toISOString()};this.store.save();return d}finally{this.inflight.delete(a)}}newRun(e,s,t){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-${Z(4).toString("hex")}`,goal:n.slice(0,200),kind:e.kind?.slice(0,40),owner:e.owner,templateId:s,state:"active",createdAt:new Date(i).toISOString(),deadlineAt:new Date(i+Math.min(t,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 s=e.runId?this.state.runs[e.runId]:void 0;if(s)s.lastActivityAt=new Date().toISOString()}runOfLease(e){return Object.values(this.state.runs).find(s=>s.leases.includes(e))}assertRunOpen(e){if(e.state==="stopping"||e.state==="stopped"){if(e.endedBy==="user")throw new c("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 c("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(j.includes(e.state)||e.state==="stopping")throw new c("RUN_ENDED",`This run has ended (${e.state}).`,"Start a new run.")}ownRun(e,s){const t=this.state.runs[e];if(!t)throw new c("NOT_FOUND",`No run ${e}.`,"Use the runId that sim_farm_acquire returned.");if(s&&t.owner.clientId!==s)throw new c("NOT_OWNED",`Run ${e} belongs to ${t.owner.label}.`);this.assertRunOpen(t);return t}note(e,s,t,i){e.notes.push({at:new Date().toISOString(),by:s,text:t.slice(0,500),udid:i});if(e.notes.length>qe)e.notes.splice(0,e.notes.length-qe)}addLane(e,s){const t=e.runId?this.state.runs[e.runId]:void 0;if(!t)return;const i=this.labels.get(e.id)?.[e.sims.length-1];t.lanes[s.udid]={udid:s.udid,name:s.name,label:i?.slice(0,80),state:"setting-up",at:new Date().toISOString()};if(t.state==="waiting")t.state="active"}overdueEnd(e){return this.clock.now()>=(this.hardDeadlines.get(e.id)??Infinity)?"deadline":"lost"}settleRun(e,s){const t=e.runId?this.state.runs[e.runId]:void 0;if(!t)return;for(const a of e.sims)if(t.lanes[a])t.lanes[a].gone=true;if(j.includes(t.state)||t.state==="stopping"||s===null)return;const i=t.leases.some(a=>this.state.leases[a]);switch(s){case"released":if(!i)this.endRun(t,this.outcomeOf(t)==="failed"?"failed":"done","released");return;case"acquire-failed":if(!i&&!Object.keys(t.lanes).length)this.endRun(t,"failed","acquire-failed");return;case"user":return this.endRun(t,"stopped","user","You stopped this run.");case"deadline":return this.endRun(t,"stopped","deadline","Ran out of time. The sims were taken back.");case"owner-exited":return this.endRun(t,"interrupted","owner-exited","The chat closed. Cleaning up.");case"lost":return this.endRun(t,"interrupted","lost","Lost touch with the chat. Cleaning up.");case"finished":return this.endRun(t,"done","finished")}}endRun(e,s,t,i,a="full"){if(j.includes(e.state))return;e.state="stopping";e.endedBy=t;if(i)this.note(e,t==="user"?"person":"farm",i);for(const n of e.leases){if(this.state.leases[n])void this.endLease(n,i??t,t==="finished"||t==="released"?a:"full",null)}for(const n of Object.values(e.lanes))n.gone=true;e.state=s;e.endedAt=new Date().toISOString();e.outcome=e.outcome??this.outcomeOf(e);this.store.event({kind:"run-end",message:`${e.owner.label}: "${e.goal}" ${s==="done"?"finished":s}.`,runId:e.id})}outcomeOf(e){const s=Object.values(e.lanes);const t=s.filter(a=>a.state==="passed").length;const i=s.filter(a=>a.state==="failed").length;if(!t&&!i)return"unknown";if(i&&t)return"mixed";return i?"failed":"passed"}report(e,s){const t=this.ownRun(e.runId,s);const i=new Date().toISOString();if(e.sequence!==void 0){if(!Number.isInteger(e.sequence)||e.sequence<0)throw new c("BAD_REQUEST","sequence must be a whole number.");if(t.lastSeq!==void 0&&e.sequence<=t.lastSeq)return{applied:false,reason:"already have this report",...this.timeLeft(t)};t.lastSeq=e.sequence}if(e.state!==void 0&&!He.includes(e.state))throw new c("BAD_REQUEST",`state must be one of ${He.join(", ")}.`);if(e.udid!==void 0){const a=t.lanes[e.udid];if(!a)throw new c("NOT_FOUND",`That sim is not in run ${t.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 c("BAD_REQUEST","counts needs whole numbers, with done no more than total.")}t.counts={done:a.done,total:a.total,passed:a.passed,failed:a.failed}}if(e.note)this.note(t,"agent",String(e.note),e.udid);t.lastReportAt=t.lastActivityAt=i;this.store.save();return{applied:true,...this.timeLeft(t)}}extend(e,s,t){const i=this.ownRun(e,t);if(!Number.isFinite(s)||s<=0)throw new c("BAD_REQUEST","minutes must be above zero.");const a=Date.parse(i.deadlineAt);const n=Date.now()+s*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,s,t,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(s&&!["passed","failed","mixed","unknown"].includes(s))throw new c("BAD_REQUEST","outcome must be passed, failed, mixed or unknown.");n.outcome=s??this.outcomeOf(n);if(t)n.summary=t.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,s="you"){const t=this.state.runs[e];if(!t)throw new c("NOT_FOUND",`No run ${e}.`);if(j.includes(t.state))return{state:t.state};this.endRun(t,"stopped","user",s==="you"?"You stopped this run.":`Stopped by ${s}.`);this.store.save();return{state:t.state}}stopAll(e="you"){const s=Object.values(this.state.runs).filter(t=>!j.includes(t.state));for(const t of s)this.stopRun(t.id,e);return{stopped:s.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(j.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 P(a.owner.pid,a.owner.pidStart)){this.endRun(a,"interrupted","owner-exited","The chat closed.");this.store.save()}}const s=this.state.settings.keepRunsHours*36e5;const t=Object.values(this.state.runs).filter(a=>j.includes(a.state)).sort((a,n)=>Date.parse(n.endedAt??n.createdAt)-Date.parse(a.endedAt??a.createdAt));let i=false;t.forEach((a,n)=>{if(n>=200||e-Date.parse(a.endedAt??a.createdAt)>s){delete this.state.runs[a.id];i=true}});if(i)this.store.save()}async status(e={}){const s=await this.budget();const t=Object.values(this.state.sims).map(a=>{const n=a.leaseId?this.state.leases[a.leaseId]:void 0;const o=n?.runId?this.state.runs[n.runId]:void 0;return{...a,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:t.length,awake:t.filter(a=>a.power==="awake").length,leased:t.filter(a=>a.leaseId).length},budget:{roomForMoreSims:s.roomFor,freeDiskGB:Math.floor(s.stats.freeDiskBytes/W),availableMemGB:Math.floor(s.stats.availableMemBytes/W),memPressure:s.stats.memPressure,loadAvg1:Number(s.stats.loadAvg1.toFixed(1)),cpuCount:s.stats.cpuCount},templates:Object.values(this.state.templates),sims:t,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:j.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 s=this.state.settings;const t={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]};if(!e||typeof e!=="object")throw new c("BAD_REQUEST","settings must be an object.");for(const[i,a]of Object.entries(e)){if(!(i in s)||typeof a!==typeof s[i])throw new c("BAD_REQUEST",`Bad setting ${i}.`);const n=t[i];if(n&&(typeof a!=="number"||!Number.isFinite(a)||a<n[0]||a>n[1])){throw new c("BAD_REQUEST",`${i} must be ${n[0]} to ${n[1]}.`)}}for(const[i,a]of Object.entries(e))s[i]=a;this.store.save();return s}};function Nt(e,s){return Math.min(s,Math.max(4,Math.round(e*.375)))}function jt(e){return Math.min(4,Math.max(1.5,e*.1))}function Pt(e,s){const t=i=>Math.round(i*10)/10;return{minFreeCores:t(Math.max(2,e.fairMinFreeShare*s)),maxSwingCores:t(Math.max(1,e.fairMaxSwingShare*s)),maxThermalLevel:e.fairMaxThermalLevel,maxSwapGrowthMB:e.fairMaxSwapGrowthMB}}function Je(e,s=Date.now()-3*6e4){const t=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>=s))continue;const o=t.get(a[2])??[];o.push(n);t.set(a[2],o)}for(const[i,a]of t){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 Ct}from"fs";import q from"os";import ge from"path";var Ke=6e4;var Ye=class{constructor(){this.disabledRoot=F;this.devicesDir=ge.join(q.homedir(),"Library/Developer/CoreSimulator/Devices");this.graphicsPids=[];this.loadCalls=0}simctl(e,s=Ke){return D("xcrun",["simctl",...e],{timeoutMs:s})}async listDevices(){const e=JSON.parse(await this.simctl(["list","devices","--json"],3e4));const s=[];for(const[t,i]of Object.entries(e.devices??{})){for(const a of i){s.push({udid:a.udid,name:a.name,state:a.state,runtime:t,deviceType:a.deviceTypeIdentifier,dataPath:a.dataPath??ge.join(this.devicesDir,a.udid,"data"),available:a.isAvailable!==false})}}return s}async create(e,s,t){return(await this.simctl(["create",e,s,t])).trim()}async clone(e,s){return(await this.simctl(["clone",e,s])).trim()}async boot(e){const s=await b("xcrun",["simctl","boot",e],{timeoutMs:Ke});if(s.code!==0&&!/current state: Booted/i.test(s.stderr)){throw new Error(`simctl boot ${e} failed: ${s.stderr.trim().slice(0,300)}`)}}async shutdown(e){const s=await b("xcrun",["simctl","shutdown",e],{timeoutMs:9e4});if(s.code!==0&&!/current state: Shutdown/i.test(s.stderr)){throw new Error(`simctl shutdown ${e} failed: ${s.stderr.trim().slice(0,300)}`)}}async delete(e){await this.simctl(["delete",e],9e4)}async install(e,s){await this.simctl(["install",e,s],18e4)}async launch(e,s){await this.simctl(["launch","--terminate-running-process",e,s],6e4)}async terminate(e,s){await b("xcrun",["simctl","terminate",e,s],{timeoutMs:2e4})}async openUrl(e,s){await this.simctl(["openurl",e,s],2e4)}async screenshot(e,s,t=1e4){const i=await b("xcrun",["simctl","io",e,"screenshot",s],{timeoutMs:t});return i.code===0&&!i.timedOut}spawn(e,s,t=2e4){return b("xcrun",["simctl","spawn",e,...s],{timeoutMs:t})}async appContainer(e,s){const t=await b("xcrun",["simctl","get_app_container",e,s,"data"],{timeoutMs:2e4});return t.code===0?t.stdout.trim()||null:null}async simTree(e){const s=await Ae();const t=s.find(i=>/launchd_sim/.test(i.command)&&i.command.includes(e));return t?Te(s,t.pid):[]}async signal(e,s){for(const t of e){try{process.kill(t,s)}catch{}}}async launchdLogTail(e,s=256*1024){const t=ge.join(this.disabledRoot,`com.apple.CoreSimulator.SimDevice.${e}`,"launchd.log");try{const i=await Ct.open(t,"r");try{const{size:a}=await i.stat();const n=Math.max(0,a-s);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,s,t,i]=await Promise.all([D("vm_stat",[],{timeoutMs:1e4}),b("sysctl",["-n","kern.memorystatus_vm_pressure_level"],{timeoutMs:5e3}),b("sysctl",["-n","vm.swapusage"],{timeoutMs:5e3}),D("df",["-k",q.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(s.stdout.trim());const l=/used = ([\d.]+)M/.exec(t.stdout)?.[1];const d=i.trim().split("\n").pop()??"";const p=Number(d.split(/\s+/)[3]??0);return{totalMemBytes:q.totalmem(),availableMemBytes:o*a,memPressure:r>=4?"critical":r>=2?"warn":"normal",swapUsedBytes:l?Number(l)*1024*1024:0,freeDiskBytes:p*1024,cpuCount:q.cpus().length,loadAvg1:q.loadavg()[0]}}async showWindow(e){const s=await b("open",["-b","com.apple.iphonesimulator","--args","-CurrentDeviceUDID",e],{timeoutMs:2e4});if(s.code===0)return;await D("open",["-b","com.apple.dt.Devices"],{timeoutMs:2e4})}async loadCounters(e,s=true){if(s&&this.loadCalls++%10===0){const T=await b("pgrep",["-x","SimMetalHost"],{timeoutMs:5e3});this.graphicsPids=T.stdout.split("\n").map(Number).filter(f=>f>0)}const t=q.cpus();let i=0;let a=0;for(const T of t){const f=T.times;const N=f.user+f.nice+f.sys+f.idle+f.irq;a+=N;i+=N-f.idle}const n=[...e,...this.graphicsPids];const[o,r,l,d]=await Promise.all([s&&n.length?b("ps",["-o","pid=,time=","-p",n.join(",")],{timeoutMs:5e3}):null,s?b("ioreg",["-r","-c","IOAccelerator","-d","1"],{timeoutMs:5e3}):null,b("sysctl",["-n","kern.memorystatus_vm_pressure_level","vm.swapusage"],{timeoutMs:5e3}),b("notifyutil",["-g","com.apple.system.thermalpressurelevel"],{timeoutMs:5e3})]);const p=new Set(this.graphicsPids);let u=0;let y=0;for(const T of o?.stdout.split("\n")??[]){const f=/^\s*(\d+)\s+(\S+)/.exec(T);if(!f)continue;const N=Fe(f[2]);if(p.has(Number(f[1])))y+=N;else u+=N}const k=r&&/"Device Utilization %"=(\d+)/.exec(r.stdout);const M=/thermalpressurelevel\s+(\d+)/.exec(d.stdout);return{hostBusyMs:i,hostTotalMs:a,cpuCount:t.length,pidsCpuMs:s?u:null,graphicsCpuMs:s?y:null,gpuPct:k?Number(k[1]):null,memPressureLevel:Number(l.stdout.trim().split("\n")[0])||1,swapUsedMB:Number(/used = ([\d.]+)M/.exec(l.stdout)?.[1]??0),thermalLevel:M?Number(M[1]):null}}async xcodeBuild(){const e=await b("xcodebuild",["-version"],{timeoutMs:2e4});return e.stdout.trim().replace(/\s+/g," ")||"unknown"}async clientsOf(e){const s=await Ae();const t=new Set((await this.simTree(e)).map(a=>a.pid));const i=new Set(Te(s,process.pid).map(a=>a.pid));return s.filter(a=>!i.has(a.pid)&&!t.has(a.pid)&&a.command.includes(e)&&!/launchd_sim|CoreSimulator/.test(a.command))}async kill(e,s){if(!await P(e,s))return;try{process.kill(e,"SIGTERM")}catch{return}for(let t=0;t<20;t++){await new Promise(i=>setTimeout(i,100));if(!await P(e,s))return}if(await P(e,s)){try{process.kill(e,"SIGKILL")}catch{}}}};import Lt from"net";import{chmodSync as Ut,rmSync as Gt,appendFileSync as Ft}from"fs";import{timingSafeEqual as Wt}from"crypto";import{promises as qt,existsSync as ye,mkdirSync as ke,readFileSync as U,renameSync as ve,writeFileSync as se,rmSync as J,openSync as Ht,fsyncSync as Qt,closeSync as zt,chmodSync as Jt,readdirSync as Kt,statSync as Xe}from"fs";import Yt from"os";import I from"path";import{createHash as Xt,randomBytes as K}from"crypto";function B(){return process.env.BUOY_FARM_HOME||I.join(Yt.homedir(),".buoy","farm")}var x=(e=B())=>({home:e,lock:I.join(e,"owner.lock"),lockOwner:I.join(e,"owner.lock","owner.json"),socket:I.join(e,"farmd.sock"),token:I.join(e,"token"),state:I.join(e,"state.json"),journal:I.join(e,"journal.ndjson"),log:I.join(e,"farmd.log"),shots:I.join(e,"shots")});function Se(e=B()){ke(e,{recursive:true,mode:448});try{Jt(e,448)}catch{}}function Ve(e=B()){const s=x(e).token;try{const t=U(s,"utf8").trim();if(t)return t}catch{}Se(e);try{se(s,K(24).toString("hex")+"\n",{mode:384,flag:"wx"})}catch(t){if(t.code!=="EEXIST")throw t}for(let t=0;t<20;t++){const i=U(s,"utf8").trim();if(i)return i;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,25)}throw new Error(`farm token at ${s} is empty`)}async function ie(e=B()){try{return JSON.parse(await qt.readFile(x(e).lockOwner,"utf8"))}catch{return null}}async function ae(e){return!!e&&await P(e.pid,e.start)}async function Vt(e,s){const t=I.join(e,"owner.claim");for(let i=0;i<20;i++){try{ke(t,{mode:448});se(I.join(t,"pid"),`${process.pid}
|
|
5
|
+
${await z(process.pid)??""}`);try{return await s()}finally{J(t,{recursive:true,force:true})}}catch(a){if(a.code!=="EEXIST")throw a;const n=Xe(t,{throwIfNoEntry:false});if(n&&Date.now()-n.mtimeMs>3e4){let o=true;try{const[r,l]=U(I.join(t,"pid"),"utf8").split("\n");o=!await P(Number(r),l||void 0)}catch{}if(o){try{ve(t,I.join(e,`owner.claim-dead-${K(4).toString("hex")}`))}catch{}}}await new Promise(o=>setTimeout(o,100))}}return null}async function Zt(e,s,t=B()){Se(t);const i=x(t);const a=await z(process.pid)??"";for(let n=0;n<3;n++){try{ke(i.lock,{mode:448})}catch(r){if(r.code!=="EEXIST")throw r;const l=await ie(t);if(l&&await ae(l))return null;if(!l){await new Promise(u=>setTimeout(u,300));const p=await ie(t);if(p&&await ae(p))return null}const d=await Vt(t,async()=>{const p=await ie(t);if(p&&await ae(p))return false;if(!ye(i.lock))return true;ve(i.lock,I.join(t,`owner.stale-${K(4).toString("hex")}`));return true});if(d===false)return null;continue}const o={pid:process.pid,start:a,version:e,host:s,since:new Date().toISOString()};se(i.lockOwner,JSON.stringify(o),{mode:384});es(t);return{info:o,release(){try{const r=JSON.parse(U(i.lockOwner,"utf8"));if(r.pid!==process.pid)return}catch{return}try{J(i.socket,{force:true})}catch{}J(i.lock,{recursive:true,force:true})}}}return null}function es(e){try{for(const s of Kt(e)){if(s.startsWith("owner.stale-")||s.startsWith("owner.claim-dead-"))J(I.join(e,s),{recursive:true,force:true})}}catch{}}function Ze(){return{version:V,seq:0,farmId:K(6).toString("hex"),nextIndex:1,templates:{},sims:{},orphans:{},leases:{},runs:{},locks:{},requests:{},events:[],settings:{...le}}}var et=e=>Xt("sha256").update(JSON.stringify(e)).digest("hex").slice(0,12);function tt(e,s,t){const i=Ht(e,t,384);try{se(i,s);Qt(i)}finally{zt(i)}}var st=class{constructor(e=B()){this.fenced=false;this.pending=[];this.open=new Map;this.p=x(e);Se(e);this.state=this.load()}get shotsPath(){return this.p.shots}fence(){this.fenced=true}assertActive(){if(this.fenced)throw new Error("This farm has stopped.")}load(){let e=Ze();if(ye(this.p.state)){const a=JSON.parse(U(this.p.state,"utf8"));if(a.version>V){throw new Error(`farm state is version ${a.version}; this farmd understands ${V}. Update Buoy.`)}e={...Ze(),...a,settings:{...le,...a.settings}}}delete e.settings.activeSlots;const s=new Map;const t=new Set;let i=e.seq;if(ye(this.p.journal)){for(const a of U(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(et(r)!==o||n.seq<=e.seq)continue;i=Math.max(i,n.seq);if(n.type==="intent")s.set(n.seq,n);else{s.delete(n.seq);t.add(n.seq)}}}for(const a of e.openIntents??[]){if(!t.has(a.seq)&&!s.has(a.seq))s.set(a.seq,{...a,type:"intent",sum:""})}this.pending=[...s.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,s){this.assertActive();const t=++this.state.seq;const i={seq:t,at:new Date().toISOString(),type:"intent",op:e,data:s};this.append(i);this.open.set(t,{...i,sum:""});return t}result(e,s,t){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:s,data:t})}append(e){this.assertActive();tt(this.p.journal,JSON.stringify({...e,sum:et(e)})+"\n","a")}save(){this.assertActive();const e=`${this.p.state}.${K(4).toString("hex")}.tmp`;this.state.openIntents=[...this.open.values()].map(({seq:s,at:t,op:i,data:a})=>({seq:s,at:t,op:i,data:a}));tt(e,JSON.stringify(this.state,null,1),"w");ve(e,this.p.state);try{if(Xe(this.p.journal).size>2*1024*1024)J(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 ts(e=B()){try{const s=JSON.parse(U(x(e).state,"utf8"));return new Set([...Object.keys(s.sims??{}),...Object.keys(s.orphans??{}),...Object.values(s.templates??{}).map(t=>t.udid)])}catch{return new Set}}var it=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 ss(e={}){const s=e.home??B();const t=x(s);const i=await Zt($,e.hostLabel??"node",s);if(!i)return null;const a=n=>{try{Ft(t.log,`${new Date().toISOString()} ${n}
|
|
6
|
+
`)}catch{}e.log?.(n)};try{return await is(e,s,i,a)}catch(n){i.release();throw n}}async function is(e,s,t,i){const a=x(s);const n=Ve(s);const o=new st(s);const r=new ze({host:e.host??new Ye,store:o,log:i,pollMs:e.pollMs,readyTimeoutMs:e.readyTimeoutMs});await r.recover();Gt(a.socket,{force:true});const l=new Set;let d=Date.now();let p=false;let u=0;const y=Lt.createServer(w=>{l.add(w);w.on("close",()=>l.delete(w));w.on("error",()=>{});let h="";w.on("data",m=>{h+=m.toString("utf8");if(h.length>1024*1024)return w.destroy();let g;while((g=h.indexOf("\n"))>=0){const S=h.slice(0,g);h=h.slice(g+1);if(S.trim())void M(w,S)}})});const k=(w,h,m)=>{if(!w.destroyed)w.write(JSON.stringify({id:h,...m})+"\n")};async function M(w,h){d=Date.now();let m;try{m=JSON.parse(h)}catch{return k(w,-1,{ok:false,error:{code:"BAD_REQUEST",message:"Not JSON."}})}u++;try{if(!m||typeof m!=="object")throw new c("BAD_REQUEST","Use a request object.");if(!as(m.token,n))throw new c("UNAUTHORIZED","Bad farm token.");if(!m.client||typeof m.client.clientId!=="string"||!m.client.clientId.trim())throw new c("BAD_REQUEST","Each call needs a clientId.");if(p&&!["hello","status"].includes(m.method)){throw new c("HOST_BUSY","The farm is stopping.","Try again in a few seconds.",true)}if(m.v>$&&it.has(m.method)){throw new c("FARMD_VERSION",`This farm runs protocol ${$}; the client speaks ${m.v}.`,"Ask it to stop when idle (method shutdown), then start a newer farm.")}if(m.v<$&&it.has(m.method)){throw new c("READ_ONLY",`This client speaks farm protocol ${m.v}; the farm runs ${$}.`,"Update Buoy to change the farm.")}ns(m);const g=await T(m);k(w,m.id,{ok:true,result:g})}catch(g){const S=g instanceof c?g.toJSON():{code:"HOST_ERROR",message:g.message,retryable:false};k(w,m?.id??-1,{ok:false,error:S})}finally{u--}}async function T(w){const h=w.params??{};const m=w.client;const g=S=>r.once(m.clientId,w.requestId,{m:w.method,q:h},S);switch(w.method){case"hello":return{protocol:$,pid:process.pid,host:t.info.host,farmId:r.state.farmId};case"status":return r.status({outside:h.outside});case"budget":return r.budget({ramGB:h.ramGB??0,diskGB:h.diskGB??0});case"setup":return g(()=>r.createTemplate(h));case"grow":return g(async()=>(await r.grow(h.templateId,h.count)).map(S=>S.name));case"shrink":return g(()=>r.shrink(h.templateId,h.count));case"removeTemplate":return g(()=>r.removeTemplate(h.templateId));case"acquire":return g(async()=>{const{lease:S,run:A,sims:re}=await r.acquire({...h,owner:m});return{runId:A.id,leaseId:S.id,epoch:S.epoch,deadlineAt:A.deadlineAt,capAt:A.capAt,sims:re.map(X=>({udid:X.udid,name:X.name,buoyDeviceId:X.buoyDeviceId,profile:X.profile}))}});case"renew":return r.renew(h.leaseId,h.epoch,m.clientId);case"release":return g(()=>r.release(h.leaseId,h.epoch,h.reset,m.clientId,h.keepRun===true));case"action":return g(()=>r.action(h.leaseId,h.epoch,h.udids,h.action,h.arg,m.clientId));case"lock":return r.lock(h.name,h.leaseId,h.epoch,h.waitMs??0,m.clientId);case"unlock":return r.unlock(h.name,h.leaseId,h.epoch,m.clientId);case"fairness":return r.fairness(h.leaseId,h.epoch,h.windows,m.clientId);case"park":return g(async()=>(await r.parkSim(h.udid,"asked"),"parked"));case"wake":return g(async()=>(await r.bootSim(h.udid)).power);case"reset":return g(async()=>(await r.fastReset(h.udid),"reset"));case"rebuild":return g(async()=>(await r.rebuildSim(h.udid)).udid);case"delete":return g(async()=>(await r.deleteSim(h.udid),"deleted"));case"endLease":{const S=r.state.leases[h.leaseId];if(!S)return{};if(S.owner.clientId!==m.clientId&&h.force!==true){throw new c("NOT_OWNED",`Lease ${h.leaseId} belongs to ${S.owner.label}.`,"Pass force: true only after a person confirms.")}return g(()=>r.endLease(h.leaseId,`ended by ${m.label}`,"full",S.owner.clientId===m.clientId?"released":"user"))}case"report":return g(async()=>r.report(h,m.clientId));case"extend":return g(async()=>r.extend(h.runId,h.minutes,m.clientId));case"finish":return g(async()=>r.finish(h.runId,h.outcome,h.summary,m.clientId));case"stopRun":{const S=r.state.runs[h.runId];if(S&&S.owner.clientId!==m.clientId&&h.force!==true){throw new c("NOT_OWNED",`Run ${h.runId} belongs to ${S.owner.label}.`,"Pass force: true only after a person confirms.")}return g(async()=>r.stopRun(h.runId))}case"stopAll":if(h.force!==true)throw new c("BAD_REQUEST","stopAll needs force: true, after a person confirms.");return g(async()=>r.stopAll());case"settings":return r.setSettings(h);case"shot":return r.shot(h.udid);case"show":return r.show(h.udid);case"shutdown":if(h.ifIdle!==false&&(!r.idle()||u>1))return{stopping:false,reason:"busy"};void oe("asked to stop");return{stopping:true};default:throw new c("BAD_REQUEST",`Unknown method ${w.method}.`)}}await new Promise((w,h)=>{y.once("error",h);y.listen(a.socket,()=>w())});Ut(a.socket,384);i(`farmd ${$} up, pid ${process.pid}, host ${e.hostLabel??"node"}`);const f=setInterval(()=>{void r.tick().catch(h=>i(`tick: ${h.message}`));const w=Date.now()-d;if(e.idleExitMs&&l.size===0&&w>e.idleExitMs){void(async()=>{await r.parkAllIdle();if(r.idle()&&l.size===0&&u===0&&Date.now()-d>e.idleExitMs)await oe("idle")})()}},e.tickMs??5e3);f.unref?.();const N=setInterval(()=>void r.meter.tick().catch(w=>i(`meter: ${w.message}`)),1e3);N.unref?.();let ne=null;function oe(w,h=10*6e4){if(!ne)ne=ct(w,h);return ne}async function ct(w,h){if(p)return;p=true;clearInterval(f);clearInterval(N);i(`farmd stopping: ${w}`);const m=Date.now()+h;while(u>0&&Date.now()<m)await new Promise(A=>setTimeout(A,200));const g=await r.drain(Math.max(0,m-Date.now()));let S=false;if(u>0||!g||he()>0){o.save();r.fence();S=true;i(`farmd stopping with ${u} call(s) and ${he()} child process(es) still running; killing them`);wt();const A=Date.now()+5e3;while(he()>0&&Date.now()<A)await new Promise(re=>setTimeout(re,100))}await r.settleFiles();if(!S&&u===0){try{await r.parkAllIdle()}catch{}}for(const A of l)A.destroy();await new Promise(A=>y.close(()=>A()));if(!S){o.save();r.fence()}t.release();e.onExit?.(w)}return{engine:r,owner:t,stop:oe}}function as(e,s){if(typeof e!=="string"||e.length!==s.length)return false;return Wt(Buffer.from(e),Buffer.from(s))}function ns(e){const s=o=>{throw new c("BAD_REQUEST",o)};const t=e.params??{};if(typeof t!=="object"||Array.isArray(t))s("Params must be an object.");const i=(o,r=false)=>{if(r&&t[o]===void 0)return;if(typeof t[o]!=="string"||!t[o].trim())s(`${o} must be text.`)};const a=o=>{if(t[o]!==void 0&&typeof t[o]!=="boolean")s(`${o} must be true or false.`)};const n=(o,r,l,d=false,p=false)=>{const u=t[o];if(p&&u===void 0)return;if(typeof u!=="number"||!Number.isFinite(u)||u<r||u>l||d&&!Number.isInteger(u))s(`${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(t.seedDir!=null)i("seedDir");i("name",true);i("launchUrl",true);a("warmLaunch");if(!["slim","stock"].includes(t.profile))s("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(t.labels!==void 0&&(!Array.isArray(t.labels)||t.labels.some(o=>typeof o!=="string")))s("labels must be a list of text.");if(!Number.isInteger(e.client.pid)||e.client.pid<=0)s("The client needs a valid pid.")}break;case"release":if(t.reset!==void 0&&!["fast","full"].includes(t.reset))s("Use fast or full reset.");break;case"action":if(!Array.isArray(t.udids)||t.udids.some(o=>typeof o!=="string"||!o))s("udids must be a list of sim ids.");if(!["reset","rebuild","open-url","screenshot","launch"].includes(t.action))s("Unknown sim action.");i("arg",t.action!=="open-url");break;case"lock":case"unlock":i("name");if(!/^[a-z0-9-]{1,40}$/.test(t.name))s("Lock names are short lowercase words.");n("waitMs",0,Number.MAX_SAFE_INTEGER,false,true);break;case"fairness":if(!Array.isArray(t.windows)||t.windows.length>500||t.windows.some(o=>!o||typeof o.id!=="string"||!Number.isFinite(o.from)||!Number.isFinite(o.to)||o.to<o.from)){s("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(t.state!==void 0&&typeof t.state!=="string")s("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 os from"net";import{existsSync as rs}from"fs";import{spawn as ls}from"child_process";import{randomBytes as at}from"crypto";function cs(e,s=["farmd"]){return()=>{const t=ls(process.execPath,[...process.execArgv,e,...s],{detached:true,stdio:"ignore",env:{...process.env}});t.unref()}}var nt=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??B();this.clientIdValue=`c-${at(5).toString("hex")}`}get clientId(){return this.owner?.clientId}async connect(){this.token=Ve(this.home);this.owner={clientId:this.clientIdValue,pid:process.pid,pidStart:await z(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 ie(this.home);if(!await ae(e)){if(!this.opts.launcher)throw new c("HOST_ERROR","The farm is not running.","Start it from Buoy Desktop or `pnpm farm status`.");this.opts.launcher()}const s=Date.now()+(this.opts.startTimeoutMs??2e4);while(Date.now()<s){await _(250);if(await this.tryOpen())return this.checkVersion()}throw new c("HOST_ERROR","The farm did not start in time.",`Check ${x(this.home).log}.`)}async checkVersion(){const e=await this.send("hello",void 0,{});if(e.protocol<$&&this.opts.launcher){const s=await this.send("shutdown",{ifIdle:true},{});if(s.stopping){this.close();await _(500);return this.connect()}}return this}tryOpen(){const e=x(this.home).socket;if(!rs(e))return Promise.resolve(false);return new Promise(s=>{const t=os.createConnection(e);t.once("connect",()=>{this.sock=t;t.on("data",i=>this.onData(i));t.on("close",()=>this.onClose());t.on("error",()=>{});s(true)});t.once("error",()=>s(false))})}onData(e){this.buf+=e.toString("utf8");let s;while((s=this.buf.indexOf("\n"))>=0){const t=this.buf.slice(0,s);this.buf=this.buf.slice(s+1);let i;try{i=JSON.parse(t)}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 c(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 c("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,s,t={}){if(!this.sock&&!this.closed)await this.reconnect();return this.send(e,s,t)}send(e,s,t){if(!this.sock)return Promise.reject(new c("HOST_ERROR","Not connected to the farm.",void 0,true));const i=this.nextId++;const a={id:i,v:$,token:this.token,client:this.owner,method:e,params:s,requestId:t.requestId};return new Promise((n,o)=>{const r=setTimeout(()=>{this.pending.delete(i);o(new c("HOST_ERROR",`Farm call ${e} timed out.`,void 0,true))},t.timeoutMs??3e4);this.pending.set(i,{resolve:n,reject:o,timer:r});this.sock.write(JSON.stringify(a)+"\n")})}async acquire(e){const{requestId:s,...t}=e;const i=s??`acq-${at(4).toString("hex")}`;const a=await this.call("acquire",t,{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 s=this.renewals.get(e);if(s)clearInterval(s);this.renewals.delete(e)}async release(e,s,t="fast",i=false){this.stopRenew(e);return this.call("release",{leaseId:e,epoch:s,reset:t,keepRun:i},{timeoutMs:6e4,requestId:`rel-${e}-${s}`})}close(){this.closed=true;for(const e of[...this.renewals.keys()])this.stopRenew(e);this.sock?.end();this.sock=null}};async function ds(e){return new nt(e).connect()}import Y from"path";import hs from"os";import{existsSync as be,readdirSync as us,statSync as ps}from"fs";function Me(e=process.cwd()){let s=e;for(;;){if(be(Y.join(s,"buoy.tools.json")))return s;const t=Y.dirname(s);if(t===s)return null;s=t}}function ot(){const e=Y.join(hs.homedir(),"Library/Developer/Xcode/DerivedData");let s=null;try{for(const t of us(e)){if(!t.startsWith("exampledevbuild-"))continue;const i=Y.join(e,t,"Build/Products/Debug-iphonesimulator/exampledevbuild.app");if(!be(i))continue;const a=ps(i).mtimeMs;if(!s||a>s.t)s={p:i,t:a}}}catch{}return s?.p??null}function rt(e=Me()){return e?Y.join(e,"example-dev-build/artifacts/pool-seed"):null}async function ms(e=Me()){const s=rt(e);let t=[];let i=[];try{const a=JSON.parse(await D("xcrun",["simctl","list","runtimes","--json"],{timeoutMs:3e4}));t=(a.runtimes??[]).filter(o=>o.isAvailable!==false&&/^iOS/.test(o.name??"")).map(o=>({id:o.identifier,name:o.name}));const n=JSON.parse(await D("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:ot(),seedDir:s&&be(s)?s:null,seedProblem:s?ue(s):"Could not find the repo's seed folder.",runtimes:t,deviceTypes:i,slimTurnsOff:ce.map(a=>({name:a.name,downside:a.downside}))}}import fs from"path";var lt=[{app:"claude",name:"Claude",match:/(^|\/)claude$/i},{app:"codex",name:"Codex",match:/(^|\/)codex$/i},{app:"cursor",name:"Cursor",match:/cursor/i}];async function ws(e){const s=await b("ps",["-o","ppid=,comm=","-p",String(e)],{timeoutMs:3e3});const t=/^\s*(\d+)\s+(.+?)\s*$/.exec(s.stdout);return s.code===0&&t?{ppid:Number(t[1]),comm:t[2]}:null}async function gs(e){const s=await b("lsof",["-a","-p",String(e),"-d","cwd","-Fn"],{timeoutMs:3e3});const t=s.stdout.split("\n").find(i=>i.startsWith("n"));return t?t.slice(1):null}function ys(e){if(!e)return void 0;return lt.find(s=>e.toLowerCase().includes(s.app))}async function ks(e={}){const s=e.env??process.env;let t=e.pid??process.pid;let i=null;for(let p=0;p<5&&t>1;p++){const u=await ws(t).catch(()=>null);if(!u)break;const y=lt.find(k=>k.match.test(u.comm));if(p>0&&y){i={app:y,pid:t};break}t=u.ppid}const a=i?.app??ys(e.clientName);const n=(i?await gs(i.pid).catch(()=>null):null)??process.cwd();const o=(await b("git",["-C",n,"rev-parse","--abbrev-ref","HEAD"],{timeoutMs:3e3}).catch(()=>null))?.stdout.trim();const r=s.CLAUDE_CODE_SESSION_ID?.trim();let l;let d="none";if(r&&(a?.app??"claude")==="claude"){l=`claude:${r}`;d="claude-session"}else if(i){l=`${i.app.app}:${i.pid}:${await z(i.pid)??""}`;d="parent-process"}return{app:a?.app??"other",appName:a?.name??(e.clientName||"Agent"),chatKey:l,chatKeySource:d,project:fs.basename(n)||void 0,projectPath:n,branch:o&&o!=="HEAD"?o:void 0,clientName:e.clientName}}function vs(e){return e.project?`${e.appName} \xB7 ${e.project}`:e.appName}export{$ as PROTOCOL_VERSION,V as STATE_VERSION,le as DEFAULT_SETTINGS,c as FarmError,Ie as ALWAYS_ENABLED,ce as SLIM_CATEGORIES,Ee as slimLabels,H as profileLabels,Oe as profileHash,ee as findDataContainer,Le as readBuoyInstallId,Ge as LoadMeter,Fe as parseCpuTime,ze as Engine,Je as crashLoop,Ye as SimctlHost,B as farmHome,x as paths,st as Store,ts as farmOwnedUdids,ss as startFarmd,cs as nodeLauncher,nt as FarmClient,ds as connectFarm,Me as findRepoRoot,ot as findExampleBuild,rt as defaultSeedDir,ms as farmDefaults,ks as detectAgent,vs as agentLabel};
|