agent-device 0.19.1 → 0.19.3

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