agent-device 0.21.3 → 0.21.4

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 (131) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.3.apk → agent-device-android-ime-helper-0.21.4.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.4.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.3.manifest.json → agent-device-android-ime-helper-0.21.4.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.3.apk → agent-device-android-snapshot-helper-0.21.4.apk} +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.4.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.4.manifest.json +16 -0
  7. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +39 -0
  8. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSystemSurfaceHostPolicy.swift +9 -1
  9. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +2 -1
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +10 -1
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +26 -124
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +46 -0
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +36 -4
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+MainThreadWork.swift +229 -0
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +15 -0
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +4 -40
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +6 -40
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +30 -9
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +22 -6
  20. package/dist/src/adapter.js +1 -1
  21. package/dist/src/adb-executor.js +2 -2
  22. package/dist/src/adb-failure.js +1 -1
  23. package/dist/src/agent-browser-process-record.js +1 -1
  24. package/dist/src/agent-device-client.js +2 -2
  25. package/dist/src/api.js +3 -11
  26. package/dist/src/app-launch.js +1 -1
  27. package/dist/src/app-lifecycle.js +1 -1
  28. package/dist/src/app-log-reconnect.js +1 -1
  29. package/dist/src/archive.js +2 -2
  30. package/dist/src/cli-help.js +2 -2
  31. package/dist/src/cli.js +4 -4
  32. package/dist/src/client-metro-companion.js +1 -1
  33. package/dist/src/client-metro.js +1 -1
  34. package/dist/src/client-types.d.ts +69 -4
  35. package/dist/src/code-signature-cache.js +1 -1
  36. package/dist/src/command-tools.js +2 -2
  37. package/dist/src/command.js +1 -1
  38. package/dist/src/connection-runtime.js +1 -1
  39. package/dist/src/contracts.js +1 -1
  40. package/dist/src/daemon-client-lifecycle.js +1 -1
  41. package/dist/src/daemon-shutdown-report.js +1 -1
  42. package/dist/src/device-claim-rule.js +1 -1
  43. package/dist/src/device-input-state.d.ts +10 -8
  44. package/dist/src/device-inventory-context.js +1 -1
  45. package/dist/src/device-session.js +1 -1
  46. package/dist/src/diagnostics.js +1 -1
  47. package/dist/src/error.js +2 -2
  48. package/dist/src/exec.js +1 -1
  49. package/dist/src/file.js +1 -1
  50. package/dist/src/find.js +1 -1
  51. package/dist/src/gesture-runtime.js +1 -1
  52. package/dist/src/helper.js +1 -1
  53. package/dist/src/index.js +1 -1
  54. package/dist/src/install-source-network-transport.js +1 -1
  55. package/dist/src/interaction2.js +1 -1
  56. package/dist/src/interactor.js +4 -4
  57. package/dist/src/internal/bin.js +1 -1
  58. package/dist/src/internal/daemon.js +2 -2
  59. package/dist/src/internal/png-worker.js +1 -1
  60. package/dist/src/ios-client.js +121 -7
  61. package/dist/src/ios-snapshot-adapter.js +1 -1
  62. package/dist/src/ios-system-surface.js +1 -1
  63. package/dist/src/limrun-delta-sync-omitted.js +1 -0
  64. package/dist/src/limrun.d.ts +0 -1598
  65. package/dist/src/location-coordinates.js +1 -1
  66. package/dist/src/mechanics.js +16 -16
  67. package/dist/src/output-common.js +2 -0
  68. package/dist/src/owner-identity.js +1 -1
  69. package/dist/src/perf-runtime-operation-builder.js +1 -1
  70. package/dist/src/perf-runtime-plan.js +1 -1
  71. package/dist/src/platform-runtime-android-adb-host.js +1 -1
  72. package/dist/src/platform-runtime-app-log-android-transport.js +1 -1
  73. package/dist/src/platform-runtime-app-log-process.js +1 -1
  74. package/dist/src/platform-runtime-host.js +1 -1
  75. package/dist/src/platform-runtime-operation-host.js +2 -2
  76. package/dist/src/platform-runtime-screen-recording-android-host.js +1 -1
  77. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  78. package/dist/src/platform-runtime-screen-recording-output-host.js +1 -1
  79. package/dist/src/platform-runtime-screen-recording-process-host.js +1 -1
  80. package/dist/src/process.js +1 -1
  81. package/dist/src/proxy.js +1 -1
  82. package/dist/src/quality-warnings.js +1 -1
  83. package/dist/src/react-native.js +1 -1
  84. package/dist/src/record-runtime.js +1 -1
  85. package/dist/src/recording-stop-observation.js +1 -0
  86. package/dist/src/registry.js +35 -36
  87. package/dist/src/replay-divergence.js +1 -1
  88. package/dist/src/reporting.js +11 -9
  89. package/dist/src/result-serialization.js +1 -1
  90. package/dist/src/runner-cache-metadata.js +1 -1
  91. package/dist/src/runner-client.js +1 -1
  92. package/dist/src/runner-disposal.js +1 -1
  93. package/dist/src/runner-operations-facade.js +1 -1
  94. package/dist/src/runner.js +1 -1
  95. package/dist/src/runtime.js +3 -3
  96. package/dist/src/runtime10.js +1 -1
  97. package/dist/src/runtime2.js +4 -4
  98. package/dist/src/runtime3.js +1 -1
  99. package/dist/src/runtime4.js +4 -4
  100. package/dist/src/runtime5.js +1 -1
  101. package/dist/src/runtime6.js +1 -1
  102. package/dist/src/runtime9.js +1 -1
  103. package/dist/src/screen-recording-completion.js +1 -1
  104. package/dist/src/screen-recording-resource-recovery.js +1 -1
  105. package/dist/src/screenshot-result.js +1 -1
  106. package/dist/src/sdk-contracts.js +2 -2
  107. package/dist/src/sdk-selectors.d.ts +36 -24
  108. package/dist/src/selector-runtime.js +1 -1
  109. package/dist/src/session-observation.js +1 -1
  110. package/dist/src/session-snapshot.js +1 -1
  111. package/dist/src/session-store.js +2 -2
  112. package/dist/src/session2.js +5 -5
  113. package/dist/src/snapshot-runtime.js +1 -1
  114. package/dist/src/snapshot.js +1 -1
  115. package/dist/src/snapshot4.js +1 -1
  116. package/dist/src/stop-sequence.js +1 -0
  117. package/dist/src/success-text.js +1 -1
  118. package/dist/src/text-entry-focus.js +1 -0
  119. package/dist/src/tool-provider.js +1 -1
  120. package/dist/src/tool-provider2.js +1 -1
  121. package/dist/src/tool-provider3.js +1 -1
  122. package/dist/src/type-text-runtime.js +1 -1
  123. package/dist/src/video.js +2 -2
  124. package/dist/src/yauzl.js +1 -0
  125. package/package.json +2 -2
  126. package/server.json +2 -2
  127. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.3.apk.sha256 +0 -1
  128. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.3.apk.sha256 +0 -1
  129. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.3.manifest.json +0 -17
  130. package/dist/src/audio-probe-support.js +0 -1
  131. package/dist/src/screen-recording-live-handle.js +0 -1
