stim 1.33.0 → 1.35.0

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.
Files changed (125) hide show
  1. package/dist/{acquire-artifact-DTh_LxrE.mjs → acquire-artifact-0E_iw7Rf.mjs} +1 -1
  2. package/dist/{act-Cur4YKtK.mjs → act-CyxFP8Vj.mjs} +9 -10
  3. package/dist/{activity-C8kBq9w0.mjs → activity-BQpJpAjA.mjs} +2 -2
  4. package/dist/{agent-device-usage-output-BTRaK_up.mjs → agent-device-usage-output-BoOC3ZF9.mjs} +3 -3
  5. package/dist/{android-D5mCdVl2.mjs → android-CjcJE7uA.mjs} +5 -5
  6. package/dist/{android-BL-QqHjc.mjs → android-YRb1UzSy.mjs} +27 -29
  7. package/dist/{android-project-BDlPnfmL.d.mts → android-project-DhO6el8N.d.mts} +1 -1
  8. package/dist/api.d.mts +1 -1
  9. package/dist/api.mjs +21 -21
  10. package/dist/{artifact-BufzdGbT.mjs → artifact-2NIRz6SC.mjs} +19 -15
  11. package/dist/{artifact-BMjubIP2.mjs → artifact-BG4h_WTC.mjs} +11 -11
  12. package/dist/{auto-placement-D7P98glJ.mjs → auto-placement-CBdWa87P.mjs} +4 -5
  13. package/dist/{browser-web-C74et-Nv.mjs → browser-web-CNlRugJv.mjs} +5 -5
  14. package/dist/{build-DFBGWOTc.mjs → build-CNE3Wo5-.mjs} +15 -16
  15. package/dist/build-artifact-cache-D7B6seMj.mjs +174 -0
  16. package/dist/build-artifact-cache.d.mts +25 -0
  17. package/dist/build-artifact-cache.mjs +2 -0
  18. package/dist/{build-cache-Cqj4FGnX.mjs → build-cache-_fkewiwH.mjs} +6 -1
  19. package/dist/{build-plan-T3Hi24ax.mjs → build-plan-BSgR9yKo.mjs} +5 -5
  20. package/dist/{cli-B2YSjc9s.mjs → cli-DK24VzHi.mjs} +17 -17
  21. package/dist/cli.mjs +1 -1
  22. package/dist/{client-0_Mnfz0a.mjs → client-Dy0eJJtz.mjs} +49 -11
  23. package/dist/{command-output-DWI9tGPU.mjs → command-output-CGxrQ3Bd.mjs} +1 -1
  24. package/dist/{dependencies-CgvBZbXD.mjs → dependencies-IVl2Ga2D.mjs} +27 -30
  25. package/dist/{dev-client-ChsHwgrn.mjs → dev-client-DDApoVvd.mjs} +2 -2
  26. package/dist/{device-android-B8TQP5AX.mjs → device-android-C-biM49_.mjs} +3 -3
  27. package/dist/{ccache-BXtzEL6M.mjs → device-capacity-C0PiTyRb.mjs} +1004 -63
  28. package/dist/device-host-worker.mjs +6 -7
  29. package/dist/{device-B0htCt2u.mjs → device-mOFYiHiw.mjs} +8 -8
  30. package/dist/{device-DOehZpyx.mjs → device-p_cp8IzW.mjs} +6 -6
  31. package/dist/{device-pool-DP4sCeCC.mjs → device-pool-nsMvt2X2.mjs} +2 -2
  32. package/dist/{device-provision-CnNOIxCF.mjs → device-provision-BYYJuRKZ.mjs} +7 -7
  33. package/dist/{doctor-C6Xn96RS.mjs → doctor-BBAb8NLe.mjs} +1 -1
  34. package/dist/{doctor-9GrW5YSP.mjs → doctor-BptE4PaK.mjs} +10 -11
  35. package/dist/{doctor-nRLBoajo.mjs → doctor-RosbBfTV.mjs} +11 -12
  36. package/dist/doctor-fingerprint.mjs +1 -1
  37. package/dist/{doctor-watchman-CDhpC3Oh.mjs → doctor-watchman-CKOnCINh.mjs} +2 -2
  38. package/dist/{eas-build-CpJ4h9tG.mjs → eas-build-BxJdzQnF.mjs} +2 -2
  39. package/dist/{eas-fallback-B3z5nL1g.mjs → eas-fallback-DU2WDF8r.mjs} +2 -2
  40. package/dist/{eas-session-ledger-Bspy-VJQ.mjs → eas-session-ledger-DCUfh6m7.mjs} +1 -1
  41. package/dist/{error-diagnostics-DoLGklYX.mjs → error-diagnostics-D6wlK-yX.mjs} +3 -3
  42. package/dist/{gc-DolXpMSB.mjs → gc-BUkonUfz.mjs} +10 -10
  43. package/dist/{gc-BWoOp9q7.mjs → gc-CvMEytXz.mjs} +2 -2
  44. package/dist/{guide-CmZB0GtP.mjs → guide-BWozWG7D.mjs} +25 -15
  45. package/dist/{hosted-android-ByG-ICuh.mjs → hosted-android-y6K3DKQT.mjs} +2 -2
  46. package/dist/{hosted-client-D19Lv0tg.mjs → hosted-client-Bb89P6an.mjs} +2 -2
  47. package/dist/{hosted-logs-D7anR6Dk.mjs → hosted-logs-DYPsnWMF.mjs} +2 -2
  48. package/dist/{hosted-logs-sync-D182b1eJ.mjs → hosted-logs-sync-DfUJ2GpF.mjs} +4 -4
  49. package/dist/{hosted-macos-D0DDQxvl.mjs → hosted-macos-DsEzYVY_.mjs} +4 -4
  50. package/dist/{hosted-native-BzXIy97W.mjs → hosted-native-C9xQYYFb.mjs} +4 -4
  51. package/dist/{ios-AdhPKXO3.mjs → ios-BCKxjpRp.mjs} +8 -8
  52. package/dist/{ios-dbXzjTxx.mjs → ios-FhMkDfNC.mjs} +19 -21
  53. package/dist/{ios-device-DXbHZfFe.mjs → ios-device-DMOnaH5n.mjs} +1 -1
  54. package/dist/{ios-project-BzfLigfh.mjs → ios-project-PXBDoaii.mjs} +5 -5
  55. package/dist/ios-signing-CCFNjjWU.mjs +202 -0
  56. package/dist/{js-swap-EDVOJmqx.mjs → js-swap-07ikLRJJ.mjs} +3 -3
  57. package/dist/{launch-CKHpthsw.mjs → launch-CTq5gBim.mjs} +13 -13
  58. package/dist/{lightened-Cv4ToJRX.mjs → lightened-DikgC3-S.mjs} +2 -2
  59. package/dist/{logs-IagR9dWI.mjs → logs-DwI3Rkpf.mjs} +5 -5
  60. package/dist/{logs-DCQ3_tGS.mjs → logs-YDMfEohb.mjs} +3 -3
  61. package/dist/{macos-Ch7vuM-G.mjs → macos-BoNM-l6f.mjs} +14 -14
  62. package/dist/{macos-pc0aVVbN.mjs → macos-C_e9f5-5.mjs} +1 -1
  63. package/dist/maintenance-run.mjs +3 -3
  64. package/dist/{native-android-B3CEDq4R.mjs → native-android-Mv4YTrVN.mjs} +11 -11
  65. package/dist/{native-gradle-artifact-inputs-BLnO2hHR.mjs → native-gradle-artifact-inputs-C_TU6wPq.mjs} +2 -2
  66. package/dist/{native-runtime-e1OU8gEN.mjs → native-runtime-oDqT4UES.mjs} +3 -3
  67. package/dist/{native-xcode-inputs-DL3ETb8s.mjs → native-xcode-inputs-DsozghTX.mjs} +1 -1
  68. package/dist/{native-xcode-ios-D4e8k2Jy.mjs → native-xcode-ios-UXnH9NRY.mjs} +13 -13
  69. package/dist/offload-worker.d.mts +6 -1
  70. package/dist/offload-worker.mjs +40 -15
  71. package/dist/{phone-reverses-rvyxW1Fl.mjs → phone-reverses-B9WyCBKQ.mjs} +1 -1
  72. package/dist/{placement-log-nnGnu8mo.mjs → placement-log-D0DZLcJk.mjs} +1 -1
  73. package/dist/{plan-placement-D3JD-T-K.mjs → plan-placement-DqmLrWoX.mjs} +4 -4
  74. package/dist/{ports-CZJJfJ8Q.mjs → ports-C1_1Qgdy.mjs} +1 -1
  75. package/dist/{prebuild-Bhs7TTcz.mjs → prebuild-BptrXmh_.mjs} +6 -6
  76. package/dist/{project-DWEXiBA9.mjs → project-Dqqj3IkW.mjs} +11 -11
  77. package/dist/{react-native-android-C6Y270GS.mjs → react-native-android-Bsm_o4A8.mjs} +18 -18
  78. package/dist/{react-native-build-DaPfzf_e.mjs → react-native-build-BTUcE926.mjs} +4 -4
  79. package/dist/{react-native-doctor-DGMPxkPS.mjs → react-native-doctor-CfsCTKZt.mjs} +4 -4
  80. package/dist/{react-native-ios-dX48_92n.mjs → react-native-ios-_cK2pjZn.mjs} +25 -19
  81. package/dist/{reload-BGwblBJ9.mjs → reload-CXgce4Yo.mjs} +1 -1
  82. package/dist/{reload-DsOByDfy.mjs → reload-DsTMtMDU.mjs} +6 -6
  83. package/dist/{remote-D0uJZ76R.mjs → remote-BsmYHUxH.mjs} +6 -6
  84. package/dist/{result-DuimMZKJ.mjs → result-DK6nTO-M.mjs} +9 -10
  85. package/dist/{server-command-BC0EgMfY.mjs → server-command-Cu2w-UjB.mjs} +2 -2
  86. package/dist/{server-expo-15RjL0ir.mjs → server-expo-CjQwxvIi.mjs} +1 -1
  87. package/dist/server-expo-DbSypdNl.mjs +2 -0
  88. package/dist/{settings-CuP55ieT.mjs → settings-DcmVICCn.mjs} +2 -2
  89. package/dist/{settings-payload-BIGGQ3or.mjs → settings-payload-BoiFMiFq.mjs} +1 -1
  90. package/dist/{settings-write-D85j8mej.mjs → settings-write-B3LzEVwf.mjs} +2 -2
  91. package/dist/{slot-launch-D4oREwhx.mjs → slot-launch-DsQmPdlg.mjs} +2 -2
  92. package/dist/{stage-DKC6tDXu.mjs → stage-Dqk0qvaI.mjs} +1 -1
  93. package/dist/{start-BsEV4S-s.mjs → start-DIFiT2P5.mjs} +5 -5
  94. package/dist/{start-DfPSLc__.mjs → start-GkRBR1e3.mjs} +1 -1
  95. package/dist/{stats-ByEUblPr.mjs → stats-Dz08IopP.mjs} +3 -3
  96. package/dist/{status-C6hLlDqW.mjs → status-DhKv_e8a.mjs} +11 -12
  97. package/dist/{status-FP1MH9qn.mjs → status-Dost__Vn.mjs} +1 -1
  98. package/dist/{status-watch-D8s823CZ.mjs → status-watch-UecLnPQD.mjs} +1 -1
  99. package/dist/status-worker.mjs +1 -1
  100. package/dist/{stop-CpTy6bod.mjs → stop-CcZISot5.mjs} +2 -2
  101. package/dist/{stop-5LKfVv-0.mjs → stop-QFOqgICJ.mjs} +2 -2
  102. package/dist/{stop-BVI2-L7s.mjs → stop-vRe6TQk5.mjs} +9 -9
  103. package/dist/supervisor-run.mjs +7 -8
  104. package/dist/{support-CqyWfZZI.mjs → support-CNqJDBrH.mjs} +3 -3
  105. package/dist/support-DW575Dnx.mjs +2050 -0
  106. package/dist/{swiftpm-artifact-inputs-uq5oV7xR.mjs → swiftpm-artifact-inputs-DQTJTczX.mjs} +1 -1
  107. package/dist/{swiftpm-macos-BuhqYB3n.mjs → swiftpm-macos-BKczZ0k9.mjs} +4 -4
  108. package/dist/{toolchain-D_jotUG7.mjs → toolchain-BDlugtoh.mjs} +1 -1
  109. package/dist/{toolchain-s5ZmG42Z.mjs → toolchain-DRQyCvlp.mjs} +406 -8
  110. package/dist/web-D1m1LKEz.mjs +2 -0
  111. package/dist/{web-DwYCTFdh.mjs → web-TDWjHUT3.mjs} +3 -3
  112. package/dist/web-run.mjs +1 -1
  113. package/dist/{workspaces-B3ahAHZc.mjs → workspaces-CY3KSdC0.mjs} +2 -2
  114. package/dist/{worktree-CrjsPIs2.mjs → worktree-D6myrQ2H.mjs} +1 -1
  115. package/dist/{worktree-BhsML6GV.mjs → worktree-fKKe8j5M.mjs} +10 -10
  116. package/package.json +12 -7
  117. package/dist/device-capacity-BAkETfIl.mjs +0 -867
  118. package/dist/device-ios-DFaYFdar.mjs +0 -716
  119. package/dist/device-lease-run-DpiCnRbZ.mjs +0 -282
  120. package/dist/idle-shutdown-6i8CHoNq.mjs +0 -142
  121. package/dist/ios-signing-D-tSX1iF.mjs +0 -489
  122. package/dist/selection-xS50Mt0V.mjs +0 -791
  123. package/dist/server-expo-gYIypb0-.mjs +0 -2
  124. package/dist/support-D8OH0z98.mjs +0 -287
  125. package/dist/web-cCfM8kwV.mjs +0 -2
@@ -0,0 +1,2050 @@
1
+ import { C as operationState, D as ownership_claim_exports, l as cancellableSleep, n as isTimeoutError, p as withWorkspaceProcessLock, r as reportSignal, t as getExecutor } from "./exec-CGuDzt40.mjs";
2
+ import { D as workspaceId$1, M as withDirLock$1, k as workspaceLogsDir$1 } from "./workspace-state-BdZ-QgmB.mjs";
3
+ import { a as formatElapsed, h as shortUdid, l as phaseLine, r as clockTime } from "./command-output-CGxrQ3Bd.mjs";
4
+ import { $ as unconfirmedKeyFinding, F as diagnoseOutcome, G as realIo, H as outdatedServer, I as diagnoseTailscale, J as setupRemedy, Q as notOnTailnetDiagnosis, R as endpoint$1, T as setDevice, U as parseMachine$1, W as reachMachine, X as diagnoseLocalUnreachable, Y as tailscaleStatusAsync, Z as diagnosisFinding, a as clearDevice, d as getConfigDir, dt as deviceSlotKey, et as readHostPermissions, ft as deviceSlotPlatforms, ht as projectDeviceSlots, k as withConfigLockAsync$1, v as loadConfig$1, w as saveConfig, z as findPeer$1 } from "./config-BW0fAtoK.mjs";
5
+ import { D as iosSimSlimProfileSetting, E as iosSimSlimDefaultSetting, _ as inertSettingWarning, a as SETTING_SHAPE_REMEDY, b as iosProjectDirSetting, p as cacheProviderSettingError, rt as settingShapeErrors, st as unknownSettingKeys, x as iosProjectDirSettingError } from "./settings-B5IBDfTx.mjs";
6
+ import { Ct as selectParked, bt as parkedMaxSetting, gt as dropParked, ht as adoptParked, xt as readParked } from "./android-Iq0M2t2d.mjs";
7
+ import { i as createNdjsonWriter } from "./ndjson-CrjIsGzw.mjs";
8
+ import { _ as withDeviceBootAdmission, _n as APP_READINESS_TIMEOUT_MS, f as runtimeMismatch, g as unknownIosRuntimeRefusal, h as unknownIosDeviceTypeRefusal, l as deviceTypeMismatch, n as DeviceAdmissionRefusal, on as MANIFEST_VERIFY_TIMEOUT_MS, t as DEFAULT_DEVICE_SLOT_WAIT_MS, u as layerNote } from "./device-capacity-C0PiTyRb.mjs";
9
+ import { _t as teardownParkedIosSim, ht as teardownOwnedIosSim } from "./workspaces-CY3KSdC0.mjs";
10
+ import { J as describeDiagnostic, s as cocoapodsInstall } from "./toolchain-DRQyCvlp.mjs";
11
+ import { E as releaseRunLease, S as parseLease, T as raiseLease, b as leaseIsExpired, j as takeLease, v as deviceLeasePath, y as fileLeaseIo } from "./activity-BQpJpAjA.mjs";
12
+ import { A as springBoardRunning, B as reportMemoryCulprits, C as renameIosSim, D as resolveOwnedIosSim, E as resolveIosCreation, F as hostMemoryPressureAdvice, M as waitForSpringBoard, N as configuredIosSimulatorViewer, P as parseIosSimulatorApp, R as readHostMemoryPressure, S as readSpringBoardPid, T as resetIosPrivacy, _ as ownedSimName, a as createOwnedIosSim, d as listAllIosSims, f as listAllIosSimsAsync, h as listIosRuntimesAsync, n as bootIosSim, p as listIosDeviceTypesAsync, u as iosSimulatorFailureAdvice, w as resetIosKeychain, y as parseRuntimeVersion } from "./ios-BdZdNsAj.mjs";
13
+ import { p as resolveOptimizations } from "./errors-DHm_U5gv.mjs";
14
+ import { releaseClaim, tryAcquireClaim } from "@stim-cli/core/ownership-claim";
15
+ import { createHash } from "node:crypto";
16
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
17
+ import { homedir, hostname } from "node:os";
18
+ import { basename, join } from "node:path";
19
+ import { LOG_ROTATE_BYTES, ambientContext, ambientEnv, withDirLockAsync } from "@stim-cli/core";
20
+ import { MACHINE_CREDENTIALS_VERSION, acceptsShape, automaticMachineEnabled, buildMachinesFile, buildMachinesLock, cannotHost, deviceHostMachinesClaims, deviceHostMachinesFile, deviceHostMachinesLock, isJsonObject, localEndpoint, parseMachine, placementWord, readBuildMachines, readDeviceHostMachines, settingDefinition } from "@stim-cli/core/state";
21
+ import chalk from "chalk";
22
+ import { InvalidArgumentError } from "commander";
23
+ import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
24
+ //#region src/device-host/machines.ts
25
+ function note$1(title, detail, fix = null) {
26
+ return {
27
+ code: "device-host-machine",
28
+ level: "note",
29
+ title,
30
+ detail,
31
+ fix
32
+ };
33
+ }
34
+ function configuredMachines() {
35
+ const remote = loadConfig$1()?.remote;
36
+ if (remote !== void 0 && !isJsonObject(remote)) return null;
37
+ const machines = remote?.machines;
38
+ if (machines === void 0) return [];
39
+ return acceptsShape(settingDefinition("remote.machines"), machines) ? machines : null;
40
+ }
41
+ /**
42
+ * The `remote.machines` entries this machine asked for device-host access, in setting order, without the ones the
43
+ * tailnet reports as running another OS than macOS, which can never host; null when the setting is invalid.
44
+ */
45
+ async function hostingMachines(status, signal) {
46
+ const configured = configuredMachines();
47
+ if (configured === null) return null;
48
+ let candidates = configured;
49
+ try {
50
+ const asked = readDeviceHostMachines();
51
+ candidates = configured.filter((machine) => asked.some((each) => each.machine === machine));
52
+ } catch {
53
+ candidates = configured;
54
+ }
55
+ if (!candidates.some((machine) => parseMachine$1(machine)?.transport === "tailscale")) return candidates;
56
+ const current = await (status ? status() : tailscaleStatusAsync(signal));
57
+ signal?.throwIfAborted();
58
+ return candidates.filter((machine) => !cannotHost(current, machine));
59
+ }
60
+ async function store(machines, operation) {
61
+ reportSignal(operation)?.throwIfAborted();
62
+ const write = () => {
63
+ reportSignal(operation)?.throwIfAborted();
64
+ const file = deviceHostMachinesFile();
65
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
66
+ try {
67
+ writeFileSync(tmp, `${JSON.stringify({
68
+ version: MACHINE_CREDENTIALS_VERSION,
69
+ machines
70
+ }, null, 2)}\n`, { mode: 384 });
71
+ renameSync(tmp, file);
72
+ } finally {
73
+ rmSync(tmp, { force: true });
74
+ }
75
+ };
76
+ const options = { ensureParent: () => mkdirSync(getConfigDir(), { recursive: true }) };
77
+ const signal = reportSignal(operation);
78
+ if (signal) await withDirLockAsync(deviceHostMachinesLock(), write, {
79
+ ...options,
80
+ signal
81
+ });
82
+ else withDirLock$1(deviceHostMachinesLock(), write, options);
83
+ }
84
+ /**
85
+ * Reports the device-host approval of each remote machine, separate from its build approval. Only --fix makes a setup
86
+ * ticket or forgets credentials; every server key stays pinned.
87
+ */
88
+ async function inspectDeviceHostMachines({ fix, version = "<version>", tickets = /* @__PURE__ */ new Map(), operation, confirmKey }, io = realIo, entries = configuredMachines()) {
89
+ if (entries === null) return {
90
+ findings: [note$1("Invalid remote.machines setting", "Use a remote object with machines as an array of tailnet names. Existing hosting credentials and pinned keys are preserved.", "Run `stim guide settings` and correct the setting before running doctor again.")],
91
+ machines: []
92
+ };
93
+ const unavailable = (state, finding) => ({
94
+ findings: [finding],
95
+ machines: entries.map((machine) => ({
96
+ machine,
97
+ state
98
+ }))
99
+ });
100
+ const unreadable = () => unavailable("credentials-unavailable", note$1("Hosting credentials are unreadable", `Stim preserves ${deviceHostMachinesFile()} and its pinned keys.`, "Restore the existing file from a trusted backup or restore read access before running doctor again."));
101
+ if (!entries.length) {
102
+ if (!fix) return {
103
+ findings: [],
104
+ machines: []
105
+ };
106
+ try {
107
+ if (!readDeviceHostMachines().length) return {
108
+ findings: [],
109
+ machines: []
110
+ };
111
+ } catch {
112
+ return unreadable();
113
+ }
114
+ }
115
+ const claim = tryAcquireClaim({
116
+ root: deviceHostMachinesClaims(),
117
+ mode: "exclusive",
118
+ label: "device-host approval"
119
+ });
120
+ if (!claim.acquired) {
121
+ releaseClaim(claim.pending);
122
+ return unavailable("busy", note$1("Device-host approval is in use", "Another doctor run holds the hosting credential claim. Run doctor again after it finishes."));
123
+ }
124
+ try {
125
+ let credentials;
126
+ try {
127
+ credentials = readDeviceHostMachines();
128
+ } catch {
129
+ return unreadable();
130
+ }
131
+ if (fix) {
132
+ const kept = credentials.filter((each) => entries.includes(each.machine));
133
+ if (kept.length !== credentials.length) {
134
+ await store(kept, operation);
135
+ credentials = kept;
136
+ }
137
+ }
138
+ if (!entries.length) return {
139
+ findings: [],
140
+ machines: []
141
+ };
142
+ const tailnet = entries.some((entry) => parseMachine$1(entry)?.transport !== "local");
143
+ const status = tailnet ? await io.status() : null;
144
+ const inspected = {
145
+ findings: [],
146
+ machines: []
147
+ };
148
+ let off = null;
149
+ if (tailnet && !isJsonObject(status)) {
150
+ off = await diagnoseTailscale(io);
151
+ inspected.findings.push(note$1("Remote machines are unreachable", `remote.machines names remote machines. ${off.message}`, off.remedy));
152
+ }
153
+ const self = isJsonObject(status) && isJsonObject(status.Self) ? status.Self : {};
154
+ const deviceName = (typeof self.HostName === "string" && self.HostName ? self.HostName : hostname()).replace(/[\p{Cc}\p{Cf}]/gu, "").trim().slice(0, 64) || "Mac";
155
+ const namedNodes = /* @__PURE__ */ new Set();
156
+ for (const machine of new Set(entries)) {
157
+ const parsed = parseMachine$1(machine);
158
+ if (!parsed) {
159
+ inspected.machines.push({
160
+ machine,
161
+ state: "invalid"
162
+ });
163
+ inspected.findings.push(note$1(`Remote machine ${machine} is not a tailnet name or local: address`, "Expected `name`, `name:port`, `local:<host>` or `local:<host>:port`."));
164
+ continue;
165
+ }
166
+ const local = parsed.transport === "local";
167
+ if (!local && off) {
168
+ inspected.machines.push({
169
+ machine,
170
+ state: "tailscale-off",
171
+ diagnosis: off
172
+ });
173
+ continue;
174
+ }
175
+ const current = local ? null : await io.status();
176
+ if (!local && !isJsonObject(current)) {
177
+ const diagnosis = await diagnoseTailscale(io);
178
+ inspected.machines.push({
179
+ machine,
180
+ state: "tailscale-off",
181
+ diagnosis
182
+ });
183
+ inspected.findings.push(diagnosisFinding("device-host-machine", machine, diagnosis));
184
+ continue;
185
+ }
186
+ const peer = local ? null : findPeer$1(current, parsed.name);
187
+ if (peer === "missing" || peer === "ambiguous") {
188
+ const diagnosis = notOnTailnetDiagnosis(machine, peer === "ambiguous");
189
+ inspected.machines.push({
190
+ machine,
191
+ state: "not-on-tailnet",
192
+ diagnosis
193
+ });
194
+ inspected.findings.push(diagnosisFinding("device-host-machine", machine, diagnosis));
195
+ continue;
196
+ }
197
+ const target = peer ? endpoint$1(peer, parsed.port) : localEndpoint(parsed.name, parsed.port);
198
+ const dnsName = peer ? { dnsName: peer.dnsName } : {};
199
+ const nodeRoute = peer ? `${peer.nodeId}:${parsed.port}` : `local:${parsed.name}:${parsed.port}`;
200
+ if (namedNodes.has(nodeRoute)) {
201
+ inspected.machines.push({
202
+ machine,
203
+ ...dnsName,
204
+ state: "invalid"
205
+ });
206
+ inspected.findings.push(note$1(`Remote machine ${machine} repeats a named node`, "Name each tailnet node and serve port only once in remote.machines."));
207
+ continue;
208
+ }
209
+ namedNodes.add(nodeRoute);
210
+ if (cannotHost(current, machine)) {
211
+ inspected.machines.push({
212
+ machine,
213
+ ...dnsName,
214
+ state: "not-asked"
215
+ });
216
+ continue;
217
+ }
218
+ const credential = credentials.find((each) => each.machine === machine);
219
+ reportSignal(operation)?.throwIfAborted();
220
+ const outcome = await reachMachine({
221
+ machine,
222
+ access: "device-host",
223
+ endpoint: target,
224
+ address: peer?.dnsName ?? parsed.name,
225
+ credential,
226
+ other: () => readBuildMachines().find((each) => each.machine === machine),
227
+ persist: async (next) => {
228
+ credentials = [...credentials.filter((each) => each.machine !== machine), next];
229
+ await store(credentials, operation);
230
+ },
231
+ fix,
232
+ deviceName,
233
+ setupFlags: ["build", "device-host"],
234
+ serverVersion: version,
235
+ io,
236
+ tickets,
237
+ ...local ? { confirmKey: (serverKey) => confirmKey?.(machine, serverKey) ?? Promise.resolve(false) } : {}
238
+ });
239
+ reportSignal(operation)?.throwIfAborted();
240
+ if (outcome.state !== "not-asked" && outcome.credential) {
241
+ const next = outcome.credential;
242
+ if (JSON.stringify(next) !== JSON.stringify(credential)) {
243
+ credentials = [...credentials.filter((each) => each.machine !== machine), next];
244
+ await store(credentials, operation);
245
+ }
246
+ }
247
+ const saved = outcome.state !== "not-asked" ? outcome.credential : void 0;
248
+ const known = {
249
+ machine,
250
+ ...dnsName,
251
+ ...saved?.deviceId ? { deviceId: saved.deviceId } : {},
252
+ ...saved ? { requestedAt: saved.requestedAt } : {}
253
+ };
254
+ if (outcome.state === "approved") {
255
+ const host = readHostPermissions(outcome.result.host);
256
+ if (host && (host.screenRecording === false || host.accessibility === false)) {
257
+ const panes = [...host.screenRecording === false ? ["Screen & System Audio Recording (Screen Recording on macOS 14)"] : [], ...host.accessibility === false ? ["Device Control and Data Access (Accessibility on macOS 26 and earlier)"] : []];
258
+ const detail = [...host.screenRecording === false ? ["Viewing hosted macOS apps needs Screen Recording."] : [], ...host.accessibility === false ? ["Controlling them needs the control permission."] : []];
259
+ inspected.findings.push(note$1(`Remote Mac ${machine} needs ${panes.join(" and ")} for ${host.name}`, detail.join(" "), `On ${machine}, approve ${host.name} in System Settings > Privacy & Security, or run \`stim-server service install\` there again to show the requests.`));
260
+ }
261
+ inspected.machines.push({
262
+ ...known,
263
+ state: "approved",
264
+ ...host ? { host } : {}
265
+ });
266
+ continue;
267
+ }
268
+ if (outcome.state === "pending") {
269
+ inspected.machines.push({
270
+ ...known,
271
+ state: "pending",
272
+ ...outcome.credential.expiresAt ? { expiresAt: outcome.credential.expiresAt } : {}
273
+ });
274
+ inspected.findings.push(note$1(`Remote machine ${machine} has not approved this machine for device hosting yet`, `It does not hold this machine's setup ticket yet${outcome.credential.expiresAt ? `; the ticket expires at ${outcome.credential.expiresAt}` : ""}.`, setupRemedy(machine, outcome.command)));
275
+ continue;
276
+ }
277
+ if (outcome.state === "not-asked") {
278
+ inspected.machines.push({
279
+ ...known,
280
+ state: "not-asked"
281
+ });
282
+ inspected.findings.push(note$1(`Remote machine ${machine} has not approved this machine for device hosting`, "This machine has not asked for hosting access.", "Run `stim doctor --fix` to make a setup ticket and print the command to run there."));
283
+ continue;
284
+ }
285
+ if (outcome.state === "outdated") {
286
+ const outdated = outdatedServer(machine, version, outcome.command);
287
+ inspected.machines.push({
288
+ ...known,
289
+ state: "outdated",
290
+ diagnosis: {
291
+ layer: "compat",
292
+ code: "server-outdated",
293
+ title: "Server is outdated",
294
+ message: outdated.detail,
295
+ remedy: outdated.fix
296
+ }
297
+ });
298
+ inspected.findings.push(note$1(outdated.title, outdated.detail, outdated.fix));
299
+ continue;
300
+ }
301
+ if (outcome.state === "unconfirmed") {
302
+ inspected.machines.push({
303
+ ...known,
304
+ state: "key-unconfirmed",
305
+ fingerprint: outcome.fingerprint
306
+ });
307
+ inspected.findings.push(unconfirmedKeyFinding("device-host-machine", machine, outcome.fingerprint));
308
+ continue;
309
+ }
310
+ if (outcome.state === "unreachable") {
311
+ const failure = {
312
+ entry: machine,
313
+ port: parsed.port,
314
+ target,
315
+ reason: outcome.reason,
316
+ transport: outcome.transport
317
+ };
318
+ const startup = !peer && outcome.transport?.kind === "http" && outcome.transport.status === 503 ? await io.startup?.(target) : null;
319
+ const diagnosis = peer ? await diagnoseOutcome(io, {
320
+ ...failure,
321
+ peer
322
+ }) : diagnoseLocalUnreachable({
323
+ ...failure,
324
+ startup
325
+ });
326
+ inspected.machines.push({
327
+ ...known,
328
+ state: "unreachable",
329
+ diagnosis
330
+ });
331
+ inspected.findings.push(diagnosisFinding("device-host-machine", machine, diagnosis));
332
+ continue;
333
+ }
334
+ inspected.machines.push({
335
+ ...known,
336
+ state: outcome.state
337
+ });
338
+ inspected.findings.push(outcome.state === "key-changed" ? note$1(`Remote machine ${machine} answered with a different server key`, "Stim refuses to connect to a stim-server that does not prove it holds the key pinned at approval.", `If that machine or its Stim home was replaced, remove ${machine} from remote.machines, run \`stim doctor --fix\`, then add it back and run \`stim doctor --fix\` again.`) : outcome.state === "lapsed" ? note$1(`Hosting request to ${machine} lapsed`, `${machine} did not approve this machine before its setup ticket expired at ${outcome.credential.expiresAt}.`, "Run `stim doctor --fix` to make a new ticket.") : note$1(`Remote machine ${machine} no longer accepts this machine for device hosting`, `${outcome.reason} The pinned key is preserved.`, "Run `stim doctor --fix` to ask again."));
339
+ }
340
+ return inspected;
341
+ } finally {
342
+ releaseClaim(claim.acquired);
343
+ }
344
+ }
345
+ //#endregion
346
+ //#region src/offload/build-machines.ts
347
+ /** The `remote.machines` entries that approved this machine for builds, in that order. */
348
+ function pairedMachines(entries = configuredMachines() ?? []) {
349
+ const credentials = readBuildMachines().filter((each) => each.state === "approved");
350
+ return entries.flatMap((entry) => credentials.filter((each) => each.machine === entry));
351
+ }
352
+ async function updateCredentials(change, operation) {
353
+ reportSignal(operation)?.throwIfAborted();
354
+ const dir = getConfigDir();
355
+ const write = () => {
356
+ reportSignal(operation)?.throwIfAborted();
357
+ const file = buildMachinesFile();
358
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
359
+ writeFileSync(tmp, `${JSON.stringify({
360
+ version: MACHINE_CREDENTIALS_VERSION,
361
+ machines: change(readBuildMachines())
362
+ }, null, 2)}\n`, { mode: 384 });
363
+ try {
364
+ renameSync(tmp, file);
365
+ } catch (error) {
366
+ rmSync(tmp, { force: true });
367
+ throw error;
368
+ }
369
+ };
370
+ const options = { ensureParent: () => mkdirSync(dir, { recursive: true }) };
371
+ const signal = reportSignal(operation);
372
+ if (signal) await withDirLockAsync(buildMachinesLock(), write, {
373
+ ...options,
374
+ signal
375
+ });
376
+ else withDirLock$1(buildMachinesLock(), write, options);
377
+ }
378
+ function note(title, detail, fix = null) {
379
+ return {
380
+ code: "build-machine",
381
+ level: "note",
382
+ title,
383
+ detail,
384
+ fix
385
+ };
386
+ }
387
+ const PROBLEM_TITLES = {
388
+ unreachable: "does not answer a build offer",
389
+ checkout: "cannot build an app outside a git checkout",
390
+ "stim-build": "runs an incompatible Stim build",
391
+ arch: "has another CPU architecture",
392
+ xcode: "has another Xcode",
393
+ "macos-sdk": "has another macOS SDK",
394
+ "simulator-sdk": "has another simulator SDK",
395
+ cocoapods: "has no CocoaPods, or another version",
396
+ bundler: "has no Bundler",
397
+ runtime: "has no simulator for this project's iOS runtime",
398
+ jdk: "runs another JDK major version",
399
+ "android-sdk": "has no Android SDK",
400
+ ndk: "lacks this project's NDK",
401
+ "build-tools": "lacks this project's Android build-tools",
402
+ "compile-sdk": "lacks this project's Android compile platform",
403
+ disk: "is low on disk",
404
+ busy: "is too busy to take builds",
405
+ platform: "cannot build this platform"
406
+ };
407
+ const NOTE_TITLES = {
408
+ jdk: "builds Android with its own JDK",
409
+ ndk: "downloads this project's NDK on its first Android build",
410
+ "build-tools": "downloads this project's Android build-tools on its first Android build",
411
+ "compile-sdk": "downloads this project's Android compile platform on its first Android build"
412
+ };
413
+ function commandFix(problem, entry) {
414
+ return problem.commands?.length && problem.lead ? [`On ${entry}, ${problem.lead}:`, ...problem.commands].join("\n") : null;
415
+ }
416
+ function problemFix(problem, entry) {
417
+ const { code } = problem;
418
+ if (problem.followsFrom) return `Fix the ${problem.followsFrom} problem on ${entry} first; this follows from it.`;
419
+ switch (code) {
420
+ case "unreachable": return `Check that stim-server runs on ${entry} and that its tailscale serve route answers, then run \`stim doctor\` again. To keep it running there, run \`stim-server service install --serve\` on ${entry}.`;
421
+ case "checkout": return "Offload syncs the files git lists; run Stim from a git checkout of the app.";
422
+ case "stim-build": return `Update stim-server on ${entry} to a Stim release with the same build compatibility version as this machine (an older stim-server needs the same Stim build): there, run \`stim-server service update --release <version>\` for this machine's release, or \`--from <dir>\` with the packed packages of this machine's checkout.`;
423
+ case "arch": return "Use a remote machine with the same CPU architecture as this machine.";
424
+ case "xcode":
425
+ case "simulator-sdk":
426
+ case "macos-sdk": return commandFix(problem, entry) ?? `Install and select the same Xcode on ${entry} and this Mac (\`xcode-select -p\` on each).`;
427
+ case "cocoapods": return commandFix(problem, entry) ?? `Install the same CocoaPods version on ${entry}, on the PATH its stim-server sets. A build sent there with --remote-build ${entry} still runs; a version that differs rewrites the COCOAPODS line of a committed Podfile.lock.`;
428
+ case "bundler": return `Install Bundler (\`gem install bundler\`) on ${entry}, on the PATH its stim-server's login shell sets.`;
429
+ case "runtime": return commandFix(problem, entry) ?? `Install that iOS simulator runtime on ${entry} with at least one iPhone simulator, or set ios.runtime here to one ${entry} has.`;
430
+ case "jdk": return commandFix(problem, entry) ?? `Start stim-server on ${entry} with JAVA_HOME at a JDK of the same major version as this machine's.`;
431
+ case "android-sdk":
432
+ case "ndk":
433
+ case "build-tools":
434
+ case "compile-sdk": return commandFix(problem, entry) ?? `Install the missing package with sdkmanager in the Android SDK stim-server on ${entry} uses (its ANDROID_HOME, else ~/Library/Android/sdk on macOS or ~/Android/Sdk on Linux).`;
435
+ case "disk": return `Free space on ${entry}'s worker root (server.workerRoot there).`;
436
+ case "platform": return `iOS and macOS builds need a Mac; ${entry} can take Android builds only.`;
437
+ case "busy": return `Builds stay on this machine until ${entry} has capacity. On ${entry}, server.maxLoadPerCore sets the load it accepts and concurrency.maxBuilds how many of its own builds it runs; it takes one offloaded build at a time.`;
438
+ }
439
+ }
440
+ const TRANSIENT = /* @__PURE__ */ new Set(["unreachable", "busy"]);
441
+ const UNPREDICTABLE = /* @__PURE__ */ new Set([
442
+ "unreachable",
443
+ "busy",
444
+ "disk",
445
+ "checkout",
446
+ "cocoapods"
447
+ ]);
448
+ /** Why a build on the machine named for it cannot work, from the toolchain differences found before this machine changes the checkout. */
449
+ function predictedRefusal(entry, problems) {
450
+ const known = problems.filter((problem) => !UNPREDICTABLE.has(problem.code));
451
+ if (known.length === 0) return null;
452
+ return {
453
+ reason: known.map((problem) => problem.reason).join("; "),
454
+ remedy: known.map((problem) => problemFix(problem, entry)).join("\n")
455
+ };
456
+ }
457
+ function offloadFindings(entry, problems, notes, operation) {
458
+ const selected = operation?.env.STIM_REMOTE_BUILD?.trim() || loadConfig$1()?.remote?.build;
459
+ const consequence = typeof selected === "string" && placementWord(selected) === "remote-only" ? "remote.build is remote-only, so automatic builds skip this machine and refuse rather than build on this Mac:" : "Builds fall back to this machine:";
460
+ return [...problems.map((problem) => ({
461
+ code: `build-machine-${problem.code}`,
462
+ level: TRANSIENT.has(problem.code) ? "note" : "cost",
463
+ title: `Remote machine ${entry} ${PROBLEM_TITLES[problem.code]}`,
464
+ detail: `${consequence} ${problem.reason}.${problem.code === "cocoapods" ? ` A build sent there with --remote-build ${entry} still runs.` : ""}`,
465
+ fix: problemFix(problem, entry)
466
+ })), ...notes.map((each) => ({
467
+ code: `build-machine-${each.code}`,
468
+ level: "note",
469
+ title: `Remote machine ${entry} ${NOTE_TITLES[each.code] ?? "needs a first-build download"}`,
470
+ detail: `The build goes there anyway: ${each.reason}.`,
471
+ fix: commandFix(each, entry)
472
+ }))];
473
+ }
474
+ async function inspectMachine(entry, tailnet, deviceName, fix, version, tickets, io, check, operation, confirmKey) {
475
+ const parsed = parseMachine$1(entry);
476
+ if (!parsed) return {
477
+ report: {
478
+ machine: entry,
479
+ state: "invalid"
480
+ },
481
+ finding: note(`Remote machine ${entry} is not a tailnet name or local: address`, "Expected `name`, `name:port`, `local:<host>` or `local:<host>:port`.")
482
+ };
483
+ const local = parsed.transport === "local";
484
+ if (!local && "off" in tailnet) return {
485
+ report: {
486
+ machine: entry,
487
+ state: "tailscale-off",
488
+ diagnosis: tailnet.off
489
+ },
490
+ finding: null
491
+ };
492
+ const status = "status" in tailnet ? tailnet.status : {};
493
+ const peer = local ? null : findPeer$1(status, parsed.name);
494
+ if (peer === "missing" || peer === "ambiguous") {
495
+ const diagnosis = notOnTailnetDiagnosis(entry, peer === "ambiguous");
496
+ return {
497
+ report: {
498
+ machine: entry,
499
+ state: "not-on-tailnet",
500
+ diagnosis
501
+ },
502
+ finding: diagnosisFinding("build-machine", entry, diagnosis)
503
+ };
504
+ }
505
+ const target = peer ? endpoint$1(peer, parsed.port) : localEndpoint(parsed.name, parsed.port);
506
+ const address = peer?.dnsName ?? parsed.name;
507
+ const credential = readBuildMachines().find((each) => each.machine === entry);
508
+ const other = () => {
509
+ try {
510
+ return readDeviceHostMachines().find((each) => each.machine === entry);
511
+ } catch {
512
+ return;
513
+ }
514
+ };
515
+ const persist = (next) => updateCredentials((credentials) => [...credentials.filter((each) => each.machine !== entry), next], operation);
516
+ reportSignal(operation)?.throwIfAborted();
517
+ const outcome = await reachMachine({
518
+ machine: entry,
519
+ access: "build",
520
+ endpoint: target,
521
+ address,
522
+ credential,
523
+ other,
524
+ persist,
525
+ fix,
526
+ deviceName,
527
+ setupFlags: cannotHost(status, entry) ? ["build"] : ["build", "device-host"],
528
+ serverVersion: version,
529
+ io,
530
+ tickets,
531
+ ...local ? { confirmKey: (serverKey) => confirmKey?.(entry, serverKey) ?? Promise.resolve(false) } : {}
532
+ });
533
+ const known = {
534
+ machine: entry,
535
+ ...peer ? { dnsName: peer.dnsName } : {}
536
+ };
537
+ reportSignal(operation)?.throwIfAborted();
538
+ if (outcome.state !== "not-asked" && outcome.credential) {
539
+ const next = outcome.credential;
540
+ if (JSON.stringify(next) !== JSON.stringify(credential)) await updateCredentials((credentials) => [...credentials.filter((each) => each.machine !== entry), next], operation);
541
+ }
542
+ const paired = {
543
+ ...known,
544
+ ...outcome.state !== "not-asked" && outcome.credential?.deviceId ? { deviceId: outcome.credential.deviceId } : {},
545
+ ...outcome.state !== "not-asked" && outcome.credential ? { requestedAt: outcome.credential.requestedAt } : {}
546
+ };
547
+ switch (outcome.state) {
548
+ case "not-asked": return {
549
+ report: {
550
+ ...known,
551
+ state: "not-asked"
552
+ },
553
+ finding: note(`Remote machine ${entry} has not approved this machine for builds`, "This machine has not asked it for build access.", "Run `stim doctor --fix` to make a setup ticket and print the command to run there.")
554
+ };
555
+ case "key-changed": return {
556
+ report: {
557
+ ...paired,
558
+ state: "key-changed"
559
+ },
560
+ finding: note(`Remote machine ${entry} answered with a different server key`, `${address} did not prove it holds the stim-server key this machine pinned at approval. Stim does not connect to it.`, `If that machine or its Stim home was replaced, remove ${entry} from remote.machines, run \`stim doctor --fix\` to forget the old pairing, then add it back and run \`stim doctor --fix\` again.`)
561
+ };
562
+ case "unconfirmed": return {
563
+ report: {
564
+ ...paired,
565
+ state: "key-unconfirmed",
566
+ fingerprint: outcome.fingerprint
567
+ },
568
+ finding: unconfirmedKeyFinding("build-machine", entry, outcome.fingerprint)
569
+ };
570
+ case "pending": return {
571
+ report: {
572
+ ...paired,
573
+ state: "pending",
574
+ ...outcome.credential.expiresAt ? { expiresAt: outcome.credential.expiresAt } : {}
575
+ },
576
+ finding: note(`Remote machine ${entry} has not approved this machine for builds yet`, `It does not hold this machine's setup ticket yet${outcome.credential.expiresAt ? `; the ticket expires at ${outcome.credential.expiresAt}` : ""}.`, setupRemedy(entry, outcome.command))
577
+ };
578
+ case "lapsed": return {
579
+ report: {
580
+ ...paired,
581
+ state: "lapsed"
582
+ },
583
+ finding: note(`Build request to ${entry} lapsed`, `${entry} did not approve this machine before its setup ticket expired at ${outcome.credential.expiresAt}.`, "Run `stim doctor --fix` to make a new ticket.")
584
+ };
585
+ case "revoked": return {
586
+ report: {
587
+ ...paired,
588
+ state: "revoked"
589
+ },
590
+ finding: note(`Remote machine ${entry} no longer accepts this machine for builds`, `${outcome.reason} It was revoked.`, "Run `stim doctor --fix` to ask again.")
591
+ };
592
+ case "outdated": {
593
+ const outdated = outdatedServer(entry, version, outcome.command);
594
+ const diagnosis = {
595
+ layer: "compat",
596
+ code: "server-outdated",
597
+ title: "Server is outdated",
598
+ message: outdated.detail,
599
+ remedy: outdated.fix
600
+ };
601
+ return {
602
+ report: {
603
+ ...paired,
604
+ state: "outdated",
605
+ diagnosis
606
+ },
607
+ finding: note(outdated.title, outdated.detail, outdated.fix)
608
+ };
609
+ }
610
+ case "unreachable": {
611
+ const failure = {
612
+ entry,
613
+ port: parsed.port,
614
+ target,
615
+ reason: outcome.reason,
616
+ transport: outcome.transport
617
+ };
618
+ const startup = !peer && outcome.transport?.kind === "http" && outcome.transport.status === 503 ? await io.startup?.(target) : null;
619
+ const diagnosis = peer ? await diagnoseOutcome(io, {
620
+ ...failure,
621
+ peer
622
+ }) : diagnoseLocalUnreachable({
623
+ ...failure,
624
+ startup
625
+ });
626
+ return {
627
+ report: {
628
+ ...paired,
629
+ state: "unreachable",
630
+ diagnosis
631
+ },
632
+ finding: diagnosisFinding("build-machine", entry, diagnosis)
633
+ };
634
+ }
635
+ }
636
+ const permissions = readHostPermissions(outcome.result.host);
637
+ const host = permissions ? { host: permissions } : {};
638
+ if (!check) return {
639
+ report: {
640
+ ...paired,
641
+ state: "approved",
642
+ ...host
643
+ },
644
+ finding: null
645
+ };
646
+ const { capacity, problems, notes = [] } = await check(outcome.credential);
647
+ return {
648
+ report: {
649
+ ...paired,
650
+ state: "approved",
651
+ ...host,
652
+ offloadable: problems.length === 0,
653
+ reasons: problems.map((problem) => problem.reason),
654
+ problems,
655
+ ...notes.length ? { notes } : {},
656
+ ...capacity ? { capacity } : {}
657
+ },
658
+ finding: null,
659
+ extra: offloadFindings(entry, problems, notes, operation)
660
+ };
661
+ }
662
+ /**
663
+ * Doctor findings and a report for each `remote.machines` entry. The worker's stim-server key is pinned on first
664
+ * contact; every later connection must prove it holds that key. With `fix`, makes a setup ticket for a named machine
665
+ * this machine holds no pairing for, or that revoked it, and forgets pairings of machines no longer named. With
666
+ * `check`, each approved machine is asked for one build offer and reports every reason it would not take this
667
+ * project's build.
668
+ */
669
+ async function inspectBuildMachines({ fix, check = null, version = "<version>", tickets = /* @__PURE__ */ new Map(), operation, confirmKey }, io = realIo, entries = configuredMachines()) {
670
+ if (entries === null) return {
671
+ findings: [note("Invalid remote.machines setting", "Use a remote object with machines as an array of tailnet names. Existing credentials and pinned keys are preserved.", "Run `stim guide settings` and correct the setting before running doctor again.")],
672
+ machines: []
673
+ };
674
+ const unnamed = (each) => !entries.includes(each.machine);
675
+ if (fix && readBuildMachines().some(unnamed)) await updateCredentials((credentials) => credentials.filter((each) => !unnamed(each)), operation);
676
+ if (entries.length === 0) return {
677
+ findings: [],
678
+ machines: []
679
+ };
680
+ const tailnet = entries.some((entry) => parseMachine$1(entry)?.transport !== "local");
681
+ const read = tailnet ? await io.status() : null;
682
+ const view = isJsonObject(read) ? { status: read } : tailnet ? { off: await diagnoseTailscale(io) } : { status: {} };
683
+ const inspection = {
684
+ findings: [],
685
+ machines: []
686
+ };
687
+ if ("off" in view) inspection.findings.push(note("Remote machines are unreachable", `remote.machines names remote machines. ${view.off.message}`, view.off.remedy));
688
+ const self = "status" in view && isJsonObject(view.status.Self) ? view.status.Self : {};
689
+ const deviceName = (typeof self.HostName === "string" && self.HostName ? self.HostName : hostname()).replace(/[\p{Cc}\p{Cf}]/gu, "").trim().slice(0, 64) || "Mac";
690
+ const inspected = await Promise.all(entries.map((entry) => inspectMachine(entry, view, deviceName, fix, version, tickets, io, check, operation, confirmKey)));
691
+ for (const { report, finding, extra = [] } of inspected) {
692
+ inspection.machines.push(report);
693
+ if (finding) inspection.findings.push(finding);
694
+ inspection.findings.push(...extra);
695
+ }
696
+ return inspection;
697
+ }
698
+ //#endregion
699
+ //#region src/engine/device-lease-run.ts
700
+ const LEASE_STEP_FLOOR_MS = 6e4;
701
+ const DEBUG_VERIFY_STEP_MS = MANIFEST_VERIFY_TIMEOUT_MS + APP_READINESS_TIMEOUT_MS;
702
+ const DEVICE_WAIT_POLL_MS = 2e3;
703
+ const DEVICE_WAIT_LINE_MS = 3e4;
704
+ const DEVICE_BUSY = "STIM_DEVICE_BUSY";
705
+ const DEVICE_LOST = "STIM_DEVICE_LOST";
706
+ function leaseStepMs(boundMs = 0) {
707
+ return Math.max(LEASE_STEP_FLOOR_MS, boundMs);
708
+ }
709
+ function parseDeviceWait(value) {
710
+ if (value === void 0 || value === null) return { seconds: 60 };
711
+ const seconds = String(value).trim() === "" ? NaN : Number(value);
712
+ if (!Number.isInteger(seconds) || seconds < 0) return { error: `Invalid --wait value ${JSON.stringify(value)}. Pass a whole number of seconds, e.g. --wait 90.` };
713
+ return { seconds };
714
+ }
715
+ function waitFlagConflict(argv) {
716
+ return argv.some((arg) => arg === "--wait" || arg.startsWith("--wait=")) && argv.includes("--no-wait");
717
+ }
718
+ function leaseExpiryText(expiresAt, now) {
719
+ const remaining = Date.parse(expiresAt) - now;
720
+ return `${clockTime(expiresAt)} (${formatElapsed(Math.max(0, remaining))} from now)`;
721
+ }
722
+ function describeDevice(lease) {
723
+ return lease.deviceName ? `${lease.deviceName} (${lease.id})` : lease.id;
724
+ }
725
+ function facts(lease) {
726
+ return {
727
+ platform: lease.platform,
728
+ id: lease.id,
729
+ deviceName: lease.deviceName,
730
+ holder: lease.holder,
731
+ expiresAt: lease.expiresAt
732
+ };
733
+ }
734
+ function waitingLine(lease, now) {
735
+ return `waiting for ${lease.holder} to release ${describeDevice(lease)}; its lease runs until ${leaseExpiryText(lease.expiresAt, now)} -- stim guide lifecycle lease`;
736
+ }
737
+ function appIdMatch(ours, theirs) {
738
+ if (!ours || !theirs) return "unknown";
739
+ return ours === theirs ? "same" : "different";
740
+ }
741
+ function bypassLines(lease, now, match) {
742
+ const consequence = {
743
+ same: "Both workspaces build the same app id, so this install terminates the app that workspace is running.",
744
+ different: "The other workspace's app id differs, so the launch below backgrounds it rather than ending it.",
745
+ unknown: "Stim cannot tell whether the two workspaces build the same app id; if they do, this install terminates the holder's running app."
746
+ }[match];
747
+ return [`--no-wait: ${lease.holder} holds ${describeDevice(lease)} until ${leaseExpiryText(lease.expiresAt, now)}, and this run is proceeding without a lease.`, consequence];
748
+ }
749
+ function busyRefusal({ lease, now, idLabel, waitSeconds }) {
750
+ return {
751
+ code: DEVICE_BUSY,
752
+ message: `${lease.holder} holds ${describeDevice(lease)} until ${leaseExpiryText(lease.expiresAt, now)}` + (waitSeconds > 0 ? `, and this command waited ${waitSeconds}s for it.` : "."),
753
+ remedy: `Wait longer with \`--wait <seconds>\`, pick another device with \`--device <${idLabel}>\`, or pass \`--no-wait\` to install anyway -- which takes no lease and, when both workspaces build the same app id, terminates the holder's running app.`,
754
+ lease: facts(lease)
755
+ };
756
+ }
757
+ function unreadableRefusal(path) {
758
+ return {
759
+ code: DEVICE_BUSY,
760
+ message: `The lease file at ${path} does not parse, so Stim cannot tell who holds that device.`,
761
+ remedy: `Read ${path} and, once you know no run depends on it, delete it. \`stim gc\` reports it on every run.`,
762
+ lease: {
763
+ platform: null,
764
+ id: null,
765
+ deviceName: null,
766
+ holder: null,
767
+ expiresAt: null
768
+ }
769
+ };
770
+ }
771
+ function untokenedRefusal(lease, now) {
772
+ return {
773
+ code: DEVICE_BUSY,
774
+ message: `This workspace holds ${describeDevice(lease)} until ${leaseExpiryText(lease.expiresAt, now)}, but its own record of that lease is gone, so this run cannot prove the lease is still its own.`,
775
+ remedy: "Run `stim device unlock`, which releases by holder, then run this command again.",
776
+ lease: facts(lease)
777
+ };
778
+ }
779
+ function otherDeviceRefusal(leasedId, requestedId) {
780
+ return {
781
+ code: "STIM_NO_DEVICE",
782
+ message: `This workspace already leases ${leasedId}, and this run asked for ${requestedId}.`,
783
+ remedy: `Run \`stim device unlock\` to give up ${leasedId}, or use it with \`--device ${leasedId}\`.`,
784
+ lease: null
785
+ };
786
+ }
787
+ function lostLine(holder, expiresAt, now) {
788
+ return `${holder ?? "another workspace"} took this device's lease${expiresAt ? ` until ${leaseExpiryText(expiresAt, now)}` : ""}. The app is already installed, so this run continues without one.`;
789
+ }
790
+ function lostRefusal(holder, expiresAt, now) {
791
+ const who = holder ?? "another workspace";
792
+ const until = expiresAt ? ` until ${leaseExpiryText(expiresAt, now)}` : "";
793
+ return {
794
+ code: DEVICE_LOST,
795
+ message: `${who} took this device's lease${until} before this run could install.`,
796
+ remedy: "Run this command again; it waits for that lease with `--wait <seconds>`.",
797
+ lease: null
798
+ };
799
+ }
800
+ function runLease({ root, platform, slot = "default", kind, expiresAt, io = fileLeaseIo }) {
801
+ const handle = {
802
+ kind,
803
+ expiresAt,
804
+ lost: false,
805
+ raise(boundMs) {
806
+ if (handle.kind === null || handle.lost) return {
807
+ ok: !handle.lost,
808
+ holder: null,
809
+ expiresAt: handle.expiresAt
810
+ };
811
+ const result = raiseLease({
812
+ root,
813
+ platform,
814
+ slot,
815
+ minMs: leaseStepMs(boundMs)
816
+ }, io);
817
+ if (result.status === "raised") {
818
+ handle.expiresAt = result.lease.expiresAt;
819
+ return {
820
+ ok: true,
821
+ holder: result.lease.holder,
822
+ expiresAt: result.lease.expiresAt
823
+ };
824
+ }
825
+ handle.lost = true;
826
+ const taken = result.status === "lost" ? result.lease : null;
827
+ return {
828
+ ok: false,
829
+ holder: taken?.holder ?? null,
830
+ expiresAt: taken?.expiresAt ?? null
831
+ };
832
+ },
833
+ release() {
834
+ if (handle.kind === null) return;
835
+ releaseRunLease({
836
+ root,
837
+ platform,
838
+ slot
839
+ }, io);
840
+ },
841
+ facts() {
842
+ if (handle.kind === null || handle.lost || handle.expiresAt === null) return null;
843
+ return {
844
+ kind: handle.kind,
845
+ expiresAt: handle.expiresAt
846
+ };
847
+ }
848
+ };
849
+ return handle;
850
+ }
851
+ /** Release the run's lease as soon as `context`'s operation is aborted; returns a function that stops listening. */
852
+ function releaseLeaseOnAbort(context, release) {
853
+ const onAbort = () => {
854
+ operationState(context).handled = true;
855
+ release();
856
+ };
857
+ if (context.signal.aborted) onAbort();
858
+ else context.signal.addEventListener("abort", onAbort, { once: true });
859
+ return () => context.signal.removeEventListener("abort", onAbort);
860
+ }
861
+ async function waitForDevice({ root, platform, slot = "default", id, idLabel, waitSeconds, noWait = false, appId = null, holderAppId = () => null, now = Date.now, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), warn = () => {}, io = fileLeaseIo, deadline, lastLine }) {
862
+ const path = deviceLeasePath(platform, id);
863
+ for (;;) {
864
+ const raw = io.readLease(path);
865
+ const current = parseLease(raw);
866
+ if (raw !== null && !current) return {
867
+ status: "refused",
868
+ refusal: unreadableRefusal(path)
869
+ };
870
+ if (!current || leaseIsExpired(current, now())) return { status: "free" };
871
+ if (current.holder === root && (current.slot ?? "default") === slot) return {
872
+ status: "ours",
873
+ lease: current
874
+ };
875
+ if (noWait) {
876
+ for (const line of bypassLines(current, now(), appIdMatch(appId, holderAppId(current.holder)))) warn(line);
877
+ return {
878
+ status: "bypassed",
879
+ lease: current
880
+ };
881
+ }
882
+ if (now() >= deadline) return {
883
+ status: "refused",
884
+ refusal: busyRefusal({
885
+ lease: current,
886
+ now: now(),
887
+ idLabel,
888
+ waitSeconds
889
+ })
890
+ };
891
+ if (lastLine.at === null || now() - lastLine.at >= 3e4) {
892
+ lastLine.at = now();
893
+ warn(waitingLine(current, now()));
894
+ }
895
+ await sleep(DEVICE_WAIT_POLL_MS);
896
+ }
897
+ }
898
+ async function acquireRunLease({ root, platform, slot = "default", id, deviceName = null, idLabel, waitSeconds, noWait, installBoundMs, appId = null, holderAppId = () => null, now = Date.now, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), warn = () => {}, io = fileLeaseIo }) {
899
+ const recorded = io.readHolder(root)[deviceSlotKey(platform, slot)];
900
+ let held = recorded;
901
+ if (recorded && recorded.id !== id) {
902
+ const other = parseLease(io.readLease(deviceLeasePath(platform, recorded.id)));
903
+ if (other && other.token === recorded.token && !leaseIsExpired(other, now())) return {
904
+ status: "refused",
905
+ refusal: otherDeviceRefusal(recorded.id, id)
906
+ };
907
+ held = void 0;
908
+ }
909
+ const path = deviceLeasePath(platform, id);
910
+ const deadline = now() + waitSeconds * 1e3;
911
+ const lastLine = { at: null };
912
+ for (;;) {
913
+ const current = parseLease(io.readLease(path));
914
+ const mine = current && held && current.token === held.token ? {
915
+ lease: current,
916
+ record: held
917
+ } : null;
918
+ if (mine && (mine.record.kind === "run" || !leaseIsExpired(mine.lease, now()))) {
919
+ const raised = raiseLease({
920
+ root,
921
+ platform,
922
+ slot,
923
+ minMs: leaseStepMs(installBoundMs)
924
+ }, io);
925
+ if (raised.status === "raised") return {
926
+ status: "leased",
927
+ kind: mine.record.kind,
928
+ expiresAt: raised.lease.expiresAt
929
+ };
930
+ }
931
+ const outcome = await waitForDevice({
932
+ root,
933
+ platform,
934
+ slot,
935
+ id,
936
+ idLabel,
937
+ waitSeconds,
938
+ noWait,
939
+ appId,
940
+ holderAppId,
941
+ now,
942
+ sleep,
943
+ warn,
944
+ io,
945
+ deadline,
946
+ lastLine
947
+ });
948
+ if (outcome.status === "refused") return outcome;
949
+ if (outcome.status === "bypassed") return { status: "unleased" };
950
+ if (outcome.status === "ours") return {
951
+ status: "refused",
952
+ refusal: untokenedRefusal(outcome.lease, now())
953
+ };
954
+ const taken = takeLease({
955
+ root,
956
+ platform,
957
+ slot,
958
+ id,
959
+ deviceName,
960
+ kind: "run",
961
+ durationMs: leaseStepMs(installBoundMs)
962
+ }, io);
963
+ if (taken.status === "unreadable") return {
964
+ status: "refused",
965
+ refusal: unreadableRefusal(taken.path)
966
+ };
967
+ if (taken.status === "taken" || taken.status === "set") return {
968
+ status: "leased",
969
+ kind: taken.status === "set" ? held?.kind ?? "run" : "run",
970
+ expiresAt: taken.lease.expiresAt
971
+ };
972
+ }
973
+ }
974
+ //#endregion
975
+ //#region src/offload/selection.ts
976
+ const FINGERPRINT_MISMATCH_REMEDY = "The build Mac fingerprints the synced checkout differently; the message names the sources that differ. Stim sends tracked and untracked files and the gitignored files the fingerprint reads, except under node_modules. A source still differs when the build Mac's dependency install or pod install writes it differently, or when the app config reads an environment variable or file that differs. Make that input agree on both Macs, for example by committing the lockfile pod install rewrote there, or rerun with --remote-build auto or --remote-build local.";
977
+ /** The remedy for a React Native worker's fingerprint-mismatch reason, or undefined for any other reason. */
978
+ function fingerprintMismatchRemedy(reason) {
979
+ return reason.startsWith("fingerprint-mismatch: the checkout there ") ? FINGERPRINT_MISMATCH_REMEDY : void 0;
980
+ }
981
+ const MISSING_PACKAGE_MANAGER = /^deps-failed: spawn (pnpm|yarn|npm) ENOENT/;
982
+ /** The remedy for a worker whose dependency install could not start its package manager; undefined for any other reason. */
983
+ function missingPackageManagerRemedy(machine, reason) {
984
+ const tool = MISSING_PACKAGE_MANAGER.exec(reason)?.[1];
985
+ if (!tool) return void 0;
986
+ return `${machine} has no ${tool} on the PATH of its stim-server service, and the app's lockfile needs it. ${tool === "npm" ? "Reinstall Node there, which ships npm" : `Install it with \`corepack enable ${tool}\` or \`npm install --global ${tool}\`, using sudo where Node is installed system-wide`}, then run the same command again, or rerun with --remote-build auto or --remote-build local.`;
987
+ }
988
+ const PODS_FAILED_PREFIX = "pod install failed: ";
989
+ /** The reason a failed worker job is reported with: a `pods-failed` code reads as a failed pod install. */
990
+ function workerFailureReason(code, message) {
991
+ return code === "pods-failed" ? `${PODS_FAILED_PREFIX}${String(message ?? "")}` : `${String(code ?? "failed")}: ${String(message ?? "")}`;
992
+ }
993
+ /** The remedy for a worker whose `pod install` failed, naming the install when it has no CocoaPods; undefined for any other reason. */
994
+ function podsFailedRemedy(machine, reason, localCocoapods) {
995
+ if (!reason.startsWith(PODS_FAILED_PREFIX)) return void 0;
996
+ const retry = "run the same command again, or rerun with --remote-build auto or --remote-build local";
997
+ if (!reason.includes("CocoaPods is not installed: no `pod` executable on PATH.")) return `Fix the pod install error on ${machine} (run pod install in its checkout under server.workerRoot there to see all of it), then ${retry}.`;
998
+ const { lead, commands } = cocoapodsInstall(localCocoapods);
999
+ return [
1000
+ `On ${machine}, ${lead}:`,
1001
+ ...commands,
1002
+ `Then ${retry}.`
1003
+ ].join("\n");
1004
+ }
1005
+ var OffloadRefusal = class extends Error {
1006
+ code = "STIM_OFFLOAD_REFUSED";
1007
+ remedy;
1008
+ constructor(machine, reason, remedy = "Run stim doctor --fix to ask for build access if not paired; it prints the stim-server setup command a person runs on the worker to approve this machine. Check stim settings get remote.machines, or rerun with --remote-build auto, remote or local.") {
1009
+ super(reason.startsWith(`${machine}: `) ? reason : `${machine}: ${reason}`);
1010
+ this.remedy = remedy;
1011
+ }
1012
+ };
1013
+ function resolveBuildMachine(flag, env, setting) {
1014
+ const selected = flag ?? (env?.trim() || void 0) ?? setting ?? "auto";
1015
+ if (typeof selected !== "string" || !selected.trim() || !parseMachine(selected)) throw Object.assign(/* @__PURE__ */ new Error("--remote-build / remote.build must be local, auto, remote, remote-only, or a tailnet machine name."), { code: "STIM_BAD_ARG" });
1016
+ return placementWord(selected) ?? selected.trim();
1017
+ }
1018
+ function parseBuildMachineOption(value) {
1019
+ try {
1020
+ return resolveBuildMachine(value);
1021
+ } catch (error) {
1022
+ throw new InvalidArgumentError(error.message);
1023
+ }
1024
+ }
1025
+ function automaticBuild(selected) {
1026
+ const word = placementWord(selected);
1027
+ return word !== null && word !== "local";
1028
+ }
1029
+ function requireLocalBuild(selected, reason) {
1030
+ const word = placementWord(selected);
1031
+ const lead = reason ? `${reason}; ` : "";
1032
+ if (word === "remote-only") throw new OffloadRefusal(selected, `${lead}remote-only never builds on this machine`);
1033
+ if ((word === "auto" || word === "remote") && !automaticMachineEnabled("build", "local")) throw new OffloadRefusal(selected, `${lead}local is disabled in remote.buildPoolDisabled; enable it or select a machine explicitly`);
1034
+ }
1035
+ function namedBuildMachine(selected) {
1036
+ return placementWord(selected) === null;
1037
+ }
1038
+ function requireConfiguredMachine(selected, machines) {
1039
+ if (!namedBuildMachine(selected)) return selected;
1040
+ const parsed = parseMachine(selected);
1041
+ const entries = Array.isArray(machines) ? machines.filter((entry) => typeof entry === "string") : [];
1042
+ const match = entries.find((entry) => {
1043
+ const candidate = parseMachine(entry);
1044
+ return candidate?.transport === parsed.transport && candidate.name === parsed.name && candidate.port === parsed.port;
1045
+ });
1046
+ if (!match) throw new OffloadRefusal(selected, `not listed in remote.machines (configured: ${entries.join(", ") || "none"})`);
1047
+ return match;
1048
+ }
1049
+ const settingSource = (flag, env, setting) => flag !== void 0 ? "flag" : env?.trim() ? "env" : setting !== void 0 ? "setting" : "default";
1050
+ /** The settings that decide where a build runs, with the layer each value came from, for this run's `--remote-build`. */
1051
+ function buildPlacementSettings(selected) {
1052
+ const flag = operationState(ambientContext()).buildMachineFlag;
1053
+ return [{
1054
+ key: "remote.build",
1055
+ value: selected,
1056
+ from: settingSource(flag, ambientEnv().STIM_REMOTE_BUILD, loadConfig$1()?.remote?.build)
1057
+ }];
1058
+ }
1059
+ function resolveBuildPlacement(flag) {
1060
+ const remote = loadConfig$1()?.remote;
1061
+ operationState(ambientContext()).buildMachineFlag = flag;
1062
+ let selected = "auto";
1063
+ try {
1064
+ selected = resolveBuildMachine(flag, ambientEnv().STIM_REMOTE_BUILD, remote?.build);
1065
+ selected = requireConfiguredMachine(selected, remote?.machines);
1066
+ if (namedBuildMachine(selected) && pairedMachines([selected]).length === 0) throw new OffloadRefusal(selected, "no remote machine is paired");
1067
+ return { selected };
1068
+ } catch (error) {
1069
+ return {
1070
+ selected,
1071
+ failure: {
1072
+ code: error.code,
1073
+ message: error.message,
1074
+ remedy: error instanceof OffloadRefusal ? error.remedy : "Pass --remote-build local, auto, remote, remote-only, or an entry from stim settings get remote.machines."
1075
+ }
1076
+ };
1077
+ }
1078
+ }
1079
+ //#endregion
1080
+ //#region src/devices/springboard-crash-reports.ts
1081
+ const REPORT_WINDOW_MS = 6e5;
1082
+ const MAX_CANDIDATES = 100;
1083
+ const MAX_STORED = 40;
1084
+ const MAX_REPORT_BYTES = 1048576;
1085
+ const MAX_COPIED_BYTES = 8388608;
1086
+ function selectSpringBoardReports(entries, udid, sinceMs) {
1087
+ const owner = `.${udid}`.toLowerCase();
1088
+ return entries.flatMap(({ name, text }) => {
1089
+ if (!/^SpringBoard-.+\.ips$/.test(name)) return [];
1090
+ try {
1091
+ const report = JSON.parse(text.slice(text.indexOf("\n") + 1));
1092
+ if (!isJsonObject(report)) return [];
1093
+ const { coalitionName, captureTime } = report;
1094
+ const capturedAt = Date.parse(typeof captureTime === "string" ? captureTime : "");
1095
+ return typeof coalitionName === "string" && coalitionName.toLowerCase().endsWith(owner) && capturedAt >= sinceMs ? [name] : [];
1096
+ } catch {
1097
+ return [];
1098
+ }
1099
+ });
1100
+ }
1101
+ /**
1102
+ * Copies this simulator's recent SpringBoard crash reports from DiagnosticReports and its Retired folder into
1103
+ * `destDir`, which keeps at most 40 of them. The source folders are only read; macOS deletes their reports after
1104
+ * about two days. Returns the matching reports now in `destDir`, how many matched but did not fit its limits, and
1105
+ * the message of a write that failed.
1106
+ */
1107
+ async function copySpringBoardCrashReports({ udid, destDir, now = Date.now(), home = homedir() }) {
1108
+ const since = now - REPORT_WINDOW_MS;
1109
+ const reportsDir = join(home, "Library/Logs/DiagnosticReports");
1110
+ const candidates = /* @__PURE__ */ new Map();
1111
+ for (const directory of [reportsDir, join(reportsDir, "Retired")]) {
1112
+ let names;
1113
+ try {
1114
+ names = await readdir(directory);
1115
+ } catch (error) {
1116
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") continue;
1117
+ throw error;
1118
+ }
1119
+ for (const name of names) {
1120
+ if (!/^SpringBoard-.+\.ips$/.test(name) || candidates.has(name)) continue;
1121
+ try {
1122
+ const path = join(directory, name);
1123
+ const { mtimeMs, size } = await stat(path);
1124
+ if (mtimeMs >= since && size <= MAX_REPORT_BYTES) candidates.set(name, {
1125
+ path,
1126
+ mtimeMs
1127
+ });
1128
+ } catch {}
1129
+ }
1130
+ }
1131
+ const newest = [...candidates].toSorted((a, b) => b[1].mtimeMs - a[1].mtimeMs).slice(0, MAX_CANDIDATES);
1132
+ const entries = [];
1133
+ for (const [name, { path }] of newest) try {
1134
+ entries.push({
1135
+ name,
1136
+ text: await readFile(path, "utf8")
1137
+ });
1138
+ } catch {}
1139
+ const matching = selectSpringBoardReports(entries, udid, since);
1140
+ if (matching.length === 0) return {
1141
+ files: [],
1142
+ dropped: 0
1143
+ };
1144
+ await mkdir(destDir, {
1145
+ recursive: true,
1146
+ mode: 448
1147
+ });
1148
+ const present = new Set(await readdir(destDir));
1149
+ let stored = [...present].filter((name) => /^SpringBoard-.+\.ips$/.test(name)).length;
1150
+ let copiedBytes = 0;
1151
+ const files = [];
1152
+ for (const { name, text } of entries) {
1153
+ if (!matching.includes(name)) continue;
1154
+ if (present.has(name)) {
1155
+ files.push(name);
1156
+ continue;
1157
+ }
1158
+ const bytes = Buffer.byteLength(text);
1159
+ if (stored >= MAX_STORED || copiedBytes + bytes > MAX_COPIED_BYTES) continue;
1160
+ try {
1161
+ await writeFile(join(destDir, name), text, {
1162
+ flag: "wx",
1163
+ mode: 384
1164
+ });
1165
+ } catch (error) {
1166
+ if (error instanceof Error && "code" in error && error.code === "EEXIST") {
1167
+ files.push(name);
1168
+ continue;
1169
+ }
1170
+ await rm(join(destDir, name), { force: true }).catch(() => {});
1171
+ return {
1172
+ files,
1173
+ dropped: 0,
1174
+ failure: error instanceof Error ? error.message : String(error)
1175
+ };
1176
+ }
1177
+ stored++;
1178
+ copiedBytes += bytes;
1179
+ files.push(name);
1180
+ }
1181
+ return {
1182
+ files,
1183
+ dropped: matching.length - files.length
1184
+ };
1185
+ }
1186
+ //#endregion
1187
+ //#region src/engine/ios-boot-log.ts
1188
+ function iosBootRecorder(root, slot, udid) {
1189
+ return (event, { level = "info", ...fields }) => {
1190
+ try {
1191
+ const writer = createNdjsonWriter(join(workspaceLogsDir$1(root), "device.ndjson"), { maxBytes: LOG_ROTATE_BYTES });
1192
+ writer.write({
1193
+ src: "device",
1194
+ platform: "ios",
1195
+ level,
1196
+ event,
1197
+ deviceId: udid,
1198
+ ...slot && slot !== "default" ? { slot } : {},
1199
+ ...fields
1200
+ });
1201
+ writer.close();
1202
+ } catch {}
1203
+ };
1204
+ }
1205
+ //#endregion
1206
+ //#region src/engine/device-ios.ts
1207
+ function recordBootPhase(record, udid, origin) {
1208
+ return (event) => {
1209
+ const pid = "pid" in event ? event.pid : void 0;
1210
+ const boot = event.phase === "boot_requested" ? origin : void 0;
1211
+ record("ios_boot", {
1212
+ phase: event.phase,
1213
+ ...pid === void 0 ? {} : { pid },
1214
+ ...boot === void 0 ? {} : { boot },
1215
+ msg: `ios boot ${udid}: ${event.phase}${pid === void 0 ? "" : ` pid ${pid}`}${boot === void 0 ? "" : ` (${boot})`}`
1216
+ });
1217
+ };
1218
+ }
1219
+ function startIosBoot(udid, configure, label, out, simulatorApp, root, slot, origin, deviceSlotWait) {
1220
+ const done = withDeviceBootAdmission({
1221
+ platform: "ios",
1222
+ key: udid
1223
+ }, async () => {
1224
+ out(chalk.dim(phaseLine("device", `booting ${label} (${udid})`)));
1225
+ await bootIosSim(udid, {
1226
+ label,
1227
+ out,
1228
+ simulatorApp,
1229
+ env: ambientContext()?.env,
1230
+ onPhase: recordBootPhase(iosBootRecorder(root, slot, udid), udid, origin)
1231
+ });
1232
+ await configure();
1233
+ await muteBootedSimulator(udid, out);
1234
+ }, {
1235
+ ...deviceSlotWait,
1236
+ root,
1237
+ out
1238
+ });
1239
+ done.catch(() => {});
1240
+ return {
1241
+ udid,
1242
+ done
1243
+ };
1244
+ }
1245
+ const SPRINGBOARD_MUTE_WAIT_MS = 6e4;
1246
+ async function muteBootedSimulator(udid, out) {
1247
+ try {
1248
+ const springBoard = await waitForSpringBoard(udid, Date.now() + SPRINGBOARD_MUTE_WAIT_MS);
1249
+ if (springBoard.state === "unreadable") throw new Error(springBoard.reason);
1250
+ if (springBoard.state === "timed-out") throw new Error(`SpringBoard did not finish starting within ${SPRINGBOARD_MUTE_WAIT_MS / 1e3}s.`);
1251
+ const response = JSON.parse(await getExecutor().runFileAsync("xcrun", [
1252
+ "devicectl",
1253
+ "device",
1254
+ "settings",
1255
+ "audio",
1256
+ "--device",
1257
+ udid,
1258
+ "--volume",
1259
+ "0",
1260
+ "--json-output",
1261
+ "-"
1262
+ ], { timeoutMs: 3e4 }));
1263
+ if (!isJsonObject(response) || !isJsonObject(response.info) || response.info.outcome !== "success" || !isJsonObject(response.result) || typeof response.result.deviceIdentifier !== "string" || response.result.deviceIdentifier.toUpperCase() !== udid.toUpperCase() || response.result.volume !== 0) throw new Error("Xcode did not confirm volume zero for this simulator.");
1264
+ out(chalk.dim(phaseLine("device", "simulator muted; turn on Sound in its Stim Desktop options")));
1265
+ } catch (error) {
1266
+ out(chalk.yellow(phaseLine("device", `Could not mute this simulator: ${error instanceof Error ? error.message : String(error)}`)));
1267
+ }
1268
+ }
1269
+ var IosDeviceMismatchError = class extends Error {
1270
+ remedy = "Run `stim worktree remove` (or `stim gc --delete`) to reap the current sim, then `stim ios` again to create the requested one, or pass `--slot <name>` to create it beside the current one.";
1271
+ };
1272
+ async function ensureOwnedIosDevice({ record, projectPath, slot, settingsRoot, label, settings, flags, note, out, reconcileIosSimulator, simSnapshot }) {
1273
+ const pressure = readHostMemoryPressure();
1274
+ const memoryAdvice = hostMemoryPressureAdvice(pressure);
1275
+ if (memoryAdvice) out(chalk.yellow(phaseLine("memory", memoryAdvice)));
1276
+ reportMemoryCulprits(pressure, (named) => out(chalk.yellow(phaseLine("memory", named))));
1277
+ const simslimProfile = iosSimSlimProfileSetting(settings, settingsRoot);
1278
+ const simslimDefault = iosSimSlimDefaultSetting(settings);
1279
+ if (record?.deviceUdid) {
1280
+ if (record.owned) {
1281
+ const listed = simSnapshot ? simSnapshot.read() : listAllIosSims({ includeUnavailable: true });
1282
+ const resolved = resolveOwnedIosSim(record.deviceUdid, listed);
1283
+ if (resolved.notOwned) note(chalk.yellow(`Note: recorded sim is now named "${resolved.notOwned}", not Stim-owned -- creating a fresh owned sim instead of booting it.`));
1284
+ else if (resolved.missing) {} else {
1285
+ const sim = resolved.sim;
1286
+ const wantedType = flags.deviceType || settings?.ios?.deviceType;
1287
+ const deviceTypes = await listIosDeviceTypesAsync({ snapshot: simSnapshot });
1288
+ const mismatch = deviceTypeMismatch(sim.deviceTypeIdentifier, wantedType, deviceTypes);
1289
+ if (mismatch) throw new IosDeviceMismatchError(`${mismatch}. Stim will not silently boot a different model.`);
1290
+ const versionMismatch = flags.runtimeFlag ? runtimeMismatch(sim.runtime, flags.runtimeFlag, await listIosRuntimesAsync({ snapshot: simSnapshot })) : null;
1291
+ if (versionMismatch) throw new IosDeviceMismatchError(`${versionMismatch}. Stim will not silently boot a different iOS version.`);
1292
+ const model = {
1293
+ model: deviceTypes.find((d) => d.identifier === sim.deviceTypeIdentifier)?.name ?? null,
1294
+ runtime: parseRuntimeVersion(sim.runtime)
1295
+ };
1296
+ const name = ownedIosName(sim, label, model, projectPath, listed) === sim.name ? sim.name : await withIosDeviceNameLock(() => renameToOwnedName(sim, label, model, projectPath));
1297
+ const updated = {
1298
+ deviceUdid: sim.udid,
1299
+ owned: true,
1300
+ deviceName: name,
1301
+ ...record.simslimManaged ? { simslimManaged: true } : {},
1302
+ ...record.simslimApplied ? { simslimApplied: record.simslimApplied } : {},
1303
+ ...record.adopted ? { adopted: true } : {},
1304
+ ...record.adoptionPending ? { adoptionPending: true } : {},
1305
+ ...record.parkedCacheKey ? { parkedCacheKey: record.parkedCacheKey } : {},
1306
+ ...record.schemeApprovals ? { schemeApprovals: record.schemeApprovals } : {}
1307
+ };
1308
+ const configure = async (freshBoot) => {
1309
+ if (record.adoptionPending) await resetAdoptedSim(sim.udid, out);
1310
+ return configureOwnedIosSim({
1311
+ record: updated,
1312
+ projectPath,
1313
+ slot,
1314
+ profile: simslimProfile,
1315
+ slimByDefault: simslimDefault,
1316
+ freshBoot,
1317
+ out,
1318
+ reconcileIosSimulator
1319
+ });
1320
+ };
1321
+ const facts = {
1322
+ deviceType: model.model,
1323
+ runtime: model.runtime
1324
+ };
1325
+ if (sim.state !== "Booted") return {
1326
+ ...updated,
1327
+ booting: startIosBoot(sim.udid, () => configure(true), name, out, flags.simulatorApp, projectPath, slot, record.adoptionPending ? "adopted" : "existing", flags.deviceSlotWait),
1328
+ ...facts
1329
+ };
1330
+ const { record: configured, rebooted } = await configure(false);
1331
+ if (rebooted) await muteBootedSimulator(sim.udid, out);
1332
+ return {
1333
+ ...configured,
1334
+ ...facts,
1335
+ booted: sim.udid
1336
+ };
1337
+ }
1338
+ } else {
1339
+ const sim = (await listAllIosSimsAsync()).find((s) => s.udid === record.deviceUdid);
1340
+ if (sim) {
1341
+ if (sim.state !== "Booted") {
1342
+ note(chalk.yellow(`Note: assigned sim ${sim.name} (${sim.udid}) is shut down and is not owned by Stim, so it will not be booted automatically.`));
1343
+ note(chalk.dim("Boot it yourself, or run `stim gc --delete` to clear the assignment so Stim can create an owned sim."));
1344
+ }
1345
+ return record;
1346
+ }
1347
+ }
1348
+ await withConfigLockAsync$1(() => {
1349
+ const current = deviceSlotPlatforms(loadConfig$1()?.projects?.[projectPath], slot)?.ios;
1350
+ if (!current) return;
1351
+ if (current.deviceUdid !== record.deviceUdid || current.owned !== record.owned) throw new Error("The simulator assignment changed during recovery. Run `stim ios` again.");
1352
+ clearDevice(projectPath, "ios", slot);
1353
+ });
1354
+ }
1355
+ const choice = await resolveIosCreation({
1356
+ deviceType: flags.deviceType || settings.ios?.deviceType,
1357
+ runtime: flags.runtime || settings.ios?.runtime
1358
+ });
1359
+ const adopted = parkedMaxSetting("ios").max > 0 ? await withIosDeviceNameLock(() => takeParkedIosSim({
1360
+ projectPath,
1361
+ slot,
1362
+ label,
1363
+ choice,
1364
+ out
1365
+ })) : null;
1366
+ if (adopted) {
1367
+ const booting = startIosBoot(adopted.deviceUdid, async () => {
1368
+ await resetAdoptedSim(adopted.deviceUdid, out);
1369
+ await configureOwnedIosSim({
1370
+ record: adopted,
1371
+ projectPath,
1372
+ slot,
1373
+ profile: simslimProfile,
1374
+ slimByDefault: simslimDefault,
1375
+ freshBoot: true,
1376
+ out,
1377
+ reconcileIosSimulator
1378
+ });
1379
+ }, adopted.deviceName, out, flags.simulatorApp, projectPath, slot, "adopted", flags.deviceSlotWait);
1380
+ return {
1381
+ ...adopted,
1382
+ booting,
1383
+ deviceType: choice.deviceType,
1384
+ runtime: choice.runtime
1385
+ };
1386
+ }
1387
+ const created = await withIosDeviceNameLock(async () => {
1388
+ const suffix = ownedIosNameSuffix(label, {
1389
+ model: choice.deviceType,
1390
+ runtime: choice.runtime
1391
+ }, projectPath, void 0, await listAllIosSimsAsync({ includeUnavailable: true }));
1392
+ const result = await createOwnedIosSim(label, { suffix }, choice);
1393
+ await withConfigLockAsync$1(() => setDevice(projectPath, "ios", {
1394
+ deviceUdid: result.udid,
1395
+ owned: true,
1396
+ deviceName: result.name
1397
+ }, slot));
1398
+ return result;
1399
+ });
1400
+ const newRecord = {
1401
+ deviceUdid: created.udid,
1402
+ owned: true,
1403
+ deviceName: created.name
1404
+ };
1405
+ const booting = startIosBoot(created.udid, () => configureOwnedIosSim({
1406
+ record: newRecord,
1407
+ projectPath,
1408
+ slot,
1409
+ profile: simslimProfile,
1410
+ slimByDefault: simslimDefault,
1411
+ freshBoot: true,
1412
+ out,
1413
+ reconcileIosSimulator
1414
+ }), created.name, out, flags.simulatorApp, projectPath, slot, "created", flags.deviceSlotWait);
1415
+ return {
1416
+ ...newRecord,
1417
+ created: true,
1418
+ booting,
1419
+ deviceType: created.deviceType,
1420
+ runtime: created.runtime
1421
+ };
1422
+ }
1423
+ function withIosDeviceNameLock(fn) {
1424
+ return withWorkspaceProcessLock(getConfigDir(), "ios-device-names", async () => fn(), { external: true });
1425
+ }
1426
+ function ownedIosNameSuffix(label, model, projectPath, udid, listed) {
1427
+ const names = new Set(listed.filter((sim) => sim.udid !== udid).map((sim) => sim.name));
1428
+ for (const project of Object.values(loadConfig$1()?.projects ?? {})) for (const { platforms } of projectDeviceSlots(project)) {
1429
+ const record = platforms.ios;
1430
+ if (record?.deviceUdid !== udid && record?.deviceName) names.add(record.deviceName);
1431
+ }
1432
+ for (const parked of readParked("ios")) if (parked.udid !== udid) names.add(parked.name);
1433
+ let suffix = "";
1434
+ for (let attempt = 0; names.has(ownedSimName(label, model, suffix)); attempt++) suffix = ` ${workspaceId$1(projectPath)}${attempt ? `-${attempt}` : ""}`;
1435
+ return suffix;
1436
+ }
1437
+ function ownedIosName(sim, label, model, projectPath, listed) {
1438
+ return ownedSimName(label, model, ownedIosNameSuffix(label, model, projectPath, sim.udid, listed));
1439
+ }
1440
+ async function renameToOwnedName(sim, label, model, projectPath) {
1441
+ const wanted = ownedIosName(sim, label, model, projectPath, await listAllIosSimsAsync({ includeUnavailable: true }));
1442
+ if (sim.name === wanted) return wanted;
1443
+ try {
1444
+ await renameIosSim(sim.udid, wanted);
1445
+ return wanted;
1446
+ } catch {
1447
+ return sim.name;
1448
+ }
1449
+ }
1450
+ async function resetAdoptedSim(udid, out) {
1451
+ out(chalk.dim(phaseLine("device", `resetting privacy grants and the keychain on ${udid}`)));
1452
+ await resetIosPrivacy(udid);
1453
+ await resetIosKeychain(udid);
1454
+ }
1455
+ async function takeParkedIosSim({ projectPath, slot, label, choice, out }) {
1456
+ const candidates = selectParked(readParked("ios"), {
1457
+ deviceTypeIdentifier: choice.deviceTypeId,
1458
+ runtimeIdentifier: choice.runtimeId
1459
+ });
1460
+ if (candidates.length === 0) return null;
1461
+ const listed = new Map((await listAllIosSimsAsync({ includeUnavailable: true })).map((sim) => [sim.udid, sim]));
1462
+ for (const parked of candidates) {
1463
+ const sim = listed.get(parked.udid);
1464
+ if (!sim || !sim.available) {
1465
+ const result = sim ? await teardownParkedIosSim(parked.udid, { label: parked.name }) : null;
1466
+ if (sim ? result?.status === "torn-down" : await dropParked("ios", parked.udid)) out(chalk.dim(phaseLine("device", `deleted parked ${parked.name} (${parked.udid}): ${sim ? "unavailable" : "gone"}`)));
1467
+ else if (result?.status === "failed") out(chalk.yellow(phaseLine("device", `could not delete unavailable parked ${parked.name} (${parked.udid}): ${result.reason}`)));
1468
+ continue;
1469
+ }
1470
+ if (!sim.name.startsWith("stim-")) {
1471
+ out(chalk.yellow(phaseLine("device", `kept parked record for ${parked.udid}: simulator is now named ${JSON.stringify(sim.name)} and is not Stim-owned`)));
1472
+ continue;
1473
+ }
1474
+ const model = {
1475
+ model: choice.deviceType,
1476
+ runtime: choice.runtime
1477
+ };
1478
+ const name = ownedSimName(label, model, ownedIosNameSuffix(label, model, projectPath, parked.udid, [...listed.values()]));
1479
+ const device = {
1480
+ deviceUdid: parked.udid,
1481
+ owned: true,
1482
+ deviceName: name,
1483
+ adopted: true,
1484
+ adoptionPending: true,
1485
+ ...parked.simslimManaged ? { simslimManaged: true } : {},
1486
+ ...parked.cacheKey ? { parkedCacheKey: parked.cacheKey } : {}
1487
+ };
1488
+ const adopted = await adoptParked({
1489
+ platform: "ios",
1490
+ projectPath,
1491
+ slot,
1492
+ udid: parked.udid,
1493
+ device
1494
+ });
1495
+ if (!adopted) continue;
1496
+ try {
1497
+ await renameIosSim(parked.udid, name);
1498
+ } catch {}
1499
+ return adopted.schemeApprovals && adopted.schemeApprovals.length > 0 ? {
1500
+ ...device,
1501
+ schemeApprovals: adopted.schemeApprovals
1502
+ } : device;
1503
+ }
1504
+ return null;
1505
+ }
1506
+ function clearIosAdoptionPending(projectPath, slot = "default") {
1507
+ return withConfigLockAsync$1(() => {
1508
+ const cfg = loadConfig$1();
1509
+ const ios = deviceSlotPlatforms(cfg?.projects?.[projectPath], slot)?.ios;
1510
+ if (!cfg || !ios?.adoptionPending) return;
1511
+ delete ios.adopted;
1512
+ delete ios.adoptionPending;
1513
+ delete ios.parkedCacheKey;
1514
+ saveConfig(cfg);
1515
+ });
1516
+ }
1517
+ function simslimProfileIdentity(profile, slimByDefault) {
1518
+ if (profile) return `profile:${createHash("sha256").update(readFileSync(profile)).digest("hex")}`;
1519
+ return slimByDefault ? "default" : null;
1520
+ }
1521
+ async function startedSpringBoardPid(udid) {
1522
+ const springBoard = await waitForSpringBoard(udid, Date.now() + SPRINGBOARD_MUTE_WAIT_MS);
1523
+ return springBoard.state === "started" ? springBoard.pid : null;
1524
+ }
1525
+ async function configureOwnedIosSim({ record, projectPath, slot, profile, slimByDefault, freshBoot, out, reconcileIosSimulator }) {
1526
+ const identity = simslimProfileIdentity(profile, slimByDefault);
1527
+ const slimConfigured = identity !== null || Boolean(record.simslimManaged);
1528
+ const applied = record.simslimApplied;
1529
+ const springBoardBefore = slimConfigured ? await readSpringBoardPid(record.deviceUdid) : null;
1530
+ if (identity !== null && record.simslimManaged && !freshBoot && applied?.profile === identity && springBoardBefore !== null && springBoardBefore === applied.springBoardPid) {
1531
+ await withConfigLockAsync$1(() => setDevice(projectPath, "ios", { ...record }, slot));
1532
+ return {
1533
+ record,
1534
+ rebooted: false
1535
+ };
1536
+ }
1537
+ if (profile) out(chalk.dim(phaseLine("device", `applying the SimSlim profile to ${record.deviceUdid}`)));
1538
+ else if (slimByDefault) out(chalk.dim(phaseLine("device", `applying SimSlim's default services to ${record.deviceUdid}`)));
1539
+ else if (record.simslimManaged) out(chalk.dim(phaseLine("device", `restoring stock simulator services on ${record.deviceUdid}`)));
1540
+ const previouslyManaged = Boolean(record.simslimManaged);
1541
+ if (identity !== null && !record.simslimManaged || applied) {
1542
+ const { simslimApplied: _applied, ...rest } = record;
1543
+ const pending = identity !== null ? {
1544
+ ...rest,
1545
+ simslimManaged: true
1546
+ } : rest;
1547
+ await withConfigLockAsync$1(() => setDevice(projectPath, "ios", pending, slot));
1548
+ record = pending;
1549
+ }
1550
+ const result = await reconcileIosSimulator({
1551
+ context: ambientContext(),
1552
+ udid: record.deviceUdid,
1553
+ profile,
1554
+ slimByDefault,
1555
+ previouslyManaged,
1556
+ out
1557
+ });
1558
+ const updated = { ...record };
1559
+ if (result.managed) updated.simslimManaged = true;
1560
+ else delete updated.simslimManaged;
1561
+ const springBoardAfter = slimConfigured ? await startedSpringBoardPid(record.deviceUdid) : null;
1562
+ if (result.managed && !result.notInstalled && identity !== null && springBoardAfter !== null) updated.simslimApplied = {
1563
+ profile: identity,
1564
+ springBoardPid: springBoardAfter
1565
+ };
1566
+ await withConfigLockAsync$1(() => setDevice(projectPath, "ios", updated, slot));
1567
+ const rebooted = slimConfigured && springBoardAfter !== springBoardBefore;
1568
+ if (rebooted && !result.notInstalled) iosBootRecorder(projectPath, slot, record.deviceUdid)("ios_boot", {
1569
+ phase: "simslim_reboot",
1570
+ pidBefore: springBoardBefore,
1571
+ pidAfter: springBoardAfter,
1572
+ msg: `ios boot ${record.deviceUdid}: simslim_reboot (SpringBoard pid ${springBoardBefore ?? "unknown"} to ${springBoardAfter ?? "unknown"})`
1573
+ });
1574
+ return {
1575
+ record: updated,
1576
+ rebooted
1577
+ };
1578
+ }
1579
+ const SPRINGBOARD_RESPAWN_POLLS = 20;
1580
+ const SPAWN_STALL_TOLERANCE_MS = 18e4;
1581
+ async function ensureIosBooted(args) {
1582
+ const { springBoardDown, ...first } = await bootOwnedIosSim(args);
1583
+ const { device, projectPath, out } = args;
1584
+ const udid = device?.deviceUdid;
1585
+ if (!springBoardDown || !device || !udid) return first;
1586
+ out(chalk.yellow(phaseLine("device", `SpringBoard is not running on ${udid}; restarting the simulator once`)));
1587
+ const record = iosBootRecorder(projectPath, args.slot, udid);
1588
+ await preserveSpringBoardReports(record, udid, projectPath);
1589
+ const stopped = await teardownOwnedIosSim(udid, { workspace: projectPath });
1590
+ if (stopped.status !== "torn-down") return {
1591
+ ...first,
1592
+ reason: `${first.reason} The restart did not run: ${stopped.reason ?? stopped.status}.`
1593
+ };
1594
+ record("ios_boot", {
1595
+ phase: "restart",
1596
+ level: "warn",
1597
+ msg: `ios boot ${udid}: restart (SpringBoard is not running after boot; restarting once)`
1598
+ });
1599
+ const { booted: _booted, booting: _booting, ...unbooted } = device;
1600
+ const { springBoardDown: stillDown, ...second } = await bootOwnedIosSim({
1601
+ ...args,
1602
+ device: unbooted,
1603
+ origin: "restart"
1604
+ });
1605
+ if (stillDown) await preserveSpringBoardReports(record, udid, projectPath);
1606
+ return stillDown ? {
1607
+ ...second,
1608
+ reason: `${second.reason} Stim already restarted the simulator once, so it did not restart it again.`
1609
+ } : second;
1610
+ }
1611
+ async function preserveSpringBoardReports(record, udid, root) {
1612
+ const dir = workspaceLogsDir$1(root);
1613
+ try {
1614
+ const { files, dropped, failure } = await copySpringBoardCrashReports({
1615
+ udid,
1616
+ destDir: dir
1617
+ });
1618
+ const limit = dropped ? `; ${dropped} more matched but exceeded the copy limits` : "";
1619
+ record("springboard_crash_reports", {
1620
+ level: files.length || dropped || failure ? "warn" : "info",
1621
+ files,
1622
+ dropped,
1623
+ ...failure ? { failure } : {},
1624
+ dir,
1625
+ msg: failure ? `could not copy a SpringBoard crash report for ${udid} (${files.length} copied before it): ${failure}` : files.length ? `copied ${files.length} SpringBoard crash report(s) for ${udid} to ${dir}: ${files.join(", ")}${limit}` : dropped ? `${dropped} SpringBoard crash report(s) for ${udid} matched but exceeded the copy limits` : `no SpringBoard crash report for ${udid} from the last 10 minutes`
1626
+ });
1627
+ } catch (error) {
1628
+ record("springboard_crash_reports", {
1629
+ level: "warn",
1630
+ files: [],
1631
+ dropped: 0,
1632
+ failure: error instanceof Error ? error.message : String(error),
1633
+ dir,
1634
+ msg: `could not copy SpringBoard crash reports for ${udid}: ${error instanceof Error ? error.message : String(error)}`
1635
+ });
1636
+ }
1637
+ }
1638
+ async function bootOwnedIosSim({ device, projectPath, slot, origin, deviceSlotWait, simulatorApp, timeoutMs, pollMs, out }) {
1639
+ const udid = device?.deviceUdid;
1640
+ if (!udid) return {
1641
+ failed: true,
1642
+ reason: "No iOS simulator is recorded for this project."
1643
+ };
1644
+ const onPhase = recordBootPhase(iosBootRecorder(projectPath, slot, udid), udid, origin ?? (device.adoptionPending ? "adopted" : "existing"));
1645
+ const openViewer = async () => {
1646
+ await configuredIosSimulatorViewer(simulatorApp, ambientContext()?.env).open(udid);
1647
+ onPhase({ phase: "viewer_opened" });
1648
+ };
1649
+ const ready = async () => {
1650
+ try {
1651
+ const stallDeadline = Date.now() + SPAWN_STALL_TOLERANCE_MS;
1652
+ const listSpringBoard = async () => {
1653
+ for (;;) try {
1654
+ return await getExecutor().runFileAsync("xcrun", [
1655
+ "simctl",
1656
+ "spawn",
1657
+ udid,
1658
+ "launchctl",
1659
+ "list"
1660
+ ], { timeoutMs: 3e4 });
1661
+ } catch (error) {
1662
+ if (!isTimeoutError(error) || Date.now() >= stallDeadline) throw error;
1663
+ const sims = await listAllIosSimsAsync().catch(() => null);
1664
+ if (sims && sims.find((s) => s.udid === udid)?.state !== "Booted") throw error;
1665
+ }
1666
+ };
1667
+ let listing = await listSpringBoard();
1668
+ for (let poll = 0; !springBoardRunning(listing) && poll < SPRINGBOARD_RESPAWN_POLLS; poll++) {
1669
+ await cancellableSleep(pollMs);
1670
+ listing = await listSpringBoard();
1671
+ }
1672
+ if (!springBoardRunning(listing)) return {
1673
+ failed: true,
1674
+ springBoardDown: true,
1675
+ reason: `Simulator ${udid} reports Booted, but SpringBoard (the system shell) is not running, so apps cannot launch. Run \`stim stop\`, then \`stim ios\` again. If it repeats, look for SpringBoard crash reports in ~/Library/Logs/DiagnosticReports.`
1676
+ };
1677
+ return {
1678
+ ok: true,
1679
+ udid
1680
+ };
1681
+ } catch (error) {
1682
+ return {
1683
+ failed: true,
1684
+ reason: `Simulator ${udid} failed its process-spawn readiness check: ${error?.message || error}. ${await iosSimulatorFailureAdvice()}`
1685
+ };
1686
+ }
1687
+ };
1688
+ const booting = device?.booting;
1689
+ if (booting?.udid === udid) {
1690
+ try {
1691
+ await booting.done;
1692
+ } catch (e) {
1693
+ return bootFailure(udid, e);
1694
+ }
1695
+ return ready();
1696
+ }
1697
+ const readiness = device?.booted === udid ? await ready() : null;
1698
+ if (readiness?.ok) {
1699
+ if (simulatorApp !== void 0) await openViewer();
1700
+ return readiness;
1701
+ }
1702
+ let resolved;
1703
+ try {
1704
+ resolved = resolveOwnedIosSim(udid, await listAllIosSimsAsync());
1705
+ } catch (e) {
1706
+ return {
1707
+ failed: true,
1708
+ reason: `Could not list simulators: ${e?.message || e}`
1709
+ };
1710
+ }
1711
+ if (resolved.missing) return {
1712
+ failed: true,
1713
+ reason: `Simulator ${udid} no longer exists. Run \`stim ios\` again to create a fresh owned sim.`
1714
+ };
1715
+ if (resolved.notOwned) return {
1716
+ failed: true,
1717
+ reason: `Simulator ${udid} is now named "${resolved.notOwned}" and is not Stim-owned; refusing to boot it.`
1718
+ };
1719
+ const sim = resolved.sim;
1720
+ if (sim.state === "Booted") {
1721
+ const result = readiness ?? await ready();
1722
+ if (result.ok && simulatorApp !== void 0) await openViewer();
1723
+ return result;
1724
+ }
1725
+ const bootDeadline = Date.now() + timeoutMs;
1726
+ try {
1727
+ await withDeviceBootAdmission({
1728
+ platform: "ios",
1729
+ key: udid
1730
+ }, async () => {
1731
+ out(chalk.dim(phaseLine("device", `booting ${sim.name} (${udid})`)));
1732
+ await bootIosSim(udid, {
1733
+ timeoutMs,
1734
+ label: sim.name,
1735
+ out,
1736
+ simulatorApp,
1737
+ env: ambientContext()?.env,
1738
+ onPhase
1739
+ });
1740
+ await muteBootedSimulator(udid, out);
1741
+ }, {
1742
+ ...deviceSlotWait,
1743
+ root: projectPath,
1744
+ out
1745
+ });
1746
+ } catch (e) {
1747
+ return bootFailure(udid, e);
1748
+ }
1749
+ const deadline = Math.max(bootDeadline, Date.now() + 2 * pollMs);
1750
+ while (Date.now() < deadline) {
1751
+ await cancellableSleep(pollMs);
1752
+ let state = null;
1753
+ try {
1754
+ state = (await listAllIosSimsAsync({ timeoutMs: 3e4 })).find((s) => s.udid === udid)?.state ?? null;
1755
+ } catch {}
1756
+ if (state === "Booted") return ready();
1757
+ }
1758
+ return {
1759
+ failed: true,
1760
+ reason: `Simulator ${udid} did not reach the Booted state within ${Math.round(timeoutMs / 1e3)}s.`
1761
+ };
1762
+ }
1763
+ function bootFailure(udid, error) {
1764
+ const refusal = error instanceof DeviceAdmissionRefusal ? error : (0, ownership_claim_exports.claimFailure)(error, "stim ios");
1765
+ if (refusal) return {
1766
+ failed: true,
1767
+ code: refusal.code,
1768
+ reason: refusal.message,
1769
+ remedy: refusal.remedy
1770
+ };
1771
+ return {
1772
+ failed: true,
1773
+ reason: `Could not boot simulator ${udid}: ${error?.message || error}`
1774
+ };
1775
+ }
1776
+ function buildLogFile(root) {
1777
+ return join(workspaceLogsDir$1(root), `build-ios.ndjson`);
1778
+ }
1779
+ function iosProjectPathError(settings, root, isExpo) {
1780
+ const error = iosProjectDirSettingError(settings, root);
1781
+ if (error || !iosProjectDirSetting(settings, root).custom || !isExpo()) return error;
1782
+ return "ios.projectPath applies to bare React Native apps only: expo prebuild generates and builds ios/. Remove it for this Expo app.";
1783
+ }
1784
+ function resolveIosBuildSetup(remoteBuild, settings, warn, env) {
1785
+ const [shapeError, ...lines] = settingShapeErrors(settings);
1786
+ if (shapeError) return {
1787
+ ok: false,
1788
+ failure: {
1789
+ code: "STIM_BAD_ARG",
1790
+ message: shapeError,
1791
+ lines,
1792
+ remedy: SETTING_SHAPE_REMEDY
1793
+ }
1794
+ };
1795
+ const placement = resolveBuildPlacement(remoteBuild);
1796
+ if (placement.failure) return {
1797
+ ok: false,
1798
+ failure: {
1799
+ ...placement.failure,
1800
+ setup: true
1801
+ }
1802
+ };
1803
+ let optimizations;
1804
+ try {
1805
+ optimizations = resolveOptimizations(settings, env);
1806
+ } catch (error) {
1807
+ return {
1808
+ ok: false,
1809
+ failure: {
1810
+ code: "STIM_BAD_ARG",
1811
+ message: error.message,
1812
+ remedy: SETTING_SHAPE_REMEDY
1813
+ }
1814
+ };
1815
+ }
1816
+ for (const key of unknownSettingKeys(settings)) warn("setting", inertSettingWarning(settings, key));
1817
+ const cacheProviderError = cacheProviderSettingError(settings);
1818
+ if (cacheProviderError) warn("cache", `${cacheProviderError} Using the local cache.`);
1819
+ return {
1820
+ ok: true,
1821
+ buildMachine: placement.selected,
1822
+ optimizations
1823
+ };
1824
+ }
1825
+ const MAX_PRINTED_DIAGNOSTICS = 6;
1826
+ function deviceLabel(device, udid) {
1827
+ const name = device?.deviceName || device?.name || null;
1828
+ return name ? `${name} (${shortUdid(udid)})` : shortUdid(udid);
1829
+ }
1830
+ function deviceShortName(device, udid) {
1831
+ return device?.deviceName || device?.name || shortUdid(udid);
1832
+ }
1833
+ function appNameFromPath(appPath) {
1834
+ if (typeof appPath !== "string" || appPath.trim() === "") return null;
1835
+ const name = basename(appPath).replace(/\.app$/i, "");
1836
+ return name === "" ? null : name;
1837
+ }
1838
+ function iosConfigurationSetting(settings) {
1839
+ const ios = settings?.["ios"];
1840
+ if (!ios || typeof ios !== "object" || Array.isArray(ios)) return null;
1841
+ const raw = ios["configuration"];
1842
+ return typeof raw === "string" && raw.trim() !== "" ? raw.trim() : null;
1843
+ }
1844
+ function resolveConfiguration(flag, settings) {
1845
+ return (typeof flag === "string" && flag.trim() !== "" ? flag.trim() : null) || iosConfigurationSetting(settings);
1846
+ }
1847
+ function resolveSchemeSelection({ scheme, easProfile }, settings) {
1848
+ if (typeof scheme === "string" || easProfile !== void 0) return scheme ?? void 0;
1849
+ return iosStringSetting(settings, "scheme") ?? void 0;
1850
+ }
1851
+ function iosStringSetting(settings, key) {
1852
+ const ios = settings?.["ios"];
1853
+ if (!ios || typeof ios !== "object" || Array.isArray(ios)) return null;
1854
+ const raw = ios[key];
1855
+ return typeof raw === "string" && raw.trim() !== "" ? raw.trim() : null;
1856
+ }
1857
+ function resolveDeviceType(flag, settings) {
1858
+ return (typeof flag === "string" && flag.trim() !== "" ? flag.trim() : null) || iosStringSetting(settings, "deviceType");
1859
+ }
1860
+ function resolveRuntime(flag, settings) {
1861
+ return (typeof flag === "string" && flag.trim() !== "" ? flag.trim() : null) || iosStringSetting(settings, "runtime");
1862
+ }
1863
+ function resolveSimulatorAppFlag(flag, physical, remoteBackend, automatic = false) {
1864
+ if (flag === void 0) return {};
1865
+ let simulatorApp;
1866
+ try {
1867
+ simulatorApp = parseIosSimulatorApp(flag, "--simulator-app");
1868
+ } catch (error) {
1869
+ return { refusal: {
1870
+ code: "STIM_BAD_ARG",
1871
+ message: error.message
1872
+ } };
1873
+ }
1874
+ if (physical || remoteBackend && !automatic) return { refusal: {
1875
+ code: "STIM_BAD_ARG",
1876
+ message: "--simulator-app only applies to a local owned iOS simulator.",
1877
+ remedy: "Drop --simulator-app when using a physical or remote device."
1878
+ } };
1879
+ return { simulatorApp };
1880
+ }
1881
+ async function deviceModelRefusal({ slot, deviceTypeFlag, runtimeFlag, deviceType, runtime, deviceTypeOrigin = null, runtimeOrigin = null, physical, remoteBackend, hosted = false, listRuntimes, signal, snapshot }) {
1882
+ if (slot && slot !== "default" && remoteBackend) return {
1883
+ code: "STIM_BAD_ARG",
1884
+ message: "Named slots currently support local simulators and physical devices.",
1885
+ remedy: "Use the default slot for a remote session."
1886
+ };
1887
+ if (typeof deviceTypeFlag === "string" && deviceTypeFlag.trim() === "") return {
1888
+ code: "STIM_BAD_ARG",
1889
+ message: "--device-type was given an empty name.",
1890
+ remedy: "Pass `--device-type <name>` with a model `xcrun simctl list devicetypes` names, e.g. \"iPad Pro 13-inch (M5)\"."
1891
+ };
1892
+ if (typeof runtimeFlag === "string" && runtimeFlag.trim() === "") return {
1893
+ code: "STIM_BAD_ARG",
1894
+ message: "--runtime was given an empty version.",
1895
+ remedy: "Pass `--runtime <version>` with a runtime `xcrun simctl list runtimes` reports, e.g. \"18.5\"."
1896
+ };
1897
+ if (remoteBackend) {
1898
+ const eas = remoteBackend === "eas";
1899
+ const given = [!eas && deviceTypeFlag && "--device-type", runtimeFlag && "--runtime"].filter(Boolean).join(" and ");
1900
+ if (given) return {
1901
+ code: "STIM_BAD_ARG",
1902
+ message: `${given} ${given.includes(" and ") ? "apply" : "applies"} only to a local owned iOS simulator; the ${remoteBackend} remote backend chooses its own ${eas ? "iOS runtime" : "device"}.`,
1903
+ remedy: `Drop ${given} for a remote run. For a local owned simulator, drop --remote and unset ios.remote with \`stim settings unset ios.remote --scope <machine|workspace|repo|committed>\`.`
1904
+ };
1905
+ return null;
1906
+ }
1907
+ if (physical || hosted) return null;
1908
+ if (!deviceType && !runtime) return null;
1909
+ let runtimes;
1910
+ try {
1911
+ runtimes = await listRuntimes({
1912
+ signal,
1913
+ snapshot
1914
+ });
1915
+ } catch (error) {
1916
+ return {
1917
+ code: "STIM_NO_DEVICE",
1918
+ message: `Could not read the installed simulator runtimes: ${error?.message || error}`,
1919
+ remedy: "Run `stim doctor` to check the simulator toolchain, then try again."
1920
+ };
1921
+ }
1922
+ const runtimeRefusal = unknownIosRuntimeRefusal(runtime, runtimes);
1923
+ if (runtimeRefusal) {
1924
+ const { message, remedy } = layerNote(runtimeRefusal, "ios.runtime", runtimeFlag, runtimeOrigin);
1925
+ return {
1926
+ code: "STIM_BAD_ARG",
1927
+ message,
1928
+ remedy
1929
+ };
1930
+ }
1931
+ const deviceTypeRefusal = unknownIosDeviceTypeRefusal(deviceType, runtimes, runtime);
1932
+ if (deviceTypeRefusal) {
1933
+ const { message, remedy } = layerNote(deviceTypeRefusal, "ios.deviceType", deviceTypeFlag, deviceTypeOrigin);
1934
+ return {
1935
+ code: "STIM_BAD_ARG",
1936
+ message,
1937
+ remedy
1938
+ };
1939
+ }
1940
+ return null;
1941
+ }
1942
+ function ownedSimFailure(error) {
1943
+ return {
1944
+ code: "STIM_NO_DEVICE",
1945
+ message: `Could not ensure an owned iOS simulator: ${error?.message || error}`,
1946
+ remedy: error instanceof IosDeviceMismatchError ? error.remedy : "Run `stim doctor` to check the simulator toolchain, then try again."
1947
+ };
1948
+ }
1949
+ function isReleaseConfiguration(configuration) {
1950
+ return typeof configuration === "string" && configuration.trim() !== "" && configuration.trim().toLowerCase() !== "debug";
1951
+ }
1952
+ function simulatorBuildArch({ physical, remoteArch, hostArch, configuration }) {
1953
+ if (physical) return null;
1954
+ if (remoteArch) return remoteArch;
1955
+ return isReleaseConfiguration(configuration) ? null : hostArch;
1956
+ }
1957
+ function iosProviderRunOptions(configuration, arch) {
1958
+ if (arch) return {
1959
+ configuration: configuration || "Debug",
1960
+ arch
1961
+ };
1962
+ return configuration ? { configuration } : null;
1963
+ }
1964
+ function podAction(podState, verdict, { prebuildRan = false } = {}) {
1965
+ if (verdict?.stale) return {
1966
+ install: true,
1967
+ reason: verdict.reason
1968
+ };
1969
+ if (verdict?.noPods && podState?.hasPodfile) return {
1970
+ install: true,
1971
+ reason: "ios/Podfile exists but no pods are installed"
1972
+ };
1973
+ if (prebuildRan && podState?.hasPodfile) return {
1974
+ install: true,
1975
+ reason: "prebuild updated ios/ in place"
1976
+ };
1977
+ return { install: false };
1978
+ }
1979
+ function xcodeFailureReport(result, logPath) {
1980
+ const diagnostics = result.diagnostics;
1981
+ const code = result.exitCode;
1982
+ const how = code === null ? "" : ` (exit code ${code})`;
1983
+ return {
1984
+ message: diagnostics.length ? `\`xcodebuild\` failed${how} with ${diagnostics.length} diagnostic${diagnostics.length === 1 ? "" : "s"}.` : `\`xcodebuild\` failed${how} with no recognizable diagnostic.`,
1985
+ remedy: diagnostics.find((d) => d?.remedy)?.remedy || `See ${logPath} for the transcript.`
1986
+ };
1987
+ }
1988
+ function printDiagnostics(note, result) {
1989
+ const diagnostics = result.diagnostics;
1990
+ const shown = diagnostics.slice(0, MAX_PRINTED_DIAGNOSTICS);
1991
+ for (const diagnostic of shown) note(chalk.red(phaseLine("error", describeDiagnostic(diagnostic))));
1992
+ const hidden = diagnostics.length - shown.length + result.truncated;
1993
+ if (hidden > 0) note(chalk.dim(phaseLine("error", `... and ${hidden} more diagnostic${hidden === 1 ? "" : "s"} in the log`)));
1994
+ if (diagnostics.length === 0) {
1995
+ note(chalk.red(phaseLine("error", "xcodebuild failed with no recognizable diagnostic; last lines:")));
1996
+ for (const line of result.tail.slice(-5)) note(chalk.dim(phaseLine("", line)));
1997
+ }
1998
+ }
1999
+ function resolveIosWait(opts, physical) {
2000
+ const noWait = opts.wait === false;
2001
+ if (opts.waitConflict) return { failure: {
2002
+ code: "STIM_BAD_ARG",
2003
+ message: "--wait and --no-wait ask for opposite things.",
2004
+ remedy: "Pass only one of `--wait <seconds>` and `--no-wait`."
2005
+ } };
2006
+ const waitParsed = parseDeviceWait(noWait ? void 0 : opts.wait);
2007
+ if ("error" in waitParsed) return { failure: {
2008
+ code: "STIM_BAD_ARG",
2009
+ message: waitParsed.error,
2010
+ remedy: "Pass a whole number of seconds, e.g. --wait 90. `--wait 0` refuses a busy lease or device slot at once."
2011
+ } };
2012
+ return {
2013
+ waitSeconds: waitParsed.seconds,
2014
+ noWait,
2015
+ checkCapacity: !physical && (noWait || waitParsed.seconds === 0),
2016
+ deviceSlotWaitMs: noWait ? 0 : opts.wait === void 0 && !physical ? DEFAULT_DEVICE_SLOT_WAIT_MS : waitParsed.seconds * 1e3
2017
+ };
2018
+ }
2019
+ function createIosDeviceWaitRun(stats, progress, signal) {
2020
+ const controller = new AbortController();
2021
+ let waiting = false;
2022
+ let boot;
2023
+ let outcome;
2024
+ return {
2025
+ policy: {
2026
+ signal: signal ? AbortSignal.any([controller.signal, signal]) : controller.signal,
2027
+ waitingFor(info) {
2028
+ waiting = info !== null;
2029
+ progress.waitingFor(info, "device-slot");
2030
+ },
2031
+ onWait: stats.addDeviceSlotWaitMs,
2032
+ onBootStart: () => progress.bootStarted()
2033
+ },
2034
+ record(next) {
2035
+ if (waiting) outcome = next;
2036
+ else stats.record(next);
2037
+ },
2038
+ booting(pending) {
2039
+ boot ??= pending?.done;
2040
+ },
2041
+ async finish() {
2042
+ const queued = waiting;
2043
+ controller.abort();
2044
+ if (queued) await boot?.catch(() => {});
2045
+ if (outcome) stats.record(outcome);
2046
+ }
2047
+ };
2048
+ }
2049
+ //#endregion
2050
+ export { pairedMachines as $, fingerprintMismatchRemedy as A, DEVICE_BUSY as B, clearIosAdoptionPending as C, OffloadRefusal as D, muteBootedSimulator as E, requireLocalBuild as F, lostLine as G, DEVICE_WAIT_POLL_MS as H, resolveBuildMachine as I, releaseLeaseOnAbort as J, lostRefusal as K, resolveBuildPlacement as L, namedBuildMachine as M, parseBuildMachineOption as N, automaticBuild as O, podsFailedRemedy as P, inspectBuildMachines as Q, workerFailureReason as R, xcodeFailureReport as S, ensureOwnedIosDevice as T, acquireRunLease as U, DEVICE_WAIT_LINE_MS as V, leaseExpiryText as W, waitFlagConflict as X, runLease as Y, waitForDevice as Z, resolveIosWait as _, deviceModelRefusal as a, resolveSimulatorAppFlag as b, iosProjectPathError as c, ownedSimFailure as d, predictedRefusal as et, podAction as f, resolveIosBuildSetup as g, resolveDeviceType as h, deviceLabel as i, missingPackageManagerRemedy as j, buildPlacementSettings as k, iosProviderRunOptions as l, resolveConfiguration as m, buildLogFile as n, hostingMachines as nt, deviceShortName as o, printDiagnostics as p, parseDeviceWait as q, createIosDeviceWaitRun as r, inspectDeviceHostMachines as rt, iosConfigurationSetting as s, appNameFromPath as t, configuredMachines as tt, isReleaseConfiguration as u, resolveRuntime as v, ensureIosBooted as w, simulatorBuildArch as x, resolveSchemeSelection as y, DEBUG_VERIFY_STEP_MS as z };