agent-device 0.19.2 → 0.20.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 (178) hide show
  1. package/README.md +61 -70
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.0.apk +0 -0
  3. package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.0.apk.sha256 +1 -0
  4. package/android/ime-helper/dist/agent-device-android-ime-helper-0.20.0.manifest.json +10 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.0.apk +0 -0
  6. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.0.apk.sha256 +1 -0
  7. package/{android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.19.2.manifest.json → android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.20.0.manifest.json} +6 -6
  8. package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +2 -0
  9. package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +5 -0
  10. package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.h +12 -10
  11. package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.m +154 -185
  12. package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +113 -19
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+BlockingSystemModalResolution.swift +82 -0
  14. package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +275 -113
  15. package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +2 -2
  16. package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +150 -104
  17. package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +56 -2
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+LifecycleCacheTests.swift +73 -0
  19. package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +44 -14
  20. package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +2 -2
  21. package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +2 -106
  22. package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +126 -11
  23. package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +51 -8
  24. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotTraversalIdentityTests.swift +24 -0
  25. package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +1 -1
  26. package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +43 -35
  27. package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +14 -0
  28. package/dist/src/agent-browser-tool.js +1 -1
  29. package/dist/src/agent-device-client.js +3 -0
  30. package/dist/src/android-adb.d.ts +1 -1
  31. package/dist/src/android-adb.js +1 -1
  32. package/dist/src/android-input-method-overlays.js +1 -0
  33. package/dist/src/android-input-ownership.js +1 -6
  34. package/dist/src/android-system-chrome.js +1 -0
  35. package/dist/src/android.js +1 -1
  36. package/dist/src/app-lifecycle.js +5 -5
  37. package/dist/src/app-log-request-scope.js +1 -0
  38. package/dist/src/app-resolution.js +1 -0
  39. package/dist/src/apple-multitouch-support.js +1 -0
  40. package/dist/src/apps.js +5 -5
  41. package/dist/src/audio-probe.js +1 -1
  42. package/dist/src/boot-diagnostics.js +2 -0
  43. package/dist/src/cli-config.js +1 -0
  44. package/dist/src/cli-help.js +64 -30
  45. package/dist/src/cli-runner.js +1 -1
  46. package/dist/src/cli.js +15 -11
  47. package/dist/src/command-schema.js +3 -3
  48. package/dist/src/config.js +1 -0
  49. package/dist/src/context.js +1 -0
  50. package/dist/src/contracts.d.ts +1 -1
  51. package/dist/src/contracts.js +1 -1
  52. package/dist/src/daemon-shutdown-report.js +1 -0
  53. package/dist/src/debug-symbols.js +1 -1
  54. package/dist/src/device-input-state.js +1 -1
  55. package/dist/src/devices2.js +1 -1
  56. package/dist/src/find.js +1 -1
  57. package/dist/src/finders.js +1 -1
  58. package/dist/src/generic.js +1 -1
  59. package/dist/src/helper.js +1 -1
  60. package/dist/src/index.d.ts +412 -289
  61. package/dist/src/index.js +1 -1
  62. package/dist/src/input-actions.js +4 -3
  63. package/dist/src/input-actions2.js +1 -1
  64. package/dist/src/install-artifact.js +1 -0
  65. package/dist/src/install-source.d.ts +5 -1
  66. package/dist/src/install-source.js +1 -1
  67. package/dist/src/install-source2.js +1 -1
  68. package/dist/src/interaction-snapshot.js +1 -1
  69. package/dist/src/interaction.d.ts +230 -0
  70. package/dist/src/interaction.js +1 -1
  71. package/dist/src/interactor.js +2 -2
  72. package/dist/src/internal/bin.js +1 -1
  73. package/dist/src/internal/daemon.js +43 -17
  74. package/dist/src/internal/png-worker.d.ts +22 -0
  75. package/dist/src/internal/png-worker.js +1 -1
  76. package/dist/src/launch-console.js +1 -0
  77. package/dist/src/lease-context.js +1 -0
  78. package/dist/src/lease.js +1 -1
  79. package/dist/src/linux.js +1 -1
  80. package/dist/src/logcat.js +5 -0
  81. package/dist/src/metro.d.ts +2 -2
  82. package/dist/src/notifications.js +1 -1
  83. package/dist/src/png-worker-contract.js +1 -1
  84. package/dist/src/process-lock.js +1 -0
  85. package/dist/src/react-native.js +1 -1
  86. package/dist/src/record-trace.js +1 -1
  87. package/dist/src/register-builtins.js +1 -0
  88. package/dist/src/registry.js +24 -24
  89. package/dist/src/reporting.js +8 -7
  90. package/dist/src/runner-client.js +1 -1
  91. package/dist/src/runner-disposal.js +2 -0
  92. package/dist/src/runner-lease.js +1 -0
  93. package/dist/src/runner-sequence.js +1 -1
  94. package/dist/src/runtime-transport.js +1 -1
  95. package/dist/src/runtime.js +3 -3
  96. package/dist/src/runtime2.js +1 -0
  97. package/dist/src/sdk-android-adb.d.ts +119 -33
  98. package/dist/src/sdk-android-adb.js +4 -4
  99. package/dist/src/sdk-app-inventory.js +1 -1
  100. package/dist/src/sdk-batch-runner.d.ts +2 -1
  101. package/dist/src/sdk-batch-runner.js +2 -2
  102. package/dist/src/sdk-batch.js +2 -2
  103. package/dist/src/sdk-contracts.d.ts +105 -98
  104. package/dist/src/sdk-contracts.js +2 -2
  105. package/dist/src/sdk-device.js +1 -0
  106. package/dist/src/sdk-finders.d.ts +3 -3
  107. package/dist/src/sdk-finders.js +1 -1
  108. package/dist/src/sdk-io.d.ts +1 -1
  109. package/dist/src/sdk-io.js +1 -1
  110. package/dist/src/sdk-remote-config.d.ts +9 -1
  111. package/dist/src/sdk-remote-config.js +1 -1
  112. package/dist/src/sdk-selectors.js +1 -1
  113. package/dist/src/selector-runtime.js +1 -1
  114. package/dist/src/selector-vocabulary.js +1 -0
  115. package/dist/src/selectors.d.ts +12 -3
  116. package/dist/src/selectors.js +1 -1
  117. package/dist/src/server.js +3 -3
  118. package/dist/src/session-target-evidence.js +1 -0
  119. package/dist/src/session.js +8 -10
  120. package/dist/src/setting-state.js +1 -1
  121. package/dist/src/simulator.js +1 -1
  122. package/dist/src/snapshot-diagnostics.js +5 -2
  123. package/dist/src/snapshot.js +1 -1
  124. package/dist/src/snapshot2.js +1 -2
  125. package/dist/src/tool-provider.js +2 -2
  126. package/dist/src/tool-provider2.js +1 -1
  127. package/dist/src/tv-remote.js +13 -12
  128. package/dist/src/url.js +1 -1
  129. package/dist/src/web.js +1 -1
  130. package/package.json +33 -20
  131. package/server.json +2 -2
  132. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.19.2.apk +0 -0
  133. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.19.2.apk.sha256 +0 -1
  134. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.19.2.manifest.json +0 -10
  135. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.19.2.apk +0 -0
  136. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.19.2.apk.sha256 +0 -1
  137. package/dist/src/apple-runner-options.js +0 -1
  138. package/dist/src/cli-output.js +0 -1
  139. package/dist/src/client.js +0 -3
  140. package/dist/src/handler-utils.js +0 -1
  141. package/dist/src/output-path.js +0 -1
  142. package/dist/src/points.js +0 -4
  143. package/dist/src/provider.js +0 -1
  144. package/dist/src/providers.js +0 -1
  145. package/dist/src/record-trace-recording.js +0 -23
  146. package/dist/src/recording-provider.js +0 -1
  147. package/dist/src/selectors2.js +0 -1
  148. package/dist/src/simctl.js +0 -1
  149. package/dist/src/snapshot-helper.js +0 -5
  150. package/dist/src/ttl-memo.js +0 -1
  151. package/dist/src/xml.js +0 -2
  152. /package/{macos-helper → apple/macos-helper}/Package.swift +0 -0
  153. /package/{macos-helper → apple/macos-helper}/Sources/AgentDeviceMacOSHelper/AudioProbe.swift +0 -0
  154. /package/{macos-helper → apple/macos-helper}/Sources/AgentDeviceMacOSHelper/SnapshotTraversal.swift +0 -0
  155. /package/{macos-helper → apple/macos-helper}/Sources/AgentDeviceMacOSHelper/main.swift +0 -0
  156. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +0 -0
  157. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.pbxproj +0 -0
  158. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.xcworkspace/contents.xcworkspacedata +0 -0
  159. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/xcshareddata/xcschemes/AgentDeviceRunner.xcscheme +0 -0
  160. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests-Bridging-Header.h +0 -0
  161. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests.entitlements +0 -0
  162. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerObjCExceptionCatcher.h +0 -0
  163. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerObjCExceptionCatcher.m +0 -0
  164. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTapPointPolicy.swift +0 -0
  165. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +0 -0
  166. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Environment.swift +0 -0
  167. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Exceptions.swift +0 -0
  168. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+FlatSnapshotFiltering.swift +0 -0
  169. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +0 -0
  170. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift +0 -0
  171. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +0 -0
  172. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +0 -0
  173. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TvRemote.swift +0 -0
  174. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/AgentDeviceRunnerUITests.xctestplan +0 -0
  175. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/RecordingScripts/recording-overlay.swift +0 -0
  176. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/RecordingScripts/recording-resize.swift +0 -0
  177. /package/dist/{apple-runner → apple/runner}/AgentDeviceRunner/RecordingScripts/recording-trim.swift +0 -0
  178. /package/{src/platforms/linux → linux}/atspi-dump.py +0 -0
@@ -1,9 +1,10 @@
1
- import{F as e}from"./sdk-contracts.js";import{Bn as t,Kn as n,Vn as r,qn as i}from"./tv-remote.js";import a from"node:fs";import o from"node:os";import s from"node:path";import{pathToFileURL as c}from"node:url";const l=[`onSuiteStart`,`onTestStart`,`onTestStep`,`onTestResult`,`onSuiteEnd`,`getExitCode`];async function u(e){let t=ee(e.modulePath);return ne(await d(await te(t),e.modulePath)({spec:e.raw,modulePath:t}),e.modulePath)}function d(t,n){let r=t.createReporter??t.default??t.reporter;if(!r)throw new e(`INVALID_ARGS`,`Custom test reporter ${n} must export default, createReporter, or reporter.`);return typeof r==`function`?r:()=>r}function ee(e){if(e.startsWith(`file:`))return e;let t=e.startsWith(`~/`)?s.join(o.homedir(),e.slice(2)):e;return s.resolve(process.cwd(),t)}async function te(t){try{return await(t.startsWith(`file:`)?import(t):import(c(t).href))}catch(n){throw new e(`INVALID_ARGS`,`Failed to load custom test reporter ${t}: ${n instanceof Error?n.message:String(n)}`)}}function ne(t,n){if(!t||typeof t!=`object`)throw new e(`INVALID_ARGS`,`Custom test reporter ${n} must export a reporter object or factory.`);let r=t;if(typeof r.name!=`string`||r.name.trim().length===0)throw new e(`INVALID_ARGS`,`Custom test reporter ${n} must define name.`);for(let t of l)if(!(r[t]===void 0||typeof r[t]==`function`))throw new e(`INVALID_ARGS`,`Custom test reporter ${n} ${t} must be a function.`);return r}function f(e){let t=Math.max(0,e)/1e3;return t>=10?`${t.toFixed(1)}s`:t>=1?`${t.toFixed(2)}s`:`${t.toFixed(3).replace(/0+$/,``).replace(/\.$/,``)}s`}function re(e){if(e.status===`skipped`)return[];let t=p(e);return t.length===0?[]:[e.attempts>1?`steps (attempt ${e.attempts}):`:`steps:`,...t.map(({stop:e,start:t})=>_(e,t))]}function ie(e){let t=p(e),n=t.findIndex(({stop:e})=>e.ok===!1);if(n<0)return[];let r=t.slice(Math.max(0,n-2),n+1);return[e.attempts>1?`steps (attempt ${e.attempts}):`:`steps:`,...r.map(({stop:e,start:t})=>_(e,t))]}function p(e){let t=oe(e);if(!t)return[];let n=se(t);if(n.length===0)return[];let r=[],i=[];for(let e of n){if(ce(e)){r.push(e);continue}le(e)&&i.push({stop:e,start:ae(r,e)})}return i}function ae(e,t){let n=t.command,r=e.findIndex(e=>e.step===t.step&&(n===void 0||e.command===void 0||e.command===n));if(!(r<0))return e.splice(r,1)[0]}function oe(e){return e.artifactsDir?s.join(e.artifactsDir,`attempt-${e.attempts}`,`replay-timing.ndjson`):void 0}function se(e){try{return a.readFileSync(e,`utf8`).split(/\r?\n/).filter(e=>e.trim().length>0).flatMap(e=>{try{let t=JSON.parse(e);return y(t)?[t]:[]}catch{return[]}})}catch{return[]}}function ce(e){return e.type===`replay_action_start`&&m(e)&&h(e,`line`)&&g(e,`command`)&&(e.positionals===void 0||Array.isArray(e.positionals))}function le(e){return de([e.type===`replay_action_stop`&&m(e)&&h(e,`line`)&&g(e,`command`),ue(e,`ok`),h(e,`durationMs`),g(e,`errorCode`),e.resultTiming===void 0||y(e.resultTiming)])}function m(e){return typeof e.step==`number`}function h(e,t){return e[t]===void 0||typeof e[t]==`number`}function g(e,t){return e[t]===void 0||typeof e[t]==`string`}function ue(e,t){return e[t]===void 0||typeof e[t]==`boolean`}function de(e){return e.every(Boolean)}function _(e,t){return` ${e.ok===!1?`[FAIL] `:e.ok===!0?``:`[info] `}${fe(t,e)}${v(e,t)}`}function v(e,t){let n=t?.line??e.line,r=[typeof n==`number`?`line ${n}`:``,typeof e.durationMs==`number`?f(e.durationMs):``,e.errorCode??``,e.resultTiming?`timing ${JSON.stringify(e.resultTiming)}`:``].filter(Boolean);return r.length>0?` (${r.join(`, `)})`:``}function fe(e,t){return[pe(e?.command??t.command),...(e?.positionals??[]).map(me)].join(` `)}function pe(e){if(!e)return`unknown`;if(!e.startsWith(`__maestro`))return e;let t=e.slice(9);return t.length>0?t[0].toLowerCase()+t.slice(1):e}function me(e){return typeof e==`string`?JSON.stringify(e):typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}function y(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}const b={interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`]},he=b.interval;function ge(e={}){let t=new Set,n=!1,r=0;return{render(i){if(i.type===`suite-start`){t.clear(),n=!1;return}if(i.type===`test-step`){if(!e.liveProgress)return;n=!0;let t=_e(r);return r+=1,{text:O(ye(i.test,e,t)),newline:!1}}if(i.type!==`test-result`)return;if(Oe(i.test)){let e=ke(i.test);if(t.has(e))return;t.add(e)}let a=ve(i.test,e);if(!a)return;let o=n?O(a):a;return n=!1,{text:o,newline:!0}}}}function _e(e){return b.frames[e%b.frames.length]??b.frames[0]}function ve(e,t={}){if(e.status===`fail`&&e.retrying)return;let n=[S(e)];return Se(n,e,t),t.verbose&&n.push(...Ne(e)),n.join(`
2
- `)}function ye(e,t,n){let r=e.title?.trim(),a=s.basename(e.file),o=i(process.stderr),c=be(n,{useColor:o}),l=`${E(e,{useColor:o})}${xe(e,{useColor:o})}`,u=`${c} `;return A(r?`${u}${A(r,Math.max(0,k(t.columns)-j(u)-j(l)))}${l}`:`${u}${a}${l}`,t.columns)}function be(e,t={}){return t.useColor?T(e,`blue`):e}function xe(e,t={}){let n=`${e.stepIndex??0}/${e.stepTotal??0}`,r=e.stepCommand?.trim(),i=e.stepValue?.trim();if(!t.useColor)return` [${[n,r,i].filter(Boolean).join(` `)}]`;let a=T(`[`,`dim`),o=T(`]`,`dim`);return` ${a}${[T(n,`dim`),r?T(r,`magenta`):``,i?T(i,`green`):``].filter(Boolean).join(` `)}${o}`}function Se(e,t,n){if(Ce(t,n))return;let r=we(t),i=Te(t);r&&e.push(r),i&&e.push(i),Ee(e,t),e.push(...x(t))}function Ce(e,t){return t.verbose===!0&&e.status===`fail`}function we(e){return e.status===`fail`&&e.title?.trim()?` file: ${s.basename(e.file)}`:void 0}function Te(e){let t=e.message?.replace(/\s+/g,` `).trim();if(t)return` ${e.status===`fail`?`failed at: ${t}`:t}`}function Ee(e,t){let n=t.hint?.replace(/\s+/g,` `).trim();t.status===`fail`&&n&&e.push(` hint: ${n}`)}function x(e){if(e.status!==`fail`||e.retrying)return[];let t=[];return e.session&&t.push(` session: ${e.session}`),e.artifactsDir&&t.push(` artifacts: ${e.artifactsDir}`),t}function S(e){let t=i(process.stderr);return`${w(e)} ${C(e)}${E(e,{useColor:t})}${e.durationMs===void 0?``:` ${De(e,{useColor:t})}`}`}function C(e){let t=e.title?.trim(),n=s.basename(e.file);return t||n}function w(e){return e.status===`pass`?t(`pass`,{passFormat:e.attempt&&e.attempt>1?`yellow`:`green`}):t(e.status===`fail`?`fail`:`skip`)}function T(e,t){return r(e,t,{validateStream:!1})}function E(e,t={}){if(typeof e.shardIndex!=`number`)return``;let n=typeof e.shardCount==`number`?e.shardCount:`?`,r=D(e),i=` [${e.shardIndex+1}/${n}${r?` ${r}`:``}]`;return t.useColor?T(i,`dim`):i}function D(e){return e.deviceName?.trim()||e.deviceId?.trim()||void 0}function De(e,t={}){let n=f(e.durationMs??0);return t.useColor?T(n,`yellow`):n}function Oe(e){return e.status===`pass`||e.status===`skip`||e.status===`fail`&&!e.retrying}function ke(e){let t=typeof e.shardIndex==`number`?e.shardIndex:``;return[e.status,e.index,e.total,e.file,e.title??``,t].join(`\0`)}function O(e){return`\r\x1B[2K${e}`}function k(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):80}function A(e,t){let n=k(t);return j(e)<=n?e:n<=0?``:n<=3?`.`.repeat(n):`${je(e,n-3)}...${Ae(e)?`\x1B[0m`:``}`}function j(e){let t=0;for(let n=0;n<e.length;){let r=M(e,n);if(r){n+=r.length;continue}t+=1,n+=1}return t}function Ae(e){return e.includes(`\x1B[`)}function je(e,t){if(t<=0)return``;let n=0,r=``;for(let i=0;i<e.length&&n<t;){let t=M(e,i);if(t){r+=t,i+=t.length;continue}r+=e[i],i+=1,n+=1}return r}function M(e,t){if(!e.startsWith(`\x1B[`,t))return null;for(let n=t+2;n<e.length;n+=1)if(Me(e.charCodeAt(n)))return e.slice(t,n+1);return null}function Me(e){return e>=64&&e<=126}function Ne(e){return e.status!==`pass`&&e.status!==`fail`||!e.artifactsDir||!e.attempt?[]:re(e.status===`pass`?Pe(e):Fe(e)).map(e=>` ${e}`)}function Pe(e){return{...N(e),status:`passed`,replayed:0,healed:0}}function Fe(e){return{...N(e),status:`failed`,error:{code:`COMMAND_FAILED`,message:e.message??`Unknown test failure`}}}function N(e){return{file:e.file,title:e.title,durationMs:e.durationMs??0,attempts:e.attempt??1,artifactsDir:e.artifactsDir,session:e.session??``}}function P(e){return+(e.failed>0)}function Ie(e){return e.status===`failed`}function F(e){return e.status===`passed`&&e.attempts>1}function I(e){let t=K(e),n=s.basename(e.file);return`${t&&t.length>0?t:n}${q(e)}`}function Le(e){return`${K(e)??s.basename(e.file)}${q(e)}`}function L(e,t){return`artifactsDir`in e&&e.artifactsDir?`${t}: ${e.artifactsDir}`:void 0}function Re(e){return K(e)?`file: ${s.basename(e.file)}`:void 0}function R(e){return e.hint?`hint: ${e.hint}`:void 0}function z(e,t){return e.diagnosticId?`${t}: ${e.diagnosticId}`:void 0}function B(e,t){return e.logPath?`${t}: ${e.logPath}`:void 0}function V(e,t,n={}){n.includeMessage&&e.push(`errorMessage: ${t.message}`),U(e,R(t)),U(e,z(t,`diagnosticId`)),U(e,B(t,`logPath`)),n.includeDetails!==!1&&H(e,t,n.detailsIndent)}function H(e,t,n){let r=t.details?JSON.stringify(t.details,null,n):void 0;r&&e.push(`details: ${r}`)}function ze(e,t){!(`shardIndex`in t)||typeof t.shardIndex!=`number`||(e.push(`shardIndex: ${t.shardIndex}`),U(e,typeof t.shardCount==`number`?`shardCount: ${t.shardCount}`:void 0),U(e,typeof t.deviceId==`string`?`deviceId: ${t.deviceId}`:void 0),U(e,typeof t.deviceName==`string`?`deviceName: ${t.deviceName}`:void 0))}function Be(e){return e.status===`passed`?(e.warnings??[]).map(e=>`warning: ${e}`):[]}function U(e,t){t&&e.push(t)}function W(e){return(Math.max(0,e)/1e3).toFixed(3)}function G(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`).replaceAll(`"`,`&quot;`).replaceAll(`'`,`&apos;`)}function Ve(e){return e!==void 0}function K(e){let t=e.title?.trim();return t&&t.length>0?t:void 0}function q(e){if(!(`shardIndex`in e)||typeof e.shardIndex!=`number`)return``;let t=typeof e.shardCount==`number`?e.shardCount:`?`,n=He(e);return` [${e.shardIndex+1}/${t}${n?` ${n}`:``}]`}function He(e){return(`deviceName`in e?e.deviceName?.trim():void 0)||(`deviceId`in e?e.deviceId?.trim():void 0)||void 0}function Ue(){let e,t,n,r=!1,i=(n,r)=>{o(),t=n.type===`test-step`?n:void 0,e??=ge({verbose:r.verbose,liveProgress:J(r),columns:r.stderr.columns});let i=e.render(n);i&&(r.stderr.write(i.newline?`${i.text}\n`:i.text),n.type===`test-step`&&J(r)&&a(r))},a=r=>{n||!t||(n=setInterval(()=>{if(!t)return;let n=e?.render(t);n&&r.stderr.write(n.newline?`${n.text}\n`:n.text)},he),n.unref?.())},o=()=>{n&&=(clearInterval(n),void 0)},s=e=>{r||!J(e)||(e.stderr.write(`\x1B[?25l`),r=!0)},c=e=>{r&&=(e.stderr.write(`\x1B[?25h`),!1)};return{name:`default`,onSuiteStart:(e,t)=>{s(t),i({type:`suite-start`,suite:e},t)},onTestStep:(e,t)=>{i({type:`test-step`,test:e},t)},onTestResult:(e,t)=>{i({type:`test-result`,test:e},t)},onSuiteEnd:(e,n)=>{o(),t=void 0,c(n),We(e,n)},getExitCode:P}}function J(e){return e.stderr.isTTY&&!process.env.CI}function We(e,t){let n=e.tests.filter(F);t.stdout.write(`${Ge(e,n.length)}\n`),Qe(e.tests.filter(Ie),t),Ze(n,t)}function Ge(e,t){let n=typeof e.durationMs==`number`?e.durationMs:void 0,r=i();return`Test summary: ${Ke(e.passed,{useColor:r})} ${qe(e.total,{useColor:r})}${e.failed>0?`, ${e.failed} failed`:``}${t>0?`, ${t} flaky`:``}${n===void 0?``:` in ${Je(n,{useColor:r})}`}`}function Ke(e,t={}){let n=`${e} passed`;return t.useColor?r(n,`green`):n}function qe(e,t={}){let n=`(${e})`;return t.useColor?r(n,`dim`):n}function Je(e,t={}){let n=f(e);return t.useColor?r(n,`yellow`):n}function Ye(){return i()?r(`✓`,`yellow`):`✓`}function Xe(e){return[R(e.error),L(e,`artifacts`),B(e.error,`log`),z(e.error,`diagnostic`)].filter(Ve)}function Ze(e,t){if(e.length!==0){t.stdout.write(`
1
+ import{_ as e}from"./sdk-contracts.js";import{Mn as t,Nn as n,Rn as r,Wn as i,zn as a}from"./tv-remote.js";import o from"node:fs";import s from"node:os";import c from"node:path";import{pathToFileURL as l}from"node:url";const u=[`onSuiteStart`,`onTestStart`,`onTestStep`,`onTestResult`,`onSuiteEnd`,`getExitCode`];async function ee(e){let t=te(e.modulePath);return re(await d(await ne(t),e.modulePath)({spec:e.raw,modulePath:t}),e.modulePath)}function d(t,n){let r=t.createReporter??t.default??t.reporter;if(!r)throw new e(`INVALID_ARGS`,`Custom test reporter ${n} must export default, createReporter, or reporter.`);return typeof r==`function`?r:()=>r}function te(e){if(e.startsWith(`file:`))return e;let t=e.startsWith(`~/`)?c.join(s.homedir(),e.slice(2)):e;return c.resolve(process.cwd(),t)}async function ne(t){try{return await(t.startsWith(`file:`)?import(t):import(l(t).href))}catch(n){throw new e(`INVALID_ARGS`,`Failed to load custom test reporter ${t}: ${n instanceof Error?n.message:String(n)}`)}}function re(t,n){if(!t||typeof t!=`object`)throw new e(`INVALID_ARGS`,`Custom test reporter ${n} must export a reporter object or factory.`);let r=t;if(typeof r.name!=`string`||r.name.trim().length===0)throw new e(`INVALID_ARGS`,`Custom test reporter ${n} must define name.`);for(let t of u)if(!(r[t]===void 0||typeof r[t]==`function`))throw new e(`INVALID_ARGS`,`Custom test reporter ${n} ${t} must be a function.`);return r}function f(e){let t=Math.max(0,e)/1e3;return t>=10?`${t.toFixed(1)}s`:t>=1?`${t.toFixed(2)}s`:`${t.toFixed(3).replace(/0+$/,``).replace(/\.$/,``)}s`}function ie(e){if(e.status===`skipped`)return[];let t=p(e);return t.length===0?[]:[e.attempts>1?`steps (attempt ${e.attempts}):`:`steps:`,...t.map(({stop:e,start:t})=>v(e,t))]}function ae(e){let t=p(e),n=t.findIndex(({stop:e})=>e.ok===!1);if(n<0)return[];let r=t.slice(Math.max(0,n-2),n+1);return[e.attempts>1?`steps (attempt ${e.attempts}):`:`steps:`,...r.map(({stop:e,start:t})=>v(e,t))]}function p(e){let t=oe(e);if(!t)return[];let n=se(t);if(n.length===0)return[];let r=[],i=[];for(let e of n){if(ce(e)){r.push(e);continue}le(e)&&i.push({stop:e,start:m(r,e)})}return i}function m(e,t){let n=t.command,r=e.findIndex(e=>e.step===t.step&&(n===void 0||e.command===void 0||e.command===n));if(!(r<0))return e.splice(r,1)[0]}function oe(e){return e.artifactsDir?c.join(e.artifactsDir,`attempt-${e.attempts}`,`replay-timing.ndjson`):void 0}function se(e){try{return o.readFileSync(e,`utf8`).split(/\r?\n/).filter(e=>e.trim().length>0).flatMap(e=>{try{let t=JSON.parse(e);return y(t)?[t]:[]}catch{return[]}})}catch{return[]}}function ce(e){return e.type===`replay_action_start`&&h(e)&&g(e,`line`)&&_(e,`command`)&&(e.positionals===void 0||Array.isArray(e.positionals))}function le(e){return de([e.type===`replay_action_stop`&&h(e)&&g(e,`line`)&&_(e,`command`),ue(e,`ok`),g(e,`durationMs`),_(e,`errorCode`),e.resultTiming===void 0||y(e.resultTiming)])}function h(e){return typeof e.step==`number`}function g(e,t){return e[t]===void 0||typeof e[t]==`number`}function _(e,t){return e[t]===void 0||typeof e[t]==`string`}function ue(e,t){return e[t]===void 0||typeof e[t]==`boolean`}function de(e){return e.every(Boolean)}function v(e,t){return` ${e.ok===!1?`[FAIL] `:e.ok===!0?``:`[info] `}${pe(t,e)}${fe(e,t)}`}function fe(e,t){let n=t?.line??e.line,r=[typeof n==`number`?`line ${n}`:``,typeof e.durationMs==`number`?f(e.durationMs):``,e.errorCode??``,e.resultTiming?`timing ${JSON.stringify(e.resultTiming)}`:``].filter(Boolean);return r.length>0?` (${r.join(`, `)})`:``}function pe(e,t){return[me(e?.command??t.command),...(e?.positionals??[]).map(he)].join(` `)}function me(e){return e??`unknown`}function he(e){return typeof e==`string`?JSON.stringify(e):typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}function y(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}const b={interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`]},ge=b.interval;function _e(e={}){let t=new Set,n=!1,r=0;return{render(i){if(i.type===`suite-start`){t.clear(),n=!1;return}if(i.type===`test-step`){if(!e.liveProgress)return;n=!0;let t=ve(r);return r+=1,{text:O(be(i.test,e,t)),newline:!1}}if(i.type!==`test-result`)return;if(ke(i.test)){let e=Ae(i.test);if(t.has(e))return;t.add(e)}let a=ye(i.test,e);if(!a)return;let o=n?O(a):a;return n=!1,{text:o,newline:!0}}}}function ve(e){return b.frames[e%b.frames.length]??b.frames[0]}function ye(e,t={}){if(e.status===`fail`&&e.retrying)return;let n=[C(e)];return Ce(n,e,t),t.verbose&&n.push(...Pe(e)),n.join(`
2
+ `)}function be(e,t,n){let r=e.title?.trim(),i=c.basename(e.file),o=a(process.stderr),s=xe(n,{useColor:o}),l=`${D(e,{useColor:o})}${Se(e,{useColor:o})}`,u=`${s} `;return A(r?`${u}${A(r,Math.max(0,k(t.columns)-j(u)-j(l)))}${l}`:`${u}${i}${l}`,t.columns)}function xe(e,t={}){return t.useColor?E(e,`blue`):e}function Se(e,t={}){let n=`${e.stepIndex??0}/${e.stepTotal??0}`,r=e.stepCommand?.trim(),i=e.stepValue?.trim();if(!t.useColor)return` [${[n,r,i].filter(Boolean).join(` `)}]`;let a=E(`[`,`dim`),o=E(`]`,`dim`);return` ${a}${[E(n,`dim`),r?E(r,`magenta`):``,i?E(i,`green`):``].filter(Boolean).join(` `)}${o}`}function Ce(e,t,n){if(we(t,n))return;let r=Te(t),i=Ee(t);r&&e.push(r),i&&e.push(i),x(e,t),e.push(...S(t))}function we(e,t){return t.verbose===!0&&e.status===`fail`}function Te(e){return e.status===`fail`&&e.title?.trim()?` file: ${c.basename(e.file)}`:void 0}function Ee(e){let t=e.message?.replace(/\s+/g,` `).trim();if(t)return` ${e.status===`fail`?`failed at: ${t}`:t}`}function x(e,t){let n=t.hint?.replace(/\s+/g,` `).trim();t.status===`fail`&&n&&e.push(` hint: ${n}`)}function S(e){if(e.status!==`fail`||e.retrying)return[];let t=[];return e.session&&t.push(` session: ${e.session}`),e.artifactsDir&&t.push(` artifacts: ${e.artifactsDir}`),t}function C(e){let t=a(process.stderr);return`${T(e)} ${w(e)}${D(e,{useColor:t})}${e.durationMs===void 0?``:` ${Oe(e,{useColor:t})}`}`}function w(e){let t=e.title?.trim(),n=c.basename(e.file);return t||n}function T(e){return e.status===`pass`?t(`pass`,{passFormat:e.attempt&&e.attempt>1?`yellow`:`green`}):t(e.status===`fail`?`fail`:`skip`)}function E(e,t){return n(e,t,{validateStream:!1})}function D(e,t={}){if(typeof e.shardIndex!=`number`)return``;let n=typeof e.shardCount==`number`?e.shardCount:`?`,r=De(e),i=` [${e.shardIndex+1}/${n}${r?` ${r}`:``}]`;return t.useColor?E(i,`dim`):i}function De(e){return e.deviceName?.trim()||e.deviceId?.trim()||void 0}function Oe(e,t={}){let n=f(e.durationMs??0);return t.useColor?E(n,`yellow`):n}function ke(e){return e.status===`pass`||e.status===`skip`||e.status===`fail`&&!e.retrying}function Ae(e){let t=typeof e.shardIndex==`number`?e.shardIndex:``;return[e.status,e.index,e.total,e.file,e.title??``,t].join(`\0`)}function O(e){return`\r\x1B[2K${e}`}function k(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):80}function A(e,t){let n=k(t);return j(e)<=n?e:n<=0?``:n<=3?`.`.repeat(n):`${Me(e,n-3)}...${je(e)?`\x1B[0m`:``}`}function j(e){let t=0;for(let n=0;n<e.length;){let r=M(e,n);if(r){n+=r.length;continue}t+=1,n+=1}return t}function je(e){return e.includes(`\x1B[`)}function Me(e,t){if(t<=0)return``;let n=0,r=``;for(let i=0;i<e.length&&n<t;){let t=M(e,i);if(t){r+=t,i+=t.length;continue}r+=e[i],i+=1,n+=1}return r}function M(e,t){if(!e.startsWith(`\x1B[`,t))return null;for(let n=t+2;n<e.length;n+=1)if(Ne(e.charCodeAt(n)))return e.slice(t,n+1);return null}function Ne(e){return e>=64&&e<=126}function Pe(e){return e.status!==`pass`&&e.status!==`fail`||!e.artifactsDir||!e.attempt?[]:ie(e.status===`pass`?Fe(e):Ie(e)).map(e=>` ${e}`)}function Fe(e){return{...N(e),status:`passed`,replayed:0,healed:0}}function Ie(e){return{...N(e),status:`failed`,error:{code:`COMMAND_FAILED`,message:e.message??`Unknown test failure`}}}function N(e){return{file:e.file,title:e.title,durationMs:e.durationMs??0,attempts:e.attempt??1,artifactsDir:e.artifactsDir,session:e.session??``}}function P(e){return+(e.failed>0)}function Le(e){return e.status===`failed`}function F(e){return e.status===`passed`&&e.attempts>1}function I(e){let t=K(e),n=c.basename(e.file);return`${t&&t.length>0?t:n}${q(e)}`}function Re(e){return`${K(e)??c.basename(e.file)}${q(e)}`}function L(e,t){return`artifactsDir`in e&&e.artifactsDir?`${t}: ${e.artifactsDir}`:void 0}function ze(e){return K(e)?`file: ${c.basename(e.file)}`:void 0}function R(e){return e.hint?`hint: ${e.hint}`:void 0}function z(e,t){return e.diagnosticId?`${t}: ${e.diagnosticId}`:void 0}function B(e,t){return e.logPath?`${t}: ${e.logPath}`:void 0}function V(e,t,n={}){n.includeMessage&&e.push(`errorMessage: ${t.message}`),U(e,R(t)),U(e,z(t,`diagnosticId`)),U(e,B(t,`logPath`)),n.includeDetails!==!1&&H(e,t,n.detailsIndent)}function H(e,t,n){let r=t.details?JSON.stringify(t.details,null,n):void 0;r&&e.push(`details: ${r}`)}function Be(e,t){!(`shardIndex`in t)||typeof t.shardIndex!=`number`||(e.push(`shardIndex: ${t.shardIndex}`),U(e,typeof t.shardCount==`number`?`shardCount: ${t.shardCount}`:void 0),U(e,typeof t.deviceId==`string`?`deviceId: ${t.deviceId}`:void 0),U(e,typeof t.deviceName==`string`?`deviceName: ${t.deviceName}`:void 0))}function Ve(e){return e.status===`passed`?(e.warnings??[]).map(e=>`warning: ${e}`):[]}function U(e,t){t&&e.push(t)}function W(e){return(Math.max(0,e)/1e3).toFixed(3)}function G(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`).replaceAll(`"`,`&quot;`).replaceAll(`'`,`&apos;`)}function He(e){return e!==void 0}function K(e){let t=e.title?.trim();return t&&t.length>0?t:void 0}function q(e){if(!(`shardIndex`in e)||typeof e.shardIndex!=`number`)return``;let t=typeof e.shardCount==`number`?e.shardCount:`?`,n=Ue(e);return` [${e.shardIndex+1}/${t}${n?` ${n}`:``}]`}function Ue(e){return(`deviceName`in e?e.deviceName?.trim():void 0)||(`deviceId`in e?e.deviceId?.trim():void 0)||void 0}function We(){let e,t,n,r=!1,i=(n,r)=>{o(),t=n.type===`test-step`?n:void 0,e??=_e({verbose:r.verbose,liveProgress:J(r),columns:r.stderr.columns});let i=e.render(n);i&&(r.stderr.write(i.newline?`${i.text}\n`:i.text),n.type===`test-step`&&J(r)&&a(r))},a=r=>{n||!t||(n=setInterval(()=>{if(!t)return;let n=e?.render(t);n&&r.stderr.write(n.newline?`${n.text}\n`:n.text)},ge),n.unref?.())},o=()=>{n&&=(clearInterval(n),void 0)},s=e=>{r||!J(e)||(e.stderr.write(`\x1B[?25l`),r=!0)},c=e=>{r&&=(e.stderr.write(`\x1B[?25h`),!1)};return{name:`default`,onSuiteStart:(e,t)=>{s(t),i({type:`suite-start`,suite:e},t)},onTestStep:(e,t)=>{i({type:`test-step`,test:e},t)},onTestResult:(e,t)=>{i({type:`test-result`,test:e},t)},onSuiteEnd:(e,n)=>{o(),t=void 0,c(n),Ge(e,n)},getExitCode:P}}function J(e){return e.stderr.isTTY&&!process.env.CI}function Ge(e,t){let n=e.tests.filter(F);t.stdout.write(`${Ke(e,n.length)}\n`),$e(e.tests.filter(Le),t),Qe(n,t)}function Ke(e,t){let n=typeof e.durationMs==`number`?e.durationMs:void 0,r=a();return`Test summary: ${qe(e.passed,{useColor:r})} ${Je(e.total,{useColor:r})}${e.failed>0?`, ${e.failed} failed`:``}${t>0?`, ${t} flaky`:``}${n===void 0?``:` in ${Ye(n,{useColor:r})}`}`}function qe(e,t={}){let r=`${e} passed`;return t.useColor?n(r,`green`):r}function Je(e,t={}){let r=`(${e})`;return t.useColor?n(r,`dim`):r}function Ye(e,t={}){let r=f(e);return t.useColor?n(r,`yellow`):r}function Xe(){return a()?n(`✓`,`yellow`):`✓`}function Ze(e){return[R(e.error),L(e,`artifacts`),B(e.error,`log`),z(e.error,`diagnostic`)].filter(He)}function Qe(e,t){if(e.length!==0){t.stdout.write(`
3
3
  `),t.stdout.write(`Flaky tests:
4
- `);for(let n of e){t.stdout.write(` ${Ye()} ${I(n)} after ${n.attempts} attempts${et(n)}\n`);for(let e of n.attemptFailures??[]){let n=typeof e.durationMs==`number`?` (${f(e.durationMs)})`:``;t.stdout.write(` attempt ${e.attempt} failed${n}: ${e.message}\n`)}}}}function Qe(e,t){if(e.length!==0){t.stdout.write(`
4
+ `);for(let n of e){t.stdout.write(` ${Xe()} ${I(n)} after ${n.attempts} attempts${nt(n)}\n`);for(let e of n.attemptFailures??[]){let n=typeof e.durationMs==`number`?` (${f(e.durationMs)})`:``;t.stdout.write(` attempt ${e.attempt} failed${n}: ${e.message}\n`)}}}}function $e(e,t){if(e.length!==0){t.stdout.write(`
5
5
  `),t.stdout.write(`Failures:
6
- `);for(let n of e)t.stdout.write(` ${I(n)}\n`),$e(n,t,` `)}}function $e(e,t,n){let r=Re(e);r&&t.stdout.write(`${n}${r}\n`),t.stdout.write(`${n}${e.error?.message??`Unknown test failure`}\n`);for(let r of Xe(e))t.stdout.write(`${n}${r}\n`);if(t.debug)for(let r of ie(e))t.stdout.write(`${n}${r}\n`)}function et(e){let t=[typeof e.finalAttemptDurationMs==`number`?`passed attempt ${f(e.finalAttemptDurationMs)}`:``,e.durationMs>0?`total ${f(e.durationMs)}`:``].filter(Boolean);return t.length>0?` (${t.join(`, `)})`:``}function tt(e){let t=nt(e);return{name:`junit`,onSuiteEnd:e=>rt(t,e),getExitCode:P}}function nt(t){if(t&&t.trim().length>0)return t;throw new e(`INVALID_ARGS`,`The junit test reporter requires an output path. Use --reporter junit:<path>.`)}function rt(t,n){let r=s.dirname(t);try{a.mkdirSync(r,{recursive:!0}),a.writeFileSync(t,it(n),`utf8`)}catch(n){throw new e(`COMMAND_FAILED`,`Failed to write JUnit report to ${t}: ${n instanceof Error?n.message:String(n)}`)}}function it(e){let t=[`<?xml version="1.0" encoding="UTF-8"?>`,`<testsuites>`,` <testsuite name="agent-device replay suite" tests="${e.total}" failures="${e.failed}" skipped="${e.skipped}" time="${W(e.durationMs)}">`];for(let n of e.tests)t.push(...at(n));return t.push(` </testsuite>`),t.push(`</testsuites>`),`${t.join(`
7
- `)}\n`}function at(e){let t=G(Le(e)),n=[` <testcase classname="${G(`${s.dirname(e.file)===`.`?e.file:s.dirname(e.file)}${q(e)}`)}" name="${t}" file="${G(e.file)}" time="${W(e.durationMs)}">`];e.status===`failed`?n.push(` <failure message="${G(e.error.message)}">${G(ot(e))}</failure>`):e.status===`skipped`&&n.push(` <skipped message="${G(e.message)}" />`);let r=st(e);return r&&n.push(` <system-out>${G(r)}</system-out>`),n.push(` </testcase>`),n}function ot(e){let t=[e.error.message];return V(t,e.error,{includeDetails:!1}),U(t,L(e,`artifactsDir`)),H(t,e.error,2),t.join(`
8
- `)}function st(e){let t=[`status: ${e.status}`,`durationMs: ${e.durationMs}`];return ct(t,e),t.join(`
9
- `)}function ct(e,t){U(e,`attempts`in t?`attempts: ${t.attempts}`:void 0),U(e,`session`in t?`session: ${t.session}`:void 0),U(e,`replayed`in t?`replayed: ${t.replayed}`:void 0),U(e,`healed`in t?`healed: ${t.healed}`:void 0);for(let n of Be(t))e.push(n);U(e,L(t,`artifactsDir`)),ze(e,t),t.status===`failed`&&lt(e,t),U(e,F(t)?`flaky: true`:void 0)}function lt(e,t){e.push(`errorCode: ${t.error.code}`),V(e,t.error,{includeMessage:!0})}function ut(e){if(e.type===`command`)return;if(e.type===`replay-test-suite`)return{type:`suite-start`,suite:{total:e.total,runnable:e.runnable,skipped:e.skipped,artifactsDir:e.artifactsDir,shardMode:e.shardMode,shardCount:e.shardCount}};let t={file:e.file,title:e.title,index:e.index,total:e.total,attempt:e.attempt,maxAttempts:e.maxAttempts,session:e.session,artifactsDir:e.artifactsDir,shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.deviceId,deviceName:e.deviceName};return e.status===`start`?{type:`test-start`,test:t}:e.status===`progress`?{type:`test-step`,test:{...t,stepIndex:e.stepIndex,stepTotal:e.stepTotal,stepCommand:e.stepCommand,stepValue:e.stepValue}}:{type:`test-result`,test:{...t,status:e.status,durationMs:e.durationMs,retrying:e.retrying,message:e.message,hint:e.hint}}}function dt(e){let t=e.reporters&&e.reporters.length>0?e.reporters.map(Y):e.json?[]:[Y(`default`)];return e.reportJunit&&t.push(Y(`junit:${e.reportJunit}`)),t}function Y(t){let n=t.trim();if(!n)throw new e(`INVALID_ARGS`,`Test reporter spec cannot be empty.`);if(pt(n))return{kind:`custom`,modulePath:n,raw:n};let{name:r,value:i}=ft(n);if(r==="default"){if(i!==void 0)throw new e(`INVALID_ARGS`,`The default test reporter does not accept options.`);return{kind:`builtin`,name:r,raw:n}}if(r===`junit`)return i===void 0?{kind:`builtin`,name:r,raw:n}:{kind:`builtin`,name:r,raw:n,outputPath:i};throw new e(`INVALID_ARGS`,`Unknown test reporter "${r}". Built-in reporters: default, junit:<path>. Custom reporters must be file paths.`)}function ft(e){let t=e.indexOf(`:`);return t<0?{name:e.trim()}:{name:e.slice(0,t).trim(),value:e.slice(t+1)}}function pt(e){return e.startsWith(`.`)||e.startsWith(`/`)||e.startsWith(`~`)||e.startsWith(`file:`)}const mt={"suite-start":`onSuiteStart`,"test-start":`onTestStart`,"test-step":`onTestStep`,"test-result":`onTestResult`};async function ht(e){let t=dt(e);return await Promise.all(t.map(yt))}async function gt(e,t,n){for(let r of e)await r.onSuiteEnd?.(t,n)}function X(e,t,n){let r=ut(t);if(!r)return;let i=mt[r.type];for(let t of e)try{let e=_t(t,r,n);e instanceof Promise&&e.catch(e=>Z(t,i,n,e))}catch(e){Z(t,i,n,e)}}function _t(e,t,n){switch(t.type){case`suite-start`:return e.onSuiteStart?.(t.suite,n);case`test-start`:return e.onTestStart?.(t.test,n);case`test-step`:return e.onTestStep?.(t.test,n);case`test-result`:return e.onTestResult?.(t.test,n)}}function Z(e,t,n,r){let i=r instanceof Error?r.message:String(r);n.stderr.write(`Reporter ${e.name} ${String(t)} failed: ${i}\n`)}function vt(e,t){let n=P(t);for(let r of e){let e=r.getExitCode?.(t);e!==void 0&&(n=Math.max(n,e))}return n}async function yt(e){return e.kind===`custom`?await u(e):e.name==="default"?Ue():tt(e.outputPath)}async function bt(e){let{suite:t,json:r,debug:i,verbose:a,reporter:o,reportJunit:s}=e,c=e.reporterRuntime??await Q({debug:i,verbose:a,reporter:o,reportJunit:s,json:r});return await gt(c.reporters,t,c.context),r&&n({success:!0,data:t}),vt(c.reporters,t)}async function Q(e){let t=await ht({reporters:e.reporter,reportJunit:e.reportJunit,json:e.json}),n=xt({debug:e.debug,verbose:e.verbose});return{reporters:t,context:n,onProgress(e){X(t,e,n)}}}function xt(e){return{debug:e.debug,verbose:e.verbose??e.debug,stdout:$(process.stdout),stderr:$(process.stderr)}}function $(e){return{isTTY:e.isTTY===!0,columns:e.columns,write:t=>e.write(t)}}export{Q as createReplayTestReporterRuntime,bt as renderReplayTestResponse};
6
+ `);for(let n of e)t.stdout.write(` ${I(n)}\n`),et(n,t,` `)}}function et(e,t,n){let r=ze(e);r&&t.stdout.write(`${n}${r}\n`),t.stdout.write(`${n}${e.error?.message??`Unknown test failure`}\n`);for(let r of Ze(e))t.stdout.write(`${n}${r}\n`);if(tt(e,t,n),t.debug)for(let r of ae(e))t.stdout.write(`${n}${r}\n`)}function tt(e,t,n){let r=i(e.error?.details);if(r)for(let e of r.split(`
7
+ `))t.stdout.write(`${n}${e}\n`)}function nt(e){let t=[typeof e.finalAttemptDurationMs==`number`?`passed attempt ${f(e.finalAttemptDurationMs)}`:``,e.durationMs>0?`total ${f(e.durationMs)}`:``].filter(Boolean);return t.length>0?` (${t.join(`, `)})`:``}function rt(e){let t=it(e);return{name:`junit`,onSuiteEnd:e=>at(t,e),getExitCode:P}}function it(t){if(t&&t.trim().length>0)return t;throw new e(`INVALID_ARGS`,`The junit test reporter requires an output path. Use --reporter junit:<path>.`)}function at(t,n){let r=c.dirname(t);try{o.mkdirSync(r,{recursive:!0}),o.writeFileSync(t,ot(n),`utf8`)}catch(n){throw new e(`COMMAND_FAILED`,`Failed to write JUnit report to ${t}: ${n instanceof Error?n.message:String(n)}`)}}function ot(e){let t=[`<?xml version="1.0" encoding="UTF-8"?>`,`<testsuites>`,` <testsuite name="agent-device replay suite" tests="${e.total}" failures="${e.failed}" skipped="${e.skipped}" time="${W(e.durationMs)}">`];for(let n of e.tests)t.push(...st(n));return t.push(` </testsuite>`),t.push(`</testsuites>`),`${t.join(`
8
+ `)}\n`}function st(e){let t=G(Re(e)),n=[` <testcase classname="${G(`${c.dirname(e.file)===`.`?e.file:c.dirname(e.file)}${q(e)}`)}" name="${t}" file="${G(e.file)}" time="${W(e.durationMs)}">`];e.status===`failed`?n.push(` <failure message="${G(e.error.message)}">${G(ct(e))}</failure>`):e.status===`skipped`&&n.push(` <skipped message="${G(e.message)}" />`);let r=lt(e);return r&&n.push(` <system-out>${G(r)}</system-out>`),n.push(` </testcase>`),n}function ct(e){let t=[e.error.message];return V(t,e.error,{includeDetails:!1}),U(t,L(e,`artifactsDir`)),H(t,e.error,2),t.join(`
9
+ `)}function lt(e){let t=[`status: ${e.status}`,`durationMs: ${e.durationMs}`];return ut(t,e),t.join(`
10
+ `)}function ut(e,t){U(e,`attempts`in t?`attempts: ${t.attempts}`:void 0),U(e,`session`in t?`session: ${t.session}`:void 0),U(e,`replayed`in t?`replayed: ${t.replayed}`:void 0),U(e,`healed`in t?`healed: ${t.healed}`:void 0);for(let n of Ve(t))e.push(n);U(e,L(t,`artifactsDir`)),Be(e,t),t.status===`failed`&&dt(e,t),U(e,F(t)?`flaky: true`:void 0)}function dt(e,t){e.push(`errorCode: ${t.error.code}`),V(e,t.error,{includeMessage:!0})}function ft(e){if(e.type===`command`)return;if(e.type===`replay-test-suite`)return{type:`suite-start`,suite:{total:e.total,runnable:e.runnable,skipped:e.skipped,artifactsDir:e.artifactsDir,shardMode:e.shardMode,shardCount:e.shardCount}};let t={file:e.file,title:e.title,index:e.index,total:e.total,attempt:e.attempt,maxAttempts:e.maxAttempts,session:e.session,artifactsDir:e.artifactsDir,shardIndex:e.shardIndex,shardCount:e.shardCount,deviceId:e.deviceId,deviceName:e.deviceName};return e.status===`start`?{type:`test-start`,test:t}:e.status===`progress`?{type:`test-step`,test:{...t,stepIndex:e.stepIndex,stepTotal:e.stepTotal,stepCommand:e.stepCommand,stepValue:e.stepValue}}:{type:`test-result`,test:{...t,status:e.status,durationMs:e.durationMs,retrying:e.retrying,message:e.message,hint:e.hint}}}function pt(e){let t=e.reporters&&e.reporters.length>0?e.reporters.map(Y):e.json?[]:[Y(`default`)];return e.reportJunit&&t.push(Y(`junit:${e.reportJunit}`)),t}function Y(t){let n=t.trim();if(!n)throw new e(`INVALID_ARGS`,`Test reporter spec cannot be empty.`);if(ht(n))return{kind:`custom`,modulePath:n,raw:n};let{name:r,value:i}=mt(n);if(r==="default"){if(i!==void 0)throw new e(`INVALID_ARGS`,`The default test reporter does not accept options.`);return{kind:`builtin`,name:r,raw:n}}if(r===`junit`)return i===void 0?{kind:`builtin`,name:r,raw:n}:{kind:`builtin`,name:r,raw:n,outputPath:i};throw new e(`INVALID_ARGS`,`Unknown test reporter "${r}". Built-in reporters: default, junit:<path>. Custom reporters must be file paths.`)}function mt(e){let t=e.indexOf(`:`);return t<0?{name:e.trim()}:{name:e.slice(0,t).trim(),value:e.slice(t+1)}}function ht(e){return e.startsWith(`.`)||e.startsWith(`/`)||e.startsWith(`~`)||e.startsWith(`file:`)}const X={"suite-start":`onSuiteStart`,"test-start":`onTestStart`,"test-step":`onTestStep`,"test-result":`onTestResult`};async function gt(e){let t=pt(e);return await Promise.all(t.map(xt))}async function _t(e,t,n){for(let r of e)await r.onSuiteEnd?.(t,n)}function vt(e,t,n){let r=ft(t);if(!r)return;let i=X[r.type];for(let t of e)try{let e=yt(t,r,n);e instanceof Promise&&e.catch(e=>Z(t,i,n,e))}catch(e){Z(t,i,n,e)}}function yt(e,t,n){switch(t.type){case`suite-start`:return e.onSuiteStart?.(t.suite,n);case`test-start`:return e.onTestStart?.(t.test,n);case`test-step`:return e.onTestStep?.(t.test,n);case`test-result`:return e.onTestResult?.(t.test,n)}}function Z(e,t,n,r){let i=r instanceof Error?r.message:String(r);n.stderr.write(`Reporter ${e.name} ${String(t)} failed: ${i}\n`)}function bt(e,t){let n=P(t);for(let r of e){let e=r.getExitCode?.(t);e!==void 0&&(n=Math.max(n,e))}return n}async function xt(e){return e.kind===`custom`?await ee(e):e.name==="default"?We():rt(e.outputPath)}async function St(e){let{suite:t,json:n,debug:i,verbose:a,reporter:o,reportJunit:s}=e,c=e.reporterRuntime??await Q({debug:i,verbose:a,reporter:o,reportJunit:s,json:n});return await _t(c.reporters,t,c.context),n&&r({success:!0,data:t}),bt(c.reporters,t)}async function Q(e){let t=await gt({reporters:e.reporter,reportJunit:e.reportJunit,json:e.json}),n=Ct({debug:e.debug,verbose:e.verbose});return{reporters:t,context:n,onProgress(e){vt(t,e,n)}}}function Ct(e){return{debug:e.debug,verbose:e.verbose??e.debug,stdout:$(process.stdout),stderr:$(process.stderr)}}function $(e){return{isTTY:e.isTTY===!0,columns:e.columns,write:t=>e.write(t)}}export{Q as createReplayTestReporterRuntime,St as renderReplayTestResponse};
@@ -1 +1 @@
1
- import{t as e}from"./rolldown-runtime.js";import{F as t,H as n,I as r,f as i,m as a,p as o,x as s}from"./sdk-contracts.js";import{C as c,D as l,F as u,S as d,h as f,j as p,y as ee}from"./sdk-android-adb.js";import{n as te,t as m}from"./version.js";import{n as h,o as ne,r as re,s as ie}from"./host-process.js";import{l as ae}from"./sdk-batch-runner.js";import{C as oe,S as se,T as ce,_ as le,g as ue,w as de,x as fe}from"./android-input-ownership.js";import{n as pe,t as me}from"./xml.js";import{a as g,o as _,r as he}from"./tool-provider.js";import{n as ge}from"./simctl.js";import{c as _e}from"./agent-browser-tool.js";import{t as ve}from"./ttl-memo.js";import{n as ye,t as be}from"./runner-provider.js";import{AsyncLocalStorage as xe}from"node:async_hooks";import v from"node:crypto";import y from"node:fs";import b from"node:os";import x from"node:path";import Se from"node:fs/promises";import Ce from"node:net";const S=new Set,C=new Map,we=`request_canceled`,Te=`request canceled`;function Ee(e,t){if(typeof e==`string`&&e.length>0)return e;let n=(typeof t==`string`?t:typeof t==`number`&&Number.isFinite(t)?String(t):`generated`).trim().replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,32)||`generated`,r=Math.random().toString(36).slice(2,10);return`req:${n}:${process.pid}:${Date.now()}:${r}`}const De=5e4,Oe=1e4;function ke(e){if(e.size<=De)return;let t=0;for(let n of e.keys()){if(t>=Oe)break;e.delete(n),t++}}function Ae(e){if(e.size<=De)return;let t=0;for(let n of e){if(t>=Oe)break;e.delete(n),t++}}function je(e){if(!e)return;ke(C);let t=new AbortController;C.set(e,t),S.has(e)&&t.abort()}function Me(e){e&&(Ae(S),S.add(e),C.get(e)?.abort())}function Ne(e){e&&(S.delete(e),C.delete(e))}function Pe(e){return e?S.has(e):!1}function Fe(e){if(e)return C.get(e)?.signal}function w(){return new t(`COMMAND_FAILED`,Te,{reason:we,hint:`The request was canceled intentionally (explicit cancel or client disconnect) — no retry is needed unless the cancellation was unintended.`})}function Ie(e){if(Pe(e))throw w()}function Le(e){return!(e instanceof t)||e.code!==`COMMAND_FAILED`?!1:e.details?.reason===we?!0:e.message===Te}const Re=new xe,ze=new xe;async function Be(e,t){return await Re.run(e,t)}function Ve(e){Re.getStore()?.(e)}async function He(e,t){return await ze.run(e,t)}function Ue(){return ze.getStore()}const We=new xe;async function Ge(e,t,n){let r=We.getStore()??[];if(r.some(n=>n.locks===e&&n.key===t))return await n();let i=(e.get(t)??Promise.resolve()).catch(()=>{}).then(()=>We.run([...r,{locks:e,key:t}],n));return e.set(t,i),i.finally(()=>{e.get(t)===i&&e.delete(t)})}const Ke="If runner build products look stale or corrupted, run `pnpm clean:xcuitest` in a local checkout, or remove ~/.agent-device/apple-runner/derived, then retry.";function T(e){if(!(e instanceof t)||e.code!==`COMMAND_FAILED`)return!1;if(e.details?.retriable===!0)return!0;let n=`${e.message??``}`.toLowerCase();return n.includes(`xcodebuild exited early`)||n.includes(`device is busy`)&&n.includes(`connecting`)?!1:!!(n.includes(`runner did not accept connection`)||n.includes(`fetch failed`)||n.includes(`econnrefused`)||n.includes(`socket hang up`))}function qe(e){return!(e instanceof t)||e.code!==`COMMAND_FAILED`?!0:!String(e.message??``).toLowerCase().includes(`xcodebuild exited early`)}function Je(e,t,n){let r=`${e}\n${t}\n${n}`.toLowerCase();return r.includes(`device is busy`)&&r.includes(`connecting`)?`Target iOS device is still connecting. Keep it unlocked, wait for device trust/connection to settle, then retry.`:`${ue(`IOS_RUNNER_CONNECT_TIMEOUT`)} ${Ke}`}function Ye(e){let{port:n,endpoints:r,logPath:i,lastError:a}=e,o=`Runner did not accept connection`;return new t(`COMMAND_FAILED`,o,{port:n,endpoints:r,logPath:i,lastError:a?String(a):void 0,reason:le({error:a,message:o,context:{platform:`ios`,phase:`connect`}}),hint:ue(`IOS_RUNNER_CONNECT_TIMEOUT`)})}async function Xe(e){let{session:n,port:r,logPath:i}=e,a=await n.testPromise,o=`Runner did not accept connection (xcodebuild exited early)`,s=le({message:o,stdout:a.stdout,stderr:a.stderr,context:{platform:`ios`,phase:`connect`}});return new t(`COMMAND_FAILED`,o,{port:r,logPath:i,xcodebuild:{exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr},reason:s,hint:Je(o,a.stdout,a.stderr)})}function Ze(e){let t=e.details?JSON.stringify(e.details):``,n=`${e.message}\n${t}`.toLowerCase();if(n.includes(`failed registering bundle identifier`)||n.includes(`app identifier`)&&n.includes(`not available`))return`Set AGENT_DEVICE_IOS_BUNDLE_ID to a unique reverse-DNS value (for example, com.yourname.agentdevice.runner), then retry.`;if(n.includes(`requires a development team`))return`Configure signing in Xcode or set AGENT_DEVICE_IOS_TEAM_ID for physical-device runs.`;if(n.includes(`no profiles for`)||n.includes(`provisioning profile`))return`Install/select a valid iOS provisioning profile, or set AGENT_DEVICE_IOS_PROVISIONING_PROFILE.`;if(n.includes(`code signing`))return`Enable Automatic Signing in Xcode or provide AGENT_DEVICE_IOS_TEAM_ID and optional AGENT_DEVICE_IOS_SIGNING_IDENTITY.`}function Qe(e){return Ze(e)??Ke}function E(e){return e.command===`status`||e.commandId?.trim()?e:{...e,commandId:$e()}}function $e(){return`runner-${v.randomUUID()}`}function D(e){if(Pe(e))throw w()}const et=45e3,tt=45e3,nt=1e4,O=new Map;async function rt(e,t,n,r,i=et,a,o){let s=se.fromTimeoutMs(i),{getEndpoints:c}=dt(e,t),{endpoints:l}=await c(s.remainingMs()),u=null,d=Math.max(1,Math.ceil(i/250));try{return await de(async({deadline:s})=>{let d=await it({device:e,port:t,command:n,timeoutMs:i,logPath:r,session:a,endpoints:l,getEndpoints:c,signal:o,attemptDeadline:s,setEndpoints:e=>{l=e},setLastError:e=>{u=e}});if(d)return d;throw lt({port:t,endpoints:l,lastError:u,signal:o})},{maxAttempts:d,baseDelayMs:300,maxDelayMs:2e3,jitter:.2,shouldRetry:qe},{deadline:s,phase:`ios_runner_connect`,signal:o})}catch(e){if(o?.aborted||Le(e))throw w();u||=e}if(o?.aborted)throw w();if(e.kind===`simulator`){let i=s.remainingMs();if(i<=0)throw Ye({port:t,endpoints:l,logPath:r,lastError:u});let a=await xt(e,t,n,i,o);return new Response(a.body,{status:a.status})}throw Ye({port:t,endpoints:l,logPath:r,lastError:u})}async function it(e){await at(e);let t=await ot(e);return t.response?t.response:await st(e)||await ct(e,t.usedCachedTunnelIp)}async function at(e){if(e.attemptDeadline?.isExpired())throw new t(`COMMAND_FAILED`,`Runner connection deadline exceeded`,{port:e.port,timeoutMs:e.timeoutMs});if(e.session?.child.exitCode!==null&&e.session?.child.exitCode!==void 0)throw await Xe({session:e.session,port:e.port,logPath:e.logPath})}async function ot(e){let t=e.endpoints,n=!1;if(e.device.kind===`device`){let r=await e.getEndpoints(e.attemptDeadline?.remainingMs());t=r.endpoints,n=r.cached,e.setEndpoints(t)}let r=n?t[0]:null;return{response:await ft(t,{command:e.command,port:e.port,timeoutMs:e.timeoutMs,signal:e.signal,attemptDeadline:e.attemptDeadline,onError:(t,n)=>{e.setLastError(n),e.device.kind===`device`&&t===r&&_t(e.device.id)}}),usedCachedTunnelIp:n}}async function st(e){return e.device.kind!==`simulator`||!e.session?.ready?null:await pt(e.device,e.port,e.command,{signal:e.signal,attemptDeadline:e.attemptDeadline,onError:e.setLastError})}async function ct(e,t){if(e.device.kind!==`device`||!t)return null;_t(e.device.id);let n=await e.getEndpoints(e.attemptDeadline?.remainingMs(),!0);return e.setEndpoints(n.endpoints),await ft(n.endpoints,{command:e.command,port:e.port,timeoutMs:e.timeoutMs,signal:e.signal,attemptDeadline:e.attemptDeadline,onError:(t,n)=>{e.setLastError(n)}})}function lt(e){if(e.signal?.aborted)throw w();return new t(`COMMAND_FAILED`,`Runner endpoint probe failed`,{port:e.port,endpoints:e.endpoints,lastError:e.lastError?String(e.lastError):void 0})}async function ut(e,n,r,i=tt,a){if(a?.aborted)throw w();let o=se.fromTimeoutMs(i),{getEndpoints:s}=dt(e,n),{endpoints:c}=await s(o.remainingMs()),l=c[0];if(!l)throw new t(`COMMAND_FAILED`,`Runner command endpoint not available`,{port:n,endpoints:c});let u=o.remainingMs();if(u<=0)throw new t(`COMMAND_FAILED`,`Runner command deadline exceeded`,{timeoutMs:i});return await yt(l,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)},u,a)}function dt(e,t){let n;return{getEndpoints:async(r,i=!1)=>{let a=await mt({device:e,timeoutBudgetMs:r,forceRefresh:i,requestTunnelIp:n,setRequestTunnelIp:e=>{n=e}});return{endpoints:vt(e,t,a.ip),cached:a.sharedCacheHit}}}}async function ft(e,n){let{command:r,port:i,timeoutMs:a,signal:o,attemptDeadline:s,onError:c}=n;for(let n of e)try{let e=s?.remainingMs()??a;if(e<=0)throw new t(`COMMAND_FAILED`,`Runner connection deadline exceeded`,{port:i,timeoutMs:a});return await yt(n,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)},Math.min(2e4,e),o)}catch(e){if(o?.aborted||Le(e))throw w();c(n,e)}return null}async function pt(e,t,n,r){let{signal:i,attemptDeadline:a,onError:o}=r,s=a?.remainingMs()??45e3;if(s<=0)return null;try{let r=await xt(e,t,n,s,i);return new Response(r.body,{status:r.status})}catch(e){if(i?.aborted||Le(e))throw w();return o(e),null}}async function mt(e){let{device:t,timeoutBudgetMs:n,forceRefresh:r,requestTunnelIp:i,setRequestTunnelIp:a}=e;if(t.kind!==`device`)return{ip:null,sharedCacheHit:!1};if(!r){let e=ht(t.id);if(e)return{ip:e,sharedCacheHit:!0};if(i!==void 0)return{ip:i,sharedCacheHit:!1}}let o=await bt(t.id,n);return a(o),o&&gt(t.id,o),{ip:o,sharedCacheHit:!1}}function ht(e){let t=O.get(e);return t?t.expiresAt<=Date.now()?(O.delete(e),null):t.ip:null}function gt(e,t){O.set(e,{ip:t,expiresAt:Date.now()+3e4})}function _t(e){O.delete(e)}function vt(e,t,n){let r=[`http://127.0.0.1:${t}/command`];return e.kind===`device`&&n&&r.unshift(`http://[${n}]:${t}/command`),r}async function yt(e,t,n,r){let i=AbortSignal.timeout(n),a=r?AbortSignal.any([r,i]):i;return await fetch(e,{...t,signal:a})}async function bt(e,t){if(typeof t==`number`&&t<=0)return null;let n=typeof t==`number`?Math.max(1,Math.min(nt,t)):nt,r=x.join(b.tmpdir(),`agent-device-devicectl-info-${process.pid}-${Date.now()}.json`);try{let t=Math.max(1,Math.ceil(n/1e3));if((await _([`devicectl`,`device`,`info`,`details`,`--device`,e,`--json-output`,r,`--timeout`,String(t)],{allowFailure:!0,timeoutMs:n})).exitCode!==0||!y.existsSync(r))return null;let i=JSON.parse(y.readFileSync(r,`utf8`));if(i.info?.outcome&&i.info.outcome!==`success`)return null;let a=(i.result?.connectionProperties?.tunnelIPAddress??i.result?.device?.connectionProperties?.tunnelIPAddress)?.trim();return a&&a.length>0?a:null}catch{return null}finally{j(r)}}async function xt(e,t,n,r,i){let a=JSON.stringify(n);return{status:200,body:f(await _(ge(e,[`spawn`,e.id,`/usr/bin/curl`,`-s`,`-X`,`POST`,`-H`,`Content-Type: application/json`,`--data`,a,`http://127.0.0.1:${t}/command`]),{allowFailure:!0,timeoutMs:r,signal:i}),`Runner did not accept connection (simctl spawn)`,e=>{let n=le({message:`Runner did not accept connection (simctl spawn)`,stdout:e.stdout,stderr:e.stderr,context:{platform:`ios`,phase:`connect`}});return{port:t,reason:n,hint:ue(n)}}).stdout}}async function St(){return await new Promise((e,n)=>{let r=Ce.createServer();r.listen(0,`127.0.0.1`,()=>{let i=r.address();if(typeof i==`object`&&i?.port){let t=i.port;r.close(()=>e(t))}else r.close(()=>n(new t(`COMMAND_FAILED`,`Failed to allocate port`)))}),r.on(`error`,n)})}function k(e,t,n,r){t&&Ct(t,e),n&&Ct(n,e),r&&process.stderr.write(e)}const A=new Map;function Ct(e,t){let n=(A.get(e)??Promise.resolve()).catch(()=>{}).then(async()=>{await y.promises.mkdir(x.dirname(e),{recursive:!0}),await y.promises.appendFile(e,t)}).catch(()=>{}).finally(()=>{A.get(e)===n&&A.delete(e)});A.set(e,n)}function j(e){try{y.existsSync(e)&&y.unlinkSync(e)}catch{}}const wt=`XCTestDevices`,Tt=`.agent-device-backup`,Et=`.agent-device-xctestdevices-backup-`;function Dt(e=b.homedir()){return x.join(e,`Library`,`Developer`,`XCTestDevices`)}function Ot(e=b.homedir()){return x.join(e,`.agent-device`,`xctest-device-set.lock`)}function kt(e=Dt()){return`${e}${Tt}`}async function At(e,n={}){if(!o(e)||e.kind!==`simulator`)return null;let r=fe(e.simulatorSetPath);if(!r)return null;let i=x.resolve(r),a=x.resolve(n.xctestDeviceSetPath??Dt()),s=x.resolve(n.backupPath??kt(a)),c=x.resolve(n.lockDirPath??Ot()),l=n.ownerStartTime??ne(process.pid),u=await It({lockDirPath:c,owner:{pid:n.ownerPid??process.pid,startTime:l,acquiredAtMs:n.nowMs??Date.now()}});try{if(jt({xctestDeviceSetPath:a,backupPath:s}),Ft(i,a))return await u(),null;y.mkdirSync(i,{recursive:!0}),y.existsSync(a)&&y.renameSync(a,s),Nt({requestedSetPath:i,xctestDeviceSetPath:a})}catch(e){throw jt({xctestDeviceSetPath:a,backupPath:s}),await u(),new t(`COMMAND_FAILED`,`Failed to redirect XCTest device set path`,{requestedSetPath:i,xctestDeviceSetPath:a,backupPath:s,error:String(e)})}let d=!1;return{release:async()=>{if(!d){d=!0;try{jt({xctestDeviceSetPath:a,backupPath:s})}finally{await u()}}}}}function jt(e){let{xctestDeviceSetPath:t,backupPath:n}=e,r=[n,...Mt(n)],i=r.find(e=>y.existsSync(e)),a=y.existsSync(t)&&y.lstatSync(t).isSymbolicLink();if(i){if(a&&Pt(t),!y.existsSync(t))y.mkdirSync(x.dirname(t),{recursive:!0}),y.renameSync(i,t);else if(a)i===n?y.rmSync(n,{recursive:!0,force:!0}):y.rmSync(i,{recursive:!0,force:!0});else{p({level:`warn`,phase:`ios_runner_xctest_device_set_restore_collision`,data:{xctestDeviceSetPath:t,activeBackupPath:i}});return}for(let e of r)e!==i&&y.existsSync(e)&&y.rmSync(e,{recursive:!0,force:!0});return}a&&(p({level:`warn`,phase:`ios_runner_xctest_device_set_orphaned_symlink`,data:{xctestDeviceSetPath:t}}),Pt(t))}function Mt(e){let t=x.dirname(e),n=x.basename(e).replace(Tt,``),r=n===wt?Et:`${n}${Et}`;try{return y.readdirSync(t).filter(e=>e.startsWith(r)).sort().map(e=>x.join(t,e))}catch{return[]}}function Nt(e){let{requestedSetPath:t,xctestDeviceSetPath:n}=e,r=x.dirname(n),i=x.join(r,`${wt}.agent-device-link-${process.pid}-${Date.now()}`);y.mkdirSync(r,{recursive:!0});try{y.symlinkSync(t,i,`dir`),y.renameSync(i,n)}catch(e){throw y.existsSync(i)&&Pt(i),e}}function Pt(e){y.existsSync(e)&&y.lstatSync(e).isSymbolicLink()&&y.unlinkSync(e)}function Ft(e,t){if(x.resolve(e)===x.resolve(t))return!0;try{return y.realpathSync.native(e)===y.realpathSync.native(t)}catch{return!1}}async function It(e){return await _e({lockDirPath:e.lockDirPath,owner:e.owner,timeoutMs:e.timeoutMs??3e4,pollMs:e.pollMs??100,ownerGraceMs:5e3,description:e.description??`XCTest device set lock`})}const Lt={iOS:{sdkName:{simulator:`iphonesimulator`,device:`iphoneos`},derivedBaseName:{simulator:`ios-simulator`,device:`ios-device`},xctestrunHints:{simulator:{preferred:[`iphonesimulator`],disallowed:[`iphoneos`,`appletvos`,`appletvsimulator`,`macos`]},device:{preferred:[`iphoneos`],disallowed:[`iphonesimulator`,`appletvos`,`appletvsimulator`,`macos`]}}},tvOS:{sdkName:{simulator:`appletvsimulator`,device:`appletvos`},derivedBaseName:{simulator:`tvos-simulator`,device:`tvos-device`},xctestrunHints:{simulator:{preferred:[`appletvsimulator`],disallowed:[`appletvos`,`iphoneos`,`iphonesimulator`,`macos`]},device:{preferred:[`appletvos`],disallowed:[`appletvsimulator`,`iphoneos`,`iphonesimulator`,`macos`]}}},macOS:{sdkName:{simulator:`macosx`,device:`macosx`},derivedBaseName:{simulator:`macos`,device:`macos`},xctestrunHints:{simulator:{preferred:[`macos`],disallowed:[`iphoneos`,`iphonesimulator`,`appletvos`,`appletvsimulator`]},device:{preferred:[`macos`],disallowed:[`iphoneos`,`iphonesimulator`,`appletvos`,`appletvsimulator`]}}},visionOS:{sdkName:{simulator:`xrsimulator`,device:`xros`},derivedBaseName:{simulator:`visionos-simulator`,device:`visionos-device`},xctestrunHints:{simulator:{preferred:[`xrsimulator`],disallowed:[`xros`,`iphoneos`,`iphonesimulator`,`appletvos`,`appletvsimulator`,`macos`]},device:{preferred:[`xros`],disallowed:[`xrsimulator`,`iphoneos`,`iphonesimulator`,`appletvos`,`appletvsimulator`,`macos`]}}}};function M(e){if(!i(e.platform))throw new t(`UNSUPPORTED_PLATFORM`,`Unsupported platform for Apple runner: ${e.platform}`);return a(e)?`macOS`:s(e.target,e.appleOs)}function Rt(e,t){return Lt[e].sdkName[Wt(t)]}function zt(e){return Lt[M(e)].derivedBaseName[Wt(e.kind)]}function Bt(e){return Lt[M(e)].xctestrunHints[Wt(e.kind)]}function Vt(e){let t=M(e);return t===`macOS`?`platform=macOS,arch=${Gt()}`:e.kind===`simulator`?`platform=${t} Simulator,id=${e.id}`:`platform=${t},id=${e.id}`}function Ht(e){let t=M(e);return t===`macOS`?`platform=macOS,arch=${Gt()}`:e.kind===`simulator`?`platform=${t} Simulator,id=${e.id}`:`generic/platform=${t}`}function Ut(e){let t=M(e);return t===`macOS`?`platform=macOS,arch=${Gt()}`:e.kind===`simulator`?`generic/platform=${t} Simulator`:`generic/platform=${t}`}function Wt(e){return e===`simulator`?`simulator`:`device`}function Gt(){return process.arch===`arm64`?`arm64`:`x86_64`}const Kt=x.join(`apple-runner`,`AgentDeviceRunner`),qt=x.join(`dist`,`apple-runner`,`AgentDeviceRunner`);function Jt(e){let t=x.join(e,Kt);return y.existsSync(t)?t:x.join(e,qt)}function Yt(e){return x.join(Jt(e),`AgentDeviceRunner.xcodeproj`)}const Xt=x.join(b.homedir(),`.agent-device`,`apple-runner`),Zt=`.agent-device-runner-cache.json`,Qt=[`-IDEPackageSupportDisableManifestSandbox=1`,`-IDEPackageSupportDisablePluginExecutionSandbox=1`,`ENABLE_USER_SCRIPT_SANDBOXING=NO`],$t=ve();function N(e){return e?.trim()??``}function P(e=process.env){return N(e.AGENT_DEVICE_IOS_BUNDLE_ID)||N(e.AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID)||`com.callstack.agentdevice.runner`}function en(e=process.env){return N(e.AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID)||`${P(e)}.uitests`}function tn(e=process.env){let t=P(e),n=en(e);return Array.from(new Set([N(e.AGENT_DEVICE_IOS_RUNNER_CONTAINER_BUNDLE_ID),`${n}.xctrunner`,t].filter(e=>e.length>0)))}const nn=tn(process.env);function F(e,t=m()){let n=M(e);return{schemaVersion:2,packageVersion:te(t),runnerSourceFingerprint:pn(t),...rn(n,e.kind),platformName:n,deviceKind:e.kind,target:e.target??`mobile`,buildDestinationFamily:Ut(e),runnerBundleBuildSettings:yn(process.env),runnerSigningBuildSettings:vn(process.env,e.kind===`device`,e),runnerPerformanceBuildSettings:bn(),runnerSandboxBuildArgs:xn()}}function rn(e,t){let n=on(an(`xcodebuild`,[`-version`])),r=Rt(e,t);return{xcodeVersion:n.version,xcodeBuildVersion:n.buildVersion,sdkName:r,sdkVersion:an(`xcrun`,[`--sdk`,r,`--show-sdk-version`]),sdkBuildVersion:an(`xcrun`,[`--sdk`,r,`--show-sdk-build-version`])}}function an(e,t){let n=JSON.stringify([e,t]),r=$t.get(n);if(r!==void 0)return r;try{let r=c(e,t,{allowFailure:!0,timeoutMs:5e3,maxBuffer:128*1024}),i=r.exitCode===0&&r.stdout.trim()||`unknown`;return $t.set(n,i),i}catch{return $t.set(n,`unknown`),`unknown`}}function on(e){return{version:e.match(/^Xcode\s+(.+)$/m)?.[1]?.trim()||`unknown`,buildVersion:e.match(/^Build version\s+(.+)$/m)?.[1]?.trim()||`unknown`}}function I(e,t){let n=process.env.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim();if(n)return x.resolve(n);let r=cn(t),i=sn(e);return x.join(i,r)}function sn(e){return x.join(Xt,`derived`,zt(e))}function cn(e){return`cache-${v.createHash(`sha256`).update(un(ln(e))).digest(`hex`).slice(0,16)}`}function ln(e){let{artifacts:t,packageVersion:n,...r}=e;return r}function un(e){return JSON.stringify(dn(e))}function dn(e){return Array.isArray(e)?e.map(e=>dn(e)):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,dn(t)]))}const fn=new Map;function pn(e){let t=Jt(e),n=hn(t),r=mn(t,n),i=fn.get(t);if(i?.fileStatsFingerprint===r)return i.sourceFingerprint;let a=v.createHash(`sha256`);for(let e of n){let n=x.relative(t,e);a.update(n),a.update(`\0`),a.update(y.readFileSync(e)),a.update(`\0`)}let o=a.digest(`hex`);return fn.set(t,{fileStatsFingerprint:r,sourceFingerprint:o}),o}function mn(e,t){let n=v.createHash(`sha256`);for(let r of t){let t=x.relative(e,r),i=y.statSync(r);n.update(t),n.update(`\0`),n.update(String(i.size)),n.update(`\0`),n.update(String(Math.trunc(i.mtimeMs))),n.update(`\0`)}return n.digest(`hex`)}function hn(e){if(!y.existsSync(e))return[];let t=[],n=[e];for(;n.length>0;){let e=n.pop();for(let r of y.readdirSync(e,{withFileTypes:!0})){let i=x.join(e,r.name);if(r.isDirectory()){if(r.name===`xcuserdata`)continue;n.push(i);continue}r.isFile()&&gn(r.name,i)&&t.push(i)}}return t.sort((e,t)=>e.localeCompare(t))}function gn(e,t){return e===`project.pbxproj`?t.includes(`${x.sep}.xcodeproj${x.sep}`):[`.jpg`,`.json`,`.png`,`.swift`,`.m`,`.h`,`.plist`,`.entitlements`,`.xctestplan`,`.xcconfig`,`.storyboard`,`.xib`].includes(x.extname(e))}function _n(e){return a(e)||e.kind===`device`?`-maximum-concurrent-test-device-destinations`:`-maximum-concurrent-test-simulator-destinations`}function vn(e=process.env,t=!1,n={platform:`apple`}){if(a(n))return[`CODE_SIGNING_ALLOWED=NO`,`CODE_SIGNING_REQUIRED=NO`,`CODE_SIGN_IDENTITY=`,`DEVELOPMENT_TEAM=`];if(!t)return[];let r=e.AGENT_DEVICE_IOS_TEAM_ID?.trim()||``,i=e.AGENT_DEVICE_IOS_SIGNING_IDENTITY?.trim()||``,o=e.AGENT_DEVICE_IOS_PROVISIONING_PROFILE?.trim()||``,s=[`CODE_SIGN_STYLE=Automatic`];return r&&s.push(`DEVELOPMENT_TEAM=${r}`),i&&s.push(`CODE_SIGN_IDENTITY=${i}`),o&&s.push(`PROVISIONING_PROFILE_SPECIFIER=${o}`),s}function yn(e=process.env){let t=P(e),n=en(e);return[`AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID=${t}`,`AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID=${n}`]}function bn(){return[`COMPILER_INDEX_STORE_ENABLE=NO`,`ENABLE_CODE_COVERAGE=NO`,`ONLY_ACTIVE_ARCH=YES`,`ENABLE_PREVIEWS=NO`,`ENABLE_DEBUG_DYLIB=NO`]}function xn(){return[...Qt,`OTHER_SWIFT_FLAGS=${Sn(process.env)}`]}function Sn(e){return oe(e.AGENT_DEVICE_XCUITEST_INCLUDE_UNIT_TESTS)?`$(inherited) -disable-sandbox -D AGENT_DEVICE_RUNNER_UNIT_TESTS`:`$(inherited) -disable-sandbox`}const Cn=new Set;function wn(e){return x.join(e,Zt)}function Tn(e,t){y.mkdirSync(e,{recursive:!0}),y.writeFileSync(wn(e),`${JSON.stringify(t,null,2)}\n`)}async function En(e,t){if(e.cache===`external`){L(`preserve`,`external_bad_artifact`,{derived:e.derived,xctestrunPath:e.xctestrunPath,reason:t});return}Cn.add(e.derived);let n=await Dn(e.derived);try{L(`clean`,`bad_artifact`,{derived:e.derived,xctestrunPath:e.xctestrunPath,reason:t}),Kn(e.derived),Mn(e.derived)}finally{await n()}}async function Dn(e){return await On({lockDirPath:kn(e),owner:{pid:process.pid,startTime:ne(process.pid),acquiredAtMs:Date.now()},description:`iOS runner cache lock`})}async function On(e){return await _e({lockDirPath:e.lockDirPath,owner:e.owner,timeoutMs:e.timeoutMs??6e5,pollMs:100,ownerGraceMs:5e3,description:e.description??`iOS runner cache lock`})}function kn(e){return x.join(x.dirname(e),`${x.basename(e)}.lock`)}function An(e,t){!Gn()&&!t&&!Cn.has(e)||(L(`clean`,t?`forced_rebuild`:`forced_clean`,{derived:e}),Kn(e),Mn(e),Cn.delete(e))}function jn(e,t,n,r){Tn(e,Ln(t,n,r))}function Mn(e){try{if(!y.existsSync(e))return;if(x.basename(e)!==`derived`){y.rmSync(e,{recursive:!0,force:!0});return}for(let t of y.readdirSync(e,{withFileTypes:!0}))Pn(t.name)&&y.rmSync(x.join(e,t.name),{recursive:!0,force:!0})}catch{}}const Nn=new Set([Zt,`Build`,`BuildCache.noindex`,`Index.noindex`,`Logs`,`ModuleCache.noindex`,`SDKStatCaches.noindex`,`SourcePackages`,`TextBasedInstallAPI`,`info.plist`]);function Pn(e){return Nn.has(e)}function Fn(e){try{let t=JSON.parse(y.readFileSync(wn(e),`utf8`));return!t||typeof t!=`object`||Array.isArray(t)?null:t}catch{return null}}function In(e,t){let n=Fn(e);return n?un(ln(n))===un(ln(t))?{ok:!0,metadata:n}:{ok:!1,reason:`cache_metadata_mismatch`}:{ok:!1,reason:`cache_metadata_missing`}}function Ln(e,t,n){let r=Rn(t,n);return r?{...e,artifacts:r}:e}function Rn(e,t){let n=Hn(e);if(n===null||t.length===0)return null;let r=[];for(let e of t){let t=Hn(e);if(t===null)return null;r.push({path:e,...t})}return{xctestrunPath:e,xctestrunMtimeMs:n.mtimeMs,xctestrunSize:n.size,productPaths:r}}function zn(e,t){let n=t?.artifacts;if(!Bn(n)||!Wn(n.xctestrunPath,e)||!Un(n.xctestrunPath,{mtimeMs:n.xctestrunMtimeMs,size:n.xctestrunSize}))return null;let r=[];for(let t of n.productPaths){if(!Wn(t.path,e)||!Un(t.path,t))return null;r.push(t.path)}return{xctestrunPath:n.xctestrunPath,productPaths:r}}function Bn(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.xctestrunPath==`string`&&Number.isInteger(t.xctestrunMtimeMs)&&Number.isInteger(t.xctestrunSize)&&Array.isArray(t.productPaths)&&t.productPaths.length>0&&t.productPaths.every(Vn)}function Vn(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.path==`string`&&Number.isInteger(t.mtimeMs)&&Number.isInteger(t.size)}function Hn(e){try{let t=y.statSync(e);return{mtimeMs:Math.trunc(t.mtimeMs),size:t.size}}catch{return null}}function Un(e,t){let n=Hn(e);return n?.mtimeMs===t.mtimeMs&&n.size===t.size}function Wn(e,t){let n=x.relative(x.resolve(t),x.resolve(e));return n!==``&&!n.startsWith(`..`)&&!x.isAbsolute(n)}function Gn(){return oe(process.env.AGENT_DEVICE_IOS_CLEAN_DERIVED)}function Kn(e,n=process.env){if(n.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim()&&!qn(e))throw new t(`COMMAND_FAILED`,`Refusing to clean AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH automatically`,{derivedPath:e,hint:`Unset AGENT_DEVICE_IOS_CLEAN_DERIVED, or move AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH under a subdirectory of ${x.join(m(),`.tmp`)}.`})}function qn(e){let t=x.resolve(m(),`.tmp`),n=x.relative(t,x.resolve(e));return n!==``&&!n.startsWith(`..`)&&!x.isAbsolute(n)}async function Jn(e){let t=In(e.derived,e.expectedCacheMetadata),n=t.ok?zn(e.derived,t.metadata):null,r=n?.xctestrunPath??e.findXctestrun(e.derived);if(!r)return{reason:`missing_xctestrun`,xctestrunPath:null};let i=n?.xctestrunPath===r,a=i?`manifest`:`scan`,o=i?n.productPaths:await e.resolveExistingXctestrunProductPaths(r);return o?!e.xctestrunReferencesProjectRoot(r,e.projectRoot)&&!i?{reason:`project_root_mismatch`,xctestrunPath:r,productPaths:o,source:a}:t.ok?{reason:`reuse_ready`,xctestrunPath:r,productPaths:o,source:a}:{reason:t.reason,xctestrunPath:r,productPaths:o,source:a}:{reason:`missing_products`,xctestrunPath:r,productPaths:[],source:a}}function L(e,t,n){p({level:e===`rebuild`?`warn`:`info`,phase:`runner_xctestrun_cache`,data:{action:e,reason:t,...n}})}const Yn=new Set([`RUNNER_PRODUCT_MISSING`,`RUNNER_PRODUCT_REPAIR_FAILED`]);async function Xn(e,n,i){if(!a(e))return;if(n.length===0)throw new t(`COMMAND_FAILED`,`Missing macOS runner product`,{reason:`RUNNER_PRODUCT_MISSING`,xctestrunPath:i});let o=Array.from(new Set(n)).sort((e,t)=>t.length-e.length);for(let e of o)if(!y.existsSync(e))throw new t(`COMMAND_FAILED`,`Missing macOS runner product`,{reason:`RUNNER_PRODUCT_MISSING`,productPath:e,xctestrunPath:i});for(let e of o)if(!await Qn(e)){await g(`codesign`,[`--remove-signature`,e],{allowFailure:!0});try{await g(`codesign`,[`--force`,`--sign`,`-`,e])}catch(n){let a=r(n,`COMMAND_FAILED`);throw new t(`COMMAND_FAILED`,`Failed to repair macOS runner product signature`,{reason:`RUNNER_PRODUCT_REPAIR_FAILED`,productPath:e,xctestrunPath:i,error:a.message,details:a.details})}}}function Zn(e){if(!(e instanceof t))return!1;let n=e.details&&typeof e.details==`object`?e.details.reason:void 0;return typeof n==`string`&&Yn.has(n)}async function Qn(e){return(await g(`codesign`,[`--verify`,`--deep`,`--strict`,e],{allowFailure:!0})).exitCode===0}const $n=new Set([`ProductPaths`,`DependentProductPaths`,`TestHostPath`,`TestBundlePath`,`UITargetAppPath`]);async function er(e){let t=await rr(e);if(!t||t.length===0)return null;let n=x.dirname(e),r=new Set,i=tr(t,n);for(let e of i.testRootPaths){if(!y.existsSync(e))return null;r.add(e)}for(let e of nr(i)){if(!e)return null;r.add(e)}return Array.from(r)}function tr(e,t){let n=[],r=new Set,i=[];for(let a of e){if(a.startsWith(`__TESTHOST__/`)){i.push(a.slice(13));continue}if(!a.startsWith(`__TESTROOT__/`))continue;let e=a.slice(13);n.push(x.join(t,e));let o=ur(e);o&&r.add(x.join(t,o))}return{testRootPaths:n,hostRoots:Array.from(r),hostRelativePaths:i}}function nr(e){return e.hostRelativePaths.map(t=>{let n=e.hostRoots.find(e=>y.existsSync(x.join(e,t)));return n?x.join(n,t):null})}async function rr(e){let t=await he(e);if(t)return ir(t);if(process.platform===`darwin`)return null;try{return cr(y.readFileSync(e,`utf8`))}catch{return null}}function ir(e){let t=new Set;for(let n of[e,...ar(e),...or(e)])for(let e of sr(n))t.add(e);return Array.from(t)}function ar(e){let t=e.TestConfigurations;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!ae(e))continue;let t=e.TestTargets;Array.isArray(t)&&n.push(...t.filter(ae))}return n}function or(e){return Object.values(e).filter(e=>ae(e)&&`TestBundlePath`in e)}function sr(e){let t=new Set;for(let[n,r]of Object.entries(e))if($n.has(n)){if(typeof r==`string`){t.add(r);continue}if(Array.isArray(r))for(let e of r)typeof e==`string`&&t.add(e)}return Array.from(t)}function cr(e){return lr(me(e))}function lr(e){let t=new Set;return pe(e,(e,n)=>{if($n.has(e)){if(n.name===`string`&&n.text){t.add(n.text);return}if(n.name===`array`)for(let e of n.children)e.name===`string`&&e.text&&t.add(e.text)}}),Array.from(t)}function ur(e){let t=/\.app(?:\/|$)/.exec(e);return!t||t.index===void 0?null:e.slice(0,t.index+4)}const dr=[`CFBundleIcons`,`CFBundleIcons~ipad`];async function fr(e){let t=e.filter(Cr);if(t.length===0)return;let n=e.filter(e=>Tr(e)&&!wr(e));for(let e of t){let t=Sr(e,n);t&&await pr(t,e)}}async function pr(e,t){let n=mr(e,t),r=await hr(e,t);(n||r)&&(await vr(t),xr(t))}function mr(e,t){let n=!1;for(let r of y.readdirSync(e,{withFileTypes:!0}))!r.isFile()||!br(r.name)||yr(x.join(e,r.name),x.join(t,r.name))&&(n=!0);return n}async function hr(e,t){let n=x.join(e,`Info.plist`),r=x.join(t,`Info.plist`),i=await he(n),a=await he(r);if(!i||!a)return!1;let o=gr(i,a);if(o.length===0)return!1;for(let e of o)await _r(r,e.key,e.value,e.shouldInsert);return!0}function gr(e,t){return dr.flatMap(n=>{let r=e[n];return r===void 0||JSON.stringify(t[n])===JSON.stringify(r)?[]:[{key:n,value:r,shouldInsert:t[n]===void 0}]})}async function _r(e,t,n,r){f(await g(`plutil`,[r?`-insert`:`-replace`,t,`-json`,JSON.stringify(n),e],{allowFailure:!0}),`Failed to update XCTest runner icon plist`,{key:t,plistPath:e})}async function vr(e){f(await g(`codesign`,[`--force`,`--sign`,`-`,`--timestamp=none`,`--generate-entitlement-der`,e],{allowFailure:!0}),`Failed to sign XCTest runner app after icon update`,{runnerAppPath:e})}function yr(e,t){if(y.existsSync(t)){let n=y.readFileSync(e),r=y.readFileSync(t);return n.equals(r)?!1:(y.copyFileSync(e,t),!0)}return y.copyFileSync(e,t),!0}function br(e){return/^AppIcon.*\.png$/.test(e)||e===`Assets.car`}function xr(e){let t=new Date;y.utimesSync(e,t,t)}function Sr(e,t){let n=x.dirname(e);return t.find(e=>x.dirname(e)===n&&x.basename(e)===`AgentDeviceRunner.app`)??t.find(t=>x.dirname(t)===n&&t!==e)??null}function Cr(e){return Tr(e)&&wr(e)&&(e.includes(`Debug-iphonesimulator`)||e.includes(`Release-iphonesimulator`)||e.includes(`Debug-appletvsimulator`)||e.includes(`Release-appletvsimulator`))}function wr(e){return x.basename(e).endsWith(`-Runner.app`)}function Tr(e){return x.basename(e).endsWith(`.app`)}const Er={PreferredScreenCaptureFormat:`screenshots`,SystemAttachmentLifetime:`keepNever`,UserAttachmentLifetime:`keepNever`};async function Dr(e,t,n,r={}){let i=r.iosXctestEnvDir?.trim(),a=i?x.resolve(i):x.dirname(e);y.mkdirSync(a,{recursive:!0});let o=n.replace(/[^a-zA-Z0-9._-]/g,`_`),s=x.join(a,`AgentDeviceRunner.env.${o}.json`),c=x.join(a,`AgentDeviceRunner.env.${o}.xctestrun`),l=await Or(e);return Mr(l,e=>Ar(e,t)),jr(l),await kr(l,s,c),{xctestrunPath:c,jsonPath:s}}async function Or(e){let n=await g(`plutil`,[`-convert`,`json`,`-o`,`-`,e],{allowFailure:!0});if(n.exitCode!==0||!n.stdout.trim())throw new t(`COMMAND_FAILED`,`Failed to read xctestrun plist`,{xctestrunPath:e,stderr:n.stderr});try{let e=JSON.parse(n.stdout);if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Root must be an object`);return e}catch(n){throw new t(`COMMAND_FAILED`,`Failed to parse xctestrun JSON`,{xctestrunPath:e,error:String(n)})}}async function kr(e,t,n){y.writeFileSync(t,JSON.stringify(e,null,2)),f(await g(`plutil`,[`-convert`,`xml1`,`-o`,n,t],{allowFailure:!0}),`Failed to write xctestrun plist`,{tmpXctestrunPath:n})}function Ar(e,t){e.EnvironmentVariables={...e.EnvironmentVariables??{},...t},e.UITestEnvironmentVariables={...e.UITestEnvironmentVariables??{},...t},e.UITargetAppEnvironmentVariables={...e.UITargetAppEnvironmentVariables??{},...t},e.TestingEnvironmentVariables={...e.TestingEnvironmentVariables??{},...t}}function jr(e){Mr(e,e=>Object.assign(e,Er),{requireTestBundlePath:!0})}function Mr(e,t,n={}){let r=e.TestConfigurations;if(Array.isArray(r))for(let e of r)!e||typeof e!=`object`||Nr(e.TestTargets,t,n);for(let n of Object.values(e)){let e=Pr(n,{requireTestBundlePath:!0});e&&t(e)}}function Nr(e,t,n){if(Array.isArray(e))for(let r of e){let e=Pr(r,n);e&&t(e)}}function Pr(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;return t.requireTestBundlePath&&!n.TestBundlePath?null:n}const Fr=new Map,R=new Set;async function Ir(e,t){let n=Lr(t);if(n)return n;let r=m(),i=F(e,r),a=I(e,i);return await Ge(Fr,a,async()=>{let n=await Dn(a);try{return await zr({device:e,options:t,projectRoot:r,expectedCacheMetadata:i,derived:a,forceRebuild:t.forceRunnerXctestrunRebuild===!0})}finally{await n()}})}function Lr(e){let n=e.iosXctestrunFile?.trim();if(!n)return null;let r=x.resolve(n);if(!y.existsSync(r))throw new t(`COMMAND_FAILED`,`Configured iOS XCTest runner .xctestrun file not found`,{configKey:`iosXctestrunFile`,xctestrunPath:r});let i=e.iosXctestDerivedDataPath?.trim(),a=i?x.resolve(i):Rr(r);return L(`reuse`,`external_xctestrun`,{derived:a,xctestrunPath:r}),{xctestrunPath:r,derived:a,cache:`external`,artifact:`valid`,buildMs:0,xctestrunPathSource:`external`}}function Rr(e){let t=v.createHash(`sha1`);t.update(e);let n=t.digest(`hex`).slice(0,12);return x.join(b.tmpdir(),`agent-device-ios-xctest-derived`,n)}async function zr(e){let{device:t,options:n,projectRoot:r,expectedCacheMetadata:i,derived:a}=e;An(a,e.forceRebuild);let o=await Wr({device:t,derived:a,projectRoot:r,expectedCacheMetadata:i}),s=o.reason===`reuse_ready`?`exact`:o.xctestrunPath?`restore-key`:`miss`;return o.reason!==`reuse_ready`&&L(`rebuild`,o.reason,{derived:a,xctestrunPath:o.xctestrunPath}),await Br({device:t,derived:a,expectedCacheMetadata:i,existing:o,cache:s})||(o.xctestrunPath&&(Kn(a),Mn(a)),await Vr({device:t,options:n,projectRoot:r,expectedCacheMetadata:i,derived:a,cache:s,reason:o.reason}))}async function Br(e){let{device:t,derived:n,expectedCacheMetadata:r,existing:i,cache:a}=e;if(i.reason!==`reuse_ready`)return null;let o=await Hr(t,n,r,i);return o?{xctestrunPath:o,derived:n,cache:a,artifact:`valid`,buildMs:0,xctestrunPathSource:i.source}:null}async function Vr(e){let{device:n,options:r,projectRoot:i,expectedCacheMetadata:a,derived:o,cache:s,reason:c}=e,l=Yt(i);if(!y.existsSync(l))throw new t(`COMMAND_FAILED`,`iOS runner project not found`,{projectPath:l});let u=Date.now();Ve({type:`command`,status:`progress`,message:`Building Apple runner...`}),await Xr(n,l,o,r);let d=Math.max(0,Date.now()-u),f=Gr(o,n);if(!f)throw new t(`COMMAND_FAILED`,`Failed to locate .xctestrun after build`);let p=await er(f);if(!p)throw new t(`COMMAND_FAILED`,`Runner build is missing expected products`,{xctestrunPath:f});return await Xn(n,p,f),await fr(p),jn(o,a,f,p),L(`build`,`built_new`,{derived:o,xctestrunPath:f}),{xctestrunPath:f,derived:o,cache:s,artifact:`rebuilt`,buildMs:d,xctestrunPathSource:`build`,reason:c}}async function Hr(e,t,n,r){try{return await Xn(e,r.productPaths,r.xctestrunPath),L(`reuse`,`reuse_ready`,{derived:t,xctestrunPath:r.xctestrunPath}),jn(t,n,r.xctestrunPath,r.productPaths),r.xctestrunPath}catch(e){if(!Zn(e))throw e;return L(`rebuild`,`repair_failed`,{derived:t,xctestrunPath:r.xctestrunPath}),null}}async function Ur(e){try{let t=m(),n=F(e,t);return(await Wr({device:e,derived:I(e,n),projectRoot:t,expectedCacheMetadata:n})).reason===`reuse_ready`}catch{return!1}}function Wr(e){let{device:t,derived:n,projectRoot:r,expectedCacheMetadata:i}=e;return Jn({derived:n,projectRoot:r,expectedCacheMetadata:i,findXctestrun:e=>Gr(e,t),xctestrunReferencesProjectRoot:Yr,resolveExistingXctestrunProductPaths:er})}function Gr(e,t){let n=Kr(e);return n.length===0?null:(n.sort((e,n)=>qr(e,n,t)),n[0]?.path??null)}function Kr(e){if(!y.existsSync(e))return[];let t=[],n=[e];for(;n.length>0;){let e=n.pop(),r=y.readdirSync(e,{withFileTypes:!0});for(let i of r){let r=x.join(e,i.name);if(i.isDirectory()){n.push(r);continue}if(i.isFile()&&i.name.endsWith(`.xctestrun`))try{let e=y.statSync(r);t.push({path:r,mtimeMs:e.mtimeMs})}catch{}}}return t}function qr(e,t,n){if(n){let r=Jr(t.path,n)-Jr(e.path,n);if(r!==0)return r}return t.mtimeMs-e.mtimeMs||e.path.localeCompare(t.path)}function Jr(e,t){let n=0,r=e.toLowerCase();x.basename(r).startsWith(`agentdevicerunner.env.`)&&(n-=1e3),r.includes(`${x.sep}macos${x.sep}`)&&(n-=5e3);let i=Bt(t);return i.preferred.length>0&&(i.preferred.some(e=>r.includes(e))?n+=2e3:n-=500),i.disallowed.some(e=>r.includes(e))&&(n-=2500),n}function Yr(e,t){try{let n=y.readFileSync(e,`utf8`),r=new Set([t]);try{r.add(y.realpathSync(t))}catch{}for(let e of r)if(n.includes(e))return!0;return!1}catch{return!1}}async function Xr(e,n,r,i){let a=yn(process.env),o=vn(process.env,e.kind===`device`,e),s=e.kind===`device`?[`-allowProvisioningUpdates`]:[],c=bn(),l=xn(),u=await At(e);try{await d(`xcodebuild`,[`build-for-testing`,`-project`,n,`-scheme`,`AgentDeviceRunner`,`-parallel-testing-enabled`,`NO`,_n(e),`1`,`-destination`,Ht(e),`-derivedDataPath`,r,...c,...l,...a,...s,...o],{detached:!0,timeoutMs:i.buildTimeoutMs,onSpawn:e=>{R.add(e),e.on(`close`,()=>{R.delete(e)})},onStdoutChunk:e=>{k(e,i.logPath,i.traceLogPath,i.verbose)},onStderrChunk:e=>{k(e,i.logPath,i.traceLogPath,i.verbose)}})}catch(e){let n=e instanceof t?e:new t(`COMMAND_FAILED`,String(e)),r=Qe(n);throw new t(`COMMAND_FAILED`,`xcodebuild build-for-testing failed`,{error:n.message,details:n.details,logPath:i.logPath,hint:r})}finally{await u?.release()}}const Zr={tap:`preflightSkippableTouchMutation`,mouseClick:`default`,longPress:`preflightSkippableTouchMutation`,drag:`preflightSkippableTouchMutation`,remotePress:`default`,type:`default`,swipe:`preflightSkippableTouchMutation`,scroll:`preflightSkippableTouchMutation`,desktopScroll:`preflightSkippableTouchMutation`,findText:`readOnly`,querySelector:`readOnly`,readText:`readOnly`,snapshot:`readOnly`,screenshot:`readOnly`,back:`default`,backInApp:`default`,backSystem:`default`,home:`default`,rotate:`default`,rotateGesture:`default`,transformGesture:`default`,appSwitcher:`default`,keyboardDismiss:`default`,keyboardReturn:`default`,alert:`readOnly`,pinch:`default`,sequence:`preflightSkippableTouchMutation`,recordStart:`default`,recordStop:`default`,status:`readOnlyReadinessProbe`,uptime:`readOnlyReadinessProbe`,shutdown:`default`},Qr={readOnly:!1,readinessProbe:!1,readinessPreflightSkipEligibleAfterHealthyMutation:!1},$r={...Qr,readOnly:!0},ei={...$r,readinessProbe:!0},ti={...Qr,readinessPreflightSkipEligibleAfterHealthyMutation:!0},ni=Object.fromEntries(Object.entries(Zr).map(([e,t])=>[e,oi(t)]));function ri(e){return ni[e]}function z(e){return ri(e).readOnly}function ii(e){return ri(e).readinessProbe}function ai(e){return ri(e).readinessPreflightSkipEligibleAfterHealthyMutation}function oi(e){switch(e){case`default`:return Qr;case`readOnly`:return $r;case`readOnlyReadinessProbe`:return ei;case`preflightSkippableTouchMutation`:return ti}}const si=process.pid,ci=ne(process.pid),li=zi(si,ci);let ui;function di(e){return{schemaVersion:1,deviceId:e.deviceId,ownerToken:li,ownerPid:si,ownerStartTime:ci,ownerStateDir:yi(),sessionId:e.sessionId,runnerPid:e.runnerPid??null,port:e.port,xctestrunPath:e.xctestrunPath,jsonPath:e.jsonPath,createdAtMs:Date.now()}}function fi(e){ui=e?.trim()||void 0}async function pi(e,t){let n=await _e({lockDirPath:`${V(e)}.lock`,owner:{pid:si,startTime:ci,acquiredAtMs:Date.now()},timeoutMs:3e4,pollMs:100,ownerGraceMs:5e3,description:`iOS runner lease for ${e}`});try{return await t()}finally{await n()}}function B(e){try{return Mi(JSON.parse(y.readFileSync(V(e),`utf8`)),e)}catch{return null}}function mi(e){return e?e.ownerToken===li?{type:`owned`,lease:e}:Li(e)?Ri(e)?{type:`stale`,lease:e,staleReason:`owner-state-dir-gone`}:{type:`busy`,lease:e}:{type:`stale`,lease:e,staleReason:`owner-process-dead`}:{type:`empty`}}async function hi(e,n,r){let i=mi(B(e));if(i.type===`empty`){await n.cleanupRunnerXcodebuildProcesses(e,void 0);return}if(i.type===`busy`){if(gi(i.lease)){await U(i.lease,`same-state-dir`,n);return}if(_i(i.lease,r)){await U(i.lease,`logical-lease-takeover`,n);return}throw new t(`COMMAND_FAILED`,r?`iOS runner for ${e} is busy after device lease admission`:`iOS runner for ${e} is already owned by another agent-device daemon`,{deviceId:e,logicalLeaseContext:r,ownerPid:i.lease.ownerPid,ownerStartTime:i.lease.ownerStartTime,ownerStateDir:i.lease.ownerStateDir,ownerToken:i.lease.ownerToken,sessionId:i.lease.sessionId,hint:bi(i.lease,r)})}await U(i.lease,i.type,n)}function gi(e){let t=yi();return!t||!e.ownerStateDir?!1:x.resolve(t)===x.resolve(e.ownerStateDir)}function _i(e,t){return!t||t.leaseProvider!==`proxy`||!t.leaseId||!t.clientId?!1:vi(t.deviceKey,e.deviceId)}function vi(e,t){if(!e)return!1;if(e===t)return!0;let[,,n]=e.split(`:`,3);return n===t}function yi(){return ui||process.env.AGENT_DEVICE_STATE_DIR?.trim()||void 0}function bi(e,t){let n=xi(e),r=Si(e);return t?[r,n,`The device is busy because another active device lease owns it, or the runner is owned by another daemon/process after lease admission.`,`Retry after the owning session closes or after the five-minute inactivity lease expires.`].join(` `):[r,n,`If the runner is still active, wait for it to finish. Do not run prepare ios-runner from another daemon/client to recover this.`].join(` `)}function xi(e){let t=`Runner owner: PID ${e.ownerPid}`;return e.ownerStateDir?`${t} with AGENT_DEVICE_STATE_DIR=${e.ownerStateDir}`:`${t}.`}function Si(e){return e.ownerStateDir?`If it is stuck, stop the owning agent-device daemon for ${Ci(`AGENT_DEVICE_STATE_DIR`,e.ownerStateDir)} and retry.`:`If it is stuck, stop the owning agent-device daemon and retry.`}function Ci(e,t){return`${e}=${wi(t)}`}function wi(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Ti(e){let t=mi(B(e));return t.type===`stale`&&t.staleReason===`owner-process-dead`?t.lease:null}function Ei(e){return{...e,ownerToken:`detached-${e.ownerToken}`}}async function Di(e,t){let n=mi(B(e));n.type===`owned`&&await U(n.lease,`owned`,t)}function Oi(e){e&&Ai({deviceId:e.deviceId,ownerToken:e.ownerToken,sessionId:e.sessionId})}function ki(e){let t=V(e.deviceId);y.mkdirSync(x.dirname(t),{recursive:!0});let n=`${t}.${process.pid}.${Date.now()}.tmp`;y.writeFileSync(n,JSON.stringify(e,null,2),`utf8`),y.renameSync(n,t)}function Ai(e){let t=B(e.deviceId);if(t&&!(e.ownerToken&&t.ownerToken!==e.ownerToken)&&!(e.sessionId&&t.sessionId!==e.sessionId))try{y.unlinkSync(V(e.deviceId))}catch{}}function V(e){return x.join(ji(),`${Bi(e)}.json`)}function ji(){let e=process.env.AGENT_DEVICE_IOS_RUNNER_LEASE_DIR?.trim();return e?x.resolve(e):x.join(b.homedir(),`.agent-device`,`apple-runner`,`leases`)}function Mi(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;if(n.schemaVersion!==1||n.deviceId!==t)return null;let r=Ni(n);return r?{schemaVersion:1,deviceId:t,...r,ownerStartTime:Pi(n.ownerStartTime),ownerStateDir:Pi(n.ownerStateDir)??void 0,runnerPid:Fi(n.runnerPid)}:null}function Ni(e){let t={ownerToken:H(e.ownerToken),ownerPid:Fi(e.ownerPid),sessionId:H(e.sessionId),port:Fi(e.port),xctestrunPath:H(e.xctestrunPath),jsonPath:H(e.jsonPath),createdAtMs:Ii(e.createdAtMs)};return Object.values(t).some(e=>e===null)?null:t}function H(e){return typeof e==`string`&&e.length>0?e:null}function Pi(e){return typeof e==`string`?e:null}function Fi(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:null}function Ii(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Li(e){return h(e.ownerPid)?e.ownerStartTime?ne(e.ownerPid)===e.ownerStartTime:!0:!1}function Ri(e){if(!e.ownerStateDir)return!1;try{return y.statSync(e.ownerStateDir),!1}catch(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}}async function U(e,t,n){p({level:t===`stale`||t===`same-state-dir`||t===`logical-lease-takeover`?`warn`:`debug`,phase:`ios_runner_lease_cleanup`,data:{deviceId:e.deviceId,ownerPid:e.ownerPid,ownerStateDir:e.ownerStateDir,ownerToken:e.ownerToken,runnerPid:e.runnerPid,sessionId:e.sessionId,reason:t}}),await n.cleanupRunnerProcessTree(e.runnerPid??void 0,`SIGTERM`),await n.cleanupRunnerXcodebuildProcesses(e.deviceId,e.ownerToken),await n.cleanupRunnerProcessTree(e.runnerPid??void 0,`SIGKILL`),n.cleanupTempFile(e.xctestrunPath),n.cleanupTempFile(e.jsonPath),Oi(e)}function zi(e,t){let n=v.createHash(`sha256`);return n.update(String(e)),n.update(`\0`),n.update(t??`unknown-start`),`owner-${e}-${n.digest(`hex`).slice(0,8)}`}function Bi(e){return e.replaceAll(/[^A-Za-z0-9._-]/g,`-`)||`unknown-device`}function Vi(e,t){return`${e}:${t}:${Date.now()}`}function Hi(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):void 0}function Ui(e=process.env){return l(e.AGENT_DEVICE_IOS_RUNNER_DETACH??``)!==!1}async function Wi(e,t){if(e.kind!==`simulator`||!Ui()||fe(e.simulatorSetPath))return null;let n=Ti(e.id);if(!n)return null;let r=t=>(p({level:`debug`,phase:`ios_runner_lease_adoption_skipped`,data:{deviceId:e.id,runnerPid:n.runnerPid,port:n.port,reason:t}}),null),i=n.runnerPid;if(!i)return r(`runner_pid_missing`);if(!h(i))return r(`runner_process_dead`);let a=Ki(e);if(!a)return r(`expected_derived_unresolved`);if(!n.xctestrunPath.startsWith(`${a}${x.sep}`))return r(`artifact_fingerprint_mismatch`);if(!await Gi(e,n.port))return r(`probe_failed`);let o=qi(e,n,i,a,t);try{ki(o.lease)}catch{return null}return p({level:`info`,phase:`ios_runner_lease_adopted`,data:{deviceId:e.id,sessionId:o.sessionId,runnerPid:i,port:n.port,previousOwnerPid:n.ownerPid}}),o}async function Gi(e,t){try{let n=await ut(e,t,E({command:`uptime`}),500);return JSON.parse(await n.text())?.ok===!0}catch{return!1}}function Ki(e){try{return I(e,F(e))}catch{return null}}function qi(e,t,n,r,i){let a=Vi(e.id,t.port),o={xctestrunPath:t.xctestrunPath,derived:r,cache:`exact`,artifact:`valid`,buildMs:0,xctestrunPathSource:`manifest`,reason:`adopted_from_lease`},{child:s,wait:c}=Ji(n);return{sessionId:a,device:e,deviceId:e.id,port:t.port,xctestrunPath:t.xctestrunPath,xctestrunArtifact:o,jsonPath:t.jsonPath,testPromise:c,child:s,ready:!0,startupTimeoutMs:Hi(i.startupTimeoutMs),lease:di({deviceId:e.id,sessionId:a,runnerPid:n,port:t.port,xctestrunPath:t.xctestrunPath,jsonPath:t.jsonPath})}}function Ji(e){let t={pid:e,exitCode:null};return{child:t,wait:new Promise(n=>{let r=setInterval(()=>{h(e)||(clearInterval(r),t.exitCode=-1,n({stdout:``,stderr:``,exitCode:-1}))},1e3);r.unref?.()})}}const Yi=1e3,Xi=2e3,Zi={cleanupRunnerProcessTree:G,cleanupRunnerXcodebuildProcesses:la,cleanupTempFile:j};async function Qi(e,t={}){t.graceful===!1?await G(e.child.pid,`SIGTERM`):await na(e),await ra(e,t.waitTimeoutMs??1e4),oa(e.child.pid)&&await G(e.child.pid,`SIGKILL`),await ia(e)}async function $i(e){await Di(e,Zi)}async function ea(e){let t=Array.from(R);await sa(e,`SIGINT`),await ca(t,`SIGINT`),await sa(e,`SIGTERM`),await ca(t,`SIGTERM`),await sa(e,`SIGKILL`),await ca(t,`SIGKILL`),await Promise.allSettled(e.map(async e=>{await ia(e)}))}async function ta(){let e=Array.from(R);await Promise.allSettled(e.map(async e=>{try{await G(e.pid,`SIGTERM`),await G(e.pid,`SIGKILL`)}finally{R.delete(e)}}))}async function na(e){try{await rt(e.device,e.port,E({command:`shutdown`}),void 0,15e3)}catch{await G(e.child.pid,`SIGTERM`)}}async function ra(e,t){try{await Promise.race([e.testPromise,new Promise(e=>setTimeout(e,t))])}catch{}}async function ia(e){await aa(e.device),j(e.xctestrunPath),j(e.jsonPath);try{await e.simulatorSetRedirect?.release()}finally{Oi(e.lease)}}async function aa(e){e.kind===`simulator`&&await Promise.allSettled(nn.map(async t=>{try{await _(ge(e,[`terminate`,e.id,t]),{allowFailure:!0,timeoutMs:Xi})}catch(n){p({level:`warn`,phase:`ios_runner_simulator_app_terminate_failed`,data:{deviceId:e.id,bundleId:t,timeoutMs:Xi,error:n instanceof Error?n.message:String(n)}})}}))}function oa(e){return e?W(e)||re(e):!1}function W(e){return e?h(e):!1}async function sa(e,t){await Promise.allSettled(e.map(async e=>{await G(e.child.pid,t)}))}async function ca(e,t){await Promise.allSettled(e.map(async e=>{await G(e.pid,t),t===`SIGKILL`&&R.delete(e)}))}async function G(e,t){if(!e||e<=0)return;try{process.kill(-e,t)}catch{}ie([e],t);let n=t===`SIGINT`?`INT`:t===`SIGTERM`?`TERM`:`KILL`;try{await g(`pkill`,[`-${n}`,`-P`,String(e)],{allowFailure:!0})}catch{}}async function la(e,t){let n=t?`xcodebuild.*test-without-building.*AgentDeviceRunner\\.env\\.session-${ua(e)}-${ua(t)}-`:`xcodebuild.*test-without-building.*AgentDeviceRunner\\.env\\.session-${ua(e)}-[0-9]`;for(let t of[`TERM`,`KILL`])try{await g(`pkill`,[`-${t}`,`-f`,n],{allowFailure:!0,timeoutMs:2e3})}catch(n){p({level:`warn`,phase:`ios_runner_stale_xcodebuild_kill_failed`,data:{deviceId:e,signal:t,error:n instanceof Error?n.message:String(n)}})}}function ua(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}async function da(e){let n=await fa(e.logPath)??ma(e.error);return n?new t(n.code??e.error.code,e.error.message,{...e.error.details??{},hint:typeof e.error.details?.hint==`string`?`${e.error.details.hint} ${n.hint}`:n.hint,runnerFailureReason:n.reason},e.error):e.error}async function fa(e){if(!e)return;let t=await va(e,65536);if(t)return pa(t)}function pa(e){let t=e.toLowerCase();if(ha(t))return{code:`IOS_TARGET_APP_CRASH`,reason:`target_app_axruntime_coretext_crash`,hint:`The target iOS app appears to have crashed while XCTest/AXRuntime read accessibility attributes. This is usually a simulator/XCTest/runtime or app accessibility payload issue, not a text-entry failure. Reproduce on the latest stable simulator runtime, reinstall the app, and capture the app crash from Console.app or ~/Library/Logs/DiagnosticReports with the exact command, selector/ref, app build, Xcode, and simulator runtime.`};if(ga(t))return{code:`IOS_TARGET_APP_CRASH`,reason:`target_app_crash`,hint:`The target iOS app appears to have crashed while the runner was executing the command. Reopen or reinstall the app, retry on a fresh/latest stable simulator runtime, and capture the app crash from Console.app or ~/Library/Logs/DiagnosticReports with the exact command, selector/ref, app build, Xcode, and simulator runtime.`}}function ma(e){if(_a(e.message))return{reason:`runner_main_thread_execution_timeout`,hint:`XCTest timed out waiting for main-thread work on the current iOS screen. The app may still be visually responsive, especially on focused React Native overlays or animating screens. Use screenshot as visual truth, use coordinate presses only to prove or leave the state, and retry snapshot -i after the UI settles or after navigating away.`}}function ha(e){return e.includes(`axruntime`)&&e.includes(`coretext`)&&(e.includes(`attributesforelement`)||e.includes(`axuielementcopymultipleattributevalues`)||e.includes(`reconstitutedsmuggledctfontfromdictionary`)||e.includes(`reconstitutedsmuggledattributedstringfromdictionary`))}function ga(e){return e.includes(`process crashed`)||e.includes(`the application under test`)||e.includes(`terminated unexpectedly`)||e.includes(`exception type:`)&&e.includes(`thread 0 crashed`)}function _a(e){return e.toLowerCase().includes(`main thread execution timed out`)}async function va(e,t){let n;try{let r=await Se.stat(e),i=Math.max(0,r.size-t),a=r.size-i;if(a<=0)return;n=await Se.open(e,`r`);let o=Buffer.alloc(a);return await n.read(o,0,a,i),o.toString(`utf8`)}catch{return}finally{await n?.close().catch(()=>{})}}const K=new Map,ya=new Map,ba=new Map,xa=1e4;function Sa(e,t){return Ge(ya,e,t)}async function q(e,t){return Aa(e.id),await Sa(e.id,async()=>{let n=K.get(e.id);if(n){let t=await wa(e,n);if(t)return t}return await pi(e.id,async()=>await Ca(e,t))})}async function Ca(e,t){let n={},r=oo(t.runnerLeaseContext,e.id);p({level:`debug`,phase:`ios_runner_session_startup`,data:{deviceId:e.id,logicalLeaseContext:r}});let i=await X(n,`adopt_detached_runner`,async()=>await Wi(e,{startupTimeoutMs:t.startupTimeoutMs}));if(i)return i.startupTimings=n,i.logicalLeaseContext=r,K.set(e.id,i),i;await X(n,`cleanup_stale_xcodebuild`,async()=>{await hi(e.id,Zi,r)}),await X(n,`ensure_booted`,async()=>{await Ia(e)}),await X(n,`verify_developer_mode`,async()=>{await Ra(e)}),t.cleanStaleBundles?await X(n,`cleanup_stale_bundles`,async()=>{await Ta(e)}):(n.cleanup_stale_bundles=0,p({level:`debug`,phase:`ios_runner_startup_cleanup_stale_bundles_skipped`}));let a=await X(n,`ensure_xctestrun`,async()=>await Ir(e,t));n.build_xctestrun=a.buildMs;let o=await X(n,`allocate_port`,async()=>await St()),{xctestrunPath:s,jsonPath:c}=await X(n,`prepare_xctestrun_env`,async()=>await Dr(a.xctestrunPath,{AGENT_DEVICE_RUNNER_PORT:String(o)},`session-${e.id}-${li}-${o}`,{iosXctestEnvDir:t.iosXctestEnvDir})),l=await X(n,`simulator_set_redirect`,async()=>await At(e)),u,d,f=[`test-without-building`,`-only-testing`,`AgentDeviceRunnerUITests/RunnerTests/testCommand`,`-parallel-testing-enabled`,`NO`,`-test-timeouts-enabled`,`NO`,`-collect-test-diagnostics`,`never`,_n(e),`1`,`-destination-timeout`,`20`,`-xctestrun`,s,`-derivedDataPath`,a.derived,`-destination`,Vt(e)];try{a.buildMs>0&&Ve({type:`command`,status:`progress`,message:`Starting XCTest runner...`}),{child:u,wait:d}=await X(n,`launch_xcodebuild`,()=>ee(`xcodebuild`,f,{allowFailure:!0,env:{...process.env,AGENT_DEVICE_RUNNER_PORT:String(o)},detached:!0}))}catch(e){throw await l?.release(),e}u.stdout?.on(`data`,e=>{k(e,t.logPath,t.traceLogPath,t.verbose)}),u.stderr?.on(`data`,e=>{k(e,t.logPath,t.traceLogPath,t.verbose)});let te=Vi(e.id,o),m=di({deviceId:e.id,sessionId:te,runnerPid:u.pid,port:o,xctestrunPath:s,jsonPath:c}),h={sessionId:te,device:e,deviceId:e.id,port:o,xctestrunPath:s,xctestrunArtifact:a,jsonPath:c,testPromise:d,child:u,ready:!1,startupTimeoutMs:Hi(t.startupTimeoutMs),startupTimings:n,logicalLeaseContext:r,simulatorSetRedirect:l??void 0,lease:m};try{ki(m)}catch(t){throw await Y(e.id,h,{graceful:!1,waitTimeoutMs:Yi}),t}return K.set(e.id,h),h}async function wa(e,t){if(!W(t.child.pid))return await X({},`stop_stale_session`,async()=>{await Y(e.id,t,{graceful:!1,waitTimeoutMs:Yi})}),null;let n=t.xctestrunArtifact;if(n?.cache===`external`)return p({level:`debug`,phase:`ios_runner_session_reuse`,data:{deviceId:e.id,sessionId:t.sessionId,ready:t.ready,cache:n.cache,logicalLeaseContext:t.logicalLeaseContext}}),t;let r=I(e,F(e));return n?.derived===r?(p({level:`debug`,phase:`ios_runner_session_reuse`,data:{deviceId:e.id,sessionId:t.sessionId,ready:t.ready,logicalLeaseContext:t.logicalLeaseContext}}),t):(p({level:`debug`,phase:`ios_runner_session_artifact_stale`,data:{deviceId:e.id,sessionId:t.sessionId,currentDerived:n?.derived,expectedDerived:r}}),await X({},`stop_stale_artifact_session`,async()=>{await Y(e.id,t)}),null)}async function Ta(e){if(e.kind===`simulator`)for(let t of nn){let n=await Ea(e,t);!n||Da(n)}}async function Ea(e,t){try{return await _(ge(e,[`uninstall`,e.id,t]),{allowFailure:!0,timeoutMs:xa})}catch(n){p({level:`warn`,phase:`ios_runner_startup_cleanup_stale_bundle_failed`,data:{deviceId:e.id,bundleId:t,timeoutMs:xa,error:n instanceof Error?n.message:String(n)}});return}}function Da(e){if(e.exitCode===0)return!0;let t=`${e.stdout}\n${e.stderr}`.toLowerCase();return t.includes(`not installed`)||t.includes(`found nothing`)||t.includes(`no such file`)||t.includes(`invalid device`)||t.includes(`could not find`)}function Oa(e){let t=K.get(e);return t?{sessionId:t.sessionId,alive:W(t.child.pid)}:null}async function J(e,t){await Sa(e.deviceId,async()=>{K.get(e.deviceId)===e&&(p({level:`warn`,phase:`ios_runner_session_invalidated`,data:{deviceId:e.deviceId,sessionId:e.sessionId,reason:t}}),await Y(e.deviceId,e,{graceful:!1,waitTimeoutMs:Yi}))})}async function Y(e,t,n={}){let r=t??K.get(e);r&&(await Qi(r,n),K.get(e)===r&&K.delete(e))}function ka(e){Aa(e);let t=ja();if(t<=0||!K.has(e))return;let n=setTimeout(()=>{ba.delete(e),p({level:`info`,phase:`ios_runner_idle_stop`,data:{deviceId:e,idleMs:t}}),Ma(e).catch(t=>{p({level:`warn`,phase:`ios_runner_idle_stop_failed`,data:{deviceId:e,error:t instanceof Error?t.message:String(t)}})})},t);n.unref?.(),ba.set(e,n),p({level:`debug`,phase:`ios_runner_idle_stop_scheduled`,data:{deviceId:e,idleMs:t}})}function Aa(e){let t=ba.get(e);t&&(clearTimeout(t),ba.delete(e))}function ja(e=process.env){let t=e.AGENT_DEVICE_IOS_RUNNER_IDLE_STOP_MS?.trim();if(t){let e=Number(t);if(Number.isFinite(e)&&e>=0)return Math.floor(e)}return 3e5}async function Ma(e){Aa(e),await Sa(e,async()=>{await pi(e,async()=>{await Y(e),await $i(e)})})}async function Na(){let e=Array.from(K.values());await ea(e);for(let t of e)K.get(t.deviceId)===t&&K.delete(t.deviceId)}async function Pa(){if(!Ui())return 0;let e=0;for(let[t,n]of K)if(n.device.kind===`simulator`&&!n.simulatorSetRedirect&&!(!n.lease||!W(n.child.pid))){try{ki(Ei(n.lease))}catch{continue}K.delete(t),Aa(t),e+=1,p({level:`info`,phase:`ios_runner_session_detached`,data:{deviceId:t,sessionId:n.sessionId,runnerPid:n.child.pid,port:n.port}})}return e}async function Fa(){await Na();let e=Array.from(K.keys());await Promise.allSettled(e.map(async e=>{await Ma(e)})),await ta()}function Ia(e){return e.kind===`simulator`?e.booted?(p({level:`debug`,phase:`ios_runner_startup_ensure_booted_skipped`,data:{deviceId:e.id}}),Promise.resolve()):La(e):Promise.resolve()}async function La(e){await _(ge(e,[`bootstatus`,e.id,`-b`]),{timeoutMs:et})}async function Ra(e){if(!o(e)||e.kind!==`device`)return;let n=await g(`DevToolsSecurity`,[`-status`],{allowFailure:!0,timeoutMs:2e3}),r=`${n.stdout}\n${n.stderr}`;if(/developer mode is currently disabled/i.test(r))throw new t(`COMMAND_FAILED`,`Developer mode is disabled for Apple development tools`,{hint:"Run `sudo DevToolsSecurity -enable`, then retry the iOS runner. UI test runners start suspended until Xcode/testmanagerd can attach.",devToolsSecurityStatus:r.trim()})}function za(e){if(!i(e.platform))throw new t(`UNSUPPORTED_PLATFORM`,`Unsupported platform for iOS runner: ${e.platform}`);if(e.kind!==`simulator`&&e.kind!==`device`)throw new t(`UNSUPPORTED_OPERATION`,`Unsupported iOS device kind for runner: ${e.kind}`)}async function Ba(e,t,n,r,i,a){ao(t,n.command);let o=E(n),s=z(o.command),c=se.fromTimeoutMs(i),l=to(t,o);l.action===`run`?await Wa({device:e,session:t,runnerCommand:o,logPath:r,deadline:c,signal:a,decision:l}):Ga(o,t,l);let u;try{u=await Ua({device:e,session:t,runnerCommand:o,logPath:r,deadline:c,timeoutMs:i,signal:a,readOnlyCommand:s})}catch(e){throw Ha(e,t,l)}try{let e=await Ka(u,t,r),n=$a(e);return n?(t.lastHealthyMutation=void 0,await J(t,n)):ai(o.command)&&(t.lastHealthyMutation={atMs:Date.now(),appBundleId:o.appBundleId}),e}catch(e){let n=eo(e);throw n?(t.lastHealthyMutation=void 0,await J(t,n),e):Va(e)?e:Ha(e,t,l)}}function Va(e){return e instanceof t&&e.details?.runner!==void 0}function Ha(e,t,n){return n.action!==`skip`||n.reason!==`recent_healthy_mutation`?e:(t.lastHealthyMutation=void 0,ro(e,{runnerReadinessPreflightSkipped:!0,runnerReadinessPreflightSkipReason:n.reason,runnerReadinessPreflightSkippedAgeMs:n.lastHealthyMutationAgeMs}))}async function Ua(e){let{device:n,session:r,runnerCommand:i,logPath:a,deadline:o,timeoutMs:s,signal:c,readOnlyCommand:l}=e,d=o.remainingMs();if(d<=0)throw new t(`COMMAND_FAILED`,`Runner command deadline exceeded`,{timeoutMs:s});return await u(`ios_runner_command_send`,async()=>l?await rt(n,r.port,i,a,d,r,c):await ut(n,r.port,i,d,c),l?{command:i.command,commandId:i.commandId,readOnly:!0,sessionReady:r.ready,timeoutMs:d}:{command:i.command,commandId:i.commandId})}async function Wa(e){let{device:t,session:n,runnerCommand:r,logPath:i,deadline:a,signal:o,decision:s}=e,c=n.ready?Math.min(1e3,a.remainingMs()):Math.min(io(n),a.remainingMs());try{await Ka(await u(`ios_runner_readiness_preflight`,async()=>await rt(t,n.port,E({command:`uptime`}),i,c,n,o),{command:r.command,commandId:r.commandId,reason:s.reason,lastHealthyMutationAgeMs:s.lastHealthyMutationAgeMs,sessionReady:n.ready,timeoutMs:c}),n,i)}catch(e){throw no(e)}}function Ga(e,t,n){p({level:`debug`,phase:`ios_runner_readiness_preflight_skipped`,data:{command:e.command,commandId:e.commandId,reason:n.reason,lastHealthyMutationAgeMs:n.reason===`recent_healthy_mutation`?n.lastHealthyMutationAgeMs:void 0,sessionReady:t.ready}})}async function Ka(e,t,n){let r=qa(await e.text());if(!r.ok)throw await da({error:Ja(r,n),logPath:n});return t.ready=!0,Za(r)}function qa(e){try{let t=JSON.parse(e);return t&&typeof t==`object`?t:{}}catch{throw new t(`COMMAND_FAILED`,`Invalid runner response`,{text:e})}}function Ja(e,n){let r=Ya(e.error?.code),i=typeof e.error?.message==`string`?e.error.message:void 0,a=typeof e.error?.hint==`string`?e.error.hint:void 0;return new t(Xa(r),i??`Runner error`,{runner:e,runnerErrorCode:r,retriable:r===`RUNNER_BUSY`?!0:void 0,xcodebuild:{exitCode:1,stdout:``,stderr:``},hint:a,logPath:n})}function Ya(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function Xa(e){return e===`RUNNER_BUSY`?`COMMAND_FAILED`:e?n(e):`COMMAND_FAILED`}function Za(e){if(!e.data||typeof e.data!=`object`||Array.isArray(e.data))return{};let t=e.data;return Qa(t),t}function Qa(e){let t=e.gestureFallback;typeof t!=`string`||t.length===0||p({level:`debug`,phase:`ios_runner_gesture_fallback`,data:{fallback:t,message:typeof e.gestureFallbackMessage==`string`?e.gestureFallbackMessage:void 0,hint:typeof e.gestureFallbackHint==`string`?e.gestureFallbackHint:void 0}})}function $a(e){if(e.runnerFatal===!0)return typeof e.runnerFatalReason==`string`&&e.runnerFatalReason.trim().length>0?e.runnerFatalReason:`runner_reported_fatal_response`}function eo(e){if(e instanceof t){if(e.code===`IOS_AX_SNAPSHOT_FAILED`)return`ax_snapshot_failure`;if(e.code===`XCTEST_RECORDED_FAILURE`)return`xctest_recorded_failure`;if(e.code===`RUNNER_WEDGED`)return`runner_main_thread_wedged`}}function to(e,t){let n=z(t.command);if(!e.ready)return n?{action:`skip`,reason:`read_only_startup_command`}:{action:`run`,reason:`startup`};if(ii(t.command))return{action:`skip`,reason:`readiness_probe_command`};if(!ai(t.command))return{action:`run`,reason:`conservative_command`};let r=e.lastHealthyMutation;if(!r)return{action:`run`,reason:`no_recent_healthy_mutation`};if(t.appBundleId!==r.appBundleId)return{action:`run`,reason:`app_activation_uncertain`};let i=Date.now()-r.atMs;return i>5e3?{action:`run`,reason:`healthy_mutation_stale`,lastHealthyMutationAgeMs:i}:{action:`skip`,reason:`recent_healthy_mutation`,lastHealthyMutationAgeMs:i}}function no(e){return ro(e,{runnerReadinessPreflightFailed:!0})}function ro(e,n){let r=e instanceof t?e:new t(`COMMAND_FAILED`,e instanceof Error?e.message:String(e),void 0,e);return new t(r.code,r.message,{...r.details??{},...n},r.cause??e)}function io(e){return e.startupTimeoutMs??45e3}async function X(e,t,n){let r=Date.now();try{return await n()}finally{let n=Date.now()-r;e[t]=n,p({level:`debug`,phase:`ios_runner_startup_${t}`,durationMs:n})}}function ao(e,t){e.startupTimingsReported||!e.startupTimings||(e.startupTimingsReported=!0,p({level:`info`,phase:`ios_runner_session_startup_timings`,durationMs:Object.values(e.startupTimings).reduce((e,t)=>e+t,0),data:{command:t,sessionId:e.sessionId,ready:e.ready,logicalLeaseContext:e.logicalLeaseContext,timings:e.startupTimings}}))}function oo(e,t){if(!e)return;let n={leaseId:Z(e.leaseId),clientId:Z(e.clientId),tenantId:Z(e.tenantId),runId:Z(e.runId),leaseProvider:Z(e.leaseProvider),deviceKey:Z(e.deviceKey)??t},r=Object.entries(n).filter(([,e])=>e!==void 0);return r.length>0?Object.fromEntries(r):void 0}function Z(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}async function so(e){let{device:t,session:n,command:r,transportError:i,options:a,signal:o,invalidationReason:s}=e;return await co(await po(t,n,r,i,a,o),{command:r,session:n,transportError:i,invalidationReason:s,invalidateSession:e.invalidateSession})}async function co(e,t){if(!e)return await fo(t,`status_recovery_unavailable`);if(e.type===`recovered`)return lo(e,t);if(e.type===`skipInvalidation`)throw uo(e,t);return await fo(t,e.reason,e.lifecycleState,e.error)}function lo(e,t){return ko({command:t.command,session:t.session,transportError:t.transportError,decision:`skipped`,reason:e.reason,lifecycleState:e.lifecycleState}),e.data}function uo(e,t){return ko({command:t.command,session:t.session,transportError:t.transportError,decision:`skipped`,reason:e.reason,lifecycleState:e.lifecycleState}),e.error}async function fo(e,t,n,r){throw ko({command:e.command,session:e.session,transportError:e.transportError,decision:`retained`,reason:t,lifecycleState:n}),await e.invalidateSession(e.session,e.invalidationReason),r??e.transportError}async function po(e,t,n,r,i,a){if(n.command===`status`||!n.commandId?.trim())return;let o=Do(r),s;try{s=await Ba(e,t,{command:`status`,statusCommandId:n.commandId},i.logPath,3e3,a)}catch(e){return p({level:`debug`,phase:`ios_runner_command_status_recovery_failed`,data:{command:n.command,commandId:n.commandId,error:e instanceof Error?e.message:String(e),...o}}),{type:`retainInvalidation`,reason:`status_probe_failed`}}let c=typeof s.lifecycleState==`string`?s.lifecycleState:``;return p({level:`debug`,phase:`ios_runner_command_status_recovery`,data:{command:n.command,commandId:n.commandId,lifecycleState:c,...o}}),mo(s,c,n,r,i)}function mo(e,n,r,i,a){return n===`completed`?ho(e,r,i,a):n===`failed`?{type:`skipInvalidation`,reason:`runner_reported_failure`,lifecycleState:n,error:go(e,r,i,a)}:n===`accepted`||n===`started`?{type:`skipInvalidation`,reason:`command_still_in_flight`,lifecycleState:n,error:_o(n,r,i,a)}:{type:`retainInvalidation`,reason:n?`unknown_lifecycle_state`:`missing_lifecycle_state`,lifecycleState:n,error:new t(`COMMAND_FAILED`,`Runner command "${r.command}" lost its transport response and lifecycle status was ${n?`"${n}"`:`missing`}, so agent-device invalidated the runner session instead of replaying the command.`,{command:r.command,commandId:r.commandId,lifecycleState:n,recovery:`lifecycle_state_not_recoverable`,hint:Oo(r.command),logPath:a.logPath,transportError:i.message},i)}}function ho(e,n,r,i){let a=vo(e.lifecycleResponseJson);if(a)return{type:`recovered`,data:a,reason:`completed_with_retained_response`,lifecycleState:`completed`};if(z(n.command))return{type:`skipInvalidation`,error:r,reason:`read_only_completed_without_retained_response`,lifecycleState:`completed`};let o=Do(r);return{type:`skipInvalidation`,reason:`completed_without_retained_response`,lifecycleState:`completed`,error:new t(`COMMAND_FAILED`,`Runner command "${n.command}" completed after the transport response was lost, but no recoverable response was retained.`,{command:n.command,commandId:n.commandId,lifecycleState:`completed`,recovery:`completed_without_retained_response`,...o,hint:bo(n.command,o),logPath:i.logPath,transportError:r.message},r)}}function go(e,r,i,a){let o=typeof e.lifecycleErrorCode==`string`?e.lifecycleErrorCode:void 0,s=typeof e.lifecycleErrorMessage==`string`?e.lifecycleErrorMessage:`Runner command failed`,c=typeof e.lifecycleErrorHint==`string`?e.lifecycleErrorHint:void 0,l=Do(i);return new t(n(o),s,{command:r.command,commandId:r.commandId,lifecycleState:`failed`,recovery:`runner_reported_failure`,...l,hint:c??xo(r.command,l),logPath:a.logPath,transportError:i.message},i)}function _o(e,n,r,i){if(z(n.command))return r;let a=Do(r);return new t(`COMMAND_FAILED`,`Runner command "${n.command}" is still ${e} after the transport response was lost.`,{command:n.command,commandId:n.commandId,lifecycleState:e,recovery:`command_still_in_flight`,...a,hint:So(n.command,e,a),logPath:i.logPath,transportError:r.message},r)}function vo(e){if(typeof e!=`string`||e.trim().length===0)return;let t=yo(e);if(t.ok)return t.data&&typeof t.data==`object`&&!Array.isArray(t.data)?t.data:{}}function yo(e){try{let t=JSON.parse(e);if(t&&typeof t==`object`)return t}catch{}return{}}function bo(e,t){return`${Co(t)}The runner is still reachable and reports "${e}" already completed, so agent-device kept the session open and will not replay it. Run snapshot -i to inspect the current UI, then continue from that observed state.`}function xo(e,t){return`${Co(t)}The runner is still reachable and reports "${e}" failed after the transport response was lost, so agent-device kept the session open and did not replay it. Run snapshot -i to inspect the current UI and retry with a selector visible in that snapshot.`}function So(e,t,n){return`${Co(n)}The runner is still reachable and reports "${e}" is ${t}, so agent-device kept the session open and will not replay it. Wait briefly, run snapshot -i to inspect the current UI, then continue from that observed state.`}function Co(e){return e.readinessPreflightSkipped===!0?`This hot command skipped the uptime preflight because the runner had just completed a healthy interaction; status recovery confirmed the runner still observed it. `:``}function wo(e,t){let n=e.details?.[t];return typeof n==`boolean`?n:void 0}function To(e,t){let n=e.details?.[t];return typeof n==`string`?n:void 0}function Eo(e,t){let n=e.details?.[t];return typeof n==`number`?n:void 0}function Do(e){let t={},n=wo(e,`runnerReadinessPreflightSkipped`);n!==void 0&&(t.readinessPreflightSkipped=n);let r=To(e,`runnerReadinessPreflightSkipReason`);r!==void 0&&(t.readinessPreflightSkipReason=r);let i=Eo(e,`runnerReadinessPreflightSkippedAgeMs`);return i!==void 0&&(t.readinessPreflightSkippedAgeMs=i),t}function Oo(e){return`The runner did not confirm that "${e}" reached a safe terminal state, so agent-device kept the conservative invalidation path. Run snapshot -i before retrying if the UI may have changed.`}function ko(e){let{command:t,session:n,transportError:r,decision:i,reason:a,lifecycleState:o}=e;p({level:i===`retained`?`warn`:`debug`,phase:`ios_runner_command_invalidation_decision`,data:{command:t.command,commandId:t.commandId,decision:i,reason:a,lifecycleState:o,runnerReachable:o!==void 0,sessionId:n.sessionId,transportError:r.message}})}const Q=new Map;function Ao(e,t){let n=e.requestId?.trim();if(n)return`request:${n}`;let r=t.commandId?.trim();if(r)return`command:${r}`}function jo(e){if(!e)return;let t=Io(e);t.touchedSession=!0,$(e,t)}function Mo(e){return e?Q.get(e)?.touchedSession===!0:!1}function No(e){if(!e)return!0;let t=Io(e);return t.recycles>=1?($(e,t),!1):($(e,t),!0)}function Po(e){if(!e)return;let t=Io(e);t.recycles+=1,$(e,t)}function Fo(e,n){return p({level:`warn`,phase:`ios_runner_recycle_budget_exhausted`,data:{command:e.command,commandId:e.commandId,requestId:n.requestId,maxRecycles:1}}),new t(`COMMAND_FAILED`,`iOS runner was already restarted during this request and "${e.command}" still failed, so agent-device stopped instead of paying for another runner boot.`,{command:e.command,commandId:e.commandId,recovery:`runner_recycle_budget_exhausted`,hint:"The current screen is overwhelming the iOS accessibility capture (usually heavy or animating content). The app session is preserved: run `screenshot` for visual truth and interact with coordinate commands, or navigate to another screen and retry. Re-running the same command immediately will likely wedge again.",logPath:n.logPath})}function Io(e){return Lo(),Q.get(e)??{touchedSession:!1,recycles:0,lastAtMs:Date.now()}}function $(e,t){t.lastAtMs=Date.now(),Q.delete(e),Q.set(e,t)}function Lo(){let e=Date.now()-6e5;for(let[t,n]of Q)n.lastAtMs<e&&Q.delete(t);for(;Q.size>512;){let e=Q.keys().next().value;if(e===void 0)break;Q.delete(e)}}async function Ro(e,n){D(n.requestId);let r=Fe(n.requestId),i=E({command:`uptime`}),a;for(let t=1;t<=2;t+=1){let o=await zo({device:e,command:i,options:n,signal:r,attempt:t,recoveryReason:a});if(o.kind===`prepared`)return o.result;a=o.recoveryReason}throw new t(`COMMAND_FAILED`,`iOS runner prepare failed`)}async function zo(e){let{device:t,command:n,options:r,signal:i,attempt:a,recoveryReason:o}=e,s=Date.now(),c=await q(t,{...r,cleanStaleBundles:a>1?!0:r.cleanStaleBundles,...qo(r,`runner_session`)}),l=Date.now()-s;try{return{kind:`prepared`,result:$o(t,await Ko(t,c,n,r,i,l,{recoveryReason:o}))}}catch(e){return await Bo({device:t,session:c,command:n,options:r,signal:i,attempt:a,error:e})}}async function Bo(e){let{device:t,session:n,command:i,options:a,signal:o,attempt:s,error:c}=e,l=r(c,`COMMAND_FAILED`);if(s===1&&Yo(l,n))return{kind:`prepared`,result:await Vo({device:t,session:n,command:i,options:a,signal:o,error:l})};if(!Uo(l))throw c;let u=l.message||`runner_health_failed`;if(s>=2)throw await Ho(n,`prepare_runner_health_failed`),c;return D(a.requestId),await J(n,`prepare_runner_health_retry`),p({level:`warn`,phase:`ios_runner_prepare_health_retry`,data:{command:i.command,commandId:i.commandId,sessionId:n.sessionId,attempt:s,maxAttempts:2,reason:u}}),{kind:`retry`,recoveryReason:u}}async function Vo(e){let{device:t,session:n,command:r,options:i,signal:a,error:o}=e,s=o.message||`runner_health_failed`;await J(n,`prepare_cached_runner_health_failed`),await En(n.xctestrunArtifact,s);let c=Date.now(),l=await q(t,{...i,cleanStaleBundles:!0,forceRunnerXctestrunRebuild:!0,...qo(i,`runner_rebuild`)}),u=Date.now()-c;try{let e=await Ko(t,l,r,i,a,u,{recoveryReason:s});return p({level:`info`,phase:`ios_runner_prepare_bad_cache_recovered`,data:{command:r.command,commandId:r.commandId,sessionId:l.sessionId,xctestrunPath:l.xctestrunArtifact?.xctestrunPath,reason:s}}),$o(t,e)}catch(e){await Ho(l,`prepare_rebuilt_runner_health_failed`);let n=Zo(e,l,s);throw es(t,{cache:l.xctestrunArtifact?.cache,artifact:l.xctestrunArtifact?.artifact,buildMs:l.xctestrunArtifact?.buildMs,connectMs:u,healthCheckMs:0,xctestrunPath:l.xctestrunArtifact?.xctestrunPath,failureReason:n.message}),n}}async function Ho(e,t){try{await J(e,t)}catch{}}function Uo(e){return Le(e)?!1:T(e)||qe(e)||Xo(e)}async function Wo(e,t,n){D(n.requestId);let i=Fe(n.requestId),a=Ao(n,t),o,s=!1;try{if(!Oa(e.id)?.alive&&Mo(a)){if(!No(a))throw Fo(t,n);s=!0}o=await q(e,n),s&&Po(a),jo(a);let r=o.ready?tt:io(o);return await Ba(e,o,t,n.logPath,r,i)}catch(a){let s=r(a,`COMMAND_FAILED`);if(s.code===`COMMAND_FAILED`&&typeof s.message==`string`&&s.message.includes(`Runner did not accept connection`)&&qe(s)&&o)return D(n.requestId),await Go({device:e,session:o,command:t,options:n,signal:i,restartReason:`runner_connect_failed_before_command_send`});if(o&&ns(s))return D(n.requestId),await Go({device:e,session:o,command:t,options:n,signal:i,restartReason:`runner_readiness_preflight_failed_before_command_send`,recoveredDiagnosticPhase:`ios_runner_readiness_preflight_recovered`});if(o&&T(s))return await so({device:e,session:o,command:t,transportError:s,options:n,signal:i,invalidationReason:`transport_error_after_command_send`,invalidateSession:J});throw a}}async function Go(e){let{device:t,command:n,options:i,signal:a,restartReason:o}=e,s=Ao(i,n);if(!No(s))throw Fo(n,i);await J(e.session,o);let c=await q(t,{...i,cleanStaleBundles:!0});Po(s);try{let r=await Ba(t,c,n,i.logPath,et,a);return e.recoveredDiagnosticPhase&&p({level:`debug`,phase:e.recoveredDiagnosticPhase,data:{command:n.command,commandId:n.commandId,recovery:`session_restarted`,sessionId:c.sessionId}}),r}catch(e){let o=r(e,`COMMAND_FAILED`);if(T(o))return await so({device:t,session:c,command:n,transportError:o,options:i,signal:a,invalidationReason:`transport_error_after_retry_command_send`,invalidateSession:J});throw e}}async function Ko(e,t,n,r,i,a,o){let s=Date.now(),c=Jo(r.prepareDeadline,r.healthTimeoutMs,`runner_health`);return Qo(await Ba(e,t,n,r.logPath,c,i),t,a,Date.now()-s,o)}function qo(e,t){if(!e.prepareDeadline)return{};let n=Jo(e.prepareDeadline,e.buildTimeoutMs,t);return{buildTimeoutMs:n,startupTimeoutMs:n}}function Jo(e,n,r){if(!e)return n??45e3;let i=Math.floor(e.remainingMs());if(i<=0)throw new t(`COMMAND_FAILED`,`prepare ios-runner timed out`,{phase:r,reason:`prepare_deadline_expired`});return i}function Yo(e,t){let n=t.xctestrunArtifact;return!n||n.cache===`miss`?!1:Uo(e)}function Xo(e){let t=e.message.toLowerCase();return t.includes(`timeout`)||t.includes(`timed out`)||t.includes(`deadline`)}function Zo(e,n,i){let a=r(e,`COMMAND_FAILED`);return new t(a.code,`artifact restored but runner did not connect`,{...a.details??{},restoredFailureReason:i,xctestrunPath:n.xctestrunArtifact?.xctestrunPath,artifact:n.xctestrunArtifact?.artifact,cache:n.xctestrunArtifact?.cache,reason:a.message},a)}function Qo(e,t,n,r,i){let a=t.xctestrunArtifact,o={...i?.recoveryReason?{recoveryReason:i.recoveryReason}:{},...i?.failureReason?{failureReason:i.failureReason}:{}};return a?{runner:e,cache:a.cache,artifact:a.artifact,buildMs:a.buildMs,connectMs:Math.max(0,n),healthCheckMs:Math.max(0,r),xctestrunPath:a.xctestrunPath,...o}:{runner:e,connectMs:Math.max(0,n),healthCheckMs:Math.max(0,r),...o}}function $o(e,t){return es(e,t),t}function es(e,t){p({level:t.failureReason?`warn`:`info`,phase:`apple_runner_prepare`,data:{platform:e.platform,target:e.target,deviceId:e.id,cache:t.cache,artifact:t.artifact,buildMs:t.buildMs,connectMs:t.connectMs,healthCheckMs:t.healthCheckMs,timingContainment:t.buildMs===void 0?{healthCheckMs:[]}:{connectMs:[`buildMs`],healthCheckMs:[]},xctestrunPath:t.xctestrunPath,recoveryReason:t.recoveryReason,failureReason:t.failureReason}})}function ts(e){return e.details?.runnerReadinessPreflightFailed===!0}function ns(e){return ts(e)&&(T(e)||rs(e))}function rs(e){let t=e.message.toLowerCase();return t.includes(`timeout`)||t.includes(`timed out`)}var is=e({abortAllIosRunnerSessions:()=>Na,detachIosSimulatorRunnerSessionsForShutdown:()=>Pa,prepareIosRunner:()=>ls,prewarmAppleRunnerCache:()=>os,prewarmIosRunnerSession:()=>ss,runAppleRunnerCommand:()=>as,stopAllIosRunnerSessions:()=>Fa});async function as(e,t,n={}){za(e),D(n.requestId);let r=E(t),i=us(e,n);return z(r.command)?ce(()=>(D(n.requestId),i.runCommand(e,r,n)),{shouldRetry:e=>(D(n.requestId),T(e))}):i.runCommand(e,r,n)}function os(e,t={}){if(o(e))return cs({device:e,options:t,failurePhase:`ios_runner_cache_prewarm_failed`,task:async t=>{await Ir(e,t)}})}function ss(e,t={}){if(!o(e))return;let n=us(e,t).prewarm;if(!n){p({level:`debug`,phase:`ios_runner_session_prewarm_unavailable`,data:{deviceId:e.id}});return}return cs({device:e,options:t,failurePhase:`ios_runner_session_prewarm_failed`,task:async t=>{await n(e,t)}})}function cs(e){let{device:t,options:n,failurePhase:r,task:i}=e,{propagateError:a=!1,...o}=n;return i(o).catch(e=>{if(p({level:`warn`,phase:r,data:{deviceId:t.id,error:e instanceof Error?e.message:String(e)}}),a)throw e})}async function ls(e,t){za(e),D(t.requestId);let n=E({command:`uptime`}),r=us(e,t);if(r.prepare)return await r.prepare(e,t);let i=Date.now();return{runner:await r.runCommand(e,n,t),connectMs:0,healthCheckMs:Math.max(0,Date.now()-i)}}function us(e,t){return ye(e,ds,void 0,{requestId:t.requestId})}const ds=be(Wo,{prepare:Ro,prewarm:async(e,t)=>{await Ro(e,{...t,healthTimeoutMs:tt})}});export{je as C,Me as S,Ie as T,Be as _,is as a,Fe as b,Ma as c,nn as d,P as f,He as g,Ue as h,as as i,fi as l,Ve as m,os as n,Oa as o,Ge as p,ss as r,ka as s,ls as t,Ur as u,Ne as v,Ee as w,Pe as x,w as y};
1
+ import{t as e}from"./rolldown-runtime.js";import{_ as t,v as n,w as r}from"./sdk-contracts.js";import{D as i,F as a,j as o,y as s}from"./sdk-android-adb.js";import{o as c,s as l}from"./sdk-device.js";import{n as u}from"./host-process.js";import{o as d,s as f,u as p}from"./boot-diagnostics.js";import{A as ee,C as m,D as h,K as g,L as te,M as _,O as ne,P as v,S as re,T as ie,U as ae,W as y,_ as b,a as x,b as S,c as oe,d as se,f as ce,g as le,h as ue,i as de,l as fe,m as pe,n as me,o as he,p as ge,r as _e,t as C,v as ve,w as ye,x as w,y as be}from"./runner-disposal.js";import{a as xe,i as Se}from"./tool-provider.js";import{a as Ce,d as T,n as we,o as Te,r as E,t as Ee,u as D}from"./runner-lease.js";import{n as De,t as Oe}from"./runner-provider.js";import ke from"node:path";import O from"node:fs/promises";const Ae={tap:`preflightSkippableTouchMutation`,mouseClick:`default`,longPress:`preflightSkippableTouchMutation`,drag:`preflightSkippableTouchMutation`,remotePress:`default`,type:`default`,swipe:`preflightSkippableTouchMutation`,scroll:`preflightSkippableTouchMutation`,desktopScroll:`preflightSkippableTouchMutation`,findText:`readOnly`,querySelector:`readOnly`,readText:`readOnly`,snapshot:`readOnly`,screenshot:`readOnly`,back:`default`,backInApp:`default`,backSystem:`default`,home:`default`,rotate:`default`,gesture:`preflightSkippableTouchMutation`,gestureViewport:`readOnly`,appSwitcher:`default`,keyboardDismiss:`default`,keyboardReturn:`default`,alert:`readOnly`,sequence:`preflightSkippableTouchMutation`,recordStart:`default`,recordStop:`default`,status:`readOnlyReadinessProbe`,uptime:`readOnlyReadinessProbe`,targetReset:`readinessPreflightExemptMutation`,shutdown:`default`},k={readOnly:!1,readinessProbe:!1,readinessPreflightExempt:!1,readinessPreflightSkipEligibleAfterHealthyMutation:!1},je={...k,readinessPreflightExempt:!0},A={...k,readOnly:!0},Me={...A,readinessProbe:!0},Ne={...k,readinessPreflightSkipEligibleAfterHealthyMutation:!0},Pe=Object.fromEntries(Object.entries(Ae).map(([e,t])=>[e,Re(t)]));function j(e){return Pe[e]}function M(e){return j(e).readOnly}function Fe(e){return j(e).readinessProbe}function Ie(e){return j(e).readinessPreflightExempt}function Le(e){return j(e).readinessPreflightSkipEligibleAfterHealthyMutation}function Re(e){switch(e){case`default`:return k;case`readinessPreflightExemptMutation`:return je;case`readOnly`:return A;case`readOnlyReadinessProbe`:return Me;case`preflightSkippableTouchMutation`:return Ne}}function ze(e,t){return`${e}:${t}:${Date.now()}`}function Be(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):void 0}function Ve(e=process.env){return i(e.AGENT_DEVICE_IOS_RUNNER_DETACH??``)!==!1}async function He(e,t){if(e.kind!==`simulator`||!Ve()||d(e.simulatorSetPath))return null;let n=Te(e.id);if(!n)return null;let r=t=>(o({level:`debug`,phase:`ios_runner_lease_adoption_skipped`,data:{deviceId:e.id,runnerPid:n.runnerPid,port:n.port,reason:t}}),null),i=n.runnerPid;if(!i)return r(`runner_pid_missing`);if(!u(i))return r(`runner_process_dead`);let a=We(e);if(!a)return r(`expected_derived_unresolved`);if(!n.xctestrunPath.startsWith(`${a}${ke.sep}`))return r(`artifact_fingerprint_mismatch`);if(!await Ue(e,n.port))return r(`probe_failed`);let s=Ge(e,n,i,a,t);try{T(s.lease)}catch{return null}return o({level:`info`,phase:`ios_runner_lease_adopted`,data:{deviceId:e.id,sessionId:s.sessionId,runnerPid:i,port:n.port,previousOwnerPid:n.ownerPid}}),s}async function Ue(e,t){try{let n=await ve(e,t,m({command:`uptime`}),500);return JSON.parse(await n.text())?.ok===!0}catch{return!1}}function We(e){try{return h(e,ie(e))}catch{return null}}function Ge(e,t,n,r,i){let a=ze(e.id,t.port),o={xctestrunPath:t.xctestrunPath,derived:r,cache:`exact`,artifact:`valid`,buildMs:0,xctestrunPathSource:`manifest`,reason:`adopted_from_lease`},{child:s,wait:c}=Ke(n);return{sessionId:a,device:e,deviceId:e.id,port:t.port,xctestrunPath:t.xctestrunPath,xctestrunArtifact:o,jsonPath:t.jsonPath,testPromise:c,child:s,ready:!0,startupTimeoutMs:Be(i.startupTimeoutMs),lease:E({deviceId:e.id,sessionId:a,runnerPid:n,port:t.port,xctestrunPath:t.xctestrunPath,jsonPath:t.jsonPath})}}function Ke(e){let t={pid:e,exitCode:null};return{child:t,wait:new Promise(n=>{let r=setInterval(()=>{u(e)||(clearInterval(r),t.exitCode=-1,n({stdout:``,stderr:``,exitCode:-1}))},1e3);r.unref?.()})}}async function qe(e){let n=await Je(e.logPath)??Xe(e.error);return n?new t(n.code??e.error.code,e.error.message,{...e.error.details??{},hint:typeof e.error.details?.hint==`string`?`${e.error.details.hint} ${n.hint}`:n.hint,runnerFailureReason:n.reason},e.error):e.error}async function Je(e){if(!e)return;let t=await et(e,65536);if(t)return Ye(t)}function Ye(e){let t=e.toLowerCase();if(Ze(t))return{code:`IOS_TARGET_APP_CRASH`,reason:`target_app_axruntime_coretext_crash`,hint:`The target iOS app appears to have crashed while XCTest/AXRuntime read accessibility attributes. This is usually a simulator/XCTest/runtime or app accessibility payload issue, not a text-entry failure. Reproduce on the latest stable simulator runtime, reinstall the app, and capture the app crash from Console.app or ~/Library/Logs/DiagnosticReports with the exact command, selector/ref, app build, Xcode, and simulator runtime.`};if(Qe(t))return{code:`IOS_TARGET_APP_CRASH`,reason:`target_app_crash`,hint:`The target iOS app appears to have crashed while the runner was executing the command. Reopen or reinstall the app, retry on a fresh/latest stable simulator runtime, and capture the app crash from Console.app or ~/Library/Logs/DiagnosticReports with the exact command, selector/ref, app build, Xcode, and simulator runtime.`}}function Xe(e){if($e(e.message))return{reason:`runner_main_thread_execution_timeout`,hint:`XCTest timed out waiting for main-thread work on the current iOS screen. The app may still be visually responsive, especially on focused React Native overlays or animating screens. Use screenshot as visual truth, use coordinate presses only to prove or leave the state, and retry snapshot -i after the UI settles or after navigating away.`}}function Ze(e){return e.includes(`axruntime`)&&e.includes(`coretext`)&&(e.includes(`attributesforelement`)||e.includes(`axuielementcopymultipleattributevalues`)||e.includes(`reconstitutedsmuggledctfontfromdictionary`)||e.includes(`reconstitutedsmuggledattributedstringfromdictionary`))}function Qe(e){return e.includes(`process crashed`)||e.includes(`the application under test`)||e.includes(`terminated unexpectedly`)||e.includes(`exception type:`)&&e.includes(`thread 0 crashed`)}function $e(e){return e.toLowerCase().includes(`main thread execution timed out`)}async function et(e,t){let n;try{let r=await O.stat(e),i=Math.max(0,r.size-t),a=r.size-i;if(a<=0)return;n=await O.open(e,`r`);let o=Buffer.alloc(a);return await n.read(o,0,a,i),o.toString(`utf8`)}catch{return}finally{await n?.close().catch(()=>{})}}const N=new Map,tt=new Map,P=new Map,nt=1e4;function F(e,t){return v(tt,e,t)}async function I(e,t){return z(e.id),await F(e.id,async()=>{let n=N.get(e.id);if(n){let t=await it(e,n);if(t)return t}return await D(e.id,async()=>await rt(e,t))})}async function rt(e,t){let n={},r=y(t.requestId),i=Lt(t.runnerLeaseContext,e.id);o({level:`debug`,phase:`ios_runner_session_startup`,data:{deviceId:e.id,logicalLeaseContext:i}});let a=await H(n,`adopt_detached_runner`,async()=>await He(e,{startupTimeoutMs:t.startupTimeoutMs}));if(a)return a.startupTimings=n,a.logicalLeaseContext=i,N.set(e.id,a),a;await H(n,`cleanup_stale_xcodebuild`,async()=>{await Ce(e.id,he,i)}),await H(n,`ensure_booted`,async()=>{await mt(e)}),await H(n,`verify_developer_mode`,async()=>{await gt(e)}),t.cleanStaleBundles?await H(n,`cleanup_stale_bundles`,async()=>{await at(e)}):(n.cleanup_stale_bundles=0,o({level:`debug`,phase:`ios_runner_startup_cleanup_stale_bundles_skipped`}));let c=await H(n,`ensure_xctestrun`,async()=>await fe(e,{...t,signal:r}));n.build_xctestrun=c.buildMs;let l=await H(n,`allocate_port`,async()=>await le()),{xctestrunPath:u,jsonPath:d}=await H(n,`prepare_xctestrun_env`,async()=>await se(c.xctestrunPath,{AGENT_DEVICE_RUNNER_PORT:String(l)},`session-${e.id}-${Ee}-${l}`,{iosXctestEnvDir:t.iosXctestEnvDir})),f=await H(n,`simulator_set_redirect`,async()=>await ge(e)),p,m,h=[`test-without-building`,`-only-testing`,`AgentDeviceRunnerUITests/RunnerTests/testCommand`,`-parallel-testing-enabled`,`NO`,`-test-timeouts-enabled`,`NO`,`-collect-test-diagnostics`,`never`,ne(e),`1`,`-destination-timeout`,`20`,`-xctestrun`,u,`-derivedDataPath`,c.derived,`-destination`,ee(e)];try{c.buildMs>0&&te({type:`command`,status:`progress`,message:`Starting XCTest runner...`}),{child:p,wait:m}=await H(n,`launch_xcodebuild`,()=>s(`xcodebuild`,h,{allowFailure:!0,env:{...process.env,AGENT_DEVICE_RUNNER_PORT:String(l)},detached:!0,signal:r}))}catch(e){throw await f?.release(),e}p.stdout?.on(`data`,e=>{b(e,t.logPath,t.traceLogPath,t.verbose)}),p.stderr?.on(`data`,e=>{b(e,t.logPath,t.traceLogPath,t.verbose)});let g=ze(e.id,l),_=E({deviceId:e.id,sessionId:g,runnerPid:p.pid,port:l,xctestrunPath:u,jsonPath:d}),v={sessionId:g,device:e,deviceId:e.id,port:l,xctestrunPath:u,xctestrunArtifact:c,jsonPath:d,testPromise:m,child:p,ready:!1,startupTimeoutMs:Be(t.startupTimeoutMs),startupTimings:n,logicalLeaseContext:i,simulatorSetRedirect:f??void 0,lease:_};if(r?.aborted)throw await de(v,{graceful:!1,waitTimeoutMs:C}),ae();try{T(_)}catch(t){throw await R(e.id,v,{graceful:!1,waitTimeoutMs:C}),t}return N.set(e.id,v),v}async function it(e,t){if(!x(t.child.pid))return await H({},`stop_stale_session`,async()=>{await R(e.id,t,{graceful:!1,waitTimeoutMs:C})}),null;let n=t.xctestrunArtifact;if(n?.cache===`external`)return o({level:`debug`,phase:`ios_runner_session_reuse`,data:{deviceId:e.id,sessionId:t.sessionId,ready:t.ready,cache:n.cache,logicalLeaseContext:t.logicalLeaseContext}}),t;let r=h(e,ie(e));return n?.derived===r?(o({level:`debug`,phase:`ios_runner_session_reuse`,data:{deviceId:e.id,sessionId:t.sessionId,ready:t.ready,logicalLeaseContext:t.logicalLeaseContext}}),t):(o({level:`debug`,phase:`ios_runner_session_artifact_stale`,data:{deviceId:e.id,sessionId:t.sessionId,currentDerived:n?.derived,expectedDerived:r}}),await H({},`stop_stale_artifact_session`,async()=>{await R(e.id,t)}),null)}async function at(e){if(e.kind===`simulator`)for(let t of ye){let n=await ot(e,t);!n||st(n)}}async function ot(e,t){try{return await xe(_(e,[`uninstall`,e.id,t]),{allowFailure:!0,timeoutMs:nt})}catch(n){o({level:`warn`,phase:`ios_runner_startup_cleanup_stale_bundle_failed`,data:{deviceId:e.id,bundleId:t,timeoutMs:nt,error:n instanceof Error?n.message:String(n)}});return}}function st(e){if(e.exitCode===0)return!0;let t=`${e.stdout}\n${e.stderr}`.toLowerCase();return t.includes(`not installed`)||t.includes(`found nothing`)||t.includes(`no such file`)||t.includes(`invalid device`)||t.includes(`could not find`)}function ct(e){let t=N.get(e);return t?{sessionId:t.sessionId,alive:x(t.child.pid)}:null}async function L(e,t){await F(e.deviceId,async()=>{N.get(e.deviceId)===e&&(o({level:`warn`,phase:`ios_runner_session_invalidated`,data:{deviceId:e.deviceId,sessionId:e.sessionId,reason:t}}),await R(e.deviceId,e,{graceful:!1,waitTimeoutMs:C}))})}async function R(e,t,n={}){let r=t??N.get(e);r&&(await de(r,n),N.get(e)===r&&N.delete(e))}function lt(e){z(e);let t=ut();if(t<=0||!N.has(e))return;let n=setTimeout(()=>{P.delete(e),o({level:`info`,phase:`ios_runner_idle_stop`,data:{deviceId:e,idleMs:t}}),B(e).catch(t=>{o({level:`warn`,phase:`ios_runner_idle_stop_failed`,data:{deviceId:e,error:t instanceof Error?t.message:String(t)}})})},t);n.unref?.(),P.set(e,n),o({level:`debug`,phase:`ios_runner_idle_stop_scheduled`,data:{deviceId:e,idleMs:t}})}function z(e){let t=P.get(e);t&&(clearTimeout(t),P.delete(e))}function ut(e=process.env){let t=e.AGENT_DEVICE_IOS_RUNNER_IDLE_STOP_MS?.trim();if(t){let e=Number(t);if(Number.isFinite(e)&&e>=0)return Math.floor(e)}return 3e5}async function B(e){z(e),await F(e,async()=>{await D(e,async()=>{await R(e),await _e(e)})})}async function dt(){let e=Array.from(N.values());await me(e);for(let t of e)N.get(t.deviceId)===t&&N.delete(t.deviceId)}async function ft(){if(!Ve())return 0;let e=0;for(let[t,n]of N)if(n.device.kind===`simulator`&&!n.simulatorSetRedirect&&!(!n.lease||!x(n.child.pid))){try{T(we(n.lease))}catch{continue}N.delete(t),z(t),e+=1,o({level:`info`,phase:`ios_runner_session_detached`,data:{deviceId:t,sessionId:n.sessionId,runnerPid:n.child.pid,port:n.port}})}return e}async function pt(){await dt();let e=Array.from(N.keys());await Promise.allSettled(e.map(async e=>{await B(e)})),await oe()}function mt(e){return e.kind===`simulator`?e.booted?(o({level:`debug`,phase:`ios_runner_startup_ensure_booted_skipped`,data:{deviceId:e.id}}),Promise.resolve()):ht(e):Promise.resolve()}async function ht(e){await xe(_(e,[`bootstatus`,e.id,`-b`]),{timeoutMs:ue})}async function gt(e){if(!l(e)||e.kind!==`device`)return;let n=await Se(`DevToolsSecurity`,[`-status`],{allowFailure:!0,timeoutMs:2e3}),r=`${n.stdout}\n${n.stderr}`;if(/developer mode is currently disabled/i.test(r))throw new t(`COMMAND_FAILED`,`Developer mode is disabled for Apple development tools`,{hint:"Run `sudo DevToolsSecurity -enable`, then retry the iOS runner. UI test runners start suspended until Xcode/testmanagerd can attach.",devToolsSecurityStatus:r.trim()})}function _t(e){if(!c(e.platform))throw new t(`UNSUPPORTED_PLATFORM`,`Unsupported platform for iOS runner: ${e.platform}`);if(e.kind!==`simulator`&&e.kind!==`device`)throw new t(`UNSUPPORTED_OPERATION`,`Unsupported iOS device kind for runner: ${e.kind}`)}async function V(e,t,n,r,i,a){It(t,n.command);let o=m(n),s=M(o.command),c=f.fromTimeoutMs(i),l=Mt(t,o);l.action===`run`?await xt({device:e,session:t,runnerCommand:o,logPath:r,deadline:c,signal:a,decision:l}):St(o,t,l);let u;try{u=await bt({device:e,session:t,runnerCommand:o,logPath:r,deadline:c,timeoutMs:i,signal:a,readOnlyCommand:s})}catch(e){throw yt(e,t,l)}try{let e=await Ct(u,t,r),n=At(e);return n?(t.lastHealthyMutation=void 0,await L(t,n)):Le(o.command)&&(t.lastHealthyMutation={atMs:Date.now(),appBundleId:o.appBundleId}),e}catch(e){let n=jt(e);throw n?(t.lastHealthyMutation=void 0,await L(t,n),e):vt(e)?e:yt(e,t,l)}}function vt(e){return e instanceof t&&e.details?.runner!==void 0}function yt(e,t,n){return n.action!==`skip`||n.reason!==`recent_healthy_mutation`?e:(t.lastHealthyMutation=void 0,Pt(e,{runnerReadinessPreflightSkipped:!0,runnerReadinessPreflightSkipReason:n.reason,runnerReadinessPreflightSkippedAgeMs:n.lastHealthyMutationAgeMs}))}async function bt(e){let{device:n,session:r,runnerCommand:i,logPath:o,deadline:s,timeoutMs:c,signal:l,readOnlyCommand:u}=e,d=s.remainingMs();if(d<=0)throw new t(`COMMAND_FAILED`,`Runner command deadline exceeded`,{timeoutMs:c});return await a(`ios_runner_command_send`,async()=>u?await be(n,r.port,i,o,d,r,l):await ve(n,r.port,i,d,l),u?{command:i.command,commandId:i.commandId,readOnly:!0,sessionReady:r.ready,timeoutMs:d}:{command:i.command,commandId:i.commandId})}async function xt(e){let{device:t,session:n,runnerCommand:r,logPath:i,deadline:o,signal:s,decision:c}=e,l=n.ready?Math.min(1e3,o.remainingMs()):Math.min(Ft(n),o.remainingMs());try{await Ct(await a(`ios_runner_readiness_preflight`,async()=>await be(t,n.port,m({command:`uptime`}),i,l,n,s),{command:r.command,commandId:r.commandId,reason:c.reason,lastHealthyMutationAgeMs:c.lastHealthyMutationAgeMs,sessionReady:n.ready,timeoutMs:l}),n,i)}catch(e){throw Nt(e)}}function St(e,t,n){o({level:`debug`,phase:`ios_runner_readiness_preflight_skipped`,data:{command:e.command,commandId:e.commandId,reason:n.reason,lastHealthyMutationAgeMs:n.reason===`recent_healthy_mutation`?n.lastHealthyMutationAgeMs:void 0,sessionReady:t.ready}})}async function Ct(e,t,n){let r=wt(await e.text());if(!r.ok)throw await qe({error:Tt(r,n),logPath:n});return t.ready=!0,Ot(r)}function wt(e){try{let t=JSON.parse(e);return t&&typeof t==`object`?t:{}}catch{throw new t(`COMMAND_FAILED`,`Invalid runner response`,{text:e})}}function Tt(e,n){let r=Et(e.error?.code),i=typeof e.error?.message==`string`?e.error.message:void 0,a=typeof e.error?.hint==`string`?e.error.hint:void 0;return new t(Dt(r),i??`Runner error`,{runner:e,runnerErrorCode:r,retriable:r===`RUNNER_BUSY`?!0:void 0,xcodebuild:{exitCode:1,stdout:``,stderr:``},hint:a,logPath:n})}function Et(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function Dt(e){return e===`RUNNER_BUSY`?`COMMAND_FAILED`:e?r(e):`COMMAND_FAILED`}function Ot(e){if(!e.data||typeof e.data!=`object`||Array.isArray(e.data))return{};let t=e.data;return kt(t),t}function kt(e){let t=e.gestureFallback;typeof t!=`string`||t.length===0||o({level:`debug`,phase:`ios_runner_gesture_fallback`,data:{fallback:t,message:typeof e.gestureFallbackMessage==`string`?e.gestureFallbackMessage:void 0,hint:typeof e.gestureFallbackHint==`string`?e.gestureFallbackHint:void 0}})}function At(e){if(e.runnerFatal===!0)return typeof e.runnerFatalReason==`string`&&e.runnerFatalReason.trim().length>0?e.runnerFatalReason:`runner_reported_fatal_response`}function jt(e){if(e instanceof t){if(e.code===`IOS_AX_SNAPSHOT_FAILED`)return`ax_snapshot_failure`;if(e.code===`XCTEST_RECORDED_FAILURE`)return`xctest_recorded_failure`;if(e.code===`RUNNER_WEDGED`)return`runner_main_thread_wedged`}}function Mt(e,t){let n=M(t.command);if(Ie(t.command))return{action:`skip`,reason:`preflight_exempt_command`};if(!e.ready)return n?{action:`skip`,reason:`read_only_startup_command`}:{action:`run`,reason:`startup`};if(Fe(t.command))return{action:`skip`,reason:`readiness_probe_command`};if(!Le(t.command))return{action:`run`,reason:`conservative_command`};let r=e.lastHealthyMutation;if(!r)return{action:`run`,reason:`no_recent_healthy_mutation`};if(t.appBundleId!==r.appBundleId)return{action:`run`,reason:`app_activation_uncertain`};let i=Date.now()-r.atMs;return i>5e3?{action:`run`,reason:`healthy_mutation_stale`,lastHealthyMutationAgeMs:i}:{action:`skip`,reason:`recent_healthy_mutation`,lastHealthyMutationAgeMs:i}}function Nt(e){return Pt(e,{runnerReadinessPreflightFailed:!0})}function Pt(e,n){let r=e instanceof t?e:new t(`COMMAND_FAILED`,e instanceof Error?e.message:String(e),void 0,e);return new t(r.code,r.message,{...r.details??{},...n},r.cause??e)}function Ft(e){return e.startupTimeoutMs??45e3}async function H(e,t,n){let r=Date.now();try{return await n()}finally{let n=Date.now()-r;e[t]=n,o({level:`debug`,phase:`ios_runner_startup_${t}`,durationMs:n})}}function It(e,t){e.startupTimingsReported||!e.startupTimings||(e.startupTimingsReported=!0,o({level:`info`,phase:`ios_runner_session_startup_timings`,durationMs:Object.values(e.startupTimings).reduce((e,t)=>e+t,0),data:{command:t,sessionId:e.sessionId,ready:e.ready,logicalLeaseContext:e.logicalLeaseContext,timings:e.startupTimings}}))}function Lt(e,t){if(!e)return;let n={leaseId:U(e.leaseId),clientId:U(e.clientId),tenantId:U(e.tenantId),runId:U(e.runId),leaseProvider:U(e.leaseProvider),deviceKey:U(e.deviceKey)??t},r=Object.entries(n).filter(([,e])=>e!==void 0);return r.length>0?Object.fromEntries(r):void 0}function U(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}async function Rt(e){let{device:t,session:n,command:r,transportError:i,options:a,signal:o,invalidationReason:s}=e;return await zt(await Ut(t,n,r,i,a,o),{command:r,session:n,transportError:i,invalidationReason:s,invalidateSession:e.invalidateSession})}async function zt(e,t){if(!e)return await Ht(t,`status_recovery_unavailable`);if(e.type===`recovered`)return Bt(e,t);if(e.type===`skipInvalidation`)throw Vt(e,t);return await Ht(t,e.reason,e.lifecycleState,e.error)}function Bt(e,t){return K({command:t.command,session:t.session,transportError:t.transportError,decision:`skipped`,reason:e.reason,lifecycleState:e.lifecycleState}),e.data}function Vt(e,t){return K({command:t.command,session:t.session,transportError:t.transportError,decision:`skipped`,reason:e.reason,lifecycleState:e.lifecycleState}),e.error}async function Ht(e,t,n,r){throw K({command:e.command,session:e.session,transportError:e.transportError,decision:`retained`,reason:t,lifecycleState:n}),await e.invalidateSession(e.session,e.invalidationReason),r??e.transportError}async function Ut(e,t,n,r,i,a){if(n.command===`status`||!n.commandId?.trim())return;let s=G(r),c;try{c=await V(e,t,{command:`status`,statusCommandId:n.commandId},i.logPath,3e3,a)}catch(e){return o({level:`debug`,phase:`ios_runner_command_status_recovery_failed`,data:{command:n.command,commandId:n.commandId,error:e instanceof Error?e.message:String(e),...s}}),{type:`retainInvalidation`,reason:`status_probe_failed`}}let l=typeof c.lifecycleState==`string`?c.lifecycleState:``;return o({level:`debug`,phase:`ios_runner_command_status_recovery`,data:{command:n.command,commandId:n.commandId,lifecycleState:l,...s}}),Wt(c,l,n,r,i)}function Wt(e,n,r,i,a){return n===`completed`?Gt(e,r,i,a):n===`failed`?{type:`skipInvalidation`,reason:`runner_reported_failure`,lifecycleState:n,error:Kt(e,r,i,a)}:n===`accepted`||n===`started`?{type:`skipInvalidation`,reason:`command_still_in_flight`,lifecycleState:n,error:qt(n,r,i,a)}:{type:`retainInvalidation`,reason:n?`unknown_lifecycle_state`:`missing_lifecycle_state`,lifecycleState:n,error:new t(`COMMAND_FAILED`,`Runner command "${r.command}" lost its transport response and lifecycle status was ${n?`"${n}"`:`missing`}, so agent-device invalidated the runner session instead of replaying the command.`,{command:r.command,commandId:r.commandId,lifecycleState:n,recovery:`lifecycle_state_not_recoverable`,hint:nn(r.command),logPath:a.logPath,transportError:i.message},i)}}function Gt(e,n,r,i){let a=Jt(e.lifecycleResponseJson);if(a)return{type:`recovered`,data:a,reason:`completed_with_retained_response`,lifecycleState:`completed`};if(M(n.command))return{type:`skipInvalidation`,error:r,reason:`read_only_completed_without_retained_response`,lifecycleState:`completed`};let o=G(r);return{type:`skipInvalidation`,reason:`completed_without_retained_response`,lifecycleState:`completed`,error:new t(`COMMAND_FAILED`,`Runner command "${n.command}" completed after the transport response was lost, but no recoverable response was retained.`,{command:n.command,commandId:n.commandId,lifecycleState:`completed`,recovery:`completed_without_retained_response`,...o,hint:Xt(n.command,o),logPath:i.logPath,transportError:r.message},r)}}function Kt(e,n,i,a){let o=typeof e.lifecycleErrorCode==`string`?e.lifecycleErrorCode:void 0,s=typeof e.lifecycleErrorMessage==`string`?e.lifecycleErrorMessage:`Runner command failed`,c=typeof e.lifecycleErrorHint==`string`?e.lifecycleErrorHint:void 0,l=G(i);return new t(r(o),s,{command:n.command,commandId:n.commandId,lifecycleState:`failed`,recovery:`runner_reported_failure`,...l,hint:c??Zt(n.command,l),logPath:a.logPath,transportError:i.message},i)}function qt(e,n,r,i){if(M(n.command))return r;let a=G(r);return new t(`COMMAND_FAILED`,`Runner command "${n.command}" is still ${e} after the transport response was lost.`,{command:n.command,commandId:n.commandId,lifecycleState:e,recovery:`command_still_in_flight`,...a,hint:Qt(n.command,e,a),logPath:i.logPath,transportError:r.message},r)}function Jt(e){if(typeof e!=`string`||e.trim().length===0)return;let t=Yt(e);if(t.ok)return t.data&&typeof t.data==`object`&&!Array.isArray(t.data)?t.data:{}}function Yt(e){try{let t=JSON.parse(e);if(t&&typeof t==`object`)return t}catch{}return{}}function Xt(e,t){return`${W(t)}The runner is still reachable and reports "${e}" already completed, so agent-device kept the session open and will not replay it. Run snapshot -i to inspect the current UI, then continue from that observed state.`}function Zt(e,t){return`${W(t)}The runner is still reachable and reports "${e}" failed after the transport response was lost, so agent-device kept the session open and did not replay it. Run snapshot -i to inspect the current UI and retry with a selector visible in that snapshot.`}function Qt(e,t,n){return`${W(n)}The runner is still reachable and reports "${e}" is ${t}, so agent-device kept the session open and will not replay it. Wait briefly, run snapshot -i to inspect the current UI, then continue from that observed state.`}function W(e){return e.readinessPreflightSkipped===!0?`This hot command skipped the uptime preflight because the runner had just completed a healthy interaction; status recovery confirmed the runner still observed it. `:``}function $t(e,t){let n=e.details?.[t];return typeof n==`boolean`?n:void 0}function en(e,t){let n=e.details?.[t];return typeof n==`string`?n:void 0}function tn(e,t){let n=e.details?.[t];return typeof n==`number`?n:void 0}function G(e){let t={},n=$t(e,`runnerReadinessPreflightSkipped`);n!==void 0&&(t.readinessPreflightSkipped=n);let r=en(e,`runnerReadinessPreflightSkipReason`);r!==void 0&&(t.readinessPreflightSkipReason=r);let i=tn(e,`runnerReadinessPreflightSkippedAgeMs`);return i!==void 0&&(t.readinessPreflightSkippedAgeMs=i),t}function nn(e){return`The runner did not confirm that "${e}" reached a safe terminal state, so agent-device kept the conservative invalidation path. Run snapshot -i before retrying if the UI may have changed.`}function K(e){let{command:t,session:n,transportError:r,decision:i,reason:a,lifecycleState:s}=e;o({level:i===`retained`?`warn`:`debug`,phase:`ios_runner_command_invalidation_decision`,data:{command:t.command,commandId:t.commandId,decision:i,reason:a,lifecycleState:s,runnerReachable:s!==void 0,sessionId:n.sessionId,transportError:r.message}})}const q=new Map;function rn(e,t){let n=e.requestId?.trim();if(n)return`request:${n}`;let r=t.commandId?.trim();if(r)return`command:${r}`}function an(e){if(!e)return;let t=J(e);t.touchedSession=!0,Y(e,t)}function on(e){return e?q.get(e)?.touchedSession===!0:!1}function sn(e){if(!e)return!0;let t=J(e);return t.recycles>=1?(Y(e,t),!1):(Y(e,t),!0)}function cn(e){if(!e)return;let t=J(e);t.recycles+=1,Y(e,t)}function ln(e,n){return o({level:`warn`,phase:`ios_runner_recycle_budget_exhausted`,data:{command:e.command,commandId:e.commandId,requestId:n.requestId,maxRecycles:1}}),new t(`COMMAND_FAILED`,`iOS runner was already restarted during this request and "${e.command}" still failed, so agent-device stopped instead of paying for another runner boot.`,{command:e.command,commandId:e.commandId,recovery:`runner_recycle_budget_exhausted`,hint:"The current screen is overwhelming the iOS accessibility capture (usually heavy or animating content). The app session is preserved: run `screenshot` for visual truth and interact with coordinate commands, or navigate to another screen and retry. Re-running the same command immediately will likely wedge again.",logPath:n.logPath})}function J(e){return un(),q.get(e)??{touchedSession:!1,recycles:0,lastAtMs:Date.now()}}function Y(e,t){t.lastAtMs=Date.now(),q.delete(e),q.set(e,t)}function un(){let e=Date.now()-6e5;for(let[t,n]of q)n.lastAtMs<e&&q.delete(t);for(;q.size>512;){let e=q.keys().next().value;if(e===void 0)break;q.delete(e)}}async function X(e,n){S(n.requestId);let r=y(n.requestId),i=m({command:`uptime`}),a;for(let t=1;t<=2;t+=1){let o=await dn({device:e,command:i,options:n,signal:r,attempt:t,recoveryReason:a});if(o.kind===`prepared`)return o.result;a=o.recoveryReason}throw new t(`COMMAND_FAILED`,`iOS runner prepare failed`)}async function dn(e){let{device:t,command:n,options:r,signal:i,attempt:a,recoveryReason:o}=e,s=Date.now(),c=await I(t,{...r,cleanStaleBundles:a>1?!0:r.cleanStaleBundles,...vn(r,`runner_session`)}),l=Date.now()-s;try{return{kind:`prepared`,result:wn(t,await _n(t,c,n,r,i,l,{recoveryReason:o}))}}catch(e){return await fn({device:t,session:c,command:n,options:r,signal:i,attempt:a,error:e})}}async function fn(e){let{device:t,session:r,command:i,options:a,signal:s,attempt:c,error:l}=e,u=n(l,`COMMAND_FAILED`);if(g(u))throw await Z(r,`prepare_runner_request_canceled`),l;if(c===1&&bn(u,r))return{kind:`prepared`,result:await pn({device:t,session:r,command:i,options:a,signal:s,error:u})};if(!mn(u))throw l;let d=u.message||`runner_health_failed`;if(c>=2)throw await Z(r,`prepare_runner_health_failed`),l;return S(a.requestId),await L(r,`prepare_runner_health_retry`),o({level:`warn`,phase:`ios_runner_prepare_health_retry`,data:{command:i.command,commandId:i.commandId,sessionId:r.sessionId,attempt:c,maxAttempts:2,reason:d}}),{kind:`retry`,recoveryReason:d}}async function pn(e){let{device:t,session:n,command:r,options:i,signal:a,error:s}=e,c=s.message||`runner_health_failed`;await L(n,`prepare_cached_runner_health_failed`),await ce(n.xctestrunArtifact,c);let l=Date.now(),u=await I(t,{...i,cleanStaleBundles:!0,forceRunnerXctestrunRebuild:!0,...vn(i,`runner_rebuild`)}),d=Date.now()-l;try{let e=await _n(t,u,r,i,a,d,{recoveryReason:c});return o({level:`info`,phase:`ios_runner_prepare_bad_cache_recovered`,data:{command:r.command,commandId:r.commandId,sessionId:u.sessionId,xctestrunPath:u.xctestrunArtifact?.xctestrunPath,reason:c}}),wn(t,e)}catch(e){await Z(u,`prepare_rebuilt_runner_health_failed`);let n=Sn(e,u,c);throw Tn(t,{cache:u.xctestrunArtifact?.cache,artifact:u.xctestrunArtifact?.artifact,buildMs:u.xctestrunArtifact?.buildMs,connectMs:d,healthCheckMs:0,xctestrunPath:u.xctestrunArtifact?.xctestrunPath,failureReason:n.message}),n}}async function Z(e,t){try{await L(e,t)}catch{}}function mn(e){return g(e)?!1:w(e)||re(e)||xn(e)}async function hn(e,t,r){S(r.requestId);let i=y(r.requestId),a=rn(r,t),o,s=!1;try{if(!ct(e.id)?.alive&&on(a)){if(!sn(a))throw ln(t,r);s=!0}o=await I(e,r),s&&cn(a),an(a);let n=o.ready?pe:Ft(o);return await V(e,o,t,r.logPath,n,i)}catch(a){let s=n(a,`COMMAND_FAILED`);if(o&&!o.ready&&g(s))throw await Z(o,`runner_startup_request_canceled`),a;if(s.code===`COMMAND_FAILED`&&typeof s.message==`string`&&s.message.includes(`Runner did not accept connection`)&&re(s)&&o)return S(r.requestId),await gn({device:e,session:o,command:t,options:r,signal:i,restartReason:`runner_connect_failed_before_command_send`});if(o&&Dn(s))return S(r.requestId),await gn({device:e,session:o,command:t,options:r,signal:i,restartReason:`runner_readiness_preflight_failed_before_command_send`,recoveredDiagnosticPhase:`ios_runner_readiness_preflight_recovered`});if(o&&w(s))return await Rt({device:e,session:o,command:t,transportError:s,options:r,signal:i,invalidationReason:`transport_error_after_command_send`,invalidateSession:L});throw a}}async function gn(e){let{device:t,command:r,options:i,signal:a,restartReason:s}=e,c=rn(i,r);if(!sn(c))throw ln(r,i);await L(e.session,s);let l=await I(t,{...i,cleanStaleBundles:!0});cn(c);try{let n=await V(t,l,r,i.logPath,ue,a);return e.recoveredDiagnosticPhase&&o({level:`debug`,phase:e.recoveredDiagnosticPhase,data:{command:r.command,commandId:r.commandId,recovery:`session_restarted`,sessionId:l.sessionId}}),n}catch(e){let o=n(e,`COMMAND_FAILED`);if(w(o))return await Rt({device:t,session:l,command:r,transportError:o,options:i,signal:a,invalidationReason:`transport_error_after_retry_command_send`,invalidateSession:L});throw e}}async function _n(e,t,n,r,i,a,o){let s=Date.now(),c=yn(r.prepareDeadline,r.healthTimeoutMs,`runner_health`);return Cn(await V(e,t,n,r.logPath,c,i),t,a,Date.now()-s,o)}function vn(e,t){if(!e.prepareDeadline)return{};let n=yn(e.prepareDeadline,e.buildTimeoutMs,t);return{buildTimeoutMs:n,startupTimeoutMs:n}}function yn(e,n,r){if(!e)return n??45e3;let i=Math.floor(e.remainingMs());if(i<=0)throw new t(`COMMAND_FAILED`,`prepare ios-runner timed out`,{phase:r,reason:`prepare_deadline_expired`});return i}function bn(e,t){let n=t.xctestrunArtifact;return!n||n.cache===`miss`?!1:mn(e)}function xn(e){let t=e.message.toLowerCase();return t.includes(`timeout`)||t.includes(`timed out`)||t.includes(`deadline`)}function Sn(e,r,i){let a=n(e,`COMMAND_FAILED`);return new t(a.code,`artifact restored but runner did not connect`,{...a.details??{},restoredFailureReason:i,xctestrunPath:r.xctestrunArtifact?.xctestrunPath,artifact:r.xctestrunArtifact?.artifact,cache:r.xctestrunArtifact?.cache,reason:a.message},a)}function Cn(e,t,n,r,i){let a=t.xctestrunArtifact,o={...i?.recoveryReason?{recoveryReason:i.recoveryReason}:{},...i?.failureReason?{failureReason:i.failureReason}:{}};return a?{runner:e,cache:a.cache,artifact:a.artifact,buildMs:a.buildMs,connectMs:Math.max(0,n),healthCheckMs:Math.max(0,r),xctestrunPath:a.xctestrunPath,...o}:{runner:e,connectMs:Math.max(0,n),healthCheckMs:Math.max(0,r),...o}}function wn(e,t){return Tn(e,t),t}function Tn(e,t){o({level:t.failureReason?`warn`:`info`,phase:`apple_runner_prepare`,data:{platform:e.platform,target:e.target,deviceId:e.id,cache:t.cache,artifact:t.artifact,buildMs:t.buildMs,connectMs:t.connectMs,healthCheckMs:t.healthCheckMs,timingContainment:t.buildMs===void 0?{healthCheckMs:[]}:{connectMs:[`buildMs`],healthCheckMs:[]},xctestrunPath:t.xctestrunPath,recoveryReason:t.recoveryReason,failureReason:t.failureReason}})}function En(e){return e.details?.runnerReadinessPreflightFailed===!0}function Dn(e){return En(e)&&(w(e)||On(e))}function On(e){let t=e.message.toLowerCase();return t.includes(`timeout`)||t.includes(`timed out`)}var kn=e({detachIosSimulatorRunnerSessionsForShutdown:()=>ft,notifyIosRunnerAppRelaunched:()=>An,prepareIosRunner:()=>Pn,prewarmAppleRunnerCache:()=>jn,prewarmIosRunnerSession:()=>Mn,runAppleRunnerCommand:()=>Q,stopAllIosRunnerSessions:()=>pt});async function Q(e,t,n={}){_t(e),S(n.requestId);let r=m(t),i=$(e,n);return M(r.command)?p(()=>(S(n.requestId),i.runCommand(e,r,n)),{shouldRetry:e=>(S(n.requestId),w(e))}):i.runCommand(e,r,n)}async function An(e,t={}){if(l(e))try{await Q(e,{command:`targetReset`},t)}catch(t){o({level:`warn`,phase:`ios_runner_target_reset_failed`,data:{deviceId:e.id,error:t instanceof Error?t.message:String(t)}}),await B(e.id)}}function jn(e,t={}){if(l(e))return Nn({device:e,options:t,failurePhase:`ios_runner_cache_prewarm_failed`,task:async t=>{await fe(e,t)}})}function Mn(e,t={}){if(!l(e))return;let n=$(e,t).prewarm;if(!n){o({level:`debug`,phase:`ios_runner_session_prewarm_unavailable`,data:{deviceId:e.id}});return}return Nn({device:e,options:t,failurePhase:`ios_runner_session_prewarm_failed`,task:async t=>{await n(e,t)}})}function Nn(e){let{device:t,options:n,failurePhase:r,task:i}=e,{propagateError:a=!1,...s}=n;return i(s).catch(e=>{if(o({level:`warn`,phase:r,data:{deviceId:t.id,error:e instanceof Error?e.message:String(e)}}),a)throw e})}async function Pn(e,t){_t(e),S(t.requestId);let n=m({command:`uptime`}),r=$(e,t);if(r.prepare)return await r.prepare(e,t);let i=Date.now();return{runner:await r.runCommand(e,n,t),connectMs:0,healthCheckMs:Math.max(0,Date.now()-i)}}function $(e,t){return De(e,Fn,void 0,{requestId:t.requestId})}const Fn=Oe(hn,{prepare:X,prewarm:async(e,t)=>{await X(e,{...t,healthTimeoutMs:pe})}});export{Q as a,lt as c,Mn as i,B as l,Pn as n,kn as o,jn as r,ct as s,An as t};
@@ -0,0 +1,2 @@
1
+ import{t as e}from"./rolldown-runtime.js";import{_ as t,v as n}from"./sdk-contracts.js";import{C as r,S as i,h as a,j as o}from"./sdk-android-adb.js";import{n as s,t as c}from"./version.js";import{c as l,h as u,o as d,s as f}from"./sdk-device.js";import{u as p}from"./sdk-batch-runner.js";import{n as ee,o as te,r as ne,s as re}from"./host-process.js";import{c as ie,l as ae,n as m,o as oe,s as se,t as ce}from"./boot-diagnostics.js";import{t as le}from"./process-lock.js";import{a as h,i as g,n as _}from"./tool-provider.js";import{i as ue,s as de}from"./runner-lease.js";import{AsyncLocalStorage as v}from"node:async_hooks";import y from"node:crypto";import b from"node:fs";import x from"node:os";import S from"node:path";import fe from"node:net";const C=new Set,w=new Map,pe=`request_canceled`,me=`request canceled`;function he(e,t){if(typeof e==`string`&&e.length>0)return e;let n=(typeof t==`string`?t:typeof t==`number`&&Number.isFinite(t)?String(t):`generated`).trim().replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,32)||`generated`,r=Math.random().toString(36).slice(2,10);return`req:${n}:${process.pid}:${Date.now()}:${r}`}const ge=5e4,_e=1e4;function ve(e){if(e.size<=ge)return;let t=0;for(let n of e.keys()){if(t>=_e)break;e.delete(n),t++}}function ye(e){if(e.size<=ge)return;let t=0;for(let n of e){if(t>=_e)break;e.delete(n),t++}}function be(e){if(!e)return;if(w.has(e))throw new t(`INVALID_ARGS`,`Request ID is already in flight: ${e}`,{requestId:e,reason:`duplicate_request_id`});ve(w);let n=new AbortController;return w.set(e,n),C.has(e)&&n.abort(),{requestId:e,controller:n}}function xe(e){e&&(ye(C),C.add(e),w.get(e)?.abort())}function Se(e,t){e&&(t&&(t.requestId!==e||w.get(e)!==t.controller)||(C.delete(e),w.delete(e)))}function Ce(e){e&&Se(e.requestId,e)}function we(e){return e?C.has(e):!1}function Te(e){if(e)return w.get(e)?.signal}function T(){return new t(`COMMAND_FAILED`,me,{reason:pe,hint:`The request was canceled intentionally (explicit cancel or client disconnect) — no retry is needed unless the cancellation was unintended.`})}function Ee(e){if(we(e))throw T()}function E(e){return!(e instanceof t)||e.code!==`COMMAND_FAILED`?!1:e.details?.reason===pe?!0:e.message===me}const De=new v,Oe=new v;async function ke(e,t){return await De.run(e,t)}function Ae(e){De.getStore()?.(e)}async function je(e,t){return await Oe.run(e,t)}function Me(){return Oe.getStore()}const Ne=new Set(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.:-`),Pe=new Set([` `,` `,`
2
+ `,`\r`]),Fe=new Set([`__defineGetter__`,`__defineSetter__`,`__proto__`,`constructor`,`prototype`]);function Ie(e,t={}){let n=t.maxDocumentChars??134217728;if(e.length>n)throw Error(`XML document exceeds maximum supported size of ${n} characters.`);return new Le(e).parse()}function D(e,t){for(let n of e){if(n.name===`dict`)for(let e=0;e<n.children.length-1;e+=1){let r=n.children[e],i=n.children[e+1];r?.name===`key`&&r.text&&i&&t(r.text,i)}D(n.children,t)}}var Le=class{roots=[];stack=[];index=0;xml;constructor(e){this.xml=e}parse(){for(this.skipByteOrderMark();this.index<this.xml.length;)this.readNextToken();return this.assertFullyClosed(),this.roots}readNextToken(){if(this.xml[this.index]!==`<`){this.readText();return}this.resolveMarkupReader()()}resolveMarkupReader(){return this.startsWith(`<!--`)?()=>this.skipUntil(`-->`,`Comment is not closed.`):this.startsWith(`<?`)?()=>this.skipUntil(`?>`,`Processing instruction is not closed.`):this.startsWith(`<![CDATA[`)?()=>this.readCdata():this.startsWith(`<!`)?()=>this.skipDeclaration():this.startsWith(`</`)?()=>this.readClosingTag():()=>this.readOpeningTag()}assertFullyClosed(){if(this.stack.length>0){let e=this.stack[this.stack.length-1];throw Error(`Unclosed XML tag <${e?.name??`unknown`}>.`)}}skipByteOrderMark(){this.xml.charCodeAt(0)===65279&&(this.index=1)}readOpeningTag(){this.index+=1,this.skipWhitespace();let e=this.readRequiredName(`Missing XML tag name at offset ${this.index}.`),{attributes:t,selfClosing:n}=this.readOpeningTagBody(),r={name:e,attributes:t,text:null,children:[]};this.addNode(r),n||this.pushOpenNode(r)}readOpeningTagBody(){let e={};for(;;){this.skipWhitespace();let t=this.readOpeningTagEnd();if(t)return{attributes:e,selfClosing:t===`self-closing`};let n=this.readAttribute();e[n.name]=n.value}}readOpeningTagEnd(){if(this.index>=this.xml.length)throw Error(`Opening XML tag is not closed.`);return this.xml[this.index]===`>`?(this.index+=1,`open`):this.xml[this.index]===`/`&&this.xml[this.index+1]===`>`?(this.index+=2,`self-closing`):null}readAttribute(){let e=this.readRequiredName(`Invalid XML attribute at offset ${this.index}.`);if(We(e),this.skipWhitespace(),this.xml[this.index]!==`=`)throw Error(`Missing value for XML attribute "${e}".`);return this.index+=1,this.skipWhitespace(),{name:e,value:this.readAttributeValue(e)}}pushOpenNode(e){if(this.stack.length>=256)throw Error(`Maximum XML nesting depth of 256 exceeded.`);this.stack.push(e)}readClosingTag(){this.index+=2,this.skipWhitespace();let e=this.readName();if(this.skipWhitespace(),this.xml[this.index]!==`>`)throw Error(`Closing XML tag </${e}> is not closed.`);this.index+=1;let t=this.stack.pop();if(!t)throw Error(`Unexpected closing XML tag </${e}>.`);if(t.name!==e)throw Error(`Expected </${t.name}> before </${e}>.`)}readText(){let e=this.xml.indexOf(`<`,this.index),t=e===-1?this.xml.length:e;this.appendText(this.xml.slice(this.index,t),!0),this.index=t}readCdata(){let e=this.index+9,t=this.xml.indexOf(`]]>`,e);if(t===-1)throw Error(`CDATA section is not closed.`);this.appendText(this.xml.slice(e,t),!1),this.index=t+3}appendText(e,t){let n=e.trim();if(!n)return;let r=this.stack[this.stack.length-1];r&&(r.text=`${r.text??``}${t?Ge(n):n}`)}addNode(e){let t=this.stack[this.stack.length-1];t?t.children.push(e):this.roots.push(e)}readName(){let e=this.index;for(;this.index<this.xml.length&&Re(this.xml[this.index]);)this.index+=1;return this.xml.slice(e,this.index)}readRequiredName(e){let t=this.readName();if(!t)throw Error(e);return t}readAttributeValue(e){let t=this.xml[this.index];if(t!==`"`&&t!==`'`)throw Error(`XML attribute "${e}" must use a quoted value.`);this.index+=1;let n=this.index,r=this.xml.indexOf(t,n);if(r===-1)throw Error(`XML attribute "${e}" is not closed.`);return this.index=r+1,Ge(this.xml.slice(n,r).trim())}skipDeclaration(){let e={quote:null,bracketDepth:0};for(let t=this.index+2;t<this.xml.length;t+=1)if(Be(e,this.xml[t])){this.index=t+1;return}throw Error(`XML declaration is not closed.`)}skipUntil(e,t){let n=this.xml.indexOf(e,this.index+e.length);if(n===-1)throw Error(t);this.index=n+e.length}skipWhitespace(){for(;this.index<this.xml.length&&ze(this.xml[this.index]);)this.index+=1}startsWith(e){return this.xml.startsWith(e,this.index)}};function Re(e){return e!==void 0&&Ne.has(e)}function ze(e){return e!==void 0&&Pe.has(e)}function Be(e,t){return t===void 0||Ve(e,t)?!1:(He(e,t),Ue(e,t))}function Ve(e,t){return e.quote?(t===e.quote&&(e.quote=null),!0):t===`"`||t===`'`?(e.quote=t,!0):!1}function He(e,t){if(t===`[`){e.bracketDepth+=1;return}t===`]`&&e.bracketDepth>0&&--e.bracketDepth}function Ue(e,t){return t===`>`&&e.bracketDepth===0}function We(e){if(Fe.has(e))throw Error(`Unsupported XML attribute name "${e}".`)}function Ge(e){return e.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g,(e,t)=>{switch(t){case`amp`:return`&`;case`lt`:return`<`;case`gt`:return`>`;case`quot`:return`"`;case`apos`:return`'`;default:return Ke(e,t)}})}function Ke(e,t){let n=t.startsWith(`#x`)?Number.parseInt(t.slice(2),16):Number(t.slice(1));if(!Number.isInteger(n)||n<0||n>1114111)return e;try{return String.fromCodePoint(n)}catch{return e}}const qe=new v;async function Je(e,t,n){let r=qe.getStore()??[];if(r.some(n=>n.locks===e&&n.key===t))return await n();let i=(e.get(t)??Promise.resolve()).catch(()=>{}).then(()=>qe.run([...r,{locks:e,key:t}],n));return e.set(t,i),i.finally(()=>{e.get(t)===i&&e.delete(t)})}function Ye(e,t={}){let n=oe(t.simulatorSetPath);return n?[`simctl`,`--set`,n,...e]:[`simctl`,...e]}function O(e,t){return!f(e)||e.kind!==`simulator`?[`simctl`,...t]:Ye(t,{simulatorSetPath:e.simulatorSetPath})}function Xe(e,t,n){return h(O(e,t),n)}const k={iOS:{sdkName:{simulator:`iphonesimulator`,device:`iphoneos`},derivedBaseName:{simulator:`ios-simulator`,device:`ios-device`},xctestrunHints:{simulator:{preferred:[`iphonesimulator`],disallowed:[`iphoneos`,`appletvos`,`appletvsimulator`,`macos`]},device:{preferred:[`iphoneos`],disallowed:[`iphonesimulator`,`appletvos`,`appletvsimulator`,`macos`]}}},tvOS:{sdkName:{simulator:`appletvsimulator`,device:`appletvos`},derivedBaseName:{simulator:`tvos-simulator`,device:`tvos-device`},xctestrunHints:{simulator:{preferred:[`appletvsimulator`],disallowed:[`appletvos`,`iphoneos`,`iphonesimulator`,`macos`]},device:{preferred:[`appletvos`],disallowed:[`appletvsimulator`,`iphoneos`,`iphonesimulator`,`macos`]}}},macOS:{sdkName:{simulator:`macosx`,device:`macosx`},derivedBaseName:{simulator:`macos`,device:`macos`},xctestrunHints:{simulator:{preferred:[`macos`],disallowed:[`iphoneos`,`iphonesimulator`,`appletvos`,`appletvsimulator`]},device:{preferred:[`macos`],disallowed:[`iphoneos`,`iphonesimulator`,`appletvos`,`appletvsimulator`]}}},visionOS:{sdkName:{simulator:`xrsimulator`,device:`xros`},derivedBaseName:{simulator:`visionos-simulator`,device:`visionos-device`},xctestrunHints:{simulator:{preferred:[`xrsimulator`],disallowed:[`xros`,`iphoneos`,`iphonesimulator`,`appletvos`,`appletvsimulator`,`macos`]},device:{preferred:[`xros`],disallowed:[`xrsimulator`,`iphoneos`,`iphonesimulator`,`appletvos`,`appletvsimulator`,`macos`]}}}};function A(e){if(!d(e.platform))throw new t(`UNSUPPORTED_PLATFORM`,`Unsupported platform for Apple runner: ${e.platform}`);return l(e)?`macOS`:u(e.target,e.appleOs)}function Ze(e,t){return k[e].sdkName[rt(t)]}function Qe(e){return k[A(e)].derivedBaseName[rt(e.kind)]}function $e(e){return k[A(e)].xctestrunHints[rt(e.kind)]}function et(e){let t=A(e);return t===`macOS`?`platform=macOS,arch=${it()}`:e.kind===`simulator`?`platform=${t} Simulator,id=${e.id}`:`platform=${t},id=${e.id}`}function tt(e){let t=A(e);return t===`macOS`?`platform=macOS,arch=${it()}`:e.kind===`simulator`?`platform=${t} Simulator,id=${e.id}`:`generic/platform=${t}`}function nt(e){let t=A(e);return t===`macOS`?`platform=macOS,arch=${it()}`:e.kind===`simulator`?`generic/platform=${t} Simulator`:`generic/platform=${t}`}function rt(e){return e===`simulator`?`simulator`:`device`}function it(){return process.arch===`arm64`?`arm64`:`x86_64`}const at=new Set;function ot(e={}){let t=new Map,n=e.now??(()=>Date.now()),r=e=>{e?.timer&&clearTimeout(e.timer)},i={get(e){let r=t.get(e);if(r){if(r.expiresAt!==void 0&&r.expiresAt<=n()){i.delete(e);return}return r.value}},set(i,a){r(t.get(i));let o=st(e.ttlMs,n),s={value:a,expiresAt:o};e.scheduleExpiry&&o!==void 0&&(s.timer=setTimeout(()=>{t.delete(i)},Math.max(0,o-n())),s.timer.unref?.()),t.set(i,s)},delete(e){let n=t.get(e);return n?(r(n),t.delete(e)):!1},clear(){for(let e of t.values())r(e);t.clear()}};return at.add(i.clear),i}function st(e,t){if(!(e===void 0||!Number.isFinite(e)))return t()+Math.max(0,e)}const ct=S.join(`apple`,`runner`,`AgentDeviceRunner`),lt=S.join(`dist`,`apple`,`runner`,`AgentDeviceRunner`);function ut(e){let t=S.join(e,ct);return b.existsSync(t)?t:S.join(e,lt)}function dt(e){return S.join(ut(e),`AgentDeviceRunner.xcodeproj`)}const ft=S.join(x.homedir(),`.agent-device`,`apple-runner`),pt=`.agent-device-runner-cache.json`,mt=[`-IDEPackageSupportDisableManifestSandbox=1`,`-IDEPackageSupportDisablePluginExecutionSandbox=1`,`ENABLE_USER_SCRIPT_SANDBOXING=NO`],ht=ot();function j(e){return e?.trim()??``}function M(e=process.env){return j(e.AGENT_DEVICE_IOS_BUNDLE_ID)||j(e.AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID)||`com.callstack.agentdevice.runner`}function gt(e=process.env){return j(e.AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID)||`${M(e)}.uitests`}function _t(e=process.env){let t=M(e),n=gt(e);return Array.from(new Set([j(e.AGENT_DEVICE_IOS_RUNNER_CONTAINER_BUNDLE_ID),`${n}.xctrunner`,t].filter(e=>e.length>0)))}const vt=_t(process.env);function N(e,t=c()){let n=A(e);return{schemaVersion:2,packageVersion:s(t),runnerSourceFingerprint:wt(t),...yt(n,e.kind),platformName:n,deviceKind:e.kind,target:e.target??`mobile`,buildDestinationFamily:nt(e),runnerBundleBuildSettings:At(process.env),runnerSigningBuildSettings:kt(process.env,e.kind===`device`,e),runnerPerformanceBuildSettings:jt(),runnerSandboxBuildArgs:Mt()}}function yt(e,t){let n=bt(P(`xcodebuild`,[`-version`])),r=Ze(e,t);return{xcodeVersion:n.version,xcodeBuildVersion:n.buildVersion,sdkName:r,sdkVersion:P(`xcrun`,[`--sdk`,r,`--show-sdk-version`]),sdkBuildVersion:P(`xcrun`,[`--sdk`,r,`--show-sdk-build-version`])}}function P(e,t){let n=JSON.stringify([e,t]),i=ht.get(n);if(i!==void 0)return i;try{let i=r(e,t,{allowFailure:!0,timeoutMs:5e3,maxBuffer:128*1024}),a=i.exitCode===0&&i.stdout.trim()||`unknown`;return ht.set(n,a),a}catch{return ht.set(n,`unknown`),`unknown`}}function bt(e){return{version:e.match(/^Xcode\s+(.+)$/m)?.[1]?.trim()||`unknown`,buildVersion:e.match(/^Build version\s+(.+)$/m)?.[1]?.trim()||`unknown`}}function F(e,t){let n=process.env.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim();if(n)return S.resolve(n);let r=St(t),i=xt(e);return S.join(i,r)}function xt(e){return S.join(ft,`derived`,Qe(e))}function St(e){return`cache-${y.createHash(`sha256`).update(L(I(e))).digest(`hex`).slice(0,16)}`}function I(e){let{artifacts:t,packageVersion:n,...r}=e;return r}function L(e){return JSON.stringify(R(e))}function R(e){return Array.isArray(e)?e.map(e=>R(e)):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,R(t)]))}const Ct=new Map;function wt(e){let t=ut(e),n=Et(t),r=Tt(t,n),i=Ct.get(t);if(i?.fileStatsFingerprint===r)return i.sourceFingerprint;let a=y.createHash(`sha256`);for(let e of n){let n=S.relative(t,e);a.update(n),a.update(`\0`),a.update(b.readFileSync(e)),a.update(`\0`)}let o=a.digest(`hex`);return Ct.set(t,{fileStatsFingerprint:r,sourceFingerprint:o}),o}function Tt(e,t){let n=y.createHash(`sha256`);for(let r of t){let t=S.relative(e,r),i=b.statSync(r);n.update(t),n.update(`\0`),n.update(String(i.size)),n.update(`\0`),n.update(String(Math.trunc(i.mtimeMs))),n.update(`\0`)}return n.digest(`hex`)}function Et(e){if(!b.existsSync(e))return[];let t=[],n=[e];for(;n.length>0;){let e=n.pop();for(let r of b.readdirSync(e,{withFileTypes:!0})){let i=S.join(e,r.name);if(r.isDirectory()){if(r.name===`xcuserdata`)continue;n.push(i);continue}r.isFile()&&Dt(r.name,i)&&t.push(i)}}return t.sort((e,t)=>e.localeCompare(t))}function Dt(e,t){return e===`project.pbxproj`?t.includes(`${S.sep}.xcodeproj${S.sep}`):[`.jpg`,`.json`,`.png`,`.swift`,`.m`,`.h`,`.plist`,`.entitlements`,`.xctestplan`,`.xcconfig`,`.storyboard`,`.xib`].includes(S.extname(e))}function Ot(e){return l(e)||e.kind===`device`?`-maximum-concurrent-test-device-destinations`:`-maximum-concurrent-test-simulator-destinations`}function kt(e=process.env,t=!1,n={platform:`apple`}){if(l(n))return[`CODE_SIGNING_ALLOWED=NO`,`CODE_SIGNING_REQUIRED=NO`,`CODE_SIGN_IDENTITY=`,`DEVELOPMENT_TEAM=`];if(!t)return[];let r=e.AGENT_DEVICE_IOS_TEAM_ID?.trim()||``,i=e.AGENT_DEVICE_IOS_SIGNING_IDENTITY?.trim()||``,a=e.AGENT_DEVICE_IOS_PROVISIONING_PROFILE?.trim()||``,o=[`CODE_SIGN_STYLE=Automatic`];return r&&o.push(`DEVELOPMENT_TEAM=${r}`),i&&o.push(`CODE_SIGN_IDENTITY=${i}`),a&&o.push(`PROVISIONING_PROFILE_SPECIFIER=${a}`),o}function At(e=process.env){let t=M(e),n=gt(e);return[`AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID=${t}`,`AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID=${n}`]}function jt(){return[`COMPILER_INDEX_STORE_ENABLE=NO`,`ENABLE_CODE_COVERAGE=NO`,`ONLY_ACTIVE_ARCH=YES`,`ENABLE_PREVIEWS=NO`,`ENABLE_DEBUG_DYLIB=NO`]}function Mt(){return[...mt,`OTHER_SWIFT_FLAGS=${Nt(process.env)}`]}function Nt(e){return ie(e.AGENT_DEVICE_XCUITEST_INCLUDE_UNIT_TESTS)?`$(inherited) -disable-sandbox -D AGENT_DEVICE_RUNNER_UNIT_TESTS`:`$(inherited) -disable-sandbox`}const Pt="If runner build products look stale or corrupted, run `pnpm clean:xcuitest` in a local checkout, or remove ~/.agent-device/apple-runner/derived, then retry.";function Ft(e){if(!(e instanceof t)||e.code!==`COMMAND_FAILED`)return!1;if(e.details?.retriable===!0)return!0;let n=`${e.message??``}`.toLowerCase();return n.includes(`xcodebuild exited early`)||n.includes(`device is busy`)&&n.includes(`connecting`)?!1:!!(n.includes(`runner did not accept connection`)||n.includes(`fetch failed`)||n.includes(`econnrefused`)||n.includes(`socket hang up`))}function It(e){return!(e instanceof t)||e.code!==`COMMAND_FAILED`?!0:!String(e.message??``).toLowerCase().includes(`xcodebuild exited early`)}function Lt(e,t,n){let r=`${e}\n${t}\n${n}`.toLowerCase();return r.includes(`device is busy`)&&r.includes(`connecting`)?`Target iOS device is still connecting. Keep it unlocked, wait for device trust/connection to settle, then retry.`:`${ce(`IOS_RUNNER_CONNECT_TIMEOUT`)} ${Pt}`}function Rt(e){let{port:n,endpoints:r,logPath:i,lastError:a}=e,o=`Runner did not accept connection`;return new t(`COMMAND_FAILED`,o,{port:n,endpoints:r,logPath:i,lastError:a?String(a):void 0,reason:m({error:a,message:o,context:{platform:`ios`,phase:`connect`}}),hint:ce(`IOS_RUNNER_CONNECT_TIMEOUT`)})}async function zt(e){let{session:n,port:r,logPath:i}=e,a=await n.testPromise,o=`Runner did not accept connection (xcodebuild exited early)`,s=m({message:o,stdout:a.stdout,stderr:a.stderr,context:{platform:`ios`,phase:`connect`}});return new t(`COMMAND_FAILED`,o,{port:r,logPath:i,xcodebuild:{exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr},reason:s,hint:Lt(o,a.stdout,a.stderr)})}function Bt(e){let t=e.details?JSON.stringify(e.details):``,n=`${e.message}\n${t}`.toLowerCase();if(n.includes(`failed registering bundle identifier`)||n.includes(`app identifier`)&&n.includes(`not available`))return`Set AGENT_DEVICE_IOS_BUNDLE_ID to a unique reverse-DNS value (for example, com.yourname.agentdevice.runner), then retry.`;if(n.includes(`requires a development team`))return`Configure signing in Xcode or set AGENT_DEVICE_IOS_TEAM_ID for physical-device runs.`;if(n.includes(`no profiles for`)||n.includes(`provisioning profile`))return`Install/select a valid iOS provisioning profile, or set AGENT_DEVICE_IOS_PROVISIONING_PROFILE.`;if(n.includes(`code signing`))return`Enable Automatic Signing in Xcode or provide AGENT_DEVICE_IOS_TEAM_ID and optional AGENT_DEVICE_IOS_SIGNING_IDENTITY.`}function Vt(e){return Bt(e)??Pt}function Ht(e){return e.command===`status`||e.commandId?.trim()?e:{...e,commandId:Ut()}}function Ut(){return`runner-${y.randomUUID()}`}function Wt(e){if(we(e))throw T()}const Gt=45e3,Kt=45e3,qt=1e4,z=new Map;async function Jt(e,t,n,r,i=Gt,a,o){let s=se.fromTimeoutMs(i),{getEndpoints:c}=nn(e,t),{endpoints:l}=await c(s.remainingMs()),u=null,d=Math.max(1,Math.ceil(i/250));try{return await ae(async({deadline:s})=>{let d=await Yt({device:e,port:t,command:n,timeoutMs:i,logPath:r,session:a,endpoints:l,getEndpoints:c,signal:o,attemptDeadline:s,setEndpoints:e=>{l=e},setLastError:e=>{u=e}});if(d)return d;throw en({port:t,endpoints:l,lastError:u,signal:o})},{maxAttempts:d,baseDelayMs:300,maxDelayMs:2e3,jitter:.2,shouldRetry:It},{deadline:s,phase:`ios_runner_connect`,signal:o})}catch(e){if(o?.aborted||E(e))throw T();u||=e}if(o?.aborted)throw T();if(e.kind===`simulator`){let i=s.remainingMs();if(i<=0)throw Rt({port:t,endpoints:l,logPath:r,lastError:u});let a=await pn(e,t,n,i,o);return new Response(a.body,{status:a.status})}throw Rt({port:t,endpoints:l,logPath:r,lastError:u})}async function Yt(e){await Xt(e);let t=await Zt(e);return t.response?t.response:await Qt(e)||await $t(e,t.usedCachedTunnelIp)}async function Xt(e){if(e.attemptDeadline?.isExpired())throw new t(`COMMAND_FAILED`,`Runner connection deadline exceeded`,{port:e.port,timeoutMs:e.timeoutMs});if(e.session?.child.exitCode!==null&&e.session?.child.exitCode!==void 0)throw await zt({session:e.session,port:e.port,logPath:e.logPath})}async function Zt(e){let t=e.endpoints,n=!1;if(e.device.kind===`device`){let r=await e.getEndpoints(e.attemptDeadline?.remainingMs());t=r.endpoints,n=r.cached,e.setEndpoints(t)}let r=n?t[0]:null;return{response:await rn(t,{command:e.command,port:e.port,timeoutMs:e.timeoutMs,signal:e.signal,attemptDeadline:e.attemptDeadline,onError:(t,n)=>{e.setLastError(n),e.device.kind===`device`&&t===r&&ln(e.device.id)}}),usedCachedTunnelIp:n}}async function Qt(e){return e.device.kind!==`simulator`||!e.session?.ready?null:await an(e.device,e.port,e.command,{signal:e.signal,attemptDeadline:e.attemptDeadline,onError:e.setLastError})}async function $t(e,t){if(e.device.kind!==`device`||!t)return null;ln(e.device.id);let n=await e.getEndpoints(e.attemptDeadline?.remainingMs(),!0);return e.setEndpoints(n.endpoints),await rn(n.endpoints,{command:e.command,port:e.port,timeoutMs:e.timeoutMs,signal:e.signal,attemptDeadline:e.attemptDeadline,onError:(t,n)=>{e.setLastError(n)}})}function en(e){if(e.signal?.aborted)throw T();return new t(`COMMAND_FAILED`,`Runner endpoint probe failed`,{port:e.port,endpoints:e.endpoints,lastError:e.lastError?String(e.lastError):void 0})}async function tn(e,n,r,i=Kt,a){if(a?.aborted)throw T();let o=se.fromTimeoutMs(i),{getEndpoints:s}=nn(e,n),{endpoints:c}=await s(o.remainingMs()),l=c[0];if(!l)throw new t(`COMMAND_FAILED`,`Runner command endpoint not available`,{port:n,endpoints:c});let u=o.remainingMs();if(u<=0)throw new t(`COMMAND_FAILED`,`Runner command deadline exceeded`,{timeoutMs:i});return await dn(l,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)},u,a)}function nn(e,t){let n;return{getEndpoints:async(r,i=!1)=>{let a=await on({device:e,timeoutBudgetMs:r,forceRefresh:i,requestTunnelIp:n,setRequestTunnelIp:e=>{n=e}});return{endpoints:un(e,t,a.ip),cached:a.sharedCacheHit}}}}async function rn(e,n){let{command:r,port:i,timeoutMs:a,signal:o,attemptDeadline:s,onError:c}=n;for(let n of e)try{let e=s?.remainingMs()??a;if(e<=0)throw new t(`COMMAND_FAILED`,`Runner connection deadline exceeded`,{port:i,timeoutMs:a});return await dn(n,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r)},Math.min(2e4,e),o)}catch(e){if(o?.aborted||E(e))throw T();c(n,e)}return null}async function an(e,t,n,r){let{signal:i,attemptDeadline:a,onError:o}=r,s=a?.remainingMs()??45e3;if(s<=0)return null;try{let r=await pn(e,t,n,s,i);return new Response(r.body,{status:r.status})}catch(e){if(i?.aborted||E(e))throw T();return o(e),null}}async function on(e){let{device:t,timeoutBudgetMs:n,forceRefresh:r,requestTunnelIp:i,setRequestTunnelIp:a}=e;if(t.kind!==`device`)return{ip:null,sharedCacheHit:!1};if(!r){let e=sn(t.id);if(e)return{ip:e,sharedCacheHit:!0};if(i!==void 0)return{ip:i,sharedCacheHit:!1}}let o=await fn(t.id,n);return a(o),o&&cn(t.id,o),{ip:o,sharedCacheHit:!1}}function sn(e){let t=z.get(e);return t?t.expiresAt<=Date.now()?(z.delete(e),null):t.ip:null}function cn(e,t){z.set(e,{ip:t,expiresAt:Date.now()+3e4})}function ln(e){z.delete(e)}function un(e,t,n){let r=[`http://127.0.0.1:${t}/command`];return e.kind===`device`&&n&&r.unshift(`http://[${n}]:${t}/command`),r}async function dn(e,t,n,r){let i=AbortSignal.timeout(n),a=r?AbortSignal.any([r,i]):i;return await fetch(e,{...t,signal:a})}async function fn(e,t){if(typeof t==`number`&&t<=0)return null;let n=typeof t==`number`?Math.max(1,Math.min(qt,t)):qt,r=S.join(x.tmpdir(),`agent-device-devicectl-info-${process.pid}-${Date.now()}.json`);try{let t=Math.max(1,Math.ceil(n/1e3));if((await h([`devicectl`,`device`,`info`,`details`,`--device`,e,`--json-output`,r,`--timeout`,String(t)],{allowFailure:!0,timeoutMs:n})).exitCode!==0||!b.existsSync(r))return null;let i=JSON.parse(b.readFileSync(r,`utf8`));if(i.info?.outcome&&i.info.outcome!==`success`)return null;let a=(i.result?.connectionProperties?.tunnelIPAddress??i.result?.device?.connectionProperties?.tunnelIPAddress)?.trim();return a&&a.length>0?a:null}catch{return null}finally{H(r)}}async function pn(e,t,n,r,i){let o=JSON.stringify(n);return{status:200,body:a(await h(O(e,[`spawn`,e.id,`/usr/bin/curl`,`-s`,`-X`,`POST`,`-H`,`Content-Type: application/json`,`--data`,o,`http://127.0.0.1:${t}/command`]),{allowFailure:!0,timeoutMs:r,signal:i}),`Runner did not accept connection (simctl spawn)`,e=>{let n=m({message:`Runner did not accept connection (simctl spawn)`,stdout:e.stdout,stderr:e.stderr,context:{platform:`ios`,phase:`connect`}});return{port:t,reason:n,hint:ce(n)}}).stdout}}async function mn(){return await new Promise((e,n)=>{let r=fe.createServer();r.listen(0,`127.0.0.1`,()=>{let i=r.address();if(typeof i==`object`&&i?.port){let t=i.port;r.close(()=>e(t))}else r.close(()=>n(new t(`COMMAND_FAILED`,`Failed to allocate port`)))}),r.on(`error`,n)})}function B(e,t,n,r){t&&hn(t,e),n&&hn(n,e),r&&process.stderr.write(e)}const V=new Map;function hn(e,t){let n=(V.get(e)??Promise.resolve()).catch(()=>{}).then(async()=>{await b.promises.mkdir(S.dirname(e),{recursive:!0}),await b.promises.appendFile(e,t)}).catch(()=>{}).finally(()=>{V.get(e)===n&&V.delete(e)});V.set(e,n)}function H(e){try{b.existsSync(e)&&b.unlinkSync(e)}catch{}}const gn=`XCTestDevices`,_n=`.agent-device-backup`,vn=`.agent-device-xctestdevices-backup-`;function yn(e=x.homedir()){return S.join(e,`Library`,`Developer`,`XCTestDevices`)}function bn(e=x.homedir()){return S.join(e,`.agent-device`,`xctest-device-set.lock`)}function xn(e=yn()){return`${e}${_n}`}async function Sn(e,n={}){if(!f(e)||e.kind!==`simulator`)return null;let r=oe(e.simulatorSetPath);if(!r)return null;let i=S.resolve(r),a=S.resolve(n.xctestDeviceSetPath??yn()),o=S.resolve(n.backupPath??xn(a)),s=S.resolve(n.lockDirPath??bn()),c=n.ownerStartTime??te(process.pid),l=await En({lockDirPath:s,owner:{pid:n.ownerPid??process.pid,startTime:c,acquiredAtMs:n.nowMs??Date.now()}});try{if(U({xctestDeviceSetPath:a,backupPath:o}),Tn(i,a))return await l(),null;b.mkdirSync(i,{recursive:!0}),b.existsSync(a)&&b.renameSync(a,o),wn({requestedSetPath:i,xctestDeviceSetPath:a})}catch(e){throw U({xctestDeviceSetPath:a,backupPath:o}),await l(),new t(`COMMAND_FAILED`,`Failed to redirect XCTest device set path`,{requestedSetPath:i,xctestDeviceSetPath:a,backupPath:o,error:String(e)})}let u=!1;return{release:async()=>{if(!u){u=!0;try{U({xctestDeviceSetPath:a,backupPath:o})}finally{await l()}}}}}function U(e){let{xctestDeviceSetPath:t,backupPath:n}=e,r=[n,...Cn(n)],i=r.find(e=>b.existsSync(e)),a=b.existsSync(t)&&b.lstatSync(t).isSymbolicLink();if(i){if(a&&W(t),!b.existsSync(t))b.mkdirSync(S.dirname(t),{recursive:!0}),b.renameSync(i,t);else if(a)i===n?b.rmSync(n,{recursive:!0,force:!0}):b.rmSync(i,{recursive:!0,force:!0});else{o({level:`warn`,phase:`ios_runner_xctest_device_set_restore_collision`,data:{xctestDeviceSetPath:t,activeBackupPath:i}});return}for(let e of r)e!==i&&b.existsSync(e)&&b.rmSync(e,{recursive:!0,force:!0});return}a&&(o({level:`warn`,phase:`ios_runner_xctest_device_set_orphaned_symlink`,data:{xctestDeviceSetPath:t}}),W(t))}function Cn(e){let t=S.dirname(e),n=S.basename(e).replace(_n,``),r=n===gn?vn:`${n}${vn}`;try{return b.readdirSync(t).filter(e=>e.startsWith(r)).sort().map(e=>S.join(t,e))}catch{return[]}}function wn(e){let{requestedSetPath:t,xctestDeviceSetPath:n}=e,r=S.dirname(n),i=S.join(r,`${gn}.agent-device-link-${process.pid}-${Date.now()}`);b.mkdirSync(r,{recursive:!0});try{b.symlinkSync(t,i,`dir`),b.renameSync(i,n)}catch(e){throw b.existsSync(i)&&W(i),e}}function W(e){b.existsSync(e)&&b.lstatSync(e).isSymbolicLink()&&b.unlinkSync(e)}function Tn(e,t){if(S.resolve(e)===S.resolve(t))return!0;try{return b.realpathSync.native(e)===b.realpathSync.native(t)}catch{return!1}}async function En(e){return await le({lockDirPath:e.lockDirPath,owner:e.owner,timeoutMs:e.timeoutMs??3e4,pollMs:e.pollMs??100,ownerGraceMs:5e3,description:e.description??`XCTest device set lock`})}const G=new Set;function Dn(e){return S.join(e,pt)}function On(e,t){b.mkdirSync(e,{recursive:!0}),b.writeFileSync(Dn(e),`${JSON.stringify(t,null,2)}\n`)}async function kn(e,t){if(e.cache===`external`){Y(`preserve`,`external_bad_artifact`,{derived:e.derived,xctestrunPath:e.xctestrunPath,reason:t});return}G.add(e.derived);let n=await An(e.derived);try{Y(`clean`,`bad_artifact`,{derived:e.derived,xctestrunPath:e.xctestrunPath,reason:t}),J(e.derived),K(e.derived)}finally{await n()}}async function An(e){return await jn({lockDirPath:Mn(e),owner:{pid:process.pid,startTime:te(process.pid),acquiredAtMs:Date.now()},description:`iOS runner cache lock`})}async function jn(e){return await le({lockDirPath:e.lockDirPath,owner:e.owner,timeoutMs:e.timeoutMs??6e5,pollMs:100,ownerGraceMs:5e3,description:e.description??`iOS runner cache lock`})}function Mn(e){return S.join(S.dirname(e),`${S.basename(e)}.lock`)}function Nn(e,t){!Kn()&&!t&&!G.has(e)||(Y(`clean`,t?`forced_rebuild`:`forced_clean`,{derived:e}),J(e),K(e),G.delete(e))}function Pn(e,t,n,r){On(e,zn(t,n,r))}function K(e){try{if(!b.existsSync(e))return;if(S.basename(e)!==`derived`){b.rmSync(e,{recursive:!0,force:!0});return}for(let t of b.readdirSync(e,{withFileTypes:!0}))In(t.name)&&b.rmSync(S.join(e,t.name),{recursive:!0,force:!0})}catch{}}const Fn=new Set([pt,`Build`,`BuildCache.noindex`,`Index.noindex`,`Logs`,`ModuleCache.noindex`,`SDKStatCaches.noindex`,`SourcePackages`,`TextBasedInstallAPI`,`info.plist`]);function In(e){return Fn.has(e)}function Ln(e){try{let t=JSON.parse(b.readFileSync(Dn(e),`utf8`));return!t||typeof t!=`object`||Array.isArray(t)?null:t}catch{return null}}function Rn(e,t){let n=Ln(e);return n?L(I(n))===L(I(t))?{ok:!0,metadata:n}:{ok:!1,reason:`cache_metadata_mismatch`}:{ok:!1,reason:`cache_metadata_missing`}}function zn(e,t,n){let r=Bn(t,n);return r?{...e,artifacts:r}:e}function Bn(e,t){let n=q(e);if(n===null||t.length===0)return null;let r=[];for(let e of t){let t=q(e);if(t===null)return null;r.push({path:e,...t})}return{xctestrunPath:e,xctestrunMtimeMs:n.mtimeMs,xctestrunSize:n.size,productPaths:r}}function Vn(e,t){let n=t?.artifacts;if(!Hn(n)||!Gn(n.xctestrunPath,e)||!Wn(n.xctestrunPath,{mtimeMs:n.xctestrunMtimeMs,size:n.xctestrunSize}))return null;let r=[];for(let t of n.productPaths){if(!Gn(t.path,e)||!Wn(t.path,t))return null;r.push(t.path)}return{xctestrunPath:n.xctestrunPath,productPaths:r}}function Hn(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.xctestrunPath==`string`&&Number.isInteger(t.xctestrunMtimeMs)&&Number.isInteger(t.xctestrunSize)&&Array.isArray(t.productPaths)&&t.productPaths.length>0&&t.productPaths.every(Un)}function Un(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.path==`string`&&Number.isInteger(t.mtimeMs)&&Number.isInteger(t.size)}function q(e){try{let t=b.statSync(e);return{mtimeMs:Math.trunc(t.mtimeMs),size:t.size}}catch{return null}}function Wn(e,t){let n=q(e);return n?.mtimeMs===t.mtimeMs&&n.size===t.size}function Gn(e,t){let n=S.relative(S.resolve(t),S.resolve(e));return n!==``&&!n.startsWith(`..`)&&!S.isAbsolute(n)}function Kn(){return ie(process.env.AGENT_DEVICE_IOS_CLEAN_DERIVED)}function J(e,n=process.env){if(n.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim()&&!qn(e))throw new t(`COMMAND_FAILED`,`Refusing to clean AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH automatically`,{derivedPath:e,hint:`Unset AGENT_DEVICE_IOS_CLEAN_DERIVED, or move AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH under a subdirectory of ${S.join(c(),`.tmp`)}.`})}function qn(e){let t=S.resolve(c(),`.tmp`),n=S.relative(t,S.resolve(e));return n!==``&&!n.startsWith(`..`)&&!S.isAbsolute(n)}async function Jn(e){let t=Rn(e.derived,e.expectedCacheMetadata),n=t.ok?Vn(e.derived,t.metadata):null,r=n?.xctestrunPath??e.findXctestrun(e.derived);if(!r)return{reason:`missing_xctestrun`,xctestrunPath:null};let i=n?.xctestrunPath===r,a=i?`manifest`:`scan`,o=i?n.productPaths:await e.resolveExistingXctestrunProductPaths(r);return o?!e.xctestrunReferencesProjectRoot(r,e.projectRoot)&&!i?{reason:`project_root_mismatch`,xctestrunPath:r,productPaths:o,source:a}:t.ok?{reason:`reuse_ready`,xctestrunPath:r,productPaths:o,source:a}:{reason:t.reason,xctestrunPath:r,productPaths:o,source:a}:{reason:`missing_products`,xctestrunPath:r,productPaths:[],source:a}}function Y(e,t,n){o({level:e===`rebuild`?`warn`:`info`,phase:`runner_xctestrun_cache`,data:{action:e,reason:t,...n}})}const Yn=new Set([`RUNNER_PRODUCT_MISSING`,`RUNNER_PRODUCT_REPAIR_FAILED`]);async function Xn(e,r,i){if(!l(e))return;if(r.length===0)throw new t(`COMMAND_FAILED`,`Missing macOS runner product`,{reason:`RUNNER_PRODUCT_MISSING`,xctestrunPath:i});let a=Array.from(new Set(r)).sort((e,t)=>t.length-e.length);for(let e of a)if(!b.existsSync(e))throw new t(`COMMAND_FAILED`,`Missing macOS runner product`,{reason:`RUNNER_PRODUCT_MISSING`,productPath:e,xctestrunPath:i});for(let e of a)if(!await Qn(e)){await g(`codesign`,[`--remove-signature`,e],{allowFailure:!0});try{await g(`codesign`,[`--force`,`--sign`,`-`,e])}catch(r){let a=n(r,`COMMAND_FAILED`);throw new t(`COMMAND_FAILED`,`Failed to repair macOS runner product signature`,{reason:`RUNNER_PRODUCT_REPAIR_FAILED`,productPath:e,xctestrunPath:i,error:a.message,details:a.details})}}}function Zn(e){if(!(e instanceof t))return!1;let n=e.details&&typeof e.details==`object`?e.details.reason:void 0;return typeof n==`string`&&Yn.has(n)}async function Qn(e){return(await g(`codesign`,[`--verify`,`--deep`,`--strict`,e],{allowFailure:!0})).exitCode===0}const $n=new Set([`ProductPaths`,`DependentProductPaths`,`TestHostPath`,`TestBundlePath`,`UITargetAppPath`]);async function er(e){let t=await rr(e);if(!t||t.length===0)return null;let n=S.dirname(e),r=new Set,i=tr(t,n);for(let e of i.testRootPaths){if(!b.existsSync(e))return null;r.add(e)}for(let e of nr(i)){if(!e)return null;r.add(e)}return Array.from(r)}function tr(e,t){let n=[],r=new Set,i=[];for(let a of e){if(a.startsWith(`__TESTHOST__/`)){i.push(a.slice(13));continue}if(!a.startsWith(`__TESTROOT__/`))continue;let e=a.slice(13);n.push(S.join(t,e));let o=ur(e);o&&r.add(S.join(t,o))}return{testRootPaths:n,hostRoots:Array.from(r),hostRelativePaths:i}}function nr(e){return e.hostRelativePaths.map(t=>{let n=e.hostRoots.find(e=>b.existsSync(S.join(e,t)));return n?S.join(n,t):null})}async function rr(e){let t=await _(e);if(t)return ir(t);if(process.platform===`darwin`)return null;try{return cr(b.readFileSync(e,`utf8`))}catch{return null}}function ir(e){let t=new Set;for(let n of[e,...ar(e),...or(e)])for(let e of sr(n))t.add(e);return Array.from(t)}function ar(e){let t=e.TestConfigurations;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!p(e))continue;let t=e.TestTargets;Array.isArray(t)&&n.push(...t.filter(p))}return n}function or(e){return Object.values(e).filter(e=>p(e)&&`TestBundlePath`in e)}function sr(e){let t=new Set;for(let[n,r]of Object.entries(e))if($n.has(n)){if(typeof r==`string`){t.add(r);continue}if(Array.isArray(r))for(let e of r)typeof e==`string`&&t.add(e)}return Array.from(t)}function cr(e){return lr(Ie(e))}function lr(e){let t=new Set;return D(e,(e,n)=>{if($n.has(e)){if(n.name===`string`&&n.text){t.add(n.text);return}if(n.name===`array`)for(let e of n.children)e.name===`string`&&e.text&&t.add(e.text)}}),Array.from(t)}function ur(e){let t=/\.app(?:\/|$)/.exec(e);return!t||t.index===void 0?null:e.slice(0,t.index+4)}const dr=[`CFBundleIcons`,`CFBundleIcons~ipad`];async function fr(e){let t=e.filter(Cr);if(t.length===0)return;let n=e.filter(e=>Tr(e)&&!wr(e));for(let e of t){let t=Sr(e,n);t&&await pr(t,e)}}async function pr(e,t){let n=mr(e,t),r=await hr(e,t);(n||r)&&(await vr(t),xr(t))}function mr(e,t){let n=!1;for(let r of b.readdirSync(e,{withFileTypes:!0}))!r.isFile()||!br(r.name)||yr(S.join(e,r.name),S.join(t,r.name))&&(n=!0);return n}async function hr(e,t){let n=S.join(e,`Info.plist`),r=S.join(t,`Info.plist`),i=await _(n),a=await _(r);if(!i||!a)return!1;let o=gr(i,a);if(o.length===0)return!1;for(let e of o)await _r(r,e.key,e.value,e.shouldInsert);return!0}function gr(e,t){return dr.flatMap(n=>{let r=e[n];return r===void 0||JSON.stringify(t[n])===JSON.stringify(r)?[]:[{key:n,value:r,shouldInsert:t[n]===void 0}]})}async function _r(e,t,n,r){a(await g(`plutil`,[r?`-insert`:`-replace`,t,`-json`,JSON.stringify(n),e],{allowFailure:!0}),`Failed to update XCTest runner icon plist`,{key:t,plistPath:e})}async function vr(e){a(await g(`codesign`,[`--force`,`--sign`,`-`,`--timestamp=none`,`--generate-entitlement-der`,e],{allowFailure:!0}),`Failed to sign XCTest runner app after icon update`,{runnerAppPath:e})}function yr(e,t){if(b.existsSync(t)){let n=b.readFileSync(e),r=b.readFileSync(t);return n.equals(r)?!1:(b.copyFileSync(e,t),!0)}return b.copyFileSync(e,t),!0}function br(e){return/^AppIcon.*\.png$/.test(e)||e===`Assets.car`}function xr(e){let t=new Date;b.utimesSync(e,t,t)}function Sr(e,t){let n=S.dirname(e);return t.find(e=>S.dirname(e)===n&&S.basename(e)===`AgentDeviceRunner.app`)??t.find(t=>S.dirname(t)===n&&t!==e)??null}function Cr(e){return Tr(e)&&wr(e)&&(e.includes(`Debug-iphonesimulator`)||e.includes(`Release-iphonesimulator`)||e.includes(`Debug-appletvsimulator`)||e.includes(`Release-appletvsimulator`))}function wr(e){return S.basename(e).endsWith(`-Runner.app`)}function Tr(e){return S.basename(e).endsWith(`.app`)}const Er={PreferredScreenCaptureFormat:`screenshots`,SystemAttachmentLifetime:`keepNever`,UserAttachmentLifetime:`keepNever`};async function Dr(e,t,n,r={}){let i=r.iosXctestEnvDir?.trim(),a=i?S.resolve(i):S.dirname(e);b.mkdirSync(a,{recursive:!0});let o=n.replace(/[^a-zA-Z0-9._-]/g,`_`),s=S.join(a,`AgentDeviceRunner.env.${o}.json`),c=S.join(a,`AgentDeviceRunner.env.${o}.xctestrun`),l=await Or(e);return Mr(l,e=>Ar(e,t)),jr(l),await kr(l,s,c),{xctestrunPath:c,jsonPath:s}}async function Or(e){let n=await g(`plutil`,[`-convert`,`json`,`-o`,`-`,e],{allowFailure:!0});if(n.exitCode!==0||!n.stdout.trim())throw new t(`COMMAND_FAILED`,`Failed to read xctestrun plist`,{xctestrunPath:e,stderr:n.stderr});try{let e=JSON.parse(n.stdout);if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Root must be an object`);return e}catch(n){throw new t(`COMMAND_FAILED`,`Failed to parse xctestrun JSON`,{xctestrunPath:e,error:String(n)})}}async function kr(e,t,n){b.writeFileSync(t,JSON.stringify(e,null,2)),a(await g(`plutil`,[`-convert`,`xml1`,`-o`,n,t],{allowFailure:!0}),`Failed to write xctestrun plist`,{tmpXctestrunPath:n})}function Ar(e,t){e.EnvironmentVariables={...e.EnvironmentVariables??{},...t},e.UITestEnvironmentVariables={...e.UITestEnvironmentVariables??{},...t},e.UITargetAppEnvironmentVariables={...e.UITargetAppEnvironmentVariables??{},...t},e.TestingEnvironmentVariables={...e.TestingEnvironmentVariables??{},...t}}function jr(e){Mr(e,e=>Object.assign(e,Er),{requireTestBundlePath:!0})}function Mr(e,t,n={}){let r=e.TestConfigurations;if(Array.isArray(r))for(let e of r)!e||typeof e!=`object`||Nr(e.TestTargets,t,n);for(let n of Object.values(e)){let e=Pr(n,{requireTestBundlePath:!0});e&&t(e)}}function Nr(e,t,n){if(Array.isArray(e))for(let r of e){let e=Pr(r,n);e&&t(e)}}function Pr(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;return t.requireTestBundlePath&&!n.TestBundlePath?null:n}const Fr=new Map,X=new Set;async function Ir(e,t){let n=Lr(t);if(n)return n;let r=c(),i=N(e,r),a=F(e,i);return await Je(Fr,a,async()=>{let n=await An(a);try{return await zr({device:e,options:t,projectRoot:r,expectedCacheMetadata:i,derived:a,forceRebuild:t.forceRunnerXctestrunRebuild===!0})}finally{await n()}})}function Lr(e){let n=e.iosXctestrunFile?.trim();if(!n)return null;let r=S.resolve(n);if(!b.existsSync(r))throw new t(`COMMAND_FAILED`,`Configured iOS XCTest runner .xctestrun file not found`,{configKey:`iosXctestrunFile`,xctestrunPath:r});let i=e.iosXctestDerivedDataPath?.trim(),a=i?S.resolve(i):Rr(r);return Y(`reuse`,`external_xctestrun`,{derived:a,xctestrunPath:r}),{xctestrunPath:r,derived:a,cache:`external`,artifact:`valid`,buildMs:0,xctestrunPathSource:`external`}}function Rr(e){let t=y.createHash(`sha1`);t.update(e);let n=t.digest(`hex`).slice(0,12);return S.join(x.tmpdir(),`agent-device-ios-xctest-derived`,n)}async function zr(e){let{device:t,options:n,projectRoot:r,expectedCacheMetadata:i,derived:a}=e;Nn(a,e.forceRebuild);let o=await Wr({device:t,derived:a,projectRoot:r,expectedCacheMetadata:i}),s=o.reason===`reuse_ready`?`exact`:o.xctestrunPath?`restore-key`:`miss`;return o.reason!==`reuse_ready`&&Y(`rebuild`,o.reason,{derived:a,xctestrunPath:o.xctestrunPath}),await Br({device:t,derived:a,expectedCacheMetadata:i,existing:o,cache:s})||(o.xctestrunPath&&(J(a),K(a)),await Vr({device:t,options:n,projectRoot:r,expectedCacheMetadata:i,derived:a,cache:s,reason:o.reason}))}async function Br(e){let{device:t,derived:n,expectedCacheMetadata:r,existing:i,cache:a}=e;if(i.reason!==`reuse_ready`)return null;let o=await Hr(t,n,r,i);return o?{xctestrunPath:o,derived:n,cache:a,artifact:`valid`,buildMs:0,xctestrunPathSource:i.source}:null}async function Vr(e){let{device:n,options:r,projectRoot:i,expectedCacheMetadata:a,derived:o,cache:s,reason:c}=e,l=dt(i);if(!b.existsSync(l))throw new t(`COMMAND_FAILED`,`iOS runner project not found`,{projectPath:l});let u=Date.now();Ae({type:`command`,status:`progress`,message:`Building Apple runner...`}),await Xr(n,l,o,r);let d=Math.max(0,Date.now()-u),f=Gr(o,n);if(!f)throw new t(`COMMAND_FAILED`,`Failed to locate .xctestrun after build`);let p=await er(f);if(!p)throw new t(`COMMAND_FAILED`,`Runner build is missing expected products`,{xctestrunPath:f});return await Xn(n,p,f),await fr(p),Pn(o,a,f,p),Y(`build`,`built_new`,{derived:o,xctestrunPath:f}),{xctestrunPath:f,derived:o,cache:s,artifact:`rebuilt`,buildMs:d,xctestrunPathSource:`build`,reason:c}}async function Hr(e,t,n,r){try{return await Xn(e,r.productPaths,r.xctestrunPath),Y(`reuse`,`reuse_ready`,{derived:t,xctestrunPath:r.xctestrunPath}),Pn(t,n,r.xctestrunPath,r.productPaths),r.xctestrunPath}catch(e){if(!Zn(e))throw e;return Y(`rebuild`,`repair_failed`,{derived:t,xctestrunPath:r.xctestrunPath}),null}}async function Ur(e){try{let t=c(),n=N(e,t);return(await Wr({device:e,derived:F(e,n),projectRoot:t,expectedCacheMetadata:n})).reason===`reuse_ready`}catch{return!1}}function Wr(e){let{device:t,derived:n,projectRoot:r,expectedCacheMetadata:i}=e;return Jn({derived:n,projectRoot:r,expectedCacheMetadata:i,findXctestrun:e=>Gr(e,t),xctestrunReferencesProjectRoot:Yr,resolveExistingXctestrunProductPaths:er})}function Gr(e,t){let n=Kr(e);return n.length===0?null:(n.sort((e,n)=>qr(e,n,t)),n[0]?.path??null)}function Kr(e){if(!b.existsSync(e))return[];let t=[],n=[e];for(;n.length>0;){let e=n.pop(),r=b.readdirSync(e,{withFileTypes:!0});for(let i of r){let r=S.join(e,i.name);if(i.isDirectory()){n.push(r);continue}if(i.isFile()&&i.name.endsWith(`.xctestrun`))try{let e=b.statSync(r);t.push({path:r,mtimeMs:e.mtimeMs})}catch{}}}return t}function qr(e,t,n){if(n){let r=Jr(t.path,n)-Jr(e.path,n);if(r!==0)return r}return t.mtimeMs-e.mtimeMs||e.path.localeCompare(t.path)}function Jr(e,t){let n=0,r=e.toLowerCase();S.basename(r).startsWith(`agentdevicerunner.env.`)&&(n-=1e3),r.includes(`${S.sep}macos${S.sep}`)&&(n-=5e3);let i=$e(t);return i.preferred.length>0&&(i.preferred.some(e=>r.includes(e))?n+=2e3:n-=500),i.disallowed.some(e=>r.includes(e))&&(n-=2500),n}function Yr(e,t){try{let n=b.readFileSync(e,`utf8`),r=new Set([t]);try{r.add(b.realpathSync(t))}catch{}for(let e of r)if(n.includes(e))return!0;return!1}catch{return!1}}async function Xr(e,n,r,a){let o=At(process.env),s=kt(process.env,e.kind===`device`,e),c=e.kind===`device`?[`-allowProvisioningUpdates`]:[],l=jt(),u=Mt(),d=await Sn(e);try{await i(`xcodebuild`,[`build-for-testing`,`-project`,n,`-scheme`,`AgentDeviceRunner`,`-parallel-testing-enabled`,`NO`,Ot(e),`1`,`-destination`,tt(e),`-derivedDataPath`,r,...l,...u,...o,...c,...s],{detached:!0,timeoutMs:a.buildTimeoutMs,signal:a.signal,onSpawn:e=>{X.add(e),e.on(`close`,()=>{X.delete(e)})},onStdoutChunk:e=>{B(e,a.logPath,a.traceLogPath,a.verbose)},onStderrChunk:e=>{B(e,a.logPath,a.traceLogPath,a.verbose)}})}catch(e){if(E(e))throw e;let n=e instanceof t?e:new t(`COMMAND_FAILED`,String(e)),r=Vt(n);throw new t(`COMMAND_FAILED`,`xcodebuild build-for-testing failed`,{error:n.message,details:n.details,logPath:a.logPath,hint:r})}finally{await d?.release()}}var Zr=e({RUNNER_INVALIDATE_WAIT_TIMEOUT_MS:()=>Qr,abortRunnerSessionsAndPrepProcesses:()=>ri,cleanupOwnedIosRunnerLease:()=>ni,disposeRunnerSession:()=>ti,isRunnerProcessAlive:()=>fi,runnerLeaseCleanupAdapter:()=>ei,stopRunnerPrepProcesses:()=>ii});const Qr=1e3,$r=2e3,ei={cleanupRunnerProcessTree:Q,cleanupRunnerXcodebuildProcesses:mi,cleanupTempFile:H};async function ti(e,t={}){let n=!1;if(t.graceful!==!1)n=await ai(e);else if(l(e.device)){await si([e]),await li(e);return}else await Q(e.child.pid,`SIGTERM`);n||(await oi(e,t.waitTimeoutMs??1e4),di(e.child.pid)&&await Q(e.child.pid,`SIGKILL`)),await li(e)}async function ni(e){await ue(e,ei)}async function ri(e){let t=Array.from(X),n=e.filter(e=>l(e.device)),r=e.filter(e=>!l(e.device));await Z(r,`SIGINT`),await pi(t,`SIGINT`),await Z(r,`SIGTERM`),await pi(t,`SIGTERM`),await Z(r,`SIGKILL`),await pi(t,`SIGKILL`),await si(n),await Promise.allSettled(e.map(async e=>{await li(e)}))}async function ii(){let e=Array.from(X);await Promise.allSettled(e.map(async e=>{try{await Q(e.pid,`SIGTERM`),await Q(e.pid,`SIGKILL`)}finally{X.delete(e)}}))}async function ai(e){try{return await Jt(e.device,e.port,Ht({command:`shutdown`}),void 0,15e3),!1}catch{return l(e.device)?(await si([e]),!0):(await Q(e.child.pid,`SIGTERM`),!1)}}async function oi(e,t){let n;try{return await Promise.race([e.testPromise.then(()=>!0,()=>!0),new Promise(e=>{n=setTimeout(()=>e(!1),t)})])||!di(e.child.pid)}finally{n&&clearTimeout(n)}}async function si(e){if(e.length===0)return;await Z(e,`SIGINT`);let t=await ci(e,5e3);await Z(t,`SIGTERM`),await Z(await ci(t,2e3),`SIGKILL`)}async function ci(e,t){let n=await Promise.all(e.map(async e=>await oi(e,t)));return e.filter((e,t)=>!n[t])}async function li(e){await ui(e.device),H(e.xctestrunPath),H(e.jsonPath);try{await e.simulatorSetRedirect?.release()}finally{de(e.lease)}}async function ui(e){e.kind===`simulator`&&await Promise.allSettled(vt.map(async t=>{try{await h(O(e,[`terminate`,e.id,t]),{allowFailure:!0,timeoutMs:$r})}catch(n){o({level:`warn`,phase:`ios_runner_simulator_app_terminate_failed`,data:{deviceId:e.id,bundleId:t,timeoutMs:$r,error:n instanceof Error?n.message:String(n)}})}}))}function di(e){return e?fi(e)||ne(e):!1}function fi(e){return e?ee(e):!1}async function Z(e,t){await Promise.allSettled(e.map(async e=>{await Q(e.child.pid,t)}))}async function pi(e,t){await Promise.allSettled(e.map(async e=>{await Q(e.pid,t),t===`SIGKILL`&&X.delete(e)}))}async function Q(e,t){if(!e||e<=0)return;try{process.kill(-e,t)}catch{}re([e],t);let n=t===`SIGINT`?`INT`:t===`SIGTERM`?`TERM`:`KILL`;try{await g(`pkill`,[`-${n}`,`-P`,String(e)],{allowFailure:!0})}catch{}}async function mi(e,t){let n=t?`xcodebuild.*test-without-building.*AgentDeviceRunner\\.env\\.session-${$(e)}-${$(t)}-`:`xcodebuild.*test-without-building.*AgentDeviceRunner\\.env\\.session-${$(e)}-[0-9]`;for(let t of[`TERM`,`KILL`])try{await g(`pkill`,[`-${t}`,`-f`,n],{allowFailure:!0,timeoutMs:2e3})}catch(n){o({level:`warn`,phase:`ios_runner_stale_xcodebuild_kill_failed`,data:{deviceId:e,signal:t,error:n instanceof Error?n.message:String(n)}})}}function $(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}export{et as A,ke as B,Ht as C,F as D,M as E,Ie as F,we as G,Se as H,D as I,be as J,E as K,Ae as L,O as M,Xe as N,Ot as O,Je as P,Me as R,It as S,N as T,T as U,Ce as V,Te as W,Ee as X,he as Y,B as _,fi as a,Wt as b,ii as c,Dr as d,kn as f,mn as g,Gt as h,ti as i,Ye as j,ot as k,Ir as l,Kt as m,ri as n,ei as o,Sn as p,xe as q,ni as r,Zr as s,Qr as t,Ur as u,tn as v,vt as w,Ft as x,Jt as y,je as z};
@@ -0,0 +1 @@
1
+ import{t as e}from"./rolldown-runtime.js";import{_ as t}from"./sdk-contracts.js";import{j as n}from"./sdk-android-adb.js";import{o as r}from"./host-process.js";import{s as i}from"./daemon-shutdown-report.js";import{t as a}from"./process-lock.js";import o from"node:crypto";import s from"node:fs";import c from"node:os";import l from"node:path";var u=e({RUNNER_OWNER_START_TIME:()=>f,RUNNER_OWNER_TOKEN:()=>p,buildDetachedRunnerLease:()=>j,buildRunnerLease:()=>h,cleanupOwnedRunnerLease:()=>M,cleanupRunnerLeasesForOwner:()=>N,prepareRunnerLeaseForStartup:()=>b,readStaleRunnerLease:()=>A,releaseRunnerLease:()=>P,setRunnerLeaseOwnerStateDir:()=>g,withRunnerLeaseLock:()=>_,writeRunnerLease:()=>F});const d=process.pid,f=r(process.pid),p=X(d,f);let m;function h(e){return{schemaVersion:1,deviceId:e.deviceId,ownerToken:p,ownerPid:d,ownerStartTime:f,ownerStateDir:w(),sessionId:e.sessionId,runnerPid:e.runnerPid??null,port:e.port,xctestrunPath:e.xctestrunPath,jsonPath:e.jsonPath,createdAtMs:Date.now()}}function g(e){m=e?.trim()||void 0}async function _(e,t){let n=await a({lockDirPath:`${L(e)}.lock`,owner:{pid:d,startTime:f,acquiredAtMs:Date.now()},timeoutMs:3e4,pollMs:100,ownerGraceMs:5e3,description:`iOS runner lease for ${e}`});try{return await t()}finally{await n()}}function v(e){try{return V(JSON.parse(s.readFileSync(L(e),`utf8`)),e)}catch{return null}}function y(e){return e?e.ownerToken===p?{type:`owned`,lease:e}:q(e)?J(e)?{type:`stale`,lease:e,staleReason:`owner-state-dir-gone`}:{type:`busy`,lease:e}:{type:`stale`,lease:e,staleReason:`owner-process-dead`}:{type:`empty`}}async function b(e,n,r){let i=y(v(e));if(i.type===`empty`){await n.cleanupRunnerXcodebuildProcesses(e,void 0);return}if(i.type===`busy`){if(x(i.lease)){await Y(i.lease,`same-state-dir`,n);return}if(S(i.lease,r)){await Y(i.lease,`logical-lease-takeover`,n);return}throw new t(`COMMAND_FAILED`,r?`iOS runner for ${e} is busy after device lease admission`:`iOS runner for ${e} is already owned by another agent-device daemon`,{deviceId:e,logicalLeaseContext:r,ownerPid:i.lease.ownerPid,ownerStartTime:i.lease.ownerStartTime,ownerStateDir:i.lease.ownerStateDir,ownerToken:i.lease.ownerToken,sessionId:i.lease.sessionId,hint:T(i.lease,r)})}await Y(i.lease,i.type,n)}function x(e){let t=w();return!t||!e.ownerStateDir?!1:l.resolve(t)===l.resolve(e.ownerStateDir)}function S(e,t){return!t||t.leaseProvider!==`proxy`||!t.leaseId||!t.clientId?!1:C(t.deviceKey,e.deviceId)}function C(e,t){if(!e)return!1;if(e===t)return!0;let[,,n]=e.split(`:`,3);return n===t}function w(){return m||process.env.AGENT_DEVICE_STATE_DIR?.trim()||void 0}function T(e,t){let n=E(e),r=D(e);return t?[r,n,`The device is busy because another active device lease owns it, or the runner is owned by another daemon/process after lease admission.`,`Retry after the owning session closes or after the five-minute inactivity lease expires.`].join(` `):[r,n,`If the runner is still active, wait for it to finish. Do not run prepare ios-runner from another daemon/client to recover this.`].join(` `)}function E(e){let t=`Runner owner: PID ${e.ownerPid}`;return e.ownerStateDir?`${t} with AGENT_DEVICE_STATE_DIR=${e.ownerStateDir}`:`${t}.`}function D(e){return e.ownerStateDir?`If it is stuck, stop the owning agent-device daemon for ${O(`AGENT_DEVICE_STATE_DIR`,e.ownerStateDir)} and retry.`:`If it is stuck, stop the owning agent-device daemon and retry.`}function O(e,t){return`${e}=${k(t)}`}function k(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function A(e){let t=y(v(e));return t.type===`stale`&&t.staleReason===`owner-process-dead`?t.lease:null}function j(e){return{...e,ownerToken:`detached-${e.ownerToken}`}}async function M(e,t){let n=y(v(e));n.type===`owned`&&await Y(n.lease,`owned`,t)}async function N(e,t){if(!Number.isInteger(e.pid)||e.pid<=0)return;let n=z(e);await Promise.all(n.map(async e=>{await Y(e,`owned`,t)}))}function P(e){e&&I({deviceId:e.deviceId,ownerToken:e.ownerToken,sessionId:e.sessionId})}function F(e){let t=L(e.deviceId);s.mkdirSync(l.dirname(t),{recursive:!0});let n=`${t}.${process.pid}.${Date.now()}.tmp`;s.writeFileSync(n,JSON.stringify(e,null,2),`utf8`),s.renameSync(n,t)}function I(e){let t=v(e.deviceId);if(t&&!(e.ownerToken&&t.ownerToken!==e.ownerToken)&&!(e.sessionId&&t.sessionId!==e.sessionId))try{s.unlinkSync(L(e.deviceId))}catch{}}function L(e){return l.join(R(),`${Z(e)}.json`)}function R(){let e=process.env.AGENT_DEVICE_IOS_RUNNER_LEASE_DIR?.trim();return e?l.resolve(e):l.join(c.homedir(),`.agent-device`,`apple-runner`,`leases`)}function z(e){let t,n=R();try{t=s.readdirSync(n,{withFileTypes:!0})}catch{return[]}let r=[];for(let i of t){if(!i.isFile()||!i.name.endsWith(`.json`))continue;let t=B(l.join(n,i.name));t&&t.ownerPid===e.pid&&(e.startTime!==void 0&&t.ownerStartTime!==e.startTime||r.push(t))}return r}function B(e){try{let t=JSON.parse(s.readFileSync(e,`utf8`)),n=U(t.deviceId);return n?V(t,n):null}catch{return null}}function V(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;if(n.schemaVersion!==1||n.deviceId!==t)return null;let r=H(n);return r?{schemaVersion:1,deviceId:t,...r,ownerStartTime:W(n.ownerStartTime),ownerStateDir:W(n.ownerStateDir)??void 0,runnerPid:G(n.runnerPid)}:null}function H(e){let t={ownerToken:U(e.ownerToken),ownerPid:G(e.ownerPid),sessionId:U(e.sessionId),port:G(e.port),xctestrunPath:U(e.xctestrunPath),jsonPath:U(e.jsonPath),createdAtMs:K(e.createdAtMs)};return Object.values(t).some(e=>e===null)?null:t}function U(e){return typeof e==`string`&&e.length>0?e:null}function W(e){return typeof e==`string`?e:null}function G(e){return typeof e==`number`&&Number.isInteger(e)&&e>0?e:null}function K(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function q(e){return i({owner:{pid:e.ownerPid,startTime:e.ownerStartTime}})===`live`}function J(e){return e.ownerStateDir?i({owner:{pid:e.ownerPid,startTime:e.ownerStartTime},stateDir:e.ownerStateDir})===`owner-state-dir-gone`:!1}async function Y(e,t,r){n({level:t===`stale`||t===`same-state-dir`||t===`logical-lease-takeover`?`warn`:`debug`,phase:`ios_runner_lease_cleanup`,data:{deviceId:e.deviceId,ownerPid:e.ownerPid,ownerStateDir:e.ownerStateDir,ownerToken:e.ownerToken,runnerPid:e.runnerPid,sessionId:e.sessionId,reason:t}}),await r.cleanupRunnerProcessTree(e.runnerPid??void 0,`SIGTERM`),await r.cleanupRunnerXcodebuildProcesses(e.deviceId,e.ownerToken),await r.cleanupRunnerProcessTree(e.runnerPid??void 0,`SIGKILL`),r.cleanupTempFile(e.xctestrunPath),r.cleanupTempFile(e.jsonPath),P(e)}function X(e,t){let n=o.createHash(`sha256`);return n.update(String(e)),n.update(`\0`),n.update(t??`unknown-start`),`owner-${e}-${n.digest(`hex`).slice(0,8)}`}function Z(e){return e.replaceAll(/[^A-Za-z0-9._-]/g,`-`)||`unknown-device`}export{b as a,u as c,F as d,M as i,g as l,j as n,A as o,h as r,P as s,p as t,_ as u};
@@ -1 +1 @@
1
- import{t as e}from"./rolldown-runtime.js";import{F as t,H as n}from"./sdk-contracts.js";var r=e({MAX_RUNNER_SEQUENCE_STEPS:()=>20,SEQUENCEABLE_RUNNER_STEP_KINDS:()=>i,buildRunnerSequenceCommand:()=>u,parseRunnerSequenceResult:()=>d,validateRunnerSequenceSteps:()=>s});const i=[`tap`,`doubleTap`,`longPress`,`drag`];function a(e){return typeof e==`string`&&i.includes(e)}function o(e,n,r){return new t(`INVALID_ARGS`,r,{stepIndex:e,kind:typeof n==`string`?n:void 0})}function s(e){if(!Array.isArray(e)||e.length===0)throw new t(`INVALID_ARGS`,`sequence requires at least one step`,{stepCount:Array.isArray(e)?e.length:0});if(e.length>20)throw new t(`INVALID_ARGS`,`sequence accepts at most 20 steps, received ${e.length}`,{stepCount:e.length,maxSteps:20});e.forEach((e,t)=>c(e,t))}function c(e,t){if(!a(e.kind))throw o(t,e.kind,`sequence step ${t} has unsupported kind "${String(e.kind)}"; allowed: ${i.join(`, `)}`);if(!Number.isFinite(e.x)||!Number.isFinite(e.y))throw o(t,e.kind,`sequence step ${t} (${e.kind}) requires finite x and y`);if(e.kind===`drag`&&(!Number.isFinite(e.x2)||!Number.isFinite(e.y2)))throw o(t,e.kind,`sequence step ${t} (drag) requires finite x2 and y2`);e.durationMs!==void 0&&l(e.durationMs,0,1e4,t,e.kind,`durationMs`),e.pauseMs!==void 0&&l(e.pauseMs,0,1e4,t,e.kind,`pauseMs`)}function l(e,t,n,r,i,a){if(!Number.isFinite(e)||e<t||e>n)throw o(r,i,`sequence step ${r} (${i}) ${a} must be between ${t} and ${n}`)}function u(e,t){return s(e),{command:`sequence`,steps:e,appBundleId:t}}function d(e){let t=p(e.sequenceResults),n=typeof e.completedSteps==`number`&&Number.isFinite(e.completedSteps)?e.completedSteps:t.filter(e=>e.ok).length,r=typeof e.failedStepIndex==`number`&&Number.isFinite(e.failedStepIndex)?e.failedStepIndex:t.findIndex(e=>!e.ok)>=0?t.findIndex(e=>!e.ok):void 0;if(r!==void 0)throw f(t,n,r);return{results:t,completedSteps:n,failedStepIndex:r}}function f(e,r,i){let a=e[i],o=a?.kind??`step`,s=a?.errorMessage??`sequence step ${i} (${o}) failed`;return new t(n(a?.errorCode),s,{failedStepIndex:i,failedStepKind:o,completedSteps:r,sequenceResults:e,hint:`Run snapshot -i to inspect the current UI, then continue from the observed state.`})}function p(e){return Array.isArray(e)?e.map(e=>{let t=e??{};return{ok:t.ok===!0,kind:typeof t.kind==`string`?t.kind:`unknown`,errorCode:typeof t.errorCode==`string`?t.errorCode:void 0,errorMessage:typeof t.errorMessage==`string`?t.errorMessage:void 0,gestureStartUptimeMs:typeof t.gestureStartUptimeMs==`number`?t.gestureStartUptimeMs:void 0,gestureEndUptimeMs:typeof t.gestureEndUptimeMs==`number`?t.gestureEndUptimeMs:void 0}}):[]}export{d as n,r,u as t};
1
+ import{t as e}from"./rolldown-runtime.js";import{_ as t,w as n}from"./sdk-contracts.js";var r=e({MAX_RUNNER_SEQUENCE_STEPS:()=>20,SEQUENCEABLE_RUNNER_STEP_KINDS:()=>i,buildRunnerSequenceCommand:()=>u,parseRunnerSequenceResult:()=>d,validateRunnerSequenceSteps:()=>s});const i=[`tap`,`doubleTap`,`longPress`];function a(e){return typeof e==`string`&&i.includes(e)}function o(e,n,r){return new t(`INVALID_ARGS`,r,{stepIndex:e,kind:typeof n==`string`?n:void 0})}function s(e){if(!Array.isArray(e)||e.length===0)throw new t(`INVALID_ARGS`,`sequence requires at least one step`,{stepCount:Array.isArray(e)?e.length:0});if(e.length>20)throw new t(`INVALID_ARGS`,`sequence accepts at most 20 steps, received ${e.length}`,{stepCount:e.length,maxSteps:20});e.forEach((e,t)=>c(e,t))}function c(e,t){if(!a(e.kind))throw o(t,e.kind,`sequence step ${t} has unsupported kind "${String(e.kind)}"; allowed: ${i.join(`, `)}`);if(!Number.isFinite(e.x)||!Number.isFinite(e.y))throw o(t,e.kind,`sequence step ${t} (${e.kind}) requires finite x and y`);e.durationMs!==void 0&&l(e.durationMs,0,1e4,t,e.kind,`durationMs`),e.pauseMs!==void 0&&l(e.pauseMs,0,1e4,t,e.kind,`pauseMs`)}function l(e,t,n,r,i,a){if(!Number.isFinite(e)||e<t||e>n)throw o(r,i,`sequence step ${r} (${i}) ${a} must be between ${t} and ${n}`)}function u(e,t){return s(e),{command:`sequence`,steps:e,appBundleId:t}}function d(e){let t=p(e.sequenceResults),n=typeof e.completedSteps==`number`&&Number.isFinite(e.completedSteps)?e.completedSteps:t.filter(e=>e.ok).length,r=typeof e.failedStepIndex==`number`&&Number.isFinite(e.failedStepIndex)?e.failedStepIndex:t.findIndex(e=>!e.ok)>=0?t.findIndex(e=>!e.ok):void 0;if(r!==void 0)throw f(t,n,r);return{results:t,completedSteps:n,failedStepIndex:r}}function f(e,r,i){let a=e[i],o=a?.kind??`step`,s=a?.errorMessage??`sequence step ${i} (${o}) failed`;return new t(n(a?.errorCode),s,{failedStepIndex:i,failedStepKind:o,completedSteps:r,sequenceResults:e,hint:`Run snapshot -i to inspect the current UI, then continue from the observed state.`})}function p(e){return Array.isArray(e)?e.map(e=>{let t=e??{};return{ok:t.ok===!0,kind:typeof t.kind==`string`?t.kind:`unknown`,errorCode:typeof t.errorCode==`string`?t.errorCode:void 0,errorMessage:typeof t.errorMessage==`string`?t.errorMessage:void 0,gestureStartUptimeMs:typeof t.gestureStartUptimeMs==`number`?t.gestureStartUptimeMs:void 0,gestureEndUptimeMs:typeof t.gestureEndUptimeMs==`number`?t.gestureEndUptimeMs:void 0}}):[]}export{d as n,r,u as t};
@@ -1 +1 @@
1
- import{F as e}from"./sdk-contracts.js";import{URL as t}from"node:url";function n(n){if(!n)return;let o=r(n.metroHost),s=i(n.metroPort),c=`http`,l=r(n.bundleUrl);if(l){let n;try{n=new t(l)}catch(t){throw new e(`INVALID_ARGS`,`Invalid runtime bundle URL: ${l}`,{},t)}(n.protocol===`http:`||n.protocol===`https:`)&&(o??=r(n.hostname),s??=i(n.port.length>0?Number(n.port):a(n.protocol)),c=n.protocol===`https:`?`https`:`http`)}if(!(!o||!s))return{host:o,port:s,scheme:c}}function r(e){let t=e?.trim();return t&&t.length>0?t:void 0}function i(e){if(Number.isInteger(e)&&!(e<=0||e>65535))return e}function a(e){if(e===`https:`)return 443;if(e===`http:`)return 80}export{r as n,n as t};
1
+ import{_ as e}from"./sdk-contracts.js";import{URL as t}from"node:url";function n(n){if(!n)return;let o=r(n.metroHost),s=i(n.metroPort),c=`http`,l=r(n.bundleUrl);if(l){let n;try{n=new t(l)}catch(t){throw new e(`INVALID_ARGS`,`Invalid runtime bundle URL: ${l}`,{},t)}(n.protocol===`http:`||n.protocol===`https:`)&&(o??=r(n.hostname),s??=i(n.port.length>0?Number(n.port):a(n.protocol)),c=n.protocol===`https:`?`https`:`http`)}if(!(!o||!s))return{host:o,port:s,scheme:c}}function r(e){let t=e?.trim();return t&&t.length>0?t:void 0}function i(e){if(Number.isInteger(e)&&!(e<=0||e>65535))return e}function a(e){if(e===`https:`)return 443;if(e===`http:`)return 80}export{r as n,n as t};