@@ -1,2 +1,2 @@
1
- import{z as e}from"./sdk-contracts.js";function t(e){let t=e?.resume;if(typeof t?.allowed==`boolean`&&!(!Number.isInteger(t.from)||typeof t.planDigest!=`string`)&&!(!t.allowed&&typeof t.reason!=`string`)&&(t.repairSessionHeld===void 0||t.repairSessionHeld===!0)&&!(t.alternateFrom!==void 0&&!Number.isInteger(t.alternateFrom)))return t}const n={digest:8192,default:24576,full:65536};function r(e){return e===`digest`||e===`full`?e:`default`}function i(e,t=256){let n=Buffer.from(e,`utf8`);if(n.length<=t)return e;let r=`…<truncated>`,i=Buffer.byteLength(r,`utf8`),a=Math.max(0,t-i);for(;a>0&&(n[a]&192)==128;)--a;return`${n.subarray(0,a).toString(`utf8`)}${r}`}function a(t,n=256){return i(e(t),n)}function o(e,t){let n=e;for(let e of t)e.value&&(n=n.split(e.value).join(`<var:${e.name}>`));return n}function s(e){return(t,n)=>a(o(t,e),n)}function c(e,t){return e.state!==`available`||e.refs.length<=t?e:{...e,refs:e.refs.slice(0,t),truncated:!0}}function l(e,t){let n=r(t),i=n===`digest`?8:20,a=c(e.screen,i),o=n===`digest`?[]:e.suggestions.slice(0,5);return{...e,screen:a,suggestions:o}}function u(e){return Buffer.byteLength(JSON.stringify(e),`utf8`)}function d(e){let{divergence:t,level:i,writeOverflowArtifact:a}=e,o=r(i),s=n[o],c=l(t,i),d=u(c);if(d<=s)return c;let p=d-s,m=a(l(t,`full`)),h=f(c);return`artifactPath`in m?{...h,overflow:{omittedBytes:p,artifactPath:m.artifactPath}}:{...h,artifactUnavailable:!0}}function f(e){return{version:e.version,kind:e.kind,step:{index:e.step.index,source:{path:a(e.step.source.path),line:e.step.source.line}},action:a(e.action),cause:{code:e.cause.code,message:a(e.cause.message),...e.cause.hint?{hint:a(e.cause.hint)}:{}},screen:{state:`unavailable`,reason:`omitted-for-size`,hint:`The screen digest and suggestions were omitted to stay within the response byte budget. See overflow.artifactPath (or retry at --level full) for the complete report.`},suggestions:[],suggestionCount:e.suggestionCount,resume:e.resume,repairHint:e.repairHint,...e.targetBinding?{targetBinding:e.targetBinding}:{}}}function p(e){let t=e?.divergence;if(!t||typeof t!=`object`)return null;let n=t,r=[...E(n.step),...S(n.kind,n.targetBinding),...m(n.repairHint,n.resume),...D(n.screen),...j(n.suggestions,n.suggestionCount),...N(n.overflow,n.artifactUnavailable)];return r.length>0?r.join(`
1
+ import{B as e}from"./sdk-contracts.js";function t(e){let t=e?.resume;if(typeof t?.allowed==`boolean`&&!(!Number.isInteger(t.from)||typeof t.planDigest!=`string`)&&!(!t.allowed&&typeof t.reason!=`string`)&&(t.repairSessionHeld===void 0||t.repairSessionHeld===!0)&&!(t.alternateFrom!==void 0&&!Number.isInteger(t.alternateFrom)))return t}const n={digest:8192,default:24576,full:65536};function r(e){return e===`digest`||e===`full`?e:`default`}function i(e,t=256){let n=Buffer.from(e,`utf8`);if(n.length<=t)return e;let r=`…<truncated>`,i=Buffer.byteLength(r,`utf8`),a=Math.max(0,t-i);for(;a>0&&(n[a]&192)==128;)--a;return`${n.subarray(0,a).toString(`utf8`)}${r}`}function a(t,n=256){return i(e(t),n)}function o(e,t){let n=e;for(let e of t)e.value&&(n=n.split(e.value).join(`<var:${e.name}>`));return n}function s(e){return(t,n)=>a(o(t,e),n)}function c(e,t){return e.state!==`available`||e.refs.length<=t?e:{...e,refs:e.refs.slice(0,t),truncated:!0}}function l(e,t){let n=r(t),i=n===`digest`?8:20,a=c(e.screen,i),o=n===`digest`?[]:e.suggestions.slice(0,5);return{...e,screen:a,suggestions:o}}function u(e){return Buffer.byteLength(JSON.stringify(e),`utf8`)}function d(e){let{divergence:t,level:i,writeOverflowArtifact:a}=e,o=r(i),s=n[o],c=l(t,i),d=u(c);if(d<=s)return c;let p=d-s,m=a(l(t,`full`)),h=f(c);return`artifactPath`in m?{...h,overflow:{omittedBytes:p,artifactPath:m.artifactPath}}:{...h,artifactUnavailable:!0}}function f(e){return{version:e.version,kind:e.kind,step:{index:e.step.index,source:{path:a(e.step.source.path),line:e.step.source.line}},action:a(e.action),cause:{code:e.cause.code,message:a(e.cause.message),...e.cause.hint?{hint:a(e.cause.hint)}:{}},screen:{state:`unavailable`,reason:`omitted-for-size`,hint:`The screen digest and suggestions were omitted to stay within the response byte budget. See overflow.artifactPath (or retry at --level full) for the complete report.`},suggestions:[],suggestionCount:e.suggestionCount,resume:e.resume,repairHint:e.repairHint,...e.targetBinding?{targetBinding:e.targetBinding}:{}}}function p(e){let t=e?.divergence;if(!t||typeof t!=`object`)return null;let n=t,r=[...E(n.step),...S(n.kind,n.targetBinding),...m(n.repairHint,n.resume),...D(n.screen),...j(n.suggestions,n.suggestionCount),...N(n.overflow,n.artifactUnavailable)];return r.length>0?r.join(`
2
2
  `):null}function m(e,t){if(typeof e!=`string`)return[];let n=v(e,t);return[`Repair hint: ${e}${n?` — ${n}`:``}`]}function h(e){let t=e;if(!t||typeof t.allowed!=`boolean`)return;if(!t.allowed)return{allowed:!1,reason:typeof t.reason==`string`?t.reason:void 0};let{from:n,planDigest:r,alternateFrom:i}=t;if(typeof n==`number`&&typeof r==`string`&&r.length!==0)return{allowed:!0,from:n,planDigest:r,alternateFrom:typeof i==`number`?i:void 0}}function g(e,t){return`replay --from ${e} --plan-digest ${t}`}function _(e){return e?.repairSessionHeld===!0}function v(e,t){let n=y(e,h(t));if(n!==void 0)return _(t)?`${n} Read-only inspection while armed (snapshot -i, get attrs, find, is) is excluded from the healed script by default — no --no-record needed. If the step you are repairing is itself a read, add --record to that command so it lands in the heal.`:n}function y(e,t){switch(e){case`record-and-heal`:return t?.allowed?`press the correct control via a blessed @ref from screen.refs (recorded), then ${g(t.from,t.planDigest)}.`:`press the correct control via a blessed @ref from screen.refs (recorded). ${x(t)}`;case`state-repair`:return t?.allowed?`fix app state with --no-record actions, then ${g(t.from,t.planDigest)} to re-run it.`:`fix app state with --no-record actions. ${x(t)}`;case`caution`:return b({lead:`something already matches the recorded selector; a blind re-press may repeat the mistake.`,guidance:t});case`manual`:return b({lead:`no safe automated repair could be proven; inspect the screen and repair by hand.`,guidance:t});default:return}}function b(e){let{lead:t,guidance:n}=e;if(!n?.allowed)return`${t} ${x(n)}`;let r=`if you fixed app state with --no-record actions: ${g(n.from,n.planDigest)}`;return n.alternateFrom===void 0?`${t} ${r}.`:`${t} ${r}; ${`if you performed the step's intent as a recorded action: ${g(n.alternateFrom,n.planDigest)}`}.`}function x(e){return e&&!e.allowed&&e.reason?`This step cannot currently be resumed automatically (${e.reason}) — run a fresh full replay instead.`:`This step cannot currently be resumed automatically — run a fresh full replay instead.`}function S(e,t){if(typeof e!=`string`||e===`action-failure`)return[];let n=t;return n?[C(e,n.matchCount),...w(n.mismatches),...T(n.candidates)]:[]}function C(e,t){return`Target binding: ${e}${typeof t==`number`?` (matchCount ${t})`:``} — recorded target evidence did not verify.`}function w(e){return!Array.isArray(e)||e.length===0?[]:[` mismatches: ${e.slice(0,5).join(`; `)}`]}function T(e){return!Array.isArray(e)||e.length===0?[]:[` ${e.length} candidate(s) shared the recorded identity:`,...e.slice(0,5).map(e=>` ${A(e)}`)]}function E(e){let t=e;if(typeof t?.index!=`number`)return[];let n=t.source,r=typeof n?.path==`string`&&typeof n.line==`number`?` (${n.path}:${n.line})`:``;return[`Divergence at step ${t.index}${r}`]}function D(e){let t=e;return t?.state===`available`&&Array.isArray(t.refs)?O(t.refs,t.refsGeneration):t?.state===`unavailable`?[k(t)]:[]}function O(e,t){let n=e.slice(0,8).map(A),r=e.length-n.length;return[`Screen: ${e.length} actionable ref(s) captured (refsGeneration ${t}).`,...n,...r>0?[` ... ${r} more`]:[]]}function k(e){let t=typeof e.hint==`string`&&e.hint.length>0?` ${e.hint}`:``;return`Screen: unavailable (${String(e.reason??`unknown`)}).${t}`}function A(e){let t=e,n=typeof t.label==`string`?` "${t.label}"`:``;return` @${String(t.ref)} [${String(t.role)}]${n}`}function j(e,t){return Array.isArray(e)&&e.length>0?[`Suggestions:`,...e.slice(0,5).map(M)]:typeof t==`number`&&t>0?[`Suggestions: ${t} available (omitted at this response level; rerun with --json for the full report).`]:[]}function M(e){let t=e,n=typeof t.label==`string`?` "${t.label}"`:``;return` - [${String(t.basis)}]${n} ${String(t.selector)}`}function N(e,t){return e&&typeof e==`object`?[`Full report written to ${String(e.artifactPath)}.`]:t===!0?[`Full report exceeded the response budget and the overflow artifact could not be written.`]:[]}export{o as a,t as i,s as n,p as r,d as t};
@@ -1,11 +1,13 @@
1
- import{C as e}from"./sdk-contracts.js";import{r as t}from"./replay-divergence.js";import{n}from"./entities.js";import{n as r,t as i}from"./color.js";import{t as a}from"./status-markers.js";import o from"node:path";import s from"node:fs";import c from"node:os";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(`~/`)?o.join(c.homedir(),e.slice(2)):e;return o.resolve(process.cwd(),t)}async function ne(t){try{return await(t.startsWith(`file:`)?import(t):import(l(t).href))}catch(n){let r=n instanceof Error?n.message:String(n);throw new e(`INVALID_ARGS`,`Failed to load custom test reporter ${t}: ${r}`)}}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?o.join(e.artifactsDir,`attempt-${e.attempts}`,`replay-timing.ndjson`):void 0}function se(e){try{return s.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,i=0,a=()=>{t.clear(),n=!1,r=0},o=t=>{if(!e.liveProgress)return;let a=ve(i);i+=1;let o=be(t.test,e,a),s=O(n?r:0,e.columns,e.terminalReflowsOnResize!==!1);return n=!0,r=j(o),{text:`${s}${o}`,newline:!1}},s=i=>{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(r,e.columns,e.terminalReflowsOnResize!==!1)}${a}`:a;return n=!1,r=0,{text:o,newline:!0}};return{render(e){if(e.type===`suite-start`){a();return}return e.type===`test-step`?o(e):e.type===`test-result`?s(e):void 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 i=e.title?.trim(),a=o.basename(e.file),s=r(process.stderr),c=xe(n,{useColor:s}),l=`${D(e,{useColor:s})}${Se(e,{useColor:s})}`,u=`${c} `;return A(i?`${u}${A(i,Math.max(0,k(t.columns)-j(u)-j(l)))}${l}`:`${u}${a}${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: ${o.basename(e.file)}`:void 0}function Ee(e){let t=e.message?.replaceAll(/\s+/g,` `).trim();if(t)return` ${e.status===`fail`?`failed at: ${t}`:t}`}function x(e,t){let n=t.hint?.replaceAll(/\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=r(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=o.basename(e.file);return t||n}function T(e){return e.status===`pass`?a(`pass`,{passFormat:e.attempt&&e.attempt>1?`yellow`:`green`}):a(e.status===`fail`?`fail`:`skip`)}function E(e,t){return i(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,t,n){let r=n?Math.max(1,Math.ceil(e/k(t))):1,i=`\r\x1B[2K`;for(let e=1;e<r;e+=1)i+=`\x1B[1A\r\x1B[2K`;return i}function k(e){let t=typeof e==`function`?e():e;return typeof t==`number`&&Number.isFinite(t)&&t>0?Math.floor(t):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=G(e),n=o.basename(e.file);return`${t&&t.length>0?t:n}${K(e)}`}function Re(e){return`${G(e)??o.basename(e.file)}${K(e)}`}function L(e,t){return`artifactsDir`in e&&e.artifactsDir?`${t}: ${e.artifactsDir}`:void 0}function ze(e){return G(e)?`file: ${o.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 He(e){return e!==void 0}function G(e){let t=e.title?.trim();return t&&t.length>0?t:void 0}function K(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:q(r),columns:()=>r.stderr.columns,terminalReflowsOnResize:Ge()});let i=e.render(n);i&&(r.stderr.write(i.newline?`${i.text}\n`:i.text),n.type===`test-step`&&q(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||!q(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),Ke(e,n)},getExitCode:P}}function q(e){return e.stderr.isTTY&&!process.env.CI}function Ge(){return!process.env.TMUX&&!process.env.STY}function Ke(e,t){let n=e.tests.filter(F);t.stdout.write(`${qe(e,n.length)}\n`),et(e.tests.filter(Le),t),$e(n,t)}function qe(e,t){let n=typeof e.durationMs==`number`?e.durationMs:void 0,i=r();return`Test summary: ${Je(e.passed,{useColor:i})} ${Ye(e.total,{useColor:i})}${e.failed>0?`, ${e.failed} failed`:``}${t>0?`, ${t} flaky`:``}${n===void 0?``:` in ${Xe(n,{useColor:i})}`}`}function Je(e,t={}){let n=`${e} passed`;return t.useColor?i(n,`green`):n}function Ye(e,t={}){let n=`(${e})`;return t.useColor?i(n,`dim`):n}function Xe(e,t={}){let n=f(e);return t.useColor?i(n,`yellow`):n}function Ze(){return r()?i(`✓`,`yellow`):`✓`}function Qe(e){return[R(e.error),L(e,`artifacts`),B(e.error,`log`),z(e.error,`diagnostic`)].filter(He)}function $e(e,t){if(e.length!==0){t.stdout.write(`
1
+ import{C as e}from"./sdk-contracts.js";import{t}from"./output-common.js";import{r as n}from"./replay-divergence.js";import{n as r}from"./entities.js";import{n as i,t as a}from"./color.js";import{t as o}from"./status-markers.js";import s from"node:path";import c from"node:fs";import l from"node:os";import{pathToFileURL as u}from"node:url";const ee=[`onSuiteStart`,`onTestStart`,`onTestStep`,`onTestResult`,`onSuiteEnd`,`getExitCode`];async function te(e){let t=re(e.modulePath);return ae(await ne(await ie(t),e.modulePath)({spec:e.raw,modulePath:t}),e.modulePath)}function ne(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 re(e){if(e.startsWith(`file:`))return e;let t=e.startsWith(`~/`)?s.join(l.homedir(),e.slice(2)):e;return s.resolve(process.cwd(),t)}async function ie(t){try{return await(t.startsWith(`file:`)?import(t):import(u(t).href))}catch(n){let r=n instanceof Error?n.message:String(n);throw new e(`INVALID_ARGS`,`Failed to load custom test reporter ${t}: ${r}`)}}function ae(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 ee)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 d(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 oe(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 f(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=ce(e);if(!t)return[];let n=le(t);if(n.length===0)return[];let r=[],i=[];for(let e of n){if(ue(e)){r.push(e);continue}de(e)&&i.push({stop:e,start:se(r,e)})}return i}function se(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 ce(e){return e.artifactsDir?s.join(e.artifactsDir,`attempt-${e.attempts}`,`replay-timing.ndjson`):void 0}function le(e){try{return c.readFileSync(e,`utf8`).split(/\r?\n/).filter(e=>e.trim().length>0).flatMap(e=>{try{let t=JSON.parse(e);return v(t)?[t]:[]}catch{return[]}})}catch{return[]}}function ue(e){return e.type===`replay_action_start`&&m(e)&&h(e,`line`)&&g(e,`command`)&&(e.positionals===void 0||Array.isArray(e.positionals))}function de(e){return pe([e.type===`replay_action_stop`&&m(e)&&h(e,`line`)&&g(e,`command`),fe(e,`ok`),h(e,`durationMs`),g(e,`errorCode`),e.resultTiming===void 0||v(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 fe(e,t){return e[t]===void 0||typeof e[t]==`boolean`}function pe(e){return e.every(Boolean)}function _(e,t){return` ${e.ok===!1?`[FAIL] `:e.ok===!0?``:`[info] `}${he(t,e)}${me(e,t)}`}function me(e,t){let n=t?.line??e.line,r=[typeof n==`number`?`line ${n}`:``,typeof e.durationMs==`number`?d(e.durationMs):``,e.errorCode??``,e.resultTiming?`timing ${JSON.stringify(e.resultTiming)}`:``].filter(Boolean);return r.length>0?` (${r.join(`, `)})`:``}function he(e,t){return[ge(e?.command??t.command),...(e?.positionals??[]).map(_e)].join(` `)}function ge(e){return e??`unknown`}function _e(e){return typeof e==`string`?JSON.stringify(e):typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}function v(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}const y={interval:80,frames:[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`]},ve=y.interval;function ye(e={}){let t=new Set,n=!1,r=0,i=0,a=()=>{t.clear(),n=!1,r=0},o=t=>{if(!e.liveProgress)return;let a=be(i);i+=1;let o=Se(t.test,e,a),s=D(n?r:0,e.columns,e.terminalReflowsOnResize!==!1);return n=!0,r=A(o),{text:`${s}${o}`,newline:!1}},s=i=>{if(je(i.test)){let e=Me(i.test);if(t.has(e))return;t.add(e)}let a=xe(i.test,e);if(!a)return;let o=n?`${D(r,e.columns,e.terminalReflowsOnResize!==!1)}${a}`:a;return n=!1,r=0,{text:o,newline:!0}};return{render(e){if(e.type===`suite-start`){a();return}return e.type===`test-step`?o(e):e.type===`test-result`?s(e):void 0}}}function be(e){return y.frames[e%y.frames.length]??y.frames[0]}function xe(e,t={}){if(e.status===`fail`&&e.retrying)return;let n=[S(e)];return Te(n,e,t),t.verbose&&n.push(...Ie(e)),n.join(`
2
+ `)}function Se(e,t,n){let r=e.title?.trim(),a=s.basename(e.file),o=i(process.stderr),c=Ce(n,{useColor:o}),l=`${E(e,{useColor:o})}${we(e,{useColor:o})}`,u=`${c} `;return k(r?`${u}${k(r,Math.max(0,O(t.columns)-A(u)-A(l)))}${l}`:`${u}${a}${l}`,t.columns)}function Ce(e,t={}){return t.useColor?T(e,`blue`):e}function we(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 Te(e,t,n){if(Ee(t,n))return;let r=De(t),i=Oe(t);r&&e.push(r),i&&e.push(i),b(e,t),e.push(...x(t))}function Ee(e,t){return t.verbose===!0&&e.status===`fail`}function De(e){return e.status===`fail`&&e.title?.trim()?` file: ${s.basename(e.file)}`:void 0}function Oe(e){let t=e.message?.replaceAll(/\s+/g,` `).trim();if(t)return` ${e.status===`fail`?`failed at: ${t}`:t}`}function b(e,t){let n=t.hint?.replaceAll(/\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?``:` ${Ae(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`?o(`pass`,{passFormat:e.attempt&&e.attempt>1?`yellow`:`green`}):o(e.status===`fail`?`fail`:`skip`)}function T(e,t){return a(e,t,{validateStream:!1})}function E(e,t={}){if(typeof e.shardIndex!=`number`)return``;let n=typeof e.shardCount==`number`?e.shardCount:`?`,r=ke(e),i=` [${e.shardIndex+1}/${n}${r?` ${r}`:``}]`;return t.useColor?T(i,`dim`):i}function ke(e){return e.deviceName?.trim()||e.deviceId?.trim()||void 0}function Ae(e,t={}){let n=d(e.durationMs??0);return t.useColor?T(n,`yellow`):n}function je(e){return e.status===`pass`||e.status===`skip`||e.status===`fail`&&!e.retrying}function Me(e){let t=typeof e.shardIndex==`number`?e.shardIndex:``;return[e.status,e.index,e.total,e.file,e.title??``,t].join(`\0`)}function D(e,t,n){let r=n?Math.max(1,Math.ceil(e/O(t))):1,i=`\r\x1B[2K`;for(let e=1;e<r;e+=1)i+=`\x1B[1A\r\x1B[2K`;return i}function O(e){let t=typeof e==`function`?e():e;return typeof t==`number`&&Number.isFinite(t)&&t>0?Math.floor(t):80}function k(e,t){let n=O(t);return A(e)<=n?e:n<=0?``:n<=3?`.`.repeat(n):`${Pe(e,n-3)}...${Ne(e)?`\x1B[0m`:``}`}function A(e){let t=0;for(let n=0;n<e.length;){let r=j(e,n);if(r){n+=r.length;continue}t+=1,n+=1}return t}function Ne(e){return e.includes(`\x1B[`)}function Pe(e,t){if(t<=0)return``;let n=0,r=``;for(let i=0;i<e.length&&n<t;){let t=j(e,i);if(t){r+=t,i+=t.length;continue}r+=e[i],i+=1,n+=1}return r}function j(e,t){if(!e.startsWith(`\x1B[`,t))return null;for(let n=t+2;n<e.length;n+=1)if(Fe(e.charCodeAt(n)))return e.slice(t,n+1);return null}function Fe(e){return e>=64&&e<=126}function Ie(e){return e.status!==`pass`&&e.status!==`fail`||!e.artifactsDir||!e.attempt?[]:oe(e.status===`pass`?Le(e):Re(e)).map(e=>` ${e}`)}function Le(e){return{...M(e),status:`passed`,replayed:0,healed:0}}function Re(e){return{...M(e),status:`failed`,error:{code:`COMMAND_FAILED`,message:e.message??`Unknown test failure`}}}function M(e){return{file:e.file,title:e.title,durationMs:e.durationMs??0,attempts:e.attempt??1,artifactsDir:e.artifactsDir,session:e.session??``}}function N(e){return+(e.failed>0)}function ze(e){return e.status===`failed`}function P(e){return e.status===`passed`&&e.attempts>1}function F(e){let t=G(e),n=s.basename(e.file);return`${t&&t.length>0?t:n}${K(e)}`}function Be(e){return`${G(e)??s.basename(e.file)}${K(e)}`}function I(e,t){return`artifactsDir`in e&&e.artifactsDir?`${t}: ${e.artifactsDir}`:void 0}function Ve(e){return G(e)?`file: ${s.basename(e.file)}`:void 0}function L(e){return e.hint?`hint: ${e.hint}`:void 0}function R(e,t){return e.diagnosticId?`${t}: ${e.diagnosticId}`:void 0}function z(e,t){return e.logPath?`${t}: ${e.logPath}`:void 0}function B(e,t,n={}){n.includeMessage&&e.push(`errorMessage: ${t.message}`),U(e,L(t)),U(e,R(t,`diagnosticId`)),U(e,z(t,`logPath`)),n.includeDetails!==!1&&V(e,t,n.detailsIndent)}function V(e,t,n){let r=t.details?JSON.stringify(t.details,null,n):void 0;r&&e.push(`details: ${r}`)}function He(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 H(e){return((`warnings`in e?e.warnings:void 0)??[]).map(e=>`warning: ${t(e)}`)}function U(e,t){t&&e.push(t)}function W(e){return(Math.max(0,e)/1e3).toFixed(3)}function Ue(e){return e!==void 0}function G(e){let t=e.title?.trim();return t&&t.length>0?t:void 0}function K(e){if(!(`shardIndex`in e)||typeof e.shardIndex!=`number`)return``;let t=typeof e.shardCount==`number`?e.shardCount:`?`,n=We(e);return` [${e.shardIndex+1}/${t}${n?` ${n}`:``}]`}function We(e){return(`deviceName`in e?e.deviceName?.trim():void 0)||(`deviceId`in e?e.deviceId?.trim():void 0)||void 0}function Ge(){let e,t,n,r=!1,i=(n,r)=>{o(),t=n.type===`test-step`?n:void 0,e??=ye({verbose:r.verbose,liveProgress:q(r),columns:()=>r.stderr.columns,terminalReflowsOnResize:Ke()});let i=e.render(n);i&&(r.stderr.write(i.newline?`${i.text}\n`:i.text),n.type===`test-step`&&q(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)},ve),n.unref?.())},o=()=>{n&&=(clearInterval(n),void 0)},s=e=>{r||!q(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),qe(e,n)},getExitCode:N}}function q(e){return e.stderr.isTTY&&!process.env.CI}function Ke(){return!process.env.TMUX&&!process.env.STY}function qe(e,t){let n=e.tests.filter(P);t.stdout.write(`${Ye(e,n.length)}\n`),Je(e.tests,t),nt(e.tests.filter(ze),t),tt(n,t)}function Je(e,t){let n=e.map(e=>({result:e,lines:H(e)})).filter(e=>e.lines.length>0);if(n.length!==0){t.stdout.write(`
3
+ `),t.stdout.write(`Warnings:
4
+ `);for(let{result:e,lines:r}of n)for(let n of r)t.stdout.write(` ${F(e)}: ${n}\n`)}}function Ye(e,t){let n=typeof e.durationMs==`number`?e.durationMs:void 0,r=i();return`Test summary: ${Xe(e.passed,{useColor:r})} ${Ze(e.total,{useColor:r})}${e.failed>0?`, ${e.failed} failed`:``}${t>0?`, ${t} flaky`:``}${n===void 0?``:` in ${Qe(n,{useColor:r})}`}`}function Xe(e,t={}){let n=`${e} passed`;return t.useColor?a(n,`green`):n}function Ze(e,t={}){let n=`(${e})`;return t.useColor?a(n,`dim`):n}function Qe(e,t={}){let n=d(e);return t.useColor?a(n,`yellow`):n}function $e(){return i()?a(`✓`,`yellow`):`✓`}function et(e){return[L(e.error),I(e,`artifacts`),z(e.error,`log`),R(e.error,`diagnostic`)].filter(Ue)}function tt(e,t){if(e.length!==0){t.stdout.write(`
3
5
  `),t.stdout.write(`Flaky tests:
4
- `);for(let n of e){t.stdout.write(` ${Ze()} ${I(n)} after ${n.attempts} attempts${rt(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 et(e,t){if(e.length!==0){t.stdout.write(`
6
+ `);for(let n of e){t.stdout.write(` ${$e()} ${F(n)} after ${n.attempts} attempts${at(n)}\n`);for(let e of n.attemptFailures??[]){let n=typeof e.durationMs==`number`?` (${d(e.durationMs)})`:``;t.stdout.write(` attempt ${e.attempt} failed${n}: ${e.message}\n`)}}}}function nt(e,t){if(e.length!==0){t.stdout.write(`
5
7
  `),t.stdout.write(`Failures:
6
- `);for(let n of e)t.stdout.write(` ${I(n)}\n`),tt(n,t,` `)}}function tt(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 Qe(e))t.stdout.write(`${n}${r}\n`);if(nt(e,t,n),t.debug)for(let r of ae(e))t.stdout.write(`${n}${r}\n`)}function nt(e,n,r){let i=t(e.error?.details);if(i)for(let e of i.split(`
7
- `))n.stdout.write(`${r}${e}\n`)}function rt(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 it(e){let t=at(e);return{name:`junit`,onSuiteEnd:e=>ot(t,e),getExitCode:P}}function at(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 ot(t,n){let r=o.dirname(t);try{s.mkdirSync(r,{recursive:!0}),s.writeFileSync(t,st(n),`utf8`)}catch(n){let r=n instanceof Error?n.message:String(n);throw new e(`COMMAND_FAILED`,`Failed to write JUnit report to ${t}: ${r}`)}}function st(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(...ct(n));return t.push(` </testsuite>`),t.push(`</testsuites>`),`${t.join(`
8
- `)}\n`}function ct(e){let t=J(Re(e)),n=[` <testcase classname="${J(`${o.dirname(e.file)===`.`?e.file:o.dirname(e.file)}${K(e)}`)}" name="${t}" file="${J(e.file)}" time="${W(e.durationMs)}">`];e.status===`failed`?n.push(` <failure message="${J(e.error.message)}">${J(lt(e))}</failure>`):e.status===`skipped`&&n.push(` <skipped message="${J(e.message)}" />`);let r=ut(e);return r&&n.push(` <system-out>${J(r)}</system-out>`),n.push(` </testcase>`),n}function J(e){let t=e.replaceAll(/[^\t\n\r\u0020-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/gu,`�`);return n(t).replaceAll(` `,`&#9;`).replaceAll(`
9
- `,`&#10;`).replaceAll(`\r`,`&#13;`)}function lt(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(`
10
- `)}function ut(e){let t=[`status: ${e.status}`,`durationMs: ${e.durationMs}`];return dt(t,e),t.join(`
11
- `)}function dt(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`&&ft(e,t),U(e,F(t)?`flaky: true`:void 0)}function ft(e,t){e.push(`errorCode: ${t.error.code}`),V(e,t.error,{includeMessage:!0})}function pt(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 mt(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(X(n))return{kind:`custom`,modulePath:n,raw:n};let{name:r,value:i}=ht(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 ht(e){let t=e.indexOf(`:`);return t<0?{name:e.trim()}:{name:e.slice(0,t).trim(),value:e.slice(t+1)}}function X(e){return e.startsWith(`.`)||e.startsWith(`/`)||e.startsWith(`~`)||e.startsWith(`file:`)}const gt={"suite-start":`onSuiteStart`,"test-start":`onTestStart`,"test-step":`onTestStep`,"test-result":`onTestResult`};async function _t(e){let t=mt(e);return await Promise.all(t.map(St))}async function vt(e,t,n){for(let r of e)await r.onSuiteEnd?.(t,n)}function yt(e,t,n){let r=pt(t);if(!r)return;let i=gt[r.type];for(let t of e)try{let e=bt(t,r,n);e instanceof Promise&&e.catch(e=>Z(t,i,n,e))}catch(e){Z(t,i,n,e)}}function bt(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 xt(t,n){let r=P(n);for(let i of t){let t=i.getExitCode?.(n);if(t!==void 0){if(!Number.isInteger(t)||t<0||t>255)throw new e(`INVALID_ARGS`,`Test reporter ${i.name} getExitCode must return an integer from 0 to 255 or undefined.`);r=Math.max(r,t)}}return r}async function St(e){return e.kind===`custom`?await ee(e):e.name==="default"?We():it(e.outputPath)}async function Ct(e){let{suite:t,json:n,debug:r,verbose:i,reporter:a,reportJunit:o}=e,s=e.reporterRuntime??await Q({debug:r,verbose:i,reporter:a,reportJunit:o,json:n});await vt(s.reporters,t,s.context);let c=xt(s.reporters,t);if(n){let{printJson:e}=await import(`./json.js`);e({success:!0,data:t})}return c}async function Q(e){let t=await _t({reporters:e.reporter,reportJunit:e.reportJunit,json:e.json}),n=wt({debug:e.debug,verbose:e.verbose});return{reporters:t,context:n,onProgress(e){yt(t,e,n)}}}function wt(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,Ct as renderReplayTestResponse};
8
+ `);for(let n of e)t.stdout.write(` ${F(n)}\n`),rt(n,t,` `)}}function rt(e,t,n){let r=Ve(e);r&&t.stdout.write(`${n}${r}\n`),t.stdout.write(`${n}${e.error?.message??`Unknown test failure`}\n`);for(let r of et(e))t.stdout.write(`${n}${r}\n`);if(it(e,t,n),t.debug)for(let r of f(e))t.stdout.write(`${n}${r}\n`)}function it(e,t,r){let i=n(e.error?.details);if(i)for(let e of i.split(`
9
+ `))t.stdout.write(`${r}${e}\n`)}function at(e){let t=[typeof e.finalAttemptDurationMs==`number`?`passed attempt ${d(e.finalAttemptDurationMs)}`:``,e.durationMs>0?`total ${d(e.durationMs)}`:``].filter(Boolean);return t.length>0?` (${t.join(`, `)})`:``}function ot(e){let t=st(e);return{name:`junit`,onSuiteEnd:e=>ct(t,e),getExitCode:N}}function st(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 ct(t,n){let r=s.dirname(t);try{c.mkdirSync(r,{recursive:!0}),c.writeFileSync(t,lt(n),`utf8`)}catch(n){let r=n instanceof Error?n.message:String(n);throw new e(`COMMAND_FAILED`,`Failed to write JUnit report to ${t}: ${r}`)}}function lt(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(...ut(n));return t.push(` </testsuite>`),t.push(`</testsuites>`),`${t.join(`
10
+ `)}\n`}function ut(e){let t=J(Be(e)),n=[` <testcase classname="${J(`${s.dirname(e.file)===`.`?e.file:s.dirname(e.file)}${K(e)}`)}" name="${t}" file="${J(e.file)}" time="${W(e.durationMs)}">`];e.status===`failed`?n.push(` <failure message="${J(e.error.message)}">${J(dt(e))}</failure>`):e.status===`skipped`&&n.push(` <skipped message="${J(e.message)}" />`);let r=ft(e);return r&&n.push(` <system-out>${J(r)}</system-out>`),n.push(` </testcase>`),n}function J(e){let t=e.replaceAll(/[^\t\n\r\u0020-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/gu,`�`);return r(t).replaceAll(` `,`&#9;`).replaceAll(`
11
+ `,`&#10;`).replaceAll(`\r`,`&#13;`)}function dt(e){let t=[e.error.message];return B(t,e.error,{includeDetails:!1}),U(t,I(e,`artifactsDir`)),V(t,e.error,2),t.join(`
12
+ `)}function ft(e){let t=[`status: ${e.status}`,`durationMs: ${e.durationMs}`];return pt(t,e),t.join(`
13
+ `)}function pt(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 H(t))e.push(n);U(e,I(t,`artifactsDir`)),He(e,t),t.status===`failed`&&mt(e,t),U(e,P(t)?`flaky: true`:void 0)}function mt(e,t){e.push(`errorCode: ${t.error.code}`),B(e,t.error,{includeMessage:!0})}function ht(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 gt(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(vt(n))return{kind:`custom`,modulePath:n,raw:n};let{name:r,value:i}=_t(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 _t(e){let t=e.indexOf(`:`);return t<0?{name:e.trim()}:{name:e.slice(0,t).trim(),value:e.slice(t+1)}}function vt(e){return e.startsWith(`.`)||e.startsWith(`/`)||e.startsWith(`~`)||e.startsWith(`file:`)}const yt={"suite-start":`onSuiteStart`,"test-start":`onTestStart`,"test-step":`onTestStep`,"test-result":`onTestResult`};async function bt(e){let t=gt(e);return await Promise.all(t.map(wt))}async function xt(e,t,n){for(let r of e)await r.onSuiteEnd?.(t,n)}function X(e,t,n){let r=ht(t);if(!r)return;let i=yt[r.type];for(let t of e)try{let e=St(t,r,n);e instanceof Promise&&e.catch(e=>Z(t,i,n,e))}catch(e){Z(t,i,n,e)}}function St(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 Ct(t,n){let r=N(n);for(let i of t){let t=i.getExitCode?.(n);if(t!==void 0){if(!Number.isInteger(t)||t<0||t>255)throw new e(`INVALID_ARGS`,`Test reporter ${i.name} getExitCode must return an integer from 0 to 255 or undefined.`);r=Math.max(r,t)}}return r}async function wt(e){return e.kind===`custom`?await te(e):e.name==="default"?Ge():ot(e.outputPath)}async function Tt(e){let{suite:t,json:n,debug:r,verbose:i,reporter:a,reportJunit:o}=e,s=e.reporterRuntime??await Q({debug:r,verbose:i,reporter:a,reportJunit:o,json:n});await xt(s.reporters,t,s.context);let c=Ct(s.reporters,t);if(n){let{printJson:e}=await import(`./json.js`);e({success:!0,data:t})}return c}async function Q(e){let t=await bt({reporters:e.reporter,reportJunit:e.reportJunit,json:e.json}),n=Et({debug:e.debug,verbose:e.verbose});return{reporters:t,context:n,onProgress(e){X(t,e,n)}}}function Et(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,Tt as renderReplayTestResponse};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime.js";import"./capture.js";import{t}from"./snapshot-capture-annotations.js";import{m as n}from"./sdk-device.js";import{n as r,r as i}from"./success-text.js";import{n as a,t as o}from"./deploy-result-target.js";var s=e({serializeCloseResult:()=>g,serializeDeployResult:()=>p,serializeDevice:()=>d,serializeInstallFromSourceResult:()=>m,serializeOpenResult:()=>h,serializeSessionListEntry:()=>u,serializeSnapshotResult:()=>f});function c(e,t={}){let n=t.includeSerial??!0,r=l(e);return{platform:e.platform,target:e.target,device:e.name,id:e.id,...e.platform===`ios`?{device_udid:e.ios?.udid??e.id,ios_simulator_device_set:e.ios?.simulatorSetPath??null}:{},...n&&r?{serial:r}:{}}}function l(e){return n(e.platform)?e.identifiers.serial??e.id:void 0}function u(e){return{name:e.name,...e.address?{address:e.address}:{},...e.sessionStateDir?{sessionStateDir:e.sessionStateDir}:{},...e.runnerLogPath?{runnerLogPath:e.runnerLogPath}:{},...c(e.device,{includeSerial:!1}),createdAt:e.createdAt}}function d(e){return{platform:e.platform,...e.appleOs?{appleOs:e.appleOs}:{},id:e.id,name:e.name,kind:e.kind,target:e.target,...typeof e.booted==`boolean`?{booted:e.booted}:{},...e.claimedBy?{claimedBy:e.claimedBy}:{}}}function f(e){return{nodes:e.nodes,...e.truncated===void 0?{}:{truncated:e.truncated},...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.visibility?{visibility:e.visibility}:{},...t({...e,...e.snapshotQuality?{quality:e.snapshotQuality}:{}}),...e.unchanged?{unchanged:e.unchanged}:{},...e.snapshotDiagnostics?{snapshotDiagnostics:e.snapshotDiagnostics}:{},...e.fallbackScreenshotPath?{fallbackScreenshotPath:e.fallbackScreenshotPath}:{},...e.refsGeneration===void 0?{}:{refsGeneration:e.refsGeneration}}}function p(e){return i({app:e.app,appPath:e.appPath,platform:e.platform,...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.package?{package:e.package}:{}},`Installed: ${o(e)}`)}function m(e){return i({launchTarget:e.launchTarget,...e.appName?{appName:e.appName}:{},...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.packageName?{package:e.packageName}:{},...e.installablePath?{installablePath:e.installablePath}:{},...e.archivePath?{archivePath:e.archivePath}:{},...e.materializationId?{materializationId:e.materializationId}:{},...e.materializationExpiresAt?{materializationExpiresAt:e.materializationExpiresAt}:{}},`Installed: ${a(e)}`)}function h(e){let t=e.appName??e.appBundleId??e.session;return i({session:e.session,...e.warnings?.length?{warnings:e.warnings}:{},...e.sessionStateDir?{sessionStateDir:e.sessionStateDir}:{},...e.runnerLogPath?{runnerLogPath:e.runnerLogPath}:{},...e.requestLogPath?{requestLogPath:e.requestLogPath}:{},...e.eventLogPath?{eventLogPath:e.eventLogPath}:{},...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.selection?{selection:e.selection}:{},...e.startup?{startup:e.startup}:{},...e.runtime?{runtime:e.runtime}:{},...e.device?c(e.device):{},...e.snapshot?{snapshot:e.snapshot}:{},...e.initialSnapshotError?{initialSnapshotError:e.initialSnapshotError}:{}},t?`Opened: ${t}`:`Opened`)}function g(e){return{session:e.session,...e.shutdown?{shutdown:e.shutdown}:{},...`provider`in e&&e.provider?{provider:e.provider}:{},...r(e.session?`Closed: ${e.session}`:`Closed`)}}export{d as n,s as t};
1
+ import{r as e}from"./rolldown-runtime.js";import"./capture.js";import{t}from"./snapshot-capture-annotations.js";import{m as n}from"./sdk-device.js";import{i as r,r as i}from"./success-text.js";import{n as a,t as o}from"./deploy-result-target.js";var s=e({serializeCloseResult:()=>g,serializeDeployResult:()=>p,serializeDevice:()=>d,serializeInstallFromSourceResult:()=>m,serializeOpenResult:()=>h,serializeSessionListEntry:()=>u,serializeSnapshotResult:()=>f});function c(e,t={}){let n=t.includeSerial??!0,r=l(e);return{platform:e.platform,target:e.target,device:e.name,id:e.id,...e.platform===`ios`?{device_udid:e.ios?.udid??e.id,ios_simulator_device_set:e.ios?.simulatorSetPath??null}:{},...n&&r?{serial:r}:{}}}function l(e){return n(e.platform)?e.identifiers.serial??e.id:void 0}function u(e){return{name:e.name,...e.address?{address:e.address}:{},...e.sessionStateDir?{sessionStateDir:e.sessionStateDir}:{},...e.runnerLogPath?{runnerLogPath:e.runnerLogPath}:{},...c(e.device,{includeSerial:!1}),createdAt:e.createdAt}}function d(e){return{platform:e.platform,...e.appleOs?{appleOs:e.appleOs}:{},id:e.id,name:e.name,kind:e.kind,target:e.target,...typeof e.booted==`boolean`?{booted:e.booted}:{},...e.claimedBy?{claimedBy:e.claimedBy}:{}}}function f(e){return{nodes:e.nodes,...e.truncated===void 0?{}:{truncated:e.truncated},...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.visibility?{visibility:e.visibility}:{},...t({...e,...e.snapshotQuality?{quality:e.snapshotQuality}:{}}),...e.unchanged?{unchanged:e.unchanged}:{},...e.snapshotDiagnostics?{snapshotDiagnostics:e.snapshotDiagnostics}:{},...e.fallbackScreenshotPath?{fallbackScreenshotPath:e.fallbackScreenshotPath}:{},...e.refsGeneration===void 0?{}:{refsGeneration:e.refsGeneration}}}function p(e){return r({app:e.app,appPath:e.appPath,platform:e.platform,...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.package?{package:e.package}:{}},`Installed: ${o(e)}`)}function m(e){return r({launchTarget:e.launchTarget,...e.appName?{appName:e.appName}:{},...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.packageName?{package:e.packageName}:{},...e.installablePath?{installablePath:e.installablePath}:{},...e.archivePath?{archivePath:e.archivePath}:{},...e.materializationId?{materializationId:e.materializationId}:{},...e.materializationExpiresAt?{materializationExpiresAt:e.materializationExpiresAt}:{}},`Installed: ${a(e)}`)}function h(e){let t=e.appName??e.appBundleId??e.session;return r({session:e.session,...e.warnings?.length?{warnings:e.warnings}:{},...e.sessionStateDir?{sessionStateDir:e.sessionStateDir}:{},...e.runnerLogPath?{runnerLogPath:e.runnerLogPath}:{},...e.requestLogPath?{requestLogPath:e.requestLogPath}:{},...e.eventLogPath?{eventLogPath:e.eventLogPath}:{},...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.selection?{selection:e.selection}:{},...e.startup?{startup:e.startup}:{},...e.runtime?{runtime:e.runtime}:{},...e.device?c(e.device):{},...e.snapshot?{snapshot:e.snapshot}:{},...e.initialSnapshotError?{initialSnapshotError:e.initialSnapshotError}:{}},t?`Opened: ${t}`:`Opened`)}function g(e){return{session:e.session,...e.shutdown?{shutdown:e.shutdown}:{},...`provider`in e&&e.provider?{provider:e.provider}:{},...i(e.session?`Closed: ${e.session}`:`Closed`)}}export{d as n,s as t};
@@ -1,2 +1,2 @@
1
- import{A as e,C as t,T as n}from"./sdk-contracts.js";import{u as r}from"./sdk-device.js";import{i,o as a,r as o,s,t as ee}from"./apple-runner-platform.js";import c from"node:path";import l from"node:fs";import u from"node:crypto";import te from"node:os";let d;function ne(e){if(d&&d!==e)throw Error(`Apple runner host is already bound to a different implementation.`);d=e}function f(){if(!d)throw Error(`Apple runner host is not bound. Construct the client via createAppleRunnerClient() before using runner operations.`);return d}const re=(e,t,n)=>f().runCmdStreaming(e,t,n),ie=(e,t,n)=>f().runCmdSync(e,t,n),ae=(e,t,n)=>f().runCmdBackground(e,t,n),oe=(e,t,n)=>f().requireExecSuccess(e,t,n),se=e=>f().isCommandTimeoutError(e),ce=e=>f().shellQuote(e),le=e=>f().emitDiagnostic(e),ue=(e,t,n)=>f().withDiagnosticTimer(e,t,n),de=(e,t,n)=>f().retryWithPolicy(e,t,n),p=e=>f().isEnvTruthy(e),fe=e=>f().isProcessAlive(e),pe=e=>f().isProcessGroupAlive(e),me=e=>f().readProcessStartTime(e),he=e=>f().readProcessCommand(e),ge=(e,t)=>f().signalPidsBestEffort(e,t),_e=(e,t)=>f().signalProcessGroupBestEffort(e,t),m=()=>f().findProjectRoot(),ve=e=>f().readVersion(e),ye=e=>f().acquireProcessLock(e),be=(e,t,n)=>f().withKeyedLock(e,t,n),xe=e=>f().publishFileSync(e),Se=e=>f().classifyOwnerLiveness(e),Ce=e=>f().createTtlMemo(e),h=e=>f().parseBooleanLiteral(e),g=e=>f().isRecord(e),_=e=>f().resolveIosSimulatorDeviceSetPath(e),v=e=>f().emitRequestProgress(e),y=e=>f().getRequestSignal(e),b=e=>f().isRequestCanceled(e),x=e=>f().classifyBootFailure(e),S=e=>f().bootFailureHint(e),C=(e,t,n)=>f().runAppleToolCommand(e,t,n),w=(e,t)=>f().runXcrun(e,t),T=(e,t)=>f().readApplePlistJson(e,t),E=(e,t)=>f().buildSimctlArgsForDevice(e,t),D=e=>f().resolveIosPhysicalDeviceControl(e),O=(e,t)=>f().visitXmlPlistEntries(e,t),k=()=>f().leaseOwnerStateDir(),A=e=>f().hasDeviceClaimAuthority(e),j={fromTimeoutMs(e,t){return f().deadlineFromTimeoutMs(e,t)}},we=c.join(`apple`,`runner`,`AgentDeviceRunner`),Te=c.join(`dist`,`apple`,`runner`,`AgentDeviceRunner`),Ee=c.join(`apple`,`snapshot-presentation`),De=c.join(`dist`,`apple`,`snapshot-presentation`);function M(e){let t=c.join(e,we);return l.existsSync(t)?t:c.join(e,Te)}function Oe(e){return c.join(M(e),`AgentDeviceRunner.xcodeproj`)}function ke(e){let t=c.join(e,Ee);return l.existsSync(t)?t:c.join(e,De)}const Ae=new Set([`.build`,`.swiftpm`,`xcuserdata`]),je=new Set([`.build`,`.swiftpm`,`SnapshotPresentationConformance`,`Tests`,`xcuserdata`]),N=new Map;function Me(e){let t=[{path:M(e),ignoredDirectoryNames:Ae},{path:ke(e),ignoredDirectoryNames:je}],n=Pe(t),r=Ne(e,n),i=JSON.stringify(t.map(({path:e})=>e)),a=N.get(i);if(a?.fileStatsFingerprint===r)return a.sourceFingerprint;let o=u.createHash(`sha256`);for(let t of n){let n=c.relative(e,t);o.update(n),o.update(`\0`),o.update(l.readFileSync(t)),o.update(`\0`)}let s=o.digest(`hex`);return N.set(i,{fileStatsFingerprint:r,sourceFingerprint:s}),s}function Ne(e,t){let n=u.createHash(`sha256`);for(let r of t){let t=c.relative(e,r),i=l.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 Pe(e){return[...new Set(e.flatMap(({path:e,ignoredDirectoryNames:t})=>Fe(e,t)))].sort((e,t)=>e.localeCompare(t))}function Fe(e,t){return l.existsSync(e)?P(e,t):[]}function P(e,t){let n=[];for(let r of l.readdirSync(e,{withFileTypes:!0})){let i=c.join(e,r.name);r.isDirectory()?t.has(r.name)||n.push(...P(i,t)):r.isFile()&&Ie(r.name,i)&&n.push(i)}return n}function Ie(e,t){return e===`project.pbxproj`?t.includes(`${c.sep}.xcodeproj${c.sep}`):[`.jpg`,`.json`,`.png`,`.swift`,`.m`,`.h`,`.plist`,`.entitlements`,`.xctestplan`,`.xcconfig`,`.storyboard`,`.xib`].includes(c.extname(e))}const Le=c.join(te.homedir(),`.agent-device`,`apple-runner`),Re=`.agent-device-runner-cache.json`,ze=[`-IDEPackageSupportDisableManifestSandbox=1`,`-IDEPackageSupportDisablePluginExecutionSandbox=1`,`ENABLE_USER_SCRIPT_SANDBOXING=NO`];function Be(e,t){return{deadline:e!==void 0&&Number.isFinite(e)?j.fromTimeoutMs(Math.max(0,e)):void 0,signal:t}}function Ve(e,t){let n=e?.deadline;if(!n)return;let r=Math.floor(n.remainingMs());if(r<=0)throw F(t);return r}function F(e){return new t(`COMMAND_FAILED`,`The Apple runner budget ran out before this step began`,{phase:e,reason:`runner_phase_budget_exhausted`,retriable:!0})}function He(e){let t=e?.deadline,r=j.fromTimeoutMs(Math.min(45e3,t?t.remainingMs():1/0));return{attemptTimeoutMs:()=>Math.min(ee,Math.floor(r.remainingMs())),throwIfCanceled:()=>{if(e?.signal?.aborted)throw n({phase:`apple_toolchain_probe`})}}}function I(e){return e?.trim()??``}function L(e=process.env){return I(e.AGENT_DEVICE_IOS_BUNDLE_ID)||I(e.AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID)||`com.callstack.agentdevice.runner`}function R(e=process.env){return I(e.AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID)||`${L(e)}.uitests`}function Ue(e=process.env){let t=L(e),n=R(e);return Array.from(new Set([I(e.AGENT_DEVICE_IOS_RUNNER_CONTAINER_BUNDLE_ID),`${n}.xctrunner`,t].filter(e=>e.length>0)))}const We=Ue(process.env);function Ge(e,t=m(),n){let r=a(e);return{schemaVersion:2,packageVersion:ve(t),runnerSourceFingerprint:Me(t),...Ke(s(r,e.kind),n),platformName:r,deviceKind:e.kind,target:e.target??`mobile`,buildDestinationFamily:o(e),runnerBundleBuildSettings:Z(process.env),runnerSigningBuildSettings:X(process.env,e.kind===`device`,e),runnerPerformanceBuildSettings:Q(),runnerSandboxBuildArgs:$()}}let z;function B(){return z??=Ce(),z}function Ke(e,t){let n=He(t);n.throwIfCanceled();let r=B().get(e);if(r)return r;let i=qe(e,n);if(!i.ok)throw Je(i.failures);return B().set(e,i.value),i.value}function qe(e,t){let n=Ze(V(`xcodebuild`,[`-version`],t)),r=V(`xcrun`,[`--sdk`,e,`--show-sdk-version`],t),i=V(`xcrun`,[`--sdk`,e,`--show-sdk-build-version`],t);return!n.ok||!r.ok||!i.ok?{ok:!1,failures:[n,r,i].flatMap(e=>e.ok?[]:[e.failure])}:{ok:!0,value:{xcodeVersion:n.value.version,xcodeBuildVersion:n.value.buildVersion,sdkName:e,sdkVersion:r.value,sdkBuildVersion:i.value}}}function Je(e){return new t(`COMMAND_FAILED`,`Could not read the Xcode toolchain versions the Apple runner cache is keyed on (${e.map(e=>`${e.probe}: ${e.detail}`).join(`; `)})`,{reason:`apple_toolchain_probe_unavailable`,retriable:!0,probes:e,hint:"The Apple runner cache is keyed on the toolchain version, so a cache decision cannot be made without it. Retry once the host is less loaded, or check `xcode-select -p` and `xcodebuild -version`."})}function V(t,n,r){let i=[t,...n].join(` `),a;try{a=Ye(t,n,r)}catch(t){if(r.throwIfCanceled(),e(t)||Xe(t))throw t;return U(i,`probe_error`,t instanceof Error?t.message:`${t}`)}if(a.exitCode!==0)return U(i,`nonzero_exit`,`exit ${a.exitCode}${a.stderr.trim()?`: ${a.stderr.trim()}`:``}`);let o=a.stdout.trim();return o?{ok:!0,value:o}:U(i,`empty_output`,`no output`)}function Ye(e,t,n){try{return H(e,t,n)}catch(r){if(!se(r))throw r;return H(e,t,n)}}function H(e,t,n){n.throwIfCanceled();let r=n.attemptTimeoutMs();if(r<=0)throw F(`apple_toolchain_probe`);return ie(e,t,{allowFailure:!0,timeoutMs:r,maxBuffer:131072})}function Xe(e){return e instanceof t&&e.details?.reason===`runner_phase_budget_exhausted`}function Ze(e){if(!e.ok)return e;let t=e.value.match(/^Xcode\s+(.+)$/m)?.[1]?.trim(),n=e.value.match(/^Build version\s+(.+)$/m)?.[1]?.trim();return!t||!n?U(`xcodebuild -version`,`unparsable_output`,`unrecognized output: ${e.value.replaceAll(`
1
+ import{C as e,T as t,j as n}from"./sdk-contracts.js";import{u as r}from"./sdk-device.js";import{i,o as a,r as o,s,t as ee}from"./apple-runner-platform.js";import c from"node:path";import l from"node:fs";import u from"node:crypto";import te from"node:os";let d;function ne(e){if(d&&d!==e)throw Error(`Apple runner host is already bound to a different implementation.`);d=e}function f(){if(!d)throw Error(`Apple runner host is not bound. Construct the client via createAppleRunnerClient() before using runner operations.`);return d}const re=(e,t,n)=>f().runCmdStreaming(e,t,n),ie=(e,t,n)=>f().runCmdSync(e,t,n),ae=(e,t,n)=>f().runCmdBackground(e,t,n),oe=(e,t,n)=>f().requireExecSuccess(e,t,n),se=e=>f().isCommandTimeoutError(e),ce=e=>f().shellQuote(e),le=e=>f().emitDiagnostic(e),ue=(e,t,n)=>f().withDiagnosticTimer(e,t,n),de=(e,t,n)=>f().retryWithPolicy(e,t,n),p=e=>f().isEnvTruthy(e),fe=e=>f().isProcessAlive(e),pe=e=>f().isProcessGroupAlive(e),me=e=>f().readProcessStartTime(e),he=e=>f().readProcessCommand(e),ge=(e,t)=>f().signalPidsBestEffort(e,t),_e=(e,t)=>f().signalProcessGroupBestEffort(e,t),m=()=>f().findProjectRoot(),ve=e=>f().readVersion(e),ye=e=>f().acquireProcessLock(e),be=(e,t,n)=>f().withKeyedLock(e,t,n),xe=e=>f().publishFileSync(e),Se=e=>f().classifyOwnerLiveness(e),Ce=e=>f().createTtlMemo(e),h=e=>f().parseBooleanLiteral(e),g=e=>f().isRecord(e),_=e=>f().resolveIosSimulatorDeviceSetPath(e),v=e=>f().emitRequestProgress(e),y=e=>f().getRequestSignal(e),b=e=>f().isRequestCanceled(e),x=e=>f().classifyBootFailure(e),S=e=>f().bootFailureHint(e),C=(e,t,n)=>f().runAppleToolCommand(e,t,n),w=(e,t)=>f().runXcrun(e,t),T=(e,t)=>f().readApplePlistJson(e,t),E=(e,t)=>f().buildSimctlArgsForDevice(e,t),D=e=>f().resolveIosPhysicalDeviceControl(e),O=(e,t)=>f().visitXmlPlistEntries(e,t),k=()=>f().leaseOwnerStateDir(),A=e=>f().hasDeviceClaimAuthority(e),j={fromTimeoutMs(e,t){return f().deadlineFromTimeoutMs(e,t)}},we=c.join(`apple`,`runner`,`AgentDeviceRunner`),Te=c.join(`dist`,`apple`,`runner`,`AgentDeviceRunner`),Ee=c.join(`apple`,`snapshot-presentation`),De=c.join(`dist`,`apple`,`snapshot-presentation`);function M(e){let t=c.join(e,we);return l.existsSync(t)?t:c.join(e,Te)}function Oe(e){return c.join(M(e),`AgentDeviceRunner.xcodeproj`)}function ke(e){let t=c.join(e,Ee);return l.existsSync(t)?t:c.join(e,De)}const Ae=new Set([`.build`,`.swiftpm`,`xcuserdata`]),je=new Set([`.build`,`.swiftpm`,`SnapshotPresentationConformance`,`Tests`,`xcuserdata`]),N=new Map;function Me(e){let t=[{path:M(e),ignoredDirectoryNames:Ae},{path:ke(e),ignoredDirectoryNames:je}],n=Pe(t),r=Ne(e,n),i=JSON.stringify(t.map(({path:e})=>e)),a=N.get(i);if(a?.fileStatsFingerprint===r)return a.sourceFingerprint;let o=u.createHash(`sha256`);for(let t of n){let n=c.relative(e,t);o.update(n),o.update(`\0`),o.update(l.readFileSync(t)),o.update(`\0`)}let s=o.digest(`hex`);return N.set(i,{fileStatsFingerprint:r,sourceFingerprint:s}),s}function Ne(e,t){let n=u.createHash(`sha256`);for(let r of t){let t=c.relative(e,r),i=l.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 Pe(e){return[...new Set(e.flatMap(({path:e,ignoredDirectoryNames:t})=>Fe(e,t)))].sort((e,t)=>e.localeCompare(t))}function Fe(e,t){return l.existsSync(e)?P(e,t):[]}function P(e,t){let n=[];for(let r of l.readdirSync(e,{withFileTypes:!0})){let i=c.join(e,r.name);r.isDirectory()?t.has(r.name)||n.push(...P(i,t)):r.isFile()&&Ie(r.name,i)&&n.push(i)}return n}function Ie(e,t){return e===`project.pbxproj`?t.includes(`${c.sep}.xcodeproj${c.sep}`):[`.jpg`,`.json`,`.png`,`.swift`,`.m`,`.h`,`.plist`,`.entitlements`,`.xctestplan`,`.xcconfig`,`.storyboard`,`.xib`].includes(c.extname(e))}const Le=c.join(te.homedir(),`.agent-device`,`apple-runner`),Re=`.agent-device-runner-cache.json`,ze=[`-IDEPackageSupportDisableManifestSandbox=1`,`-IDEPackageSupportDisablePluginExecutionSandbox=1`,`ENABLE_USER_SCRIPT_SANDBOXING=NO`];function Be(e,t){return{deadline:e!==void 0&&Number.isFinite(e)?j.fromTimeoutMs(Math.max(0,e)):void 0,signal:t}}function Ve(e,t){let n=e?.deadline;if(!n)return;let r=Math.floor(n.remainingMs());if(r<=0)throw F(t);return r}function F(t){return new e(`COMMAND_FAILED`,`The Apple runner budget ran out before this step began`,{phase:t,reason:`runner_phase_budget_exhausted`,retriable:!0})}function He(e){let n=e?.deadline,r=j.fromTimeoutMs(Math.min(45e3,n?n.remainingMs():1/0));return{attemptTimeoutMs:()=>Math.min(ee,Math.floor(r.remainingMs())),throwIfCanceled:()=>{if(e?.signal?.aborted)throw t({phase:`apple_toolchain_probe`})}}}function I(e){return e?.trim()??``}function L(e=process.env){return I(e.AGENT_DEVICE_IOS_BUNDLE_ID)||I(e.AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID)||`com.callstack.agentdevice.runner`}function R(e=process.env){return I(e.AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID)||`${L(e)}.uitests`}function Ue(e=process.env){let t=L(e),n=R(e);return Array.from(new Set([I(e.AGENT_DEVICE_IOS_RUNNER_CONTAINER_BUNDLE_ID),`${n}.xctrunner`,t].filter(e=>e.length>0)))}const We=Ue(process.env);function Ge(e,t=m(),n){let r=a(e);return{schemaVersion:2,packageVersion:ve(t),runnerSourceFingerprint:Me(t),...Ke(s(r,e.kind),n),platformName:r,deviceKind:e.kind,target:e.target??`mobile`,buildDestinationFamily:o(e),runnerBundleBuildSettings:Z(process.env),runnerSigningBuildSettings:X(process.env,e.kind===`device`,e),runnerPerformanceBuildSettings:Q(),runnerSandboxBuildArgs:$()}}let z;function B(){return z??=Ce(),z}function Ke(e,t){let n=He(t);n.throwIfCanceled();let r=B().get(e);if(r)return r;let i=qe(e,n);if(!i.ok)throw Je(i.failures);return B().set(e,i.value),i.value}function qe(e,t){let n=Ze(V(`xcodebuild`,[`-version`],t)),r=V(`xcrun`,[`--sdk`,e,`--show-sdk-version`],t),i=V(`xcrun`,[`--sdk`,e,`--show-sdk-build-version`],t);return!n.ok||!r.ok||!i.ok?{ok:!1,failures:[n,r,i].flatMap(e=>e.ok?[]:[e.failure])}:{ok:!0,value:{xcodeVersion:n.value.version,xcodeBuildVersion:n.value.buildVersion,sdkName:e,sdkVersion:r.value,sdkBuildVersion:i.value}}}function Je(t){return new e(`COMMAND_FAILED`,`Could not read the Xcode toolchain versions the Apple runner cache is keyed on (${t.map(e=>`${e.probe}: ${e.detail}`).join(`; `)})`,{reason:`apple_toolchain_probe_unavailable`,retriable:!0,probes:t,hint:"The Apple runner cache is keyed on the toolchain version, so a cache decision cannot be made without it. Retry once the host is less loaded, or check `xcode-select -p` and `xcodebuild -version`."})}function V(e,t,r){let i=[e,...t].join(` `),a;try{a=Ye(e,t,r)}catch(e){if(r.throwIfCanceled(),n(e)||Xe(e))throw e;return U(i,`probe_error`,e instanceof Error?e.message:`${e}`)}if(a.exitCode!==0)return U(i,`nonzero_exit`,`exit ${a.exitCode}${a.stderr.trim()?`: ${a.stderr.trim()}`:``}`);let o=a.stdout.trim();return o?{ok:!0,value:o}:U(i,`empty_output`,`no output`)}function Ye(e,t,n){try{return H(e,t,n)}catch(r){if(!se(r))throw r;return H(e,t,n)}}function H(e,t,n){n.throwIfCanceled();let r=n.attemptTimeoutMs();if(r<=0)throw F(`apple_toolchain_probe`);return ie(e,t,{allowFailure:!0,timeoutMs:r,maxBuffer:131072})}function Xe(t){return t instanceof e&&t.details?.reason===`runner_phase_budget_exhausted`}function Ze(e){if(!e.ok)return e;let t=e.value.match(/^Xcode\s+(.+)$/m)?.[1]?.trim(),n=e.value.match(/^Build version\s+(.+)$/m)?.[1]?.trim();return!t||!n?U(`xcodebuild -version`,`unparsable_output`,`unrecognized output: ${e.value.replaceAll(`
2
2
  `,` `)}`):{ok:!0,value:{version:t,buildVersion:n}}}function U(e,t,n){return{ok:!1,failure:{probe:e,reason:t,detail:n.length>200?`${n.slice(0,200)}…`:n}}}function Qe(e,t){let n=process.env.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim();if(n)return c.resolve(n);let r=W(t),i=$e(e);return c.join(i,r)}function $e(e){return c.join(Le,`derived`,i(e))}function W(e){return`cache-${u.createHash(`sha256`).update(J(G(e))).digest(`hex`).slice(0,16)}`}function G(e){let{artifacts:t,packageVersion:n,...r}=e;return r}function et(e,t){let n=G(e),r=G(t);return[...new Set([...Object.keys(n),...Object.keys(r)])].sort((e,t)=>e.localeCompare(t)).flatMap(e=>{let t=K(n[e]),i=K(r[e]);return t===i?[]:[{key:e,expected:q(t),actual:q(i)}]})}function K(e){return e===void 0?`(absent)`:J(e)}function q(e){return e.length<=300?e:`${e.slice(0,149)}…${e.slice(-149)}`}function J(e){return JSON.stringify(Y(e))}function Y(e){return Array.isArray(e)?e.map(e=>Y(e)):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Y(t)]))}function tt(e){return r(e)||e.kind===`device`?`-maximum-concurrent-test-device-destinations`:`-maximum-concurrent-test-simulator-destinations`}function X(e=process.env,t=!1,n={platform:`apple`}){if(r(n))return[`CODE_SIGNING_ALLOWED=NO`,`CODE_SIGNING_REQUIRED=NO`,`CODE_SIGN_IDENTITY=`,`DEVELOPMENT_TEAM=`];if(!t)return[];let i=e.AGENT_DEVICE_IOS_TEAM_ID?.trim()||``,a=e.AGENT_DEVICE_IOS_SIGNING_IDENTITY?.trim()||``,o=e.AGENT_DEVICE_IOS_PROVISIONING_PROFILE?.trim()||``,s=[`CODE_SIGN_STYLE=${o?`Manual`:`Automatic`}`];return i&&s.push(`DEVELOPMENT_TEAM=${i}`),a&&s.push(`CODE_SIGN_IDENTITY=${a}`),o&&s.push(`PROVISIONING_PROFILE_SPECIFIER=${o}`),s}function Z(e=process.env){let t=L(e),n=R(e);return[`AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID=${t}`,`AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID=${n}`]}function Q(){return[`COMPILER_INDEX_STORE_ENABLE=NO`,`ENABLE_CODE_COVERAGE=NO`,`ONLY_ACTIVE_ARCH=YES`,`ENABLE_PREVIEWS=NO`,`ENABLE_DEBUG_DYLIB=NO`]}function $(){return[...ze,`OTHER_SWIFT_FLAGS=${nt(process.env)}`]}function nt(e){return p(e.AGENT_DEVICE_XCUITEST_INCLUDE_UNIT_TESTS)?`$(inherited) -disable-sandbox -D AGENT_DEVICE_RUNNER_UNIT_TESTS`:`$(inherited) -disable-sandbox`}export{be as $,fe as A,oe as B,Se as C,y as D,m as E,h as F,ae as G,_ as H,xe as I,ce as J,re as K,T as L,g as M,b as N,A as O,k as P,ue as Q,he as R,x as S,v as T,de as U,D as V,C as W,_e as X,ge as Y,O as Z,j as _,et as a,S as b,L as c,tt as d,Q as f,Oe as g,J as h,Be as i,pe as j,p as k,Z as l,X as m,Re as n,Ve as o,$ as p,w as q,G as r,Ge as s,We as t,Qe as u,ye as v,le as w,E as x,ne as y,me as z};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime.js";import{A as t,C as n,T as r,w as i}from"./sdk-contracts.js";import{g as a}from"./sdk-batch-runner.js";import{c as o,l as s}from"./sdk-device.js";import{o as c}from"./sdk-remote-config.js";import{c as l,r as u}from"./diagnostics.js";import{C as d,O as f,S as p,m,p as h,t as ee,x as g,y as te}from"./owner-identity.js";import{a as ne,f as re,l as ie,p as ae,r as oe}from"./exec.js";import{t as se}from"./file.js";import"./diagnostics2.js";import{n as ce}from"./command.js";import{i as le,n as ue,r as de}from"./retry.js";import{n as fe,r as pe}from"./version.js";import{t as me}from"./ttl-memo.js";import"./process.js";import{n as he,t as ge}from"./boot-diagnostics.js";import{t as _e}from"./keyed-lock.js";import{i as ve,r as ye}from"./request-cancel.js";import{t as be}from"./request.js";import{r as xe}from"./device-isolation.js";import{a as Se,o as Ce,r as we}from"./tool-provider.js";import{t as Te}from"./physical-device-control.js";import{t as Ee}from"./simctl.js";import{a as De,i as Oe,o as ke}from"./runner.js";import{$ as Ae,A as _,B as je,F as Me,G as Ne,H as Pe,Q as Fe,T as Ie,U as Le,W as v,_ as Re,c as ze,d as Be,i as y,o as Ve,q as He,s as Ue,t as We,u as Ge,w as b,x as Ke,y as qe}from"./runner-cache-metadata.js";import{a as Je}from"./apple-runner-platform.js";import{A as x,C as Ye,E as Xe,F as S,I as Ze,L as Qe,M as C,N as $e,O as w,P as et,S as tt,T as nt,_ as T,a as E,b as rt,c as it,d as at,f as ot,g as st,h as D,i as ct,j as lt,k as ut,l as dt,m as ft,n as pt,o as mt,p as ht,r as gt,t as O,u as _t,v as vt,w as yt,x as bt,y as xt}from"./runner-disposal.js";import{t as St}from"./plist-xml.js";import{n as Ct,t as wt}from"./runner-owner-state.js";import k from"node:path";import Tt from"node:fs";import Et from"node:fs/promises";const Dt={PreferredScreenCaptureFormat:`screenshots`,SystemAttachmentLifetime:`keepNever`,UserAttachmentLifetime:`keepNever`};async function Ot(e,t,n,r={}){let i=r.iosXctestEnvDir?.trim(),a=i?k.resolve(i):k.dirname(e);Tt.mkdirSync(a,{recursive:!0});let o=n.replaceAll(/[^a-zA-Z0-9._-]/g,`_`),s=k.join(a,`AgentDeviceRunner.env.${o}.json`),c=k.join(a,`AgentDeviceRunner.env.${o}.xctestrun`),l=await kt(e);return Nt(l,e=>jt(e,t)),Mt(l),await At(l,s,c),{xctestrunPath:c,jsonPath:s}}async function kt(e){let t=await v(`plutil`,[`-convert`,`json`,`-o`,`-`,e],{allowFailure:!0});if(t.exitCode!==0||!t.stdout.trim())throw new n(`COMMAND_FAILED`,`Failed to read xctestrun plist`,{xctestrunPath:e,stderr:t.stderr});try{let e=JSON.parse(t.stdout);if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Root must be an object`);return e}catch(t){throw new n(`COMMAND_FAILED`,`Failed to parse xctestrun JSON`,{xctestrunPath:e,error:String(t)})}}async function At(e,t,n){Tt.writeFileSync(t,JSON.stringify(e,null,2)),je(await v(`plutil`,[`-convert`,`xml1`,`-o`,n,t],{allowFailure:!0}),`Failed to write xctestrun plist`,{tmpXctestrunPath:n})}function jt(e,t){e.EnvironmentVariables={...e.EnvironmentVariables??{},...t},e.UITestEnvironmentVariables={...e.UITestEnvironmentVariables??{},...t},e.UITargetAppEnvironmentVariables={...e.UITargetAppEnvironmentVariables??{},...t},e.TestingEnvironmentVariables={...e.TestingEnvironmentVariables??{},...t}}function Mt(e){Nt(e,e=>Object.assign(e,Dt),{requireTestBundlePath:!0})}function Nt(e,t,n={}){let r=e.TestConfigurations;if(Array.isArray(r))for(let e of r)!e||typeof e!=`object`||Pt(e.TestTargets,t,n);for(let n of Object.values(e)){let e=Ft(n,{requireTestBundlePath:!0});e&&t(e)}}function Pt(e,t,n){if(Array.isArray(e))for(let r of e){let e=Ft(r,n);e&&t(e)}}function Ft(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;return t.requireTestBundlePath&&!n.TestBundlePath?null:n}const It={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:`alertAction`,sequence:`preflightSkippableTouchMutation`,recordStart:`default`,recordStop:`default`,status:`readOnlyReadinessProbe`,uptime:`readOnlyReadinessProbe`,activate:`readinessPreflightExemptMutation`,terminate:`readinessPreflightExemptMutation`,targetReset:`readinessPreflightExemptMutation`,shutdown:`default`},A={readOnly:!1,readinessProbe:!1,readinessPreflightExempt:!1,readinessPreflightSkipEligibleAfterHealthyMutation:!1},Lt={...A,readinessPreflightExempt:!0},j={...A,readOnly:!0},Rt={...j,readinessProbe:!0},zt={...A,readinessPreflightSkipEligibleAfterHealthyMutation:!0};function M(e){return N(e).readOnly}function Bt(e){return N(e).readinessProbe}function Vt(e){return N(e).readinessPreflightExempt}function Ht(e){return N(e).readinessPreflightSkipEligibleAfterHealthyMutation}function N(e){switch(It[e.command]){case`default`:return A;case`readinessPreflightExemptMutation`:return Lt;case`readOnly`:return j;case`alertAction`:return(e.action??`get`).toLowerCase()===`get`?j:A;case`readOnlyReadinessProbe`:return Rt;case`preflightSkippableTouchMutation`:return zt}}function Ut(e,t){return`${e}:${t}:${Date.now()}`}function Wt(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):void 0}function Gt(e=process.env){return Me(e.AGENT_DEVICE_IOS_RUNNER_DETACH??``)!==!1}async function Kt(e,t){if(e.kind!==`simulator`||!Gt()||Pe(e.simulatorSetPath))return null;let n=ht(e.id);if(!n)return null;let r=t=>(b({level:`debug`,phase:`ios_runner_lease_adoption_skipped`,data:{deviceId:e.id,runnerPid:n.runnerPid,port:n.port,reason:t}}),null);if(t.expectedRunnerSessionId!==void 0&&n.sessionId!==t.expectedRunnerSessionId)return r(`session_identity_mismatch`);let i=n.runnerPid;if(!i)return r(`runner_pid_missing`);if(!_(i))return r(`runner_process_dead`);if(!D(n,i))return r(`runner_pid_recycled`);let a=Jt(e,t.budget);if(!a)return r(`expected_derived_unresolved`);if(!n.xctestrunPath.startsWith(`${a}${k.sep}`))return r(`artifact_fingerprint_mismatch`);if(!await qt(e,n.port))return r(`probe_failed`);if(!_(i)||!D(n,i))return r(`runner_pid_recycled`);let o=Yt(e,n,i,a,t);try{T(o.lease)}catch{return null}return b({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 qt(e,t){try{let n=await Xe(e,t,S({command:`uptime`}),500);return JSON.parse(await n.text())?.ok===!0}catch{return!1}}function Jt(e,n){try{return Ge(e,Ue(e,void 0,n))}catch(e){if(t(e))throw e;return null}}function Yt(e,t,n,r,i){let a=t.sessionId,o={xctestrunPath:t.xctestrunPath,derived:r,cache:`exact`,artifact:`valid`,buildMs:0,xctestrunPathSource:`manifest`,reason:`adopted_from_lease`},{child:s,wait:c}=Xt(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:Wt(Ve(i.budget,`runner_session_adoption`)),lease:_t({deviceId:e.id,sessionId:a,runnerPid:n,port:t.port,xctestrunPath:t.xctestrunPath,jsonPath:t.jsonPath})}}function Xt(e){let t={pid:e,exitCode:null};return{child:t,wait:new Promise(n=>{let r=setInterval(()=>{_(e)||(clearInterval(r),t.exitCode=-1,n({stdout:``,stderr:``,exitCode:-1}))},1e3);r.unref?.()})}}async function Zt(e){let t=await Qt(e.logPath)??en(e.error);return t?new n(t.code??e.error.code,e.error.message,{...e.error.details??{},hint:typeof e.error.details?.hint==`string`?`${e.error.details.hint} ${t.hint}`:t.hint,runnerFailureReason:t.reason},e.error):e.error}async function Qt(e){if(!e)return;let t=await an(e,65536);if(t)return $t(t)}function $t(e){let t=e.toLowerCase();if(tn(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(nn(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 en(e){if(rn(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 tn(e){return e.includes(`axruntime`)&&e.includes(`coretext`)&&(e.includes(`attributesforelement`)||e.includes(`axuielementcopymultipleattributevalues`)||e.includes(`reconstitutedsmuggledctfontfromdictionary`)||e.includes(`reconstitutedsmuggledattributedstringfromdictionary`))}function nn(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 rn(e){return e.toLowerCase().includes(`main thread execution timed out`)}async function an(e,t){let n;try{let r=await Et.stat(e),i=Math.max(0,r.size-t),a=r.size-i;if(a<=0)return;n=await Et.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(()=>{})}}function on(){let e=new AbortController,t=!1,n={stdout:``,stderr:``};return{wake:e.signal,observe:(r,i)=>{if(t)return;let a=n[r]+i;if(a.includes(`AGENT_DEVICE_RUNNER_LISTENER_READY`)){t=!0,n.stdout=``,n.stderr=``,e.abort();return}n[r]=a.slice(-33)},finish:()=>{t=!0,n.stdout=``,n.stderr=``,e.abort()}}}function sn(e){let t=on(),n=Ne(`xcodebuild`,[`test-without-building`,`-only-testing`,`AgentDeviceRunnerUITests/RunnerTests/testCommand`,`-parallel-testing-enabled`,`NO`,`-test-timeouts-enabled`,`NO`,`-collect-test-diagnostics`,`never`,Be(e.device),`1`,`-destination-timeout`,`20`,`-xctestrun`,e.xctestrunPath,`-derivedDataPath`,e.derivedPath,`-destination`,Je(e.device)],{allowFailure:!0,env:{...process.env,AGENT_DEVICE_RUNNER_PORT:String(e.port)},detached:!0,signal:e.signal}),r=(n,r)=>{t.observe(n,r),Qe(r,e.logPath,e.traceLogPath,e.verbose)};return n.child.stdout?.on(`data`,e=>r(`stdout`,e)),n.child.stderr?.on(`data`,e=>r(`stderr`,e)),n.wait.then(t.finish,t.finish),{...n,startupRetryWake:t.wake}}const P=new Map,cn=new Map,F=new Map,ln=1e4;function I(e,t){return Ae(cn,e,t)}async function L(e,t){return V(e.id),await I(e.id,async()=>{let n=y(t.startupTimeoutMs,C(t)),r=P.get(e.id);if(r){dn(r,t.expectedRunnerSessionId);let i=await mn(e,r,n);if(i)return i}return await st(e.id,async()=>await un(e,t,n))})}async function un(e,t,n){let i={},a=n.signal,o=Kn(t.runnerLeaseContext,e.id);b({level:`debug`,phase:`ios_runner_session_startup`,data:{deviceId:e.id,logicalLeaseContext:o}});let s=await W(i,`adopt_detached_runner`,async()=>await Kt(e,{budget:n,expectedRunnerSessionId:t.expectedRunnerSessionId}));if(s)return s.startupTimings=i,s.logicalLeaseContext=o,P.set(e.id,s),s;fn(t.expectedRunnerSessionId),await W(i,`cleanup_stale_xcodebuild`,async()=>{await ot(e,mt,o)}),await W(i,`ensure_booted`,async()=>{await Tn(e)}),await W(i,`verify_developer_mode`,async()=>{await Dn(e)}),t.cleanStaleBundles?await W(i,`cleanup_stale_bundles`,async()=>{await hn(e)}):(i.cleanup_stale_bundles=0,b({level:`debug`,phase:`ios_runner_startup_cleanup_stale_bundles_skipped`}));let c=Ve(n,`runner_session_startup`),l=await W(i,`ensure_xctestrun`,async()=>await vt(e,{...t,budget:y(t.buildTimeoutMs,a)}));i.build_xctestrun=l.buildMs;let u=await W(i,`allocate_port`,async()=>await Ze()),{xctestrunPath:d,jsonPath:f}=await W(i,`prepare_xctestrun_env`,async()=>await Ot(l.xctestrunPath,{AGENT_DEVICE_RUNNER_PORT:String(u)},`session-${e.id}-${ft()}-${u}`,{iosXctestEnvDir:t.iosXctestEnvDir})),p=await W(i,`simulator_set_redirect`,async()=>await tt(e)),m;try{l.buildMs>0&&Ie({type:`command`,status:`progress`,message:`Starting XCTest runner...`}),m=await W(i,`launch_xcodebuild`,()=>sn({device:e,port:u,xctestrunPath:d,derivedPath:l.derived,signal:a,logPath:t.logPath,traceLogPath:t.traceLogPath,verbose:t.verbose}))}catch(e){throw await p?.release(),e}let h=Ut(e.id,u),ee=_t({deviceId:e.id,sessionId:h,runnerPid:m.child.pid,port:u,xctestrunPath:d,jsonPath:f}),g={sessionId:h,device:e,deviceId:e.id,port:u,xctestrunPath:d,xctestrunArtifact:l,jsonPath:f,testPromise:m.wait,child:m.child,ready:!1,startupRetryWake:m.startupRetryWake,startupTimeoutMs:Wt(c),startupTimings:i,logicalLeaseContext:o,simulatorSetRedirect:p??void 0,lease:ee,speculative:t.speculative===!0};if(a?.aborted)throw await ct(g,{graceful:!1,waitTimeoutMs:O,leaseLockHeld:!0}),r();try{T(ee)}catch(t){throw await B(e.id,g,{graceful:!1,waitTimeoutMs:O,leaseLockHeld:!0}),t}return P.set(e.id,g),g}function dn(e,t){if(t!==void 0&&e.sessionId!==t)throw pn()}function fn(e){if(e!==void 0)throw pn()}function pn(){return new n(`COMMAND_FAILED`,`Apple runner session ownership changed before command dispatch`,{reason:`runner_session_ownership_changed`})}async function mn(e,t,n){if(!E(t.child.pid))return await W({},`stop_stale_session`,async()=>{await B(e.id,t,{graceful:!1,waitTimeoutMs:O})}),null;let r=t.xctestrunArtifact;if(r?.cache===`external`)return b({level:`debug`,phase:`ios_runner_session_reuse`,data:{deviceId:e.id,sessionId:t.sessionId,ready:t.ready,cache:r.cache,logicalLeaseContext:t.logicalLeaseContext}}),t;let i=Ge(e,Ue(e,void 0,n));return r?.derived===i?(b({level:`debug`,phase:`ios_runner_session_reuse`,data:{deviceId:e.id,sessionId:t.sessionId,ready:t.ready,logicalLeaseContext:t.logicalLeaseContext}}),t):(b({level:`debug`,phase:`ios_runner_session_artifact_stale`,data:{deviceId:e.id,sessionId:t.sessionId,currentDerived:r?.derived,expectedDerived:i}}),await W({},`stop_stale_artifact_session`,async()=>{await B(e.id,t)}),null)}async function hn(e){e.kind===`simulator`&&await Promise.allSettled(We.map(async t=>{let n=await gn(e,t);!n||_n(n)}))}async function gn(e,t){try{return await He(Ke(e,[`uninstall`,e.id,t]),{allowFailure:!0,timeoutMs:ln})}catch(n){b({level:`warn`,phase:`ios_runner_startup_cleanup_stale_bundle_failed`,data:{deviceId:e.id,bundleId:t,timeoutMs:ln,error:n instanceof Error?n.message:String(n)}});return}}function _n(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 R(e){let t=P.get(e);return t?{sessionId:t.sessionId,alive:E(t.child.pid),ready:t.ready}:null}async function z(e,t){await I(e.deviceId,async()=>{P.get(e.deviceId)===e&&(b({level:`warn`,phase:`ios_runner_session_invalidated`,data:{deviceId:e.deviceId,sessionId:e.sessionId,reason:t}}),await B(e.deviceId,e,{graceful:!1,waitTimeoutMs:O}))})}async function B(e,t,n={}){let r=t??P.get(e);r&&(await ct(r,n),P.get(e)===r&&P.delete(e))}function vn(e){V(e);let t=yn();if(t<=0||!P.has(e))return;let n=setTimeout(()=>{F.delete(e),b({level:`info`,phase:`ios_runner_idle_stop`,data:{deviceId:e,idleMs:t}}),H(e).catch(t=>{b({level:`warn`,phase:`ios_runner_idle_stop_failed`,data:{deviceId:e,error:t instanceof Error?t.message:String(t)}})})},t);n.unref?.(),F.set(e,n),b({level:`debug`,phase:`ios_runner_idle_stop_scheduled`,data:{deviceId:e,idleMs:t}})}function V(e){let t=F.get(e);t&&(clearTimeout(t),F.delete(e))}function yn(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}function bn(e,t){e.speculative&&!Bt(t)&&(e.speculative=!1)}async function xn(e){return await I(e,async()=>{let t=P.get(e);return t?.speculative?(b({level:`debug`,phase:`ios_runner_speculative_released`,data:{deviceId:e,sessionId:t.sessionId,ready:t.ready}}),await H(e),!0):!1})}async function H(e){V(e),await I(e,async()=>{await st(e,async()=>{await B(e,void 0,{leaseLockHeld:!0}),await gt(e)})})}async function Sn(){let e=Array.from(P.values());await pt(e);for(let t of e)P.get(t.deviceId)===t&&P.delete(t.deviceId)}async function Cn(){if(!Gt())return 0;let e=0;for(let[t,n]of P)if(n.device.kind===`simulator`&&!n.simulatorSetRedirect&&!(!n.lease||!E(n.child.pid))){try{T(dt(n.lease))}catch{continue}P.delete(t),V(t),e+=1,b({level:`info`,phase:`ios_runner_session_detached`,data:{deviceId:t,sessionId:n.sessionId,runnerPid:n.child.pid,port:n.port}})}return e}async function wn(){await Sn();let e=Array.from(P.keys());await Promise.allSettled(e.map(async e=>{await H(e)})),await it()}function Tn(e){return e.kind===`simulator`?e.booted?(b({level:`debug`,phase:`ios_runner_startup_ensure_booted_skipped`,data:{deviceId:e.id}}),Promise.resolve()):En(e):Promise.resolve()}async function En(e){await He(Ke(e,[`bootstatus`,e.id,`-b`]),{timeoutMs:Ye})}async function Dn(e){if(!s(e)||e.kind!==`device`)return;let t=await v(`DevToolsSecurity`,[`-status`],{allowFailure:!0,timeoutMs:2e3}),r=`${t.stdout}\n${t.stderr}`;if(/developer mode is currently disabled/i.test(r))throw new n(`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 On(e){if(!o(e.platform))throw new n(`UNSUPPORTED_PLATFORM`,`Unsupported platform for iOS runner: ${e.platform}`);if(e.kind!==`simulator`&&e.kind!==`device`)throw new n(`UNSUPPORTED_OPERATION`,`Unsupported iOS device kind for runner: ${e.kind}`)}async function U(e,t,n,r,i,a){Gn(t,n.command);let o=S(n),s=M(o),c=Re.fromTimeoutMs(i),l=Vn(t,o);l.action===`run`?await Mn({device:e,session:t,runnerCommand:o,logPath:r,deadline:c,signal:a,decision:l}):Nn(o,t,l);let u;try{u=await jn({device:e,session:t,runnerCommand:o,logPath:r,deadline:c,timeoutMs:i,signal:a,readOnlyCommand:s})}catch(e){throw An(e,t,l)}try{let e=await Pn(u,t,r),n=Bn(e);return n?(t.lastHealthyMutation=void 0,await z(t,n)):Ht(o)&&(t.lastHealthyMutation={atMs:Date.now(),appBundleId:o.appBundleId}),e}catch(e){let n=lt(e);throw n?(t.lastHealthyMutation=void 0,await z(t,n),e):kn(e)?e:An(e,t,l)}}function kn(e){return e instanceof n&&e.details?.runner!==void 0}function An(e,t,n){return n.action!==`skip`||n.reason!==`recent_healthy_mutation`?e:(t.lastHealthyMutation=void 0,Un(e,{runnerReadinessPreflightSkipped:!0,runnerReadinessPreflightSkipReason:n.reason,runnerReadinessPreflightSkippedAgeMs:n.lastHealthyMutationAgeMs}))}async function jn(e){let{device:t,session:r,runnerCommand:i,logPath:a,deadline:o,timeoutMs:s,signal:c,readOnlyCommand:l}=e,u=o.remainingMs();if(u<=0)throw new n(`COMMAND_FAILED`,`Runner command deadline exceeded`,{timeoutMs:s});let d=l?{command:i.command,commandId:i.commandId,readOnly:!0,sessionReady:r.ready,timeoutMs:u}:{command:i.command,commandId:i.commandId};return await Fe(`ios_runner_command_send`,async()=>l?await yt(t,r.port,i,a,u,r,c):await Xe(t,r.port,i,u,c),d)}async function Mn(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(Wn(n),a.remainingMs());try{await Pn(await Fe(`ios_runner_readiness_preflight`,async()=>await yt(t,n.port,S({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 Hn(e)}}function Nn(e,t,n){b({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 Pn(e,t,n){let r=Fn(await e.text());if(!r.ok)throw await Zt({error:In(r,n),logPath:n});return t.ready=!0,Rn(r)}function Fn(e){try{let t=JSON.parse(e);return t&&typeof t==`object`?t:{}}catch{throw new n(`COMMAND_FAILED`,`Invalid runner response`,{text:e})}}function In(e,t){let r=Ln(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,o=ut(r);return new n(o.code,i??`Runner error`,{runner:e,...o.details,xcodebuild:{exitCode:1,stdout:``,stderr:``},hint:a,logPath:t})}function Ln(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function Rn(e){if(!e.data||typeof e.data!=`object`||Array.isArray(e.data))return{};let t=e.data;return zn(t),t}function zn(e){let t=e.gestureFallback;typeof t==`string`&&t.length!==0&&b({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 Bn(e){if(e.runnerFatal===!0)return typeof e.runnerFatalReason==`string`&&e.runnerFatalReason.trim().length>0?e.runnerFatalReason:`runner_reported_fatal_response`}function Vn(e,t){let n=M(t);if(Vt(t))return{action:`skip`,reason:`preflight_exempt_command`};if(!e.ready)return n?{action:`skip`,reason:`read_only_startup_command`}:{action:`run`,reason:`startup`};if(Bt(t))return{action:`skip`,reason:`readiness_probe_command`};if(!Ht(t))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 Hn(e){return Un(e,{runnerReadinessPreflightFailed:!0})}function Un(e,t){let r=e instanceof n?e:new n(`COMMAND_FAILED`,e instanceof Error?e.message:String(e),void 0,e);return new n(r.code,r.message,{...r.details??{},...t},r.cause??e)}function Wn(e){return e.startupTimeoutMs??45e3}async function W(e,t,n){let r=Date.now();try{return await n()}finally{let n=Date.now()-r;e[t]=n,b({level:`debug`,phase:`ios_runner_startup_${t}`,durationMs:n})}}function Gn(e,t){if(e.startupTimingsReported||!e.startupTimings)return;e.startupTimingsReported=!0;let n=Object.values(e.startupTimings).reduce((e,t)=>e+t,0);b({level:`info`,phase:`ios_runner_session_startup_timings`,durationMs:n,data:{command:t,sessionId:e.sessionId,ready:e.ready,logicalLeaseContext:e.logicalLeaseContext,timings:e.startupTimings}})}function Kn(e,t){if(!e)return;let n={leaseId:G(e.leaseId),clientId:G(e.clientId),tenantId:G(e.tenantId),runId:G(e.runId),leaseProvider:G(e.leaseProvider),deviceKey:G(e.deviceKey)??t},r=Object.entries(n).filter(([,e])=>e!==void 0);return r.length>0?Object.fromEntries(r):void 0}function G(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}async function qn(e){let{device:t,session:n,command:r,transportError:i,options:a,signal:o,invalidationReason:s}=e;return await Jn(await Qn(t,n,r,i,a,o),{command:r,session:n,transportError:i,invalidationReason:s,invalidateSession:e.invalidateSession})}async function Jn(e,t){if(!e)return await Zn(t,`status_recovery_unavailable`);if(e.type===`recovered`)return Yn(e,t);if(e.type===`skipInvalidation`)throw Xn(e,t);return await Zn(t,e.reason,e.lifecycleState,e.error)}function Yn(e,t){return J({command:t.command,session:t.session,transportError:t.transportError,decision:`skipped`,reason:e.reason,lifecycleState:e.lifecycleState}),e.data}function Xn(e,t){return J({command:t.command,session:t.session,transportError:t.transportError,decision:`skipped`,reason:e.reason,lifecycleState:e.lifecycleState}),e.error}async function Zn(e,t,n,r){throw J({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 Qn(e,t,n,r,i,a){if(n.command===`status`||!n.commandId?.trim())return;let o=q(r),s;try{s=await U(e,t,{command:`status`,statusCommandId:n.commandId},i.logPath,3e3,a)}catch(e){return b({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 b({level:`debug`,phase:`ios_runner_command_status_recovery`,data:{command:n.command,commandId:n.commandId,lifecycleState:c,...o}}),$n(s,c,n,r,i)}function $n(e,t,r,i,a){return t===`completed`?er(e,r,i,a):t===`failed`?{type:`skipInvalidation`,reason:`runner_reported_failure`,lifecycleState:t,error:tr(e,r,i,a)}:t===`accepted`||t===`started`?{type:`skipInvalidation`,reason:`command_still_in_flight`,lifecycleState:t,error:nr(t,r,i,a)}:{type:`retainInvalidation`,reason:t?`unknown_lifecycle_state`:`missing_lifecycle_state`,lifecycleState:t,error:new n(`COMMAND_FAILED`,`Runner command "${r.command}" lost its transport response and lifecycle status was ${t?`"${t}"`:`missing`}, so agent-device invalidated the runner session instead of replaying the command.`,{command:r.command,commandId:r.commandId,lifecycleState:t,recovery:`lifecycle_state_not_recoverable`,hint:dr(r.command),logPath:a.logPath,transportError:i.message},i)}}function er(e,t,r,i){let a=rr(e.lifecycleResponseJson);if(a)return{type:`recovered`,data:a,reason:`completed_with_retained_response`,lifecycleState:`completed`};if(M(t))return{type:`skipInvalidation`,error:r,reason:`read_only_completed_without_retained_response`,lifecycleState:`completed`};let o=q(r);return{type:`skipInvalidation`,reason:`completed_without_retained_response`,lifecycleState:`completed`,error:new n(`COMMAND_FAILED`,`Runner command "${t.command}" completed after the transport response was lost, but no recoverable response was retained.`,{command:t.command,commandId:t.commandId,lifecycleState:`completed`,recovery:`completed_without_retained_response`,...o,hint:ar(t.command,o),logPath:i.logPath,transportError:r.message},r)}}function tr(e,t,r,i){let a=typeof e.lifecycleErrorCode==`string`?e.lifecycleErrorCode:void 0,o=typeof e.lifecycleErrorMessage==`string`?e.lifecycleErrorMessage:`Runner command failed`,s=typeof e.lifecycleErrorHint==`string`?e.lifecycleErrorHint:void 0,c=q(r),l=ut(a);return new n(l.code,o,{command:t.command,commandId:t.commandId,lifecycleState:`failed`,recovery:`runner_reported_failure`,...l.details,...c,hint:s??or(t.command,c),logPath:i.logPath,transportError:r.message},r)}function nr(e,t,r,i){if(M(t))return r;let a=q(r);return new n(`COMMAND_FAILED`,`Runner command "${t.command}" is still ${e} after the transport response was lost.`,{command:t.command,commandId:t.commandId,lifecycleState:e,recovery:`command_still_in_flight`,...a,hint:sr(t.command,e,a),logPath:i.logPath,transportError:r.message},r)}function rr(e){if(typeof e!=`string`||e.trim().length===0)return;let t=ir(e);if(t.ok)return t.data&&typeof t.data==`object`&&!Array.isArray(t.data)?t.data:{}}function ir(e){try{let t=JSON.parse(e);if(t&&typeof t==`object`)return t}catch{}return{}}function ar(e,t){return`${K(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 or(e,t){return`${K(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 sr(e,t,n){return`${K(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 K(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 cr(e,t){let n=e.details?.[t];return typeof n==`boolean`?n:void 0}function lr(e,t){let n=e.details?.[t];return typeof n==`string`?n:void 0}function ur(e,t){let n=e.details?.[t];return typeof n==`number`?n:void 0}function q(e){let t={},n=cr(e,`runnerReadinessPreflightSkipped`);n!==void 0&&(t.readinessPreflightSkipped=n);let r=lr(e,`runnerReadinessPreflightSkipReason`);r!==void 0&&(t.readinessPreflightSkipReason=r);let i=ur(e,`runnerReadinessPreflightSkippedAgeMs`);return i!==void 0&&(t.readinessPreflightSkippedAgeMs=i),t}function dr(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 J(e){let{command:t,session:n,transportError:r,decision:i,reason:a,lifecycleState:o}=e;b({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 Y=new Map;function fr(e,t){let n=e.requestId?.trim();if(n)return`request:${n}`;let r=t.commandId?.trim();if(r)return`command:${r}`}function pr(e){if(!e)return;let t=vr(e);t.touchedSession=!0,X(e,t)}function mr(e){return e?Y.get(e)?.touchedSession===!0:!1}function hr(e){if(!e)return!0;let t=vr(e);return t.recycles>=1?(X(e,t),!1):(X(e,t),!0)}function gr(e){if(!e)return;let t=vr(e);t.recycles+=1,X(e,t)}function _r(e,t){return b({level:`warn`,phase:`ios_runner_recycle_budget_exhausted`,data:{command:e.command,commandId:e.commandId,requestId:t.requestId,maxRecycles:1}}),new n(`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:"Check the runner log for the underlying failure before retrying — a provisioning or code-signing error there means the runner cannot install on this device, and no retry will help. If the runner is healthy, the current screen is likely too heavy or animating for accessibility capture: the app session is preserved, so run `screenshot` for visual truth and interact by coordinates, or navigate to another screen.",logPath:t.logPath})}function vr(e){return yr(),Y.get(e)??{touchedSession:!1,recycles:0,lastAtMs:Date.now()}}function X(e,t){t.lastAtMs=Date.now(),Y.delete(e),Y.set(e,t)}function yr(){let e=Date.now()-6e5;for(let[t,n]of Y)n.lastAtMs<e&&Y.delete(t);for(;Y.size>512;){let e=Y.keys().next().value;if(e===void 0)break;Y.delete(e)}}async function br(e,t){w(t.requestId);let r=C(t),i=S({command:`uptime`}),a;for(let n=1;n<=2;n+=1){let o=await xr({device:e,command:i,options:t,signal:r,attempt:n,recoveryReason:a});if(o.kind===`prepared`)return o.result;a=o.recoveryReason}throw new n(`COMMAND_FAILED`,`iOS runner prepare failed`)}async function xr(e){let{device:t,command:n,options:r,signal:i,attempt:a,recoveryReason:o}=e,s=Date.now(),c=await L(t,{...r,cleanStaleBundles:a>1||r.cleanStaleBundles,...kr(r,`runner_session`)}),l=Date.now()-s;try{return{kind:`prepared`,result:Fr(t,await Or(t,c,n,r,i,l,{recoveryReason:o}))}}catch(e){return await Sr({device:t,session:c,command:n,options:r,signal:i,attempt:a,error:e})}}async function Sr(e){let{device:n,session:r,command:a,options:o,signal:s,attempt:c,error:l}=e,u=i(l,`COMMAND_FAILED`);if(t(u))throw await Z(r,`prepare_runner_request_canceled`),l;if(c===1&&jr(u,r))return{kind:`prepared`,result:await Cr({device:n,session:r,command:a,options:o,signal:s,error:u})};if(!wr(u))throw l;let d=u.message||`runner_health_failed`;if(c>=2)throw await Z(r,`prepare_runner_health_failed`),l;return w(o.requestId),await z(r,`prepare_runner_health_retry`),b({level:`warn`,phase:`ios_runner_prepare_health_retry`,data:{command:a.command,commandId:a.commandId,sessionId:r.sessionId,attempt:c,maxAttempts:2,reason:d}}),{kind:`retry`,recoveryReason:d}}async function Cr(e){let{device:t,session:n,command:r,options:i,signal:a,error:o}=e,s=o.message||`runner_health_failed`;await z(n,`prepare_cached_runner_health_failed`),await bt(n.xctestrunArtifact,s);let c=Date.now(),l=await L(t,{...i,cleanStaleBundles:!0,forceRunnerXctestrunRebuild:!0,...kr(i,`runner_rebuild`)}),u=Date.now()-c;try{let e=await Or(t,l,r,i,a,u,{recoveryReason:s});return b({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}}),Fr(t,e)}catch(e){await Z(l,`prepare_rebuilt_runner_health_failed`);let n=Nr(e,l,s);throw Ir(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 Z(e,t){try{await z(e,t)}catch{}}function wr(e){return t(e)?!1:x(e)||et(e)||Mr(e)}async function Tr(e,n,r){w(r.requestId);let a=C(r),o=fr(r,n),s,c=!1;try{if(!R(e.id)?.alive&&mr(o)){if(!hr(o))throw _r(n,r);c=!0}s=await L(e,r),dn(s,r.expectedRunnerSessionId),bn(s,n),c&&gr(o),pr(o);let t=s.ready?nt:Wn(s);return await U(e,s,n,r.logPath,t,a)}catch(o){if(r.expectedRunnerSessionId!==void 0)throw o;let c=i(o,`COMMAND_FAILED`);if(s&&!s.ready&&t(c))throw await Z(s,`runner_startup_request_canceled`),o;if($e(c)&&s)return w(r.requestId),await Er({device:e,session:s,command:n,options:r,signal:a,restartReason:`runner_connect_failed_before_command_send`});if(s&&Rr(c))return w(r.requestId),await Er({device:e,session:s,command:n,options:r,signal:a,restartReason:`runner_readiness_preflight_failed_before_command_send`,recoveredDiagnosticPhase:`ios_runner_readiness_preflight_recovered`});if(s&&x(c))return await qn({device:e,session:s,command:n,transportError:c,options:r,signal:a,invalidationReason:`transport_error_after_command_send`,invalidateSession:z});throw o}}async function Er(e){let{device:t,command:n,options:r,signal:a,restartReason:o}=e,s=fr(r,n);if(!hr(s))throw _r(n,r);await z(e.session,o);let c=await L(t,{...r,cleanStaleBundles:!0}).catch(t=>{throw Dr(t,e)});gr(s);try{let i=await U(t,c,n,r.logPath,Ye,a);return e.recoveredDiagnosticPhase&&b({level:`debug`,phase:e.recoveredDiagnosticPhase,data:{command:n.command,commandId:n.commandId,recovery:`session_restarted`,sessionId:c.sessionId}}),i}catch(o){let s=i(o,`COMMAND_FAILED`);if(x(s))try{return await qn({device:t,session:c,command:n,transportError:s,options:r,signal:a,invalidationReason:`transport_error_after_retry_command_send`,invalidateSession:z})}catch(t){throw Dr(t,e,c)}throw Dr(o,e,c)}}function Dr(e,t,r){return e instanceof n?new n(e.code,e.message,{...e.details??{},runnerRestarted:!0,runnerRestartReason:t.restartReason,runnerRestartCommand:t.command.command,...t.command.commandId?{runnerRestartCommandId:t.command.commandId}:{},runnerInvalidatedSessionId:t.session.sessionId,...r?{runnerRestartSessionId:r.sessionId}:{},...e.details?.logPath===void 0&&t.options.logPath?{logPath:t.options.logPath}:{}},e.cause??e):e}async function Or(e,t,n,r,i,a,o){let s=Date.now(),c=Ar(r.prepareDeadline,r.healthTimeoutMs,`runner_health`);return Pr(await U(e,t,n,r.logPath,c,i),t,a,Date.now()-s,o)}function kr(e,t){if(!e.prepareDeadline)return{};let n=Ar(e.prepareDeadline,e.buildTimeoutMs,t);return{buildTimeoutMs:n,startupTimeoutMs:n}}function Ar(e,t,r){if(!e)return t??45e3;let i=Math.floor(e.remainingMs());if(i<=0)throw new n(`COMMAND_FAILED`,`prepare ios-runner timed out`,{phase:r,reason:`prepare_deadline_expired`});return i}function jr(e,t){let n=t.xctestrunArtifact;return!n||n.cache===`miss`?!1:wr(e)}function Mr(e){let t=e.message.toLowerCase();return t.includes(`timeout`)||t.includes(`timed out`)||t.includes(`deadline`)}function Nr(e,t,r){let a=i(e,`COMMAND_FAILED`);return new n(a.code,`artifact restored but runner did not connect`,{...a.details??{},restoredFailureReason:r,xctestrunPath:t.xctestrunArtifact?.xctestrunPath,artifact:t.xctestrunArtifact?.artifact,cache:t.xctestrunArtifact?.cache,reason:a.message},a)}function Pr(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 Fr(e,t){return Ir(e,t),t}function Ir(e,t){b({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 Lr(e){return e.details?.runnerReadinessPreflightFailed===!0}function Rr(e){return Lr(e)&&(x(e)||zr(e))}function zr(e){let t=e.message.toLowerCase();return t.includes(`timeout`)||t.includes(`timed out`)}async function Br(e,t,n={}){On(e),w(n.requestId);let r=S(t),i=Q(e,n);return M(r)?Le(()=>(w(n.requestId),i.runCommand(e,r,n)),{shouldRetry:e=>(w(n.requestId),x(e))}):i.runCommand(e,r,n)}async function Vr(e,t={}){if(s(e))try{await Br(e,{command:`targetReset`},t)}catch(t){b({level:`warn`,phase:`ios_runner_target_reset_failed`,data:{deviceId:e.id,error:t instanceof Error?t.message:String(t)}}),await H(e.id)}}function Hr(e,t={}){if(s(e))return Wr({device:e,options:t,failurePhase:`ios_runner_cache_prewarm_failed`,task:async t=>{await vt(e,{...t,budget:y(t.buildTimeoutMs,t.signal)})}})}function Ur(e,t={}){if(!s(e))return;let n=Q(e,t).prewarm;if(!n){b({level:`debug`,phase:`ios_runner_session_prewarm_unavailable`,data:{deviceId:e.id}});return}return Wr({device:e,options:t,failurePhase:`ios_runner_session_prewarm_failed`,task:async t=>{await n(e,t)}})}function Wr(e){let{device:t,options:n,failurePhase:r,task:i}=e,{propagateError:a=!1,...o}=n;return i(o).catch(e=>{if(b({level:`warn`,phase:r,data:{deviceId:t.id,error:e instanceof Error?e.message:String(e)}}),a)throw e})}async function Gr(e,t){On(e),w(t.requestId);let n=S({command:`uptime`}),r=Q(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 Q(e,t){return ke(e,Jr,void 0,{requestId:t.requestId})}function Kr(e,t={}){return s(e)?Q(e,t).hasLiveSession(e):!1}async function qr(e,t={}){if(!s(e))return!1;let n=Q(e,t).releaseSpeculativeSession;return n?await n(e):!1}const Jr=De(Tr,{prepare:br,hasLiveSession:e=>{let t=R(e.id);return t!==null&&t.alive&&t.ready},releaseSpeculativeSession:async e=>await xn(e.id),prewarm:async(e,t)=>{let{healthCheck:n,...r}=t;if(n===!1){await L(e,{...r,speculative:!0});return}await br(e,{...r,speculative:!0,healthTimeoutMs:nt})}});function Yr(e){return qe(e),{runAppleRunnerCommand:Br,notifyIosRunnerAppRelaunched:Vr,hasLiveIosRunnerSession:Kr,releaseSpeculativeIosRunnerSessionFor:qr,prewarmAppleRunnerCache:Hr,prewarmIosRunnerSession:Ur,prepareIosRunner:Gr,resolveRunnerAppBundleId:ze,hasCachedAppleRunnerArtifact:xt,detachIosSimulatorRunnerSessionsForShutdown:Cn,getRunnerSessionSnapshot:R,scheduleIosRunnerIdleStop:vn,stopIosRunnerSession:H,stopAllIosRunnerSessions:wn,runApplePressSeries:Oe,cleanupRunnerLeasesForOwner:at,readStaleRunnerLease:ht,verifyLeaseRunnerPidIdentity:D,runnerLeaseCleanupAdapter:mt,applyXctestRunnerAppIconFromDerivedPath:rt}}const Xr={runCmdStreaming:re,runCmdSync:ae,runCmdBackground:ie,requireExecSuccess:ne,isCommandTimeoutError:oe,shellQuote:ce,emitDiagnostic:u,withDiagnosticTimer:l,retryWithPolicy:le,isEnvTruthy:de,deadlineFromTimeoutMs:(e,t)=>ue.fromTimeoutMs(e,t),isProcessAlive:h,isProcessGroupAlive:m,readProcessStartTime:g,readProcessCommand:te,signalPidsBestEffort:p,signalProcessGroupBestEffort:d,findProjectRoot:fe,readVersion:pe,acquireProcessLock:se,withKeyedLock:_e,publishFileSync:f,classifyOwnerLiveness:ee,createTtlMemo:me,parseBooleanLiteral:c,isRecord:a,resolveIosSimulatorDeviceSetPath:xe,emitRequestProgress:be,getRequestSignal:ye,isRequestCanceled:ve,classifyBootFailure:he,bootFailureHint:ge,runAppleToolCommand:Se,runXcrun:Ce,readApplePlistJson:we,buildSimctlArgsForDevice:Ee,resolveIosPhysicalDeviceControl:Te,visitXmlPlistEntries:St,leaseOwnerStateDir:Ct,hasDeviceClaimAuthority:e=>wt()?.(e)??!1};var Zr=e({applyXctestRunnerAppIconFromDerivedPath:()=>gi,cleanupRunnerLeasesForOwner:()=>pi,detachIosSimulatorRunnerSessionsForShutdown:()=>si,getRunnerSessionSnapshot:()=>ci,hasCachedAppleRunnerArtifact:()=>oi,hasLiveIosRunnerSession:()=>ei,notifyIosRunnerAppRelaunched:()=>$r,prepareIosRunner:()=>ii,prewarmAppleRunnerCache:()=>ni,prewarmIosRunnerSession:()=>ri,readStaleRunnerLease:()=>mi,releaseSpeculativeIosRunnerSessionFor:()=>ti,resolveRunnerAppBundleId:()=>ai,runApplePressSeries:()=>fi,runAppleRunnerCommand:()=>Qr,scheduleIosRunnerIdleStop:()=>li,stopAllIosRunnerSessions:()=>di,stopIosRunnerSession:()=>ui,verifyLeaseRunnerPidIdentity:()=>hi});const $=Yr(Xr),Qr=$.runAppleRunnerCommand,$r=$.notifyIosRunnerAppRelaunched,ei=$.hasLiveIosRunnerSession,ti=$.releaseSpeculativeIosRunnerSessionFor,ni=$.prewarmAppleRunnerCache,ri=$.prewarmIosRunnerSession,ii=$.prepareIosRunner,ai=$.resolveRunnerAppBundleId,oi=$.hasCachedAppleRunnerArtifact,si=$.detachIosSimulatorRunnerSessionsForShutdown,ci=$.getRunnerSessionSnapshot,li=$.scheduleIosRunnerIdleStop,ui=$.stopIosRunnerSession,di=$.stopAllIosRunnerSessions,fi=$.runApplePressSeries,pi=$.cleanupRunnerLeasesForOwner,mi=$.readStaleRunnerLease,hi=$.verifyLeaseRunnerPidIdentity,gi=$.applyXctestRunnerAppIconFromDerivedPath;export{di as _,ei as a,ni as c,ti as d,ai as f,li as g,Zr as h,oi as i,ri as l,Qr as m,si as n,$r as o,fi as p,ci as r,ii as s,gi as t,mi as u,ui as v,hi as y};
1
+ import{r as e}from"./rolldown-runtime.js";import{C as t,T as n,j as r,w as i}from"./sdk-contracts.js";import{g as a}from"./sdk-batch-runner.js";import{c as o,l as s}from"./sdk-device.js";import{o as c}from"./sdk-remote-config.js";import{c as l,r as u}from"./diagnostics.js";import{D as d,S as f,m as p,p as m,t as h,x as g,y as _}from"./owner-identity.js";import{a as ee,f as te,l as ne,m as re,p as ie,r as ae}from"./exec.js";import{t as oe}from"./file.js";import"./diagnostics2.js";import{n as se}from"./command.js";import{i as ce,n as le,r as ue}from"./retry.js";import{n as de,r as fe}from"./version.js";import{t as pe}from"./ttl-memo.js";import"./process.js";import{n as me,t as he}from"./boot-diagnostics.js";import{t as ge}from"./keyed-lock.js";import{i as _e,r as ve}from"./request-cancel.js";import{t as ye}from"./request.js";import{r as be}from"./device-isolation.js";import{a as xe,o as Se,r as Ce}from"./tool-provider.js";import{t as we}from"./physical-device-control.js";import{t as Te}from"./simctl.js";import{a as Ee,i as De,o as Oe}from"./runner.js";import{$ as ke,A as v,B as Ae,F as je,G as Me,H as Ne,Q as Pe,T as Fe,U as Ie,W as y,_ as Le,c as Re,d as ze,i as b,o as Be,q as Ve,s as He,t as Ue,u as We,w as x,x as Ge,y as Ke}from"./runner-cache-metadata.js";import{a as qe}from"./apple-runner-platform.js";import{A as S,B as Je,C as Ye,E as Xe,F as Ze,I as Qe,L as $e,M as et,N as C,O as w,P as tt,R as T,S as nt,T as rt,_ as E,a as D,b as it,c as at,d as ot,f as st,g as ct,h as O,i as lt,j as ut,k as dt,l as ft,m as pt,n as mt,o as ht,p as gt,r as _t,t as k,u as vt,v as yt,w as bt,x as xt,y as St,z as Ct}from"./runner-disposal.js";import{t as wt}from"./plist-xml.js";import{n as Tt,t as Et}from"./runner-owner-state.js";import A from"node:path";import Dt from"node:fs";import Ot from"node:fs/promises";const kt={PreferredScreenCaptureFormat:`screenshots`,SystemAttachmentLifetime:`keepNever`,UserAttachmentLifetime:`keepNever`};async function At(e,t,n,r={}){let i=r.iosXctestEnvDir?.trim(),a=i?A.resolve(i):A.dirname(e);Dt.mkdirSync(a,{recursive:!0});let o=n.replaceAll(/[^a-zA-Z0-9._-]/g,`_`),s=A.join(a,`AgentDeviceRunner.env.${o}.json`),c=A.join(a,`AgentDeviceRunner.env.${o}.xctestrun`),l=await jt(e);return Ft(l,e=>Nt(e,t)),Pt(l),await Mt(l,s,c),{xctestrunPath:c,jsonPath:s}}async function jt(e){let n=await y(`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 Mt(e,t,n){Dt.writeFileSync(t,JSON.stringify(e,null,2)),Ae(await y(`plutil`,[`-convert`,`xml1`,`-o`,n,t],{allowFailure:!0}),`Failed to write xctestrun plist`,{tmpXctestrunPath:n})}function Nt(e,t){e.EnvironmentVariables={...e.EnvironmentVariables??{},...t},e.UITestEnvironmentVariables={...e.UITestEnvironmentVariables??{},...t},e.UITargetAppEnvironmentVariables={...e.UITargetAppEnvironmentVariables??{},...t},e.TestingEnvironmentVariables={...e.TestingEnvironmentVariables??{},...t}}function Pt(e){Ft(e,e=>Object.assign(e,kt),{requireTestBundlePath:!0})}function Ft(e,t,n={}){let r=e.TestConfigurations;if(Array.isArray(r))for(let e of r)!e||typeof e!=`object`||It(e.TestTargets,t,n);for(let n of Object.values(e)){let e=Lt(n,{requireTestBundlePath:!0});e&&t(e)}}function It(e,t,n){if(Array.isArray(e))for(let r of e){let e=Lt(r,n);e&&t(e)}}function Lt(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return null;let n=e;return t.requireTestBundlePath&&!n.TestBundlePath?null:n}const Rt={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:`alertAction`,sequence:`preflightSkippableTouchMutation`,recordStart:`default`,recordStop:`default`,status:`readOnlyReadinessProbe`,uptime:`readOnlyReadinessProbe`,activate:`readinessPreflightExemptMutation`,terminate:`readinessPreflightExemptMutation`,targetReset:`readinessPreflightExemptMutation`,shutdown:`default`},j={readOnly:!1,readinessProbe:!1,readinessPreflightExempt:!1,readinessPreflightSkipEligibleAfterHealthyMutation:!1},zt={...j,readinessPreflightExempt:!0},M={...j,readOnly:!0},Bt={...M,readinessProbe:!0},Vt={...j,readinessPreflightSkipEligibleAfterHealthyMutation:!0};function N(e){return P(e).readOnly}function Ht(e){return P(e).readinessProbe}function Ut(e){return P(e).readinessPreflightExempt}function Wt(e){return P(e).readinessPreflightSkipEligibleAfterHealthyMutation}function P(e){switch(Rt[e.command]){case`default`:return j;case`readinessPreflightExemptMutation`:return zt;case`readOnly`:return M;case`alertAction`:return(e.action??`get`).toLowerCase()===`get`?M:j;case`readOnlyReadinessProbe`:return Bt;case`preflightSkippableTouchMutation`:return Vt}}function Gt(e,t){return`${e}:${t}:${Date.now()}`}function Kt(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):void 0}function qt(e=process.env){return je(e.AGENT_DEVICE_IOS_RUNNER_DETACH??``)!==!1}async function Jt(e,t){if(e.kind!==`simulator`||!qt()||Ne(e.simulatorSetPath))return null;let n=gt(e.id);if(!n)return null;let r=t=>(x({level:`debug`,phase:`ios_runner_lease_adoption_skipped`,data:{deviceId:e.id,runnerPid:n.runnerPid,port:n.port,reason:t}}),null);if(t.expectedRunnerSessionId!==void 0&&n.sessionId!==t.expectedRunnerSessionId)return r(`session_identity_mismatch`);let i=n.runnerPid;if(!i)return r(`runner_pid_missing`);if(!v(i))return r(`runner_process_dead`);if(!O(n,i))return r(`runner_pid_recycled`);let a=Xt(e,t.budget);if(!a)return r(`expected_derived_unresolved`);if(!n.xctestrunPath.startsWith(`${a}${A.sep}`))return r(`artifact_fingerprint_mismatch`);if(!await Yt(e,n.port))return r(`probe_failed`);if(!v(i)||!O(n,i))return r(`runner_pid_recycled`);let o=Zt(e,n,i,a,t);try{E(o.lease)}catch{return null}return x({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 Yt(e,t){try{let n=await Xe(e,t,T({command:`uptime`}),500);return JSON.parse(await n.text())?.ok===!0}catch{return!1}}function Xt(e,t){try{return We(e,He(e,void 0,t))}catch(e){if(r(e))throw e;return null}}function Zt(e,t,n,r,i){let a=t.sessionId,o={xctestrunPath:t.xctestrunPath,derived:r,cache:`exact`,artifact:`valid`,buildMs:0,xctestrunPathSource:`manifest`,reason:`adopted_from_lease`},{child:s,wait:c}=Qt(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:Kt(Be(i.budget,`runner_session_adoption`)),lease:vt({deviceId:e.id,sessionId:a,runnerPid:n,port:t.port,xctestrunPath:t.xctestrunPath,jsonPath:t.jsonPath})}}function Qt(e){let t={pid:e,exitCode:null};return{child:t,wait:new Promise(n=>{let r=setInterval(()=>{v(e)||(clearInterval(r),t.exitCode=-1,n({stdout:``,stderr:``,exitCode:-1}))},1e3);r.unref?.()})}}async function $t(e){let n=await en(e.logPath)??nn(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 en(e){if(!e)return;let t=await sn(e,65536);if(t)return tn(t)}function tn(e){let t=e.toLowerCase();if(rn(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(an(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 nn(e){if(on(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 rn(e){return e.includes(`axruntime`)&&e.includes(`coretext`)&&(e.includes(`attributesforelement`)||e.includes(`axuielementcopymultipleattributevalues`)||e.includes(`reconstitutedsmuggledctfontfromdictionary`)||e.includes(`reconstitutedsmuggledattributedstringfromdictionary`))}function an(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 on(e){return e.toLowerCase().includes(`main thread execution timed out`)}async function sn(e,t){let n;try{let r=await Ot.stat(e),i=Math.max(0,r.size-t),a=r.size-i;if(a<=0)return;n=await Ot.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(()=>{})}}function cn(){let e=new AbortController,t=!1,n={stdout:``,stderr:``};return{wake:e.signal,observe:(r,i)=>{if(t)return;let a=n[r]+i;if(a.includes(`AGENT_DEVICE_RUNNER_LISTENER_READY`)){t=!0,n.stdout=``,n.stderr=``,e.abort();return}n[r]=a.slice(-33)},finish:()=>{t=!0,n.stdout=``,n.stderr=``,e.abort()}}}function ln(e){let t=cn(),n=Me(`xcodebuild`,[`test-without-building`,`-only-testing`,`AgentDeviceRunnerUITests/RunnerTests/testCommand`,`-parallel-testing-enabled`,`NO`,`-test-timeouts-enabled`,`NO`,`-collect-test-diagnostics`,`never`,ze(e.device),`1`,`-destination-timeout`,`20`,`-xctestrun`,e.xctestrunPath,`-derivedDataPath`,e.derivedPath,`-destination`,qe(e.device)],{allowFailure:!0,env:{...process.env,AGENT_DEVICE_RUNNER_PORT:String(e.port)},detached:!0,signal:e.signal}),r=(n,r)=>{t.observe(n,r),Je(r,e.logPath,e.traceLogPath,e.verbose)};return n.child.stdout?.on(`data`,e=>r(`stdout`,e)),n.child.stderr?.on(`data`,e=>r(`stderr`,e)),n.wait.then(t.finish,t.finish),{...n,startupRetryWake:t.wake}}const F=new Map,un=new Map,I=new Map,dn=1e4;function L(e,t){return ke(un,e,t)}async function R(e,t){return H(e.id),await L(e.id,async()=>{let n=b(t.startupTimeoutMs,C(t)),r=F.get(e.id);if(r){pn(r,t.expectedRunnerSessionId);let i=await gn(e,r,n);if(i)return i}return await ct(e.id,async()=>await fn(e,t,n))})}async function fn(e,t,r){let i={},a=r.signal,o=Xn(t.runnerLeaseContext,e.id);x({level:`debug`,phase:`ios_runner_session_startup`,data:{deviceId:e.id,logicalLeaseContext:o}});let s=await G(i,`adopt_detached_runner`,async()=>await Jt(e,{budget:r,expectedRunnerSessionId:t.expectedRunnerSessionId}));if(s)return s.startupTimings=i,s.logicalLeaseContext=o,F.set(e.id,s),s;mn(t.expectedRunnerSessionId),await G(i,`cleanup_stale_xcodebuild`,async()=>{await st(e,ht,o)}),await G(i,`ensure_booted`,async()=>{await On(e)}),await G(i,`verify_developer_mode`,async()=>{await An(e)}),t.cleanStaleBundles?await G(i,`cleanup_stale_bundles`,async()=>{await _n(e)}):(i.cleanup_stale_bundles=0,x({level:`debug`,phase:`ios_runner_startup_cleanup_stale_bundles_skipped`}));let c=Be(r,`runner_session_startup`),l=await G(i,`ensure_xctestrun`,async()=>await yt(e,{...t,budget:b(t.buildTimeoutMs,a)}));i.build_xctestrun=l.buildMs;let u=await G(i,`allocate_port`,async()=>await Ct()),{xctestrunPath:d,jsonPath:f}=await G(i,`prepare_xctestrun_env`,async()=>await At(l.xctestrunPath,{AGENT_DEVICE_RUNNER_PORT:String(u)},`session-${e.id}-${pt()}-${u}`,{iosXctestEnvDir:t.iosXctestEnvDir})),p=await G(i,`simulator_set_redirect`,async()=>await nt(e)),m;try{l.buildMs>0&&Fe({type:`command`,status:`progress`,message:`Starting XCTest runner...`}),m=await G(i,`launch_xcodebuild`,()=>ln({device:e,port:u,xctestrunPath:d,derivedPath:l.derived,signal:a,logPath:t.logPath,traceLogPath:t.traceLogPath,verbose:t.verbose}))}catch(e){throw await p?.release(),e}let h=Gt(e.id,u),g=vt({deviceId:e.id,sessionId:h,runnerPid:m.child.pid,port:u,xctestrunPath:d,jsonPath:f}),_={sessionId:h,device:e,deviceId:e.id,port:u,xctestrunPath:d,xctestrunArtifact:l,jsonPath:f,testPromise:m.wait,child:m.child,ready:!1,startupRetryWake:m.startupRetryWake,startupTimeoutMs:Kt(c),startupTimings:i,logicalLeaseContext:o,simulatorSetRedirect:p??void 0,lease:g,speculative:t.speculative===!0};if(a?.aborted)throw await lt(_,{graceful:!1,waitTimeoutMs:k,leaseLockHeld:!0}),n();try{E(g)}catch(t){throw await V(e.id,_,{graceful:!1,waitTimeoutMs:k,leaseLockHeld:!0}),t}return F.set(e.id,_),_}function pn(e,t){if(t!==void 0&&e.sessionId!==t)throw hn()}function mn(e){if(e!==void 0)throw hn()}function hn(){return new t(`COMMAND_FAILED`,`Apple runner session ownership changed before command dispatch`,{reason:`runner_session_ownership_changed`})}async function gn(e,t,n){if(!D(t.child.pid))return await G({},`stop_stale_session`,async()=>{await V(e.id,t,{graceful:!1,waitTimeoutMs:k})}),null;let r=t.xctestrunArtifact;if(r?.cache===`external`)return x({level:`debug`,phase:`ios_runner_session_reuse`,data:{deviceId:e.id,sessionId:t.sessionId,ready:t.ready,cache:r.cache,logicalLeaseContext:t.logicalLeaseContext}}),t;let i=We(e,He(e,void 0,n));return r?.derived===i?(x({level:`debug`,phase:`ios_runner_session_reuse`,data:{deviceId:e.id,sessionId:t.sessionId,ready:t.ready,logicalLeaseContext:t.logicalLeaseContext}}),t):(x({level:`debug`,phase:`ios_runner_session_artifact_stale`,data:{deviceId:e.id,sessionId:t.sessionId,currentDerived:r?.derived,expectedDerived:i}}),await G({},`stop_stale_artifact_session`,async()=>{await V(e.id,t)}),null)}async function _n(e){e.kind===`simulator`&&await Promise.allSettled(Ue.map(async t=>{let n=await vn(e,t);!n||yn(n)}))}async function vn(e,t){try{return await Ve(Ge(e,[`uninstall`,e.id,t]),{allowFailure:!0,timeoutMs:dn})}catch(n){x({level:`warn`,phase:`ios_runner_startup_cleanup_stale_bundle_failed`,data:{deviceId:e.id,bundleId:t,timeoutMs:dn,error:n instanceof Error?n.message:String(n)}});return}}function yn(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 z(e){let t=F.get(e);return t?{sessionId:t.sessionId,alive:D(t.child.pid),ready:t.ready}:null}async function B(e,t){await L(e.deviceId,async()=>{F.get(e.deviceId)===e&&(x({level:`warn`,phase:`ios_runner_session_invalidated`,data:{deviceId:e.deviceId,sessionId:e.sessionId,reason:t}}),await V(e.deviceId,e,{graceful:!1,waitTimeoutMs:k}))})}async function V(e,t,n={}){let r=t??F.get(e);r&&(await lt(r,n),F.get(e)===r&&F.delete(e))}function bn(e){H(e);let t=xn();if(t<=0||!F.has(e))return;let n=setTimeout(()=>{I.delete(e),x({level:`info`,phase:`ios_runner_idle_stop`,data:{deviceId:e,idleMs:t}}),U(e).catch(t=>{x({level:`warn`,phase:`ios_runner_idle_stop_failed`,data:{deviceId:e,error:t instanceof Error?t.message:String(t)}})})},t);n.unref?.(),I.set(e,n),x({level:`debug`,phase:`ios_runner_idle_stop_scheduled`,data:{deviceId:e,idleMs:t}})}function H(e){let t=I.get(e);t&&(clearTimeout(t),I.delete(e))}function xn(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}function Sn(e,t){e.speculative&&!Ht(t)&&(e.speculative=!1)}async function Cn(e){return await L(e,async()=>{let t=F.get(e);return t?.speculative?(x({level:`debug`,phase:`ios_runner_speculative_released`,data:{deviceId:e,sessionId:t.sessionId,ready:t.ready}}),await U(e),!0):!1})}async function U(e){H(e),await L(e,async()=>{await ct(e,async()=>{await V(e,void 0,{leaseLockHeld:!0}),await _t(e)})})}async function wn(e,t){if(t.retain&&F.get(e)?.runnerMainThreadBusy!==!0){bn(e);return}t.retain&&x({level:`info`,phase:`ios_runner_retain_skipped_busy`,data:{deviceId:e}}),await U(e)}async function Tn(){let e=Array.from(F.values());await mt(e);for(let t of e)F.get(t.deviceId)===t&&F.delete(t.deviceId)}async function En(){if(!qt())return 0;let e=0;for(let[t,n]of F)if(n.device.kind===`simulator`&&!n.simulatorSetRedirect&&!(!n.lease||!D(n.child.pid))){try{E(ft(n.lease))}catch{continue}F.delete(t),H(t),e+=1,x({level:`info`,phase:`ios_runner_session_detached`,data:{deviceId:t,sessionId:n.sessionId,runnerPid:n.child.pid,port:n.port}})}return e}async function Dn(){await Tn();let e=Array.from(F.keys());await Promise.allSettled(e.map(async e=>{await U(e)})),await at()}function On(e){return e.kind===`simulator`?e.booted?(x({level:`debug`,phase:`ios_runner_startup_ensure_booted_skipped`,data:{deviceId:e.id}}),Promise.resolve()):kn(e):Promise.resolve()}async function kn(e){await Ve(Ge(e,[`bootstatus`,e.id,`-b`]),{timeoutMs:Ye})}async function An(e){if(!s(e)||e.kind!==`device`)return;let n=await y(`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 jn(e){if(!o(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 W(e,t,n,r,i,a){Yn(t,n.command);let o=T(n),s=N(o),c=Le.fromTimeoutMs(i),l=Gn(t,o);l.action===`run`?await In({device:e,session:t,runnerCommand:o,logPath:r,deadline:c,signal:a,decision:l}):Ln(o,t,l);let u;try{u=await Fn({device:e,session:t,runnerCommand:o,logPath:r,deadline:c,timeoutMs:i,signal:a,readOnlyCommand:s})}catch(e){throw Pn(e,t,l)}try{let e=await Rn(u,t,r),n=Mn(e);n!==void 0&&(t.runnerMainThreadBusy=n);let i=Wn(e);return i?(t.lastHealthyMutation=void 0,await B(t,i)):Wt(o)&&(t.lastHealthyMutation={atMs:Date.now(),appBundleId:o.appBundleId}),e}catch(e){ut(e)?t.runnerMainThreadBusy=!0:Nn(e)&&(t.runnerMainThreadBusy=!1);let n=et(e);throw n?(t.lastHealthyMutation=void 0,await B(t,n),e):Nn(e)?e:Pn(e,t,l)}}function Mn(e){return typeof e.runnerMainThreadBusy==`boolean`?e.runnerMainThreadBusy:void 0}function Nn(e){return e instanceof t&&e.details?.runner!==void 0}function Pn(e,t,n){return n.action!==`skip`||n.reason!==`recent_healthy_mutation`?e:(t.lastHealthyMutation=void 0,qn(e,{runnerReadinessPreflightSkipped:!0,runnerReadinessPreflightSkipReason:n.reason,runnerReadinessPreflightSkippedAgeMs:n.lastHealthyMutationAgeMs}))}async function Fn(e){let{device:n,session:r,runnerCommand:i,logPath:a,deadline:o,timeoutMs:s,signal:c,readOnlyCommand:l}=e,u=o.remainingMs();if(u<=0)throw new t(`COMMAND_FAILED`,`Runner command deadline exceeded`,{timeoutMs:s});let d=l?{command:i.command,commandId:i.commandId,readOnly:!0,sessionReady:r.ready,timeoutMs:u}:{command:i.command,commandId:i.commandId};return await Pe(`ios_runner_command_send`,async()=>l?await bt(n,r.port,i,a,u,r,c):await Xe(n,r.port,i,u,c),d)}async function In(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(Jn(n),a.remainingMs());try{await Rn(await Pe(`ios_runner_readiness_preflight`,async()=>await bt(t,n.port,T({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 Kn(e)}}function Ln(e,t,n){x({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 Rn(e,t,n){let r=zn(await e.text());if(!r.ok)throw await $t({error:Bn(r,n),logPath:n});return t.ready=!0,Hn(r)}function zn(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 Bn(e,n){let r=Vn(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,o=dt(r);return new t(o.code,i??`Runner error`,{runner:e,...o.details,xcodebuild:{exitCode:1,stdout:``,stderr:``},hint:a,logPath:n})}function Vn(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}function Hn(e){if(!e.data||typeof e.data!=`object`||Array.isArray(e.data))return{};let t=e.data;return Un(t),t}function Un(e){let t=e.gestureFallback;typeof t==`string`&&t.length!==0&&x({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 Wn(e){if(e.runnerFatal===!0)return typeof e.runnerFatalReason==`string`&&e.runnerFatalReason.trim().length>0?e.runnerFatalReason:`runner_reported_fatal_response`}function Gn(e,t){let n=N(t);if(Ut(t))return{action:`skip`,reason:`preflight_exempt_command`};if(!e.ready)return n?{action:`skip`,reason:`read_only_startup_command`}:{action:`run`,reason:`startup`};if(Ht(t))return{action:`skip`,reason:`readiness_probe_command`};if(!Wt(t))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 Kn(e){return qn(e,{runnerReadinessPreflightFailed:!0})}function qn(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 Jn(e){return e.startupTimeoutMs??45e3}async function G(e,t,n){let r=Date.now();try{return await n()}finally{let n=Date.now()-r;e[t]=n,x({level:`debug`,phase:`ios_runner_startup_${t}`,durationMs:n})}}function Yn(e,t){if(e.startupTimingsReported||!e.startupTimings)return;e.startupTimingsReported=!0;let n=Object.values(e.startupTimings).reduce((e,t)=>e+t,0);x({level:`info`,phase:`ios_runner_session_startup_timings`,durationMs:n,data:{command:t,sessionId:e.sessionId,ready:e.ready,logicalLeaseContext:e.logicalLeaseContext,timings:e.startupTimings}})}function Xn(e,t){if(!e)return;let n={leaseId:K(e.leaseId),clientId:K(e.clientId),tenantId:K(e.tenantId),runId:K(e.runId),leaseProvider:K(e.leaseProvider),deviceKey:K(e.deviceKey)??t},r=Object.entries(n).filter(([,e])=>e!==void 0);return r.length>0?Object.fromEntries(r):void 0}function K(e){return typeof e==`string`&&e.trim().length>0?e.trim():void 0}async function Zn(e){let{device:t,session:n,command:r,transportError:i,options:a,signal:o,invalidationReason:s}=e;return await Qn(await nr(t,n,r,i,a,o),{command:r,session:n,transportError:i,invalidationReason:s,invalidateSession:e.invalidateSession})}async function Qn(e,t){if(!e)return await tr(t,`status_recovery_unavailable`);if(e.type===`recovered`)return $n(e,t);if(e.type===`skipInvalidation`)throw er(e,t);return await tr(t,e.reason,e.lifecycleState,e.error)}function $n(e,t){return _r({command:t.command,session:t.session,transportError:t.transportError,decision:`skipped`,reason:e.reason,lifecycleState:e.lifecycleState}),e.data}function er(e,t){return _r({command:t.command,session:t.session,transportError:t.transportError,decision:`skipped`,reason:e.reason,lifecycleState:e.lifecycleState}),e.error}async function tr(e,t,n,r){throw _r({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 nr(e,t,n,r,i,a){if(n.command===`status`||!n.commandId?.trim())return;let o=q(r),s;try{s=await W(e,t,{command:`status`,statusCommandId:n.commandId},i.logPath,3e3,a)}catch(e){return x({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 x({level:`debug`,phase:`ios_runner_command_status_recovery`,data:{command:n.command,commandId:n.commandId,lifecycleState:c,...o}}),rr(s,c,n,r,i)}function rr(e,n,r,i,a){return n===`completed`?ir(e,r,i,a):n===`failed`?{type:`skipInvalidation`,reason:`runner_reported_failure`,lifecycleState:n,error:ar(e,r,i,a)}:n===`accepted`||n===`started`?{type:`skipInvalidation`,reason:`command_still_in_flight`,lifecycleState:n,error:or(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:gr(r.command),logPath:a.logPath,transportError:i.message},i)}}function ir(e,n,r,i){let a=sr(e.lifecycleResponseJson);if(a)return{type:`recovered`,data:a,reason:`completed_with_retained_response`,lifecycleState:`completed`};if(N(n))return{type:`skipInvalidation`,error:r,reason:`read_only_completed_without_retained_response`,lifecycleState:`completed`};let o=q(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:lr(n.command,o),logPath:i.logPath,transportError:r.message},r)}}function ar(e,n,r,i){let a=typeof e.lifecycleErrorCode==`string`?e.lifecycleErrorCode:void 0,o=typeof e.lifecycleErrorMessage==`string`?e.lifecycleErrorMessage:`Runner command failed`,s=typeof e.lifecycleErrorHint==`string`?e.lifecycleErrorHint:void 0,c=q(r),l=dt(a);return new t(l.code,o,{command:n.command,commandId:n.commandId,lifecycleState:`failed`,recovery:`runner_reported_failure`,...l.details,...c,hint:s??ur(n.command,c),logPath:i.logPath,transportError:r.message},r)}function or(e,n,r,i){if(N(n))return r;let a=q(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:dr(n.command,e,a),logPath:i.logPath,transportError:r.message},r)}function sr(e){if(typeof e!=`string`||e.trim().length===0)return;let t=cr(e);if(t.ok)return t.data&&typeof t.data==`object`&&!Array.isArray(t.data)?t.data:{}}function cr(e){try{let t=JSON.parse(e);if(t&&typeof t==`object`)return t}catch{}return{}}function lr(e,t){return`${fr(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 ur(e,t){return`${fr(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 dr(e,t,n){return`${fr(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 fr(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 pr(e,t){let n=e.details?.[t];return typeof n==`boolean`?n:void 0}function mr(e,t){let n=e.details?.[t];return typeof n==`string`?n:void 0}function hr(e,t){let n=e.details?.[t];return typeof n==`number`?n:void 0}function q(e){let t={},n=pr(e,`runnerReadinessPreflightSkipped`);n!==void 0&&(t.readinessPreflightSkipped=n);let r=mr(e,`runnerReadinessPreflightSkipReason`);r!==void 0&&(t.readinessPreflightSkipReason=r);let i=hr(e,`runnerReadinessPreflightSkippedAgeMs`);return i!==void 0&&(t.readinessPreflightSkippedAgeMs=i),t}function gr(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 _r(e){let{command:t,session:n,transportError:r,decision:i,reason:a,lifecycleState:o}=e;x({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 J=new Map;function vr(e,t){let n=e.requestId?.trim();if(n)return`request:${n}`;let r=t.commandId?.trim();if(r)return`command:${r}`}function yr(e){if(!e)return;let t=wr(e);t.touchedSession=!0,Y(e,t)}function br(e){return e?J.get(e)?.touchedSession===!0:!1}function xr(e){if(!e)return!0;let t=wr(e);return t.recycles>=1?(Y(e,t),!1):(Y(e,t),!0)}function Sr(e){if(!e)return;let t=wr(e);t.recycles+=1,Y(e,t)}function Cr(e,n){return x({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:"Check the runner log for the underlying failure before retrying — a provisioning or code-signing error there means the runner cannot install on this device, and no retry will help. If the runner is healthy, the current screen is likely too heavy or animating for accessibility capture: the app session is preserved, so run `screenshot` for visual truth and interact by coordinates, or navigate to another screen.",logPath:n.logPath})}function wr(e){return Tr(),J.get(e)??{touchedSession:!1,recycles:0,lastAtMs:Date.now()}}function Y(e,t){t.lastAtMs=Date.now(),J.delete(e),J.set(e,t)}function Tr(){let e=Date.now()-6e5;for(let[t,n]of J)n.lastAtMs<e&&J.delete(t);for(;J.size>512;){let e=J.keys().next().value;if(e===void 0)break;J.delete(e)}}async function Er(e,n){w(n.requestId);let r=C(n),i=T({command:`uptime`}),a;for(let t=1;t<=2;t+=1){let o=await Dr({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 Dr(e){let{device:t,command:n,options:r,signal:i,attempt:a,recoveryReason:o}=e,s=Date.now(),c=await R(t,{...r,cleanStaleBundles:a>1||r.cleanStaleBundles,...Pr(r,`runner_session`)}),l=Date.now()-s;try{return{kind:`prepared`,result:zr(t,await Nr(t,c,n,r,i,l,{recoveryReason:o}))}}catch(e){return await Or({device:t,session:c,command:n,options:r,signal:i,attempt:a,error:e})}}async function Or(e){let{device:t,session:n,command:a,options:o,signal:s,attempt:c,error:l}=e,u=i(l,`COMMAND_FAILED`);if(r(u))throw await X(n,`prepare_runner_request_canceled`),l;if(c===1&&Ir(u,n))return{kind:`prepared`,result:await kr({device:t,session:n,command:a,options:o,signal:s,error:u})};if(!Ar(u))throw l;let d=u.message||`runner_health_failed`;if(c>=2)throw await X(n,`prepare_runner_health_failed`),l;return w(o.requestId),await B(n,`prepare_runner_health_retry`),x({level:`warn`,phase:`ios_runner_prepare_health_retry`,data:{command:a.command,commandId:a.commandId,sessionId:n.sessionId,attempt:c,maxAttempts:2,reason:d}}),{kind:`retry`,recoveryReason:d}}async function kr(e){let{device:t,session:n,command:r,options:i,signal:a,error:o}=e,s=o.message||`runner_health_failed`;await B(n,`prepare_cached_runner_health_failed`),await xt(n.xctestrunArtifact,s);let c=Date.now(),l=await R(t,{...i,cleanStaleBundles:!0,forceRunnerXctestrunRebuild:!0,...Pr(i,`runner_rebuild`)}),u=Date.now()-c;try{let e=await Nr(t,l,r,i,a,u,{recoveryReason:s});return x({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}}),zr(t,e)}catch(e){await X(l,`prepare_rebuilt_runner_health_failed`);let n=Lr(e,l,s);throw Br(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 X(e,t){try{await B(e,t)}catch{}}function Ar(e){return r(e)?!1:S(e)||$e(e)}async function jr(e,t,n){w(n.requestId);let a=C(n),o=vr(n,t),s,c=!1;try{if(!z(e.id)?.alive&&br(o)){if(!xr(o))throw Cr(t,n);c=!0}s=await R(e,n),pn(s,n.expectedRunnerSessionId),Sn(s,t),c&&Sr(o),yr(o);let r=s.ready?rt:Jn(s);return await W(e,s,t,n.logPath,r,a)}catch(o){if(n.expectedRunnerSessionId!==void 0)throw o;let c=i(o,`COMMAND_FAILED`);if(s&&!s.ready&&r(c))throw await X(s,`runner_startup_request_canceled`),o;if(Qe(c)&&s)return w(n.requestId),await Mr({device:e,session:s,command:t,options:n,signal:a,restartReason:`runner_connect_failed_before_command_send`});if(s&&Ze(c))return w(n.requestId),await Mr({device:e,session:s,command:t,options:n,signal:a,restartReason:`runner_readiness_preflight_failed_before_command_send`,recoveredDiagnosticPhase:`ios_runner_readiness_preflight_recovered`});if(s&&S(c))return await Zn({device:e,session:s,command:t,transportError:c,options:n,signal:a,invalidationReason:`transport_error_after_command_send`,invalidateSession:B});throw o}}async function Mr(e){let{device:t,command:n,options:r,signal:a,restartReason:o}=e,s=vr(r,n);if(!xr(s))throw Cr(n,r);await B(e.session,o);let c=await R(t,{...r,cleanStaleBundles:!0}).catch(t=>{throw Z(t,e)});Sr(s);try{let i=await W(t,c,n,r.logPath,Ye,a);return e.recoveredDiagnosticPhase&&x({level:`debug`,phase:e.recoveredDiagnosticPhase,data:{command:n.command,commandId:n.commandId,recovery:`session_restarted`,sessionId:c.sessionId}}),i}catch(o){let s=i(o,`COMMAND_FAILED`);if(S(s))try{return await Zn({device:t,session:c,command:n,transportError:s,options:r,signal:a,invalidationReason:`transport_error_after_retry_command_send`,invalidateSession:B})}catch(t){throw Z(t,e,c)}throw Z(o,e,c)}}function Z(e,n,r){return e instanceof t?new t(e.code,e.message,{...e.details??{},runnerRestarted:!0,runnerRestartReason:n.restartReason,runnerRestartCommand:n.command.command,...n.command.commandId?{runnerRestartCommandId:n.command.commandId}:{},runnerInvalidatedSessionId:n.session.sessionId,...r?{runnerRestartSessionId:r.sessionId}:{},...e.details?.logPath===void 0&&n.options.logPath?{logPath:n.options.logPath}:{}},e.cause??e):e}async function Nr(e,t,n,r,i,a,o){let s=Date.now(),c=Fr(r.prepareDeadline,r.healthTimeoutMs,`runner_health`);return Rr(await W(e,t,n,r.logPath,c,i),t,a,Date.now()-s,o)}function Pr(e,t){if(!e.prepareDeadline)return{};let n=Fr(e.prepareDeadline,e.buildTimeoutMs,t);return{buildTimeoutMs:n,startupTimeoutMs:n}}function Fr(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 Ir(e,t){let n=t.xctestrunArtifact;return!n||n.cache===`miss`?!1:tt(e)}function Lr(e,n,r){let a=i(e,`COMMAND_FAILED`);return new t(a.code,`artifact restored but runner did not connect`,{...a.details??{},restoredFailureReason:r,xctestrunPath:n.xctestrunArtifact?.xctestrunPath,artifact:n.xctestrunArtifact?.artifact,cache:n.xctestrunArtifact?.cache,reason:a.message},a)}function Rr(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 zr(e,t){return Br(e,t),t}function Br(e,t){x({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}})}async function Vr(e,t,n={}){jn(e),w(n.requestId);let r=T(t),i=Q(e,n);return N(r)?Ie(()=>(w(n.requestId),i.runCommand(e,r,n)),{shouldRetry:e=>(w(n.requestId),S(e))}):i.runCommand(e,r,n)}async function Hr(e,t={}){if(s(e))try{await Vr(e,{command:`targetReset`},t)}catch(t){x({level:`warn`,phase:`ios_runner_target_reset_failed`,data:{deviceId:e.id,error:t instanceof Error?t.message:String(t)}}),await U(e.id)}}function Ur(e,t={}){if(s(e))return Gr({device:e,options:t,failurePhase:`ios_runner_cache_prewarm_failed`,task:async t=>{await yt(e,{...t,budget:b(t.buildTimeoutMs,t.signal)})}})}function Wr(e,t={}){if(!s(e))return;let n=Q(e,t).prewarm;if(!n){x({level:`debug`,phase:`ios_runner_session_prewarm_unavailable`,data:{deviceId:e.id}});return}return Gr({device:e,options:t,failurePhase:`ios_runner_session_prewarm_failed`,task:async t=>{await n(e,t)}})}function Gr(e){let{device:t,options:n,failurePhase:r,task:i}=e,{propagateError:a=!1,...o}=n;return i(o).catch(e=>{if(x({level:`warn`,phase:r,data:{deviceId:t.id,error:e instanceof Error?e.message:String(e)}}),a)throw e})}async function Kr(e,t){jn(e),w(t.requestId);let n=T({command:`uptime`}),r=Q(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 Q(e,t){return Oe(e,Yr,void 0,{requestId:t.requestId})}function qr(e,t={}){return s(e)?Q(e,t).hasLiveSession(e):!1}async function Jr(e,t={}){if(!s(e))return!1;let n=Q(e,t).releaseSpeculativeSession;return n?await n(e):!1}const Yr=Ee(jr,{prepare:Er,hasLiveSession:e=>{let t=z(e.id);return t!==null&&t.alive&&t.ready},releaseSpeculativeSession:async e=>await Cn(e.id),prewarm:async(e,t)=>{let{healthCheck:n,...r}=t;if(n===!1){await R(e,{...r,speculative:!0});return}await Er(e,{...r,speculative:!0,healthTimeoutMs:rt})}});function Xr(e){return Ke(e),{runAppleRunnerCommand:Vr,notifyIosRunnerAppRelaunched:Hr,hasLiveIosRunnerSession:qr,releaseSpeculativeIosRunnerSessionFor:Jr,prewarmAppleRunnerCache:Ur,prewarmIosRunnerSession:Wr,prepareIosRunner:Kr,resolveRunnerAppBundleId:Re,hasCachedAppleRunnerArtifact:St,detachIosSimulatorRunnerSessionsForShutdown:En,getRunnerSessionSnapshot:z,releaseIosRunnerOnClose:wn,stopIosRunnerSession:U,stopAllIosRunnerSessions:Dn,runApplePressSeries:De,cleanupRunnerLeasesForOwner:ot,readStaleRunnerLease:gt,verifyLeaseRunnerPidIdentity:O,runnerLeaseCleanupAdapter:ht,applyXctestRunnerAppIconFromDerivedPath:it}}const Zr={runCmdStreaming:te,runCmdSync:ie,runCmdBackground:ne,requireExecSuccess:ee,isCommandTimeoutError:ae,shellQuote:se,emitDiagnostic:u,withDiagnosticTimer:l,retryWithPolicy:ce,isEnvTruthy:ue,deadlineFromTimeoutMs:(e,t)=>le.fromTimeoutMs(e,t),isProcessAlive:m,isProcessGroupAlive:p,readProcessStartTime:g,readProcessCommand:_,signalPidsBestEffort:f,signalProcessGroupBestEffort:re,findProjectRoot:de,readVersion:fe,acquireProcessLock:oe,withKeyedLock:ge,publishFileSync:d,classifyOwnerLiveness:h,createTtlMemo:pe,parseBooleanLiteral:c,isRecord:a,resolveIosSimulatorDeviceSetPath:be,emitRequestProgress:ye,getRequestSignal:ve,isRequestCanceled:_e,classifyBootFailure:me,bootFailureHint:he,runAppleToolCommand:xe,runXcrun:Se,readApplePlistJson:Ce,buildSimctlArgsForDevice:Te,resolveIosPhysicalDeviceControl:we,visitXmlPlistEntries:wt,leaseOwnerStateDir:Tt,hasDeviceClaimAuthority:e=>Et()?.(e)??!1};var Qr=e({applyXctestRunnerAppIconFromDerivedPath:()=>_i,cleanupRunnerLeasesForOwner:()=>mi,detachIosSimulatorRunnerSessionsForShutdown:()=>ci,getRunnerSessionSnapshot:()=>li,hasCachedAppleRunnerArtifact:()=>si,hasLiveIosRunnerSession:()=>ti,notifyIosRunnerAppRelaunched:()=>ei,prepareIosRunner:()=>ai,prewarmAppleRunnerCache:()=>ri,prewarmIosRunnerSession:()=>ii,readStaleRunnerLease:()=>hi,releaseIosRunnerOnClose:()=>ui,releaseSpeculativeIosRunnerSessionFor:()=>ni,resolveRunnerAppBundleId:()=>oi,runApplePressSeries:()=>pi,runAppleRunnerCommand:()=>$r,stopAllIosRunnerSessions:()=>fi,stopIosRunnerSession:()=>di,verifyLeaseRunnerPidIdentity:()=>gi});const $=Xr(Zr),$r=$.runAppleRunnerCommand,ei=$.notifyIosRunnerAppRelaunched,ti=$.hasLiveIosRunnerSession,ni=$.releaseSpeculativeIosRunnerSessionFor,ri=$.prewarmAppleRunnerCache,ii=$.prewarmIosRunnerSession,ai=$.prepareIosRunner,oi=$.resolveRunnerAppBundleId,si=$.hasCachedAppleRunnerArtifact,ci=$.detachIosSimulatorRunnerSessionsForShutdown,li=$.getRunnerSessionSnapshot,ui=$.releaseIosRunnerOnClose,di=$.stopIosRunnerSession,fi=$.stopAllIosRunnerSessions,pi=$.runApplePressSeries,mi=$.cleanupRunnerLeasesForOwner,hi=$.readStaleRunnerLease,gi=$.verifyLeaseRunnerPidIdentity,_i=$.applyXctestRunnerAppIconFromDerivedPath;export{fi as _,ti as a,ri as c,ui as d,ni as f,Qr as g,$r as h,si as i,ii as l,pi as m,ci as n,ei as o,oi as p,li as r,ai as s,_i as t,hi as u,di as v,gi as y};