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