agent-device 0.16.11 → 0.16.12

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 CHANGED
@@ -56,7 +56,7 @@ agent-device help workflow
56
56
 
57
57
  The installed CLI help is the source of truth for agents. Start with `agent-device help workflow`, then follow the topic-specific help when a task needs dogfooding, debugging, replay, or React Native profiling.
58
58
 
59
- Prerequisites depend on the target platform: Node.js 22+, Xcode for iOS/tvOS/macOS targets, Android SDK + ADB for Android, and macOS Accessibility permission for desktop automation. See [Installation](https://incubator.callstack.com/agent-device/docs/installation) for platform setup.
59
+ Prerequisites depend on the target platform: Node.js 22+, Xcode for iOS/tvOS/macOS targets, Android SDK + ADB for Android, and macOS Accessibility permission for desktop automation. See [Installation](https://oss.callstack.com/agent-device/docs/installation) for platform setup.
60
60
 
61
61
  Try the basic loop:
62
62
 
@@ -84,9 +84,9 @@ Snapshots assign refs like `@e1`, `@e2`, and `@e3` to elements on the current sc
84
84
 
85
85
  ## Next Steps
86
86
 
87
- - **Set up your agent**: run the CLI from Cursor, Codex, Claude Code, Windsurf, or another agent terminal. For skills, rules, direct MCP tools, and client-specific setup, see [AI Agent Setup](https://incubator.callstack.com/agent-device/docs/agent-setup).
88
- - **Try the sample app**: clone the repo and run the bundled Expo fixture when you want a guided first dogfood run with screenshots, replay, and performance evidence. See [Quick Start](https://incubator.callstack.com/agent-device/docs/quick-start).
89
- - **Go deeper**: use [Commands](https://incubator.callstack.com/agent-device/docs/commands), [Replay & E2E](https://incubator.callstack.com/agent-device/docs/replay-e2e), and [Debugging & Profiling](https://incubator.callstack.com/agent-device/docs/debugging-profiling) for production workflows.
87
+ - **Set up your agent**: run the CLI from Cursor, Codex, Claude Code, Windsurf, or another agent terminal. For skills, rules, direct MCP tools, and client-specific setup, see [AI Agent Setup](https://oss.callstack.com/agent-device/docs/agent-setup).
88
+ - **Try the sample app**: clone the repo and run the bundled Expo fixture when you want a guided first dogfood run with screenshots, replay, and performance evidence. See [Quick Start](https://oss.callstack.com/agent-device/docs/quick-start).
89
+ - **Go deeper**: use [Commands](https://oss.callstack.com/agent-device/docs/commands), [Replay & E2E](https://oss.callstack.com/agent-device/docs/replay-e2e), and [Debugging & Profiling](https://oss.callstack.com/agent-device/docs/debugging-profiling) for production workflows.
90
90
 
91
91
  ## Where To Run agent-device
92
92
 
@@ -94,7 +94,7 @@ Snapshots assign refs like `@e1`, `@e2`, and `@e3` to elements on the current sc
94
94
  | --- | --- | --- |
95
95
  | Local | Exploration, debugging, and development loops on simulators, emulators, physical devices, macOS apps, and Linux desktop targets. | Follow the Quick Start. |
96
96
  | CI/CD | Automated PR and merge validation with replay scripts and captured artifacts. | Try the [EAS workflow template](https://github.com/callstackincubator/eas-agent-device/blob/main/.eas/workflows/agent-qa-mobile.yml). GitHub Actions template coming soon. |
97
- | Cloud / remote execution | Linux runners, managed devices, and remote execution. | Use [Agent Device Cloud](https://agent-device.dev/cloud), see [Commands](https://incubator.callstack.com/agent-device/docs/commands) for remote profiles, or [contact Callstack](mailto:hello@callstack.com) for team-scale QA. |
97
+ | Cloud / remote execution | Linux runners, managed devices, and remote execution. | Use [Agent Device Cloud](https://agent-device.dev/cloud), see [Commands](https://oss.callstack.com/agent-device/docs/commands) for remote profiles, or [contact Callstack](mailto:hello@callstack.com) for team-scale QA. |
98
98
 
99
99
  ## How It Works
100
100
 
@@ -122,8 +122,8 @@ Used by teams and developers at Callstack, Expensify, Shopify, Kindred, Total Wi
122
122
 
123
123
  ## Documentation
124
124
 
125
- - [Docs](https://incubator.callstack.com/agent-device/)
126
- - [Agent-readable docs](https://incubator.callstack.com/agent-device/llms-full.txt)
125
+ - [Docs](https://oss.callstack.com/agent-device/)
126
+ - [Agent-readable docs](https://oss.callstack.com/agent-device/llms-full.txt)
127
127
 
128
128
  ## Contributing
129
129
 
@@ -131,4 +131,4 @@ See [CONTRIBUTING.md](CONTRIBUTING.md).
131
131
 
132
132
  ## Made at Callstack
133
133
 
134
- `agent-device` is open source and MIT licensed. Visit [agent-device.dev](https://agent-device.dev/), try the [EAS workflow template](https://github.com/callstackincubator/eas-agent-device/blob/main/.eas/workflows/agent-qa-mobile.yml), read the [incubator docs](https://incubator.callstack.com/agent-device/), or contact us at hello@callstack.com.
134
+ `agent-device` is open source and MIT licensed. Visit [agent-device.dev](https://agent-device.dev/), try the [EAS workflow template](https://github.com/callstackincubator/eas-agent-device/blob/main/.eas/workflows/agent-qa-mobile.yml), read the [docs](https://oss.callstack.com/agent-device/), or contact us at hello@callstack.com.
@@ -0,0 +1 @@
1
+ 825882995f94410c3166f554017193b0c4258b66d513bdfd8d5f0f08e640a2ab agent-device-android-multitouch-helper-0.16.12.apk
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "android-multitouch-helper",
3
- "version": "0.16.11",
4
- "assetName": "agent-device-android-multitouch-helper-0.16.11.apk",
5
- "sha256": "2b408efdce7368b2a0f8d7ca0cf1fdec6165330919a09e7276ec0704653f7bb3",
3
+ "version": "0.16.12",
4
+ "assetName": "agent-device-android-multitouch-helper-0.16.12.apk",
5
+ "sha256": "825882995f94410c3166f554017193b0c4258b66d513bdfd8d5f0f08e640a2ab",
6
6
  "packageName": "com.callstack.agentdevice.multitouchhelper",
7
- "versionCode": 16011,
7
+ "versionCode": 16012,
8
8
  "instrumentationRunner": "com.callstack.agentdevice.multitouchhelper/.MultiTouchInstrumentation",
9
9
  "statusProtocol": "android-multitouch-helper-v1"
10
10
  }
@@ -0,0 +1 @@
1
+ ac2eb5f57dc44bf5d9a2a9ebce7b4e1040aa5f14361283bf497bf9502ff8cb6d agent-device-android-snapshot-helper-0.16.12.apk
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "android-snapshot-helper",
3
- "version": "0.16.11",
4
- "releaseTag": "v0.16.11",
5
- "assetName": "agent-device-android-snapshot-helper-0.16.11.apk",
3
+ "version": "0.16.12",
4
+ "releaseTag": "v0.16.12",
5
+ "assetName": "agent-device-android-snapshot-helper-0.16.12.apk",
6
6
  "apkUrl": null,
7
- "sha256": "df75ea0154748d4c06368a62808b7b071b86de7e322c96c756076114b6611416",
8
- "checksumName": "agent-device-android-snapshot-helper-0.16.11.apk.sha256",
7
+ "sha256": "ac2eb5f57dc44bf5d9a2a9ebce7b4e1040aa5f14361283bf497bf9502ff8cb6d",
8
+ "checksumName": "agent-device-android-snapshot-helper-0.16.12.apk.sha256",
9
9
  "packageName": "com.callstack.agentdevice.snapshothelper",
10
- "versionCode": 16011,
10
+ "versionCode": 16012,
11
11
  "instrumentationRunner": "com.callstack.agentdevice.snapshothelper/.SnapshotInstrumentation",
12
12
  "minSdk": 23,
13
13
  "targetSdk": 36,
package/dist/src/2415.js CHANGED
@@ -7,7 +7,7 @@ ${r}`,i=/dumped to:\s*(\S+)/i.exec(n),i?.[1]);if(0!==l.exitCode&&!d)throw new L(
7
7
  ${t}`,n=r.indexOf("<?xml"),i=n>=0?n:r.indexOf("<hierarchy");if(i<0)return null;let a=r.lastIndexOf("</hierarchy>");if(a<0||a<i)return null;let o=r.slice(i,a+12).trim();return o.length>0?o:null}function o_(e){if(!(e instanceof L)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details?.stderr,r=("string"==typeof t?t:"").toLowerCase();return ot.some(e=>r.includes(e))}async function oI(e,t=e7(e)){try{let e=await t(["shell","dumpsys","activity","top"],{allowFailure:!0,timeoutMs:8e3}),r=`${e.stdout}
8
8
  ${e.stderr}`.trim();return r.length>0?r:null}catch{return null}}function ob(e,t,r){if(0===e.size)return;let n=new Map;for(let[e,t]of r.sourceNodes.entries()){let i=r.nodes[e];i&&n.set(t,i)}for(let[r,i]of e){let e=t.sourceNodes[r];if(!e)continue;let a=n.get(e);a&&(i.hiddenContentAbove&&(a.hiddenContentAbove=!0),i.hiddenContentBelow&&(a.hiddenContentBelow=!0))}}let oA=/\bis(?:n(?:'|&apos;|&#39;)?t| not)\s+responding\b/i,ox=/^close app$/i,oN="Wait for Android to recover, close the dialog, restart the app, or reboot the emulator, then retry.";async function oM(e){let{session:t}=e;if("android"!==t.device.platform||!t.recording)return"absent";try{let e=await oR(t),r=oT(e);if(!r?.rect)return"absent";let n=await oO(t,r);if(!n.ok)return N({level:"warn",phase:"android_blocking_dialog_tap_failed",data:{session:t.name,deviceId:t.device.id,exitCode:n.exitCode,stdout:n.stdout.trim(),stderr:n.stderr.trim()}}),"failed";if(!await oL(t))return N({level:"warn",phase:"android_blocking_dialog_still_present",data:{session:t.name,deviceId:t.device.id}}),"failed";if(t.appBundleId&&(await ea(t.device,t.appBundleId),!await o$(t,t.appBundleId)))return N({level:"warn",phase:"android_blocking_dialog_relaunch_unfocused",data:{session:t.name,deviceId:t.device.id,appBundleId:t.appBundleId}}),"failed";return N({level:"warn",phase:"android_blocking_dialog_recovered",data:{session:t.name,deviceId:t.device.id,appBundleId:t.appBundleId,x:n.x,y:n.y}}),"recovered"}catch(e){return N({level:"warn",phase:"android_blocking_dialog_recovery_failed",data:{session:t.name,deviceId:t.device.id,error:e instanceof Error?e.message:String(e)}}),"failed"}}async function oE(e){var t,r;let{session:n,command:i}=e;if("android"!==n.device.platform)return{status:"clear"};let a=await et(n.device);if(!a)return{status:"clear"};if(t=n,r=a,t.appBundleId&&r.package===t.appBundleId){if(await oD(n)){let t=`Recovered Android app ANR before ${i}: closed and relaunched ${n.appBundleId}.`;if("before-command"===e.phase)return{status:"recovered",warning:t};throw oP({session:n,command:i,focus:a,message:`Android app ANR appeared after ${i}; ${n.appBundleId} was closed and relaunched. Retry the command against the fresh app session.`,hint:"Retry the command. If the ANR returns, inspect app logs or restart the emulator."})}throw oP({session:n,command:i,focus:a,message:`Android app ANR blocked ${i}: ${oC(a)}. Automatic recovery failed.`,hint:oN})}throw oP({session:n,command:i,focus:a,message:`Android system dialog is blocking ${i}: ${oC(a)}.`,hint:oN})}async function oD(e){try{return await ok(e)}catch(t){return N({level:"warn",phase:"android_app_anr_recovery_failed",data:{session:e.name,deviceId:e.device.id,appBundleId:e.appBundleId,error:t instanceof Error?t.message:String(t)}}),!1}}async function ok(e){if(!e.appBundleId)return!1;let t=oT(await oR(e),{requireDialogSignal:!1});if(!t?.rect)return!1;let r=await oO(e,t);if(!r.ok)return!1;await ea(e.device,e.appBundleId);let n=await o$(e,e.appBundleId,{requireNoBlockingDialog:!0});return n&&N({level:"warn",phase:"android_app_anr_recovered",data:{session:e.name,deviceId:e.device.id,appBundleId:e.appBundleId,x:r.x,y:r.y}}),n}function oP(e){let{session:t,command:r,focus:n,message:i,hint:a}=e;return new L("COMMAND_FAILED",i,{command:r,expectedPackage:t.appBundleId,focusedPackage:n.package,focusedWindow:n.focusedWindow,rawFocus:n.raw,hint:a})}function oC(e){return e.package?`${e.focusedWindow} (package ${e.package})`:e.focusedWindow}async function oR(e){return e4(eX((await on(e.device,{interactiveOnly:!1,compact:!1})).nodes))}async function oO(e,t){if(!t.rect)return{ok:!1,exitCode:1,stdout:"",stderr:"button has no rect"};let{x:r,y:n}=e3(t.rect),i=await Q(e.device,["shell","input","tap",String(Math.round(r)),String(Math.round(n))],{allowFailure:!0});return 0!==i.exitCode?{ok:!1,exitCode:i.exitCode,stdout:i.stdout.trim(),stderr:i.stderr.trim()}:{ok:!0,x:r,y:n}}function oT(e,t={}){if(!1===t.requireDialogSignal||oG(e))return e.find(e=>oU(e).some(e=>ox.test(e))&&e.rect)}async function oL(e){for(let t=0;t<12;t+=1){if(!oG(await oR(e)))return!0;await eV(500)}return!oG(await oR(e))}async function o$(e,t,r={}){for(let n=0;n<12;n+=1){if(await oF(e,t,r))return!0;await eV(500)}return await oF(e,t,r)}async function oF(e,t,r){return!(r.requireNoBlockingDialog&&await et(e.device))&&(await ep(e.device)).package===t}function oU(e){let t=[e.label,e.identifier];return"string"==typeof e.value&&e.value.trim().length>0&&t.push(e.value),t.filter(e=>"string"==typeof e&&e.trim().length>0).map(e=>e.trim())}function oG(e){return e.some(e=>{let t=oU(e).join(" ").trim();return t.length>0&&oA.test(t)})}function oq(e){return!!(e&&e.width>0&&e.height>0)}function oj(e){return e.width*e.height}function oV(e,t){return t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height}let oB=[255,59,48,255],oH=[255,214,10,255],oK=[0,0,0,255],oW=["scroll","list","recyclerview","edittext","textfield"],oz=["button","link","menu","tab","textfield","searchfield","securetextfield","checkbox","radio","switch","cell"],oJ={e:["01110","10000","11110","10000","10000","10001","01110"],0:["01110","10001","10011","10101","11001","10001","01110"],1:["00100","01100","00100","00100","00100","00100","01110"],2:["01110","10001","00001","00010","00100","01000","11111"],3:["11110","00001","00001","01110","00001","00001","11110"],4:["00010","00110","01010","10010","11111","00010","00010"],5:["11111","10000","10000","11110","00001","00001","11110"],6:["01110","10000","10000","11110","10001","10001","01110"],7:["11111","00001","00010","00100","01000","01000","01000"],8:["01110","10001","10001","01110","10001","10001","01110"],9:["01110","10001","10001","01111","00001","00001","01110"]};async function oX(e){let t=eG(await o.readFile(e.screenshotPath),"screenshot"),r=function(e,t,r,n={}){let i=function(e){let t=null;for(let r of e)oQ(r)&&oq(r.rect)&&(!t||oj(r.rect)>oj(t))&&(t=r.rect);return t||function(e){let t=1/0,r=1/0,n=-1/0,i=-1/0;for(let a of e)a.rect&&oq(a.rect)&&(t=Math.min(t,a.rect.x),r=Math.min(r,a.rect.y),n=Math.max(n,a.rect.x+a.rect.width),i=Math.max(i,a.rect.y+a.rect.height));return!Number.isFinite(t)||!Number.isFinite(r)||n<=t||i<=r?null:{x:t,y:r,width:n-t,height:i-r}}(e.filter(e=>{var t;return oq(e.rect)&&!("image"===eJ((t=e).type??"")&&!o1(t.label))}))}(e.nodes),a=new Map;for(let n of e.nodes){var o,s;if(!function(e,t,r){let n=[r.label,r.value].some(o2)||o3(r.identifier);return!!function(e,t,r){if("android"!==e.backend||!r.hittable||!oq(r.rect)||oQ(r))return!1;let n=eJ(r.type??"");return!(oW.some(e=>n.includes(e))||t&&oj(r.rect)>.25*oj(t))}(e,t,r)||(oY(r)?n:n&&function(e){let t=eJ(e.type??"");return t.includes("statictext")||t.includes("image")||t.includes("text")||t.includes("other")}(r))}(e,i,n))continue;let l=(o=e.nodes,[function(e){return oY(e)&&!oQ(e)}(s=n)?s:null,ez(o,s,e=>(function(e){return oY(e)&&!oQ(e)})(e)),s.hittable?s:null,ez(o,s,e=>!0===e.hittable)].find(o0)??null);if(!l?.rect||!oq(l.rect))continue;let d=function(e,t,r){let n=o4(e);if(e.ref!==t.ref&&n)return n;let i=function(e,t){let r=null;for(let n of t){if(n.ref===e.ref||!function(e,t,r){let n=e;for(;void 0!==n.parentIndex;){let e=r[n.parentIndex];if(!e)break;if(e.ref===t.ref)return!0;n=e}return!1}(n,e,t))continue;let i=o4(n);if(!i)continue;let a=function(e){let t=0;return eJ(e.type??"").includes("text")&&(t+=2),o2(e.label)&&(t+=2),o2(e.value)&&(t+=1),t}(n);(!r||a>r.score)&&(r={label:i,score:a})}return r?.label}(t,r);return i||o4(t)}(n,l,e.nodes),c=function(e,t,r){let n=0;return e.ref===t.ref&&(n+=4),t.hittable&&(n+=3),oY(t)&&(n+=3),oY(e)&&(n+=2),r&&(n+=2),o3(t.identifier)&&(n+=1),o1(t.value)&&(n+=1),n}(n,l,d),u=function(e,t,r){var n,i;return"android"!==e.backend?t.rect:(n=oY,i=e=>!!o4(e),(!t.rect||!0!==t.hittable||n(t)||i(t)?null:function(e,t,r){let n=e.rect,i=function(e,t,r){let n=e.rect,i=new Map(t.map(e=>[e.index,e])),a=t.filter(t=>t.ref!==e.ref&&function(e,t,r){let n=e;for(;void 0!==n.parentIndex;){let e=r.get(n.parentIndex);if(!e)break;if(e.ref===t.ref)return!0;n=e}return!1}(t,e,i)&&function(e,t){let r=eJ(e.type??"");return r.includes("text")||r.includes("image")&&t(e)}(t,r)&&oq(t.rect)&&oV(n,t.rect)).map(e=>e.rect);return a.length<2?null:function(e){let t=e[0];if(void 0===t)throw Error("unionRects requires at least one rect");let r=t.x,n=t.y,i=t.x+t.width,a=t.y+t.height;for(let t of e.slice(1))r=Math.min(r,t.x),n=Math.min(n,t.y),i=Math.max(i,t.x+t.width),a=Math.max(a,t.y+t.height);return{x:r,y:n,width:i-r,height:a-n}}(a)}(e,t,r);if(!i)return null;let a=i.y-n.y,o=n.y+n.height-(i.y+i.height);if(a<0||o<0||16>Math.abs(o-a))return null;let s=Math.min(a,o),l=Math.round(i.y-s),d=Math.round(i.height+2*s);return d<=0||d>=n.height?null:{x:n.x,y:l,width:n.width,height:d}}(t,r,i))??t.rect)}(e,l,e.nodes),p=oZ(e,i,u,t,r);if(!oq(p))continue;let f=a.get(l.ref);(!f||c>f.score)&&a.set(l.ref,{ref:l.ref,label:d,rect:l.rect,overlayRect:p,score:c})}return function(e,t,r,n,i){let a=eb(e.nodes).primaryAction;if(!a?.ref||!a.rect||!oq(a.rect))return;let o=oZ(e,t,a.rect,n,i);if(!oq(o))return;let s={ref:a.ref,label:a.label,rect:a.rect,overlayRect:o,score:100},l=r.get(a.ref);r.set(a.ref,l?{...l,score:Math.max(l.score,s.score)}:s)}(e,i,a,t,r),(function(e){let t=[];for(let r of e.sort((e,t)=>oj(e.overlayRect)-oj(t.overlayRect))){let e=t.findIndex(e=>void 0!==e.label&&e.label===r.label&&(oV(e.overlayRect,r.overlayRect)||oV(r.overlayRect,e.overlayRect)));if(-1===e){t.push(r);continue}oj(r.overlayRect)<oj(t[e].overlayRect)&&(t[e]=r)}return t})([...a.values()]).sort(st).slice(0,n.maxRefs??24).sort(se).map(e=>({ref:e.ref,label:e.label,rect:e.rect,overlayRect:e.overlayRect,center:e3(e.overlayRect)}))}(e.snapshot,t.width,t.height,{maxRefs:e.maxRefs});for(let e of r){var n,i;(function(e,t,r){for(let n=0;n<2;n+=1)o6(e,t.x,t.x+t.width-1,t.y+n,r),o6(e,t.x,t.x+t.width-1,t.y+t.height-1-n,r),o9(e,t.x+n,t.y,t.y+t.height-1,r),o9(e,t.x+t.width-1-n,t.y,t.y+t.height-1,r)})(n=t,(i=e).overlayRect,oB),function(e,t,r){let n=6+5*r.length+ +Math.max(0,r.length-1),i=o8(t.x,0,Math.max(0,e.width-n)),a=t.y-11-2,o=a>=0?a:o8(t.y+2,0,Math.max(0,e.height-11));(function(e,t,r,n,i){for(let a=0;a<11;a+=1)for(let o=0;o<n;o+=1)o7(e,t+o,r+a,i)})(e,i,o,n,oH),function(e,t,r,n,i){let a=t;for(let t of n.toLowerCase()){let n=oJ[t];if(n)for(let t=0;t<n.length;t+=1)for(let o=0;o<n[t].length;o+=1)"1"===n[t][o]&&o7(e,a+o,r+t,i);a+=6}}(e,i+3,o+2,r,oK)}(n,i.overlayRect,i.ref)}return await o.writeFile(e.screenshotPath,eO.sync.write(t)),r}function oZ(e,t,r,n,i){if("android"===e.backend||!t)return o5(function(e){return{x:Math.round(e.x),y:Math.round(e.y),width:Math.round(e.width),height:Math.round(e.height)}}(r),n,i);let a=n/t.width,o=i/t.height;return o5({x:Math.round((r.x-t.x)*a),y:Math.round((r.y-t.y)*o),width:Math.max(1,Math.round(r.width*a)),height:Math.max(1,Math.round(r.height*o))},n,i)}function oY(e){let t=[e.type,e.role,e.subrole].map(e=>eJ(e??"")).join(" ");return oz.some(e=>t.includes(e))}function oQ(e){let t=[e.type,e.role,e.subrole].map(e=>eJ(e??"")).join(" ");return t.includes("application")||t.includes("window")}function o0(e){return!!(e?.rect&&oq(e.rect)&&!oQ(e))}function o1(e){if("string"!=typeof e)return!1;let t=e.trim();return!(!t||/^(true|false)$/i.test(t))}function o2(e){var t;let r;return!!o1(e)&&(t=e,"toolbar"!==(r=t?.trim().toLowerCase())&&"window"!==r&&"application"!==r&&r?.startsWith("vertical scroll bar")!==!0)}function o3(e){var t;return"string"==typeof e&&!!o2(e)&&(t=e,!/^[a-z0-9_.]+:id\/[a-z0-9_.-]+$/i.test(t.trim()))}function o4(e){let t=[e.label,e.value].find(o2);return t?t.trim():o3(e.identifier)?e.identifier.trim():void 0}function o5(e,t,r){let n=o8(e.x,0,Math.max(0,t-1)),i=o8(e.y,0,Math.max(0,r-1)),a=Math.max(1,t-n),o=Math.max(1,r-i);return{x:n,y:i,width:o8(e.width,1,a),height:o8(e.height,1,o)}}function o8(e,t,r){return Number.isFinite(e)?Math.max(t,Math.min(r,e)):t}function o6(e,t,r,n,i){for(let a=t;a<=r;a+=1)o7(e,a,n,i)}function o9(e,t,r,n,i){for(let a=r;a<=n;a+=1)o7(e,t,a,i)}function o7(e,t,r,n){if(t<0||r<0||t>=e.width||r>=e.height)return;let i=(e.width*r+t)*4;e.data[i]=n[0],e.data[i+1]=n[1],e.data[i+2]=n[2],e.data[i+3]=n[3]}function se(e,t){var r,n;let i=e.overlayRect.y-t.overlayRect.y;if(0!==i)return i;let a=e.overlayRect.x-t.overlayRect.x;return 0!==a?a:(r=e.ref,n=t.ref,Number.parseInt(r.replace(/^\D+/,""),10)-Number.parseInt(n.replace(/^\D+/,""),10))}function st(e,t){return t.score!==e.score?t.score-e.score:se(e,t)}function sr(e){return"number"==typeof e.gestureClockOriginAtMs&&"number"==typeof e.gestureClockOriginUptimeMs&&"number"==typeof e.gestureStartUptimeMs?Math.max(0,e.gestureClockOriginAtMs+(e.gestureStartUptimeMs-e.gestureClockOriginUptimeMs)-e.recordingStartedAt):"number"==typeof e.runnerStartedAtUptimeMs&&"number"==typeof e.gestureStartUptimeMs?Math.max(0,e.gestureStartUptimeMs-e.runnerStartedAtUptimeMs):"number"==typeof e.gestureStartUptimeMs&&"number"==typeof e.gestureEndUptimeMs?Math.max(0,e.fallbackFinishedAtMs-(e.gestureEndUptimeMs-e.gestureStartUptimeMs)-e.recordingStartedAt):Math.max(0,e.fallbackStartedAtMs-e.recordingStartedAt)}let sn=new WeakMap;function si(e){if(!e)return;let t=sn.get(e);if(t)return t;let r=sa(e.nodes??[]);if(r)return sn.set(e,r),r}let sa=eF,so={referenceWidth:1e3,referenceHeight:1e3};function ss(e,t,r,n,i={},a=Date.now(),o=Date.now()){var s,l,d,c,u,p,f,m,h;let w,g,v,y=e.recording;if(!y)return;let S={...i,...n??{}},_=sh(S.effectiveDurationMs)??sh(S.durationMs),I={recordingStartedAt:y.startedAt,gestureClockOriginAtMs:y.gestureClockOriginAtMs,gestureClockOriginUptimeMs:y.gestureClockOriginUptimeMs,runnerStartedAtUptimeMs:"ios-device-runner"===y.platform?y.runnerStartedAtUptimeMs:void 0,gestureStartUptimeMs:sh(S.gestureStartUptimeMs),gestureEndUptimeMs:sh(S.gestureEndUptimeMs),fallbackStartedAtMs:a,fallbackFinishedAtMs:o},b="number"==typeof(s={gestureStartUptimeMs:sh(S.gestureStartUptimeMs),gestureEndUptimeMs:sh(S.gestureEndUptimeMs),reportedDurationMs:_,fallbackStartedAtMs:a,fallbackFinishedAtMs:o}).gestureStartUptimeMs&&"number"==typeof s.gestureEndUptimeMs?Math.max(0,s.gestureEndUptimeMs-s.gestureStartUptimeMs):"number"==typeof s.reportedDurationMs?Math.max(0,s.reportedDurationMs):Math.max(0,s.fallbackFinishedAtMs-s.fallbackStartedAtMs),A="ios"===e.device.platform&&void 0===sh(S.gestureStartUptimeMs)&&function(e,t){switch(e){case"click":case"fill":case"focus":return!0;case"press":{let e=sw(sh(t.count),1)??1,r=!0===t.doubleTap,n=sw(sh(t.holdMs),1);return 1===e&&!r&&void 0===n}case"react-native":return"dismiss-overlay"===t.action;default:return!1}}(t,S)?function(e){let t=Math.max(0,e.gestureDurationMs);if(t<600)return sr(e);let r=Math.min(Math.max(.15*t,120),260);return Math.max(0,e.fallbackFinishedAtMs-r-e.recordingStartedAt)}({...I,gestureDurationMs:b}):sr(I),x=(l=e.snapshot,w=sh((d=S).referenceWidth),g=sh(d.referenceHeight),void 0!==w&&w>0&&void 0!==g&&g>0?{referenceWidth:w,referenceHeight:g}:si(l)),M=(c=t,u=r,p=S,f=A,m=b,h=x,v=sl[c],v?.(u,p,f,m,h)??[]);0!==M.length&&(y.gestureEvents.push(...M),N({level:"debug",phase:"record_touch_visualization_event",data:{session:e.name,command:t,count:M.length,tMs:A,gestureDurationMs:b,kinds:M.map(e=>e.kind)}}))}let sl={click:(e,t,r,n,i)=>sd(e,t,r,i),press:(e,t,r,n,i)=>sd(e,t,r,i),"react-native":(e,t,r,n,i)=>"dismiss-overlay"===e[0]?sd(e,t,r,i):[],fill:(e,t,r,n,i)=>sc(e,t,r,i),focus:(e,t,r,n,i)=>sc(e,t,r,i),longpress:function(e,t,r,n,i){let a=sg(t,e);if(!a)return[];let{x:o,y:s}=a;return[sf(r,o,s,sS(n,[sh(t.durationMs),sh(e[2])],800),i)]},scroll:function(e,t,r,n,i){let a=sv(t,e),o=sm(t.contentDirection)??sm(t.direction);if(!a||!o)return[];let{x1:s,y1:l,x2:d,y2:c}=a,u=sS(n,[],250),p=sh(t.amount)??sh(e[1]),f=sh(t.pixels);return[{kind:"scroll",tMs:r,x:s,y:l,x2:d,y2:c,...i,durationMs:u,contentDirection:o,...void 0!==p?{amount:p}:{},...void 0!==f?{pixels:f}:{}}]},pan:su,fling:su,swipe:su,pinch:function(e,t,r,n,i){let a=sg(t,e,1),o=sh(t.scale)??sh(e[0]);if(!a||void 0===o||o<=0)return[];let{x:s,y:l}=a;return[{kind:"pinch",tMs:r,x:s,y:l,...i,scale:o,durationMs:sS(n,[],280)}]}};function sd(e,t,r,n){let i=sg(t,e);if(!i)return[];let{x:a,y:o}=i,s=sw(sh(t.count),1)??1,l=sw(sh(t.intervalMs),0)??0,d=!0===t.doubleTap,c=sw(sh(t.holdMs),1),u=[];for(let e=0;e<s;e+=1){let t=r+e*l;if(void 0!==c&&c>0){u.push(sf(t,a,o,c,n));continue}u.push(sp(t,a,o,n)),d&&u.push(sp(t+90,a,o,n))}return u}function sc(e,t,r,n){let i=sg(t,e);if(!i)return[];let{x:a,y:o}=i;return[sp(r,a,o,n)]}function su(e,t,r,n,i){let a=sv(t,e);if(!a)return[];let{x1:o,y1:s,x2:l,y2:d}=a,c=sS(n,[sh(t.effectiveDurationMs),sh(t.durationMs),sh(e[4])],250),u=sw(sh(t.count),1)??1,p=sw(sh(t.pauseMs),0)??0,f="ping-pong"===t.pattern?"ping-pong":"one-way";return Array.from({length:u},(e,t)=>{var n,a,u,m,h,w,g,v,y,S,_,I,b;let A,{startX:x,startY:N,endX:M,endY:E}=(n=t,a=f,u=o,m=s,h=l,w=d,"ping-pong"===a&&n%2==1?{startX:h,startY:w,endX:u,endY:m}:{startX:u,startY:m,endX:h,endY:w});return g=r+t*(c+p),v=x,y=N,S=M,_=E,I=c,"back-swipe"===(A=function(e,t,r,n,i){if(!i||Math.abs(r-e)<=1.25*Math.abs(n-t))return"swipe";let a=.08*i.referenceWidth;return e<=a&&r>e||e>=i.referenceWidth-a&&r<e?"back-swipe":"swipe"}(v,y,S,_,b=i))?{kind:A,tMs:g,x:v,y,x2:S,y2:_,...b,durationMs:I,edge:function(e,t,r){if(r){let t=.08*r.referenceWidth;if(e<=t)return"left";if(e>=r.referenceWidth-t)return"right"}return t>=e?"left":"right"}(v,S,b)}:{kind:A,tMs:g,x:v,y,x2:S,y2:_,...b,durationMs:I}})}function sp(e,t,r,n){return{kind:"tap",tMs:e,x:t,y:r,...n}}function sf(e,t,r,n,i){return{kind:"longpress",tMs:e,x:t,y:r,...i,durationMs:n}}function sm(e){if("string"!=typeof e)return;let t=e.trim().toLowerCase();switch(t){case"up":case"down":case"left":case"right":return t;default:return}}function sh(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"!=typeof e||0===e.trim().length)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function sw(e,t){if(void 0===e)return;let r=Math.floor(e);return r>=t?r:void 0}function sg(e,t,r=0){let n=sh(e.x)??sh(t[r]),i=sh(e.y)??sh(t[r+1]);if(void 0!==n&&void 0!==i)return{x:n,y:i}}function sv(e,t){let r=sy(e.x1,e.x,t[0]),n=sy(e.y1,e.y,t[1]),i=sy(e.x2,t[2]),a=sy(e.y2,t[3]);if(void 0!==r&&void 0!==n&&void 0!==i&&void 0!==a)return{x1:r,y1:n,x2:i,y2:a}}function sy(...e){return e.map(sh).find(e=>void 0!==e)}function sS(e,t,r){return sw(e,1)??t.map(e=>sw(e,1)).find(e=>void 0!==e)??r}let s_={pan:"pan",fling:"fling",swipe:"swipe-preset",pinch:"pinch",rotate:"rotate-gesture",transform:"transform-gesture"};async function sI(e){var t,r,n,i,a,o,s,l;let d,c,u,p,f,{req:m,session:h,logPath:w,sessionStore:g,contextFromFlags:v}=e,y=function(e){if("pan"===e.command||"fling"===e.command||"rotate-gesture"===e.command||"transform-gesture"===e.command)return{ok:!1,message:"Use gesture pan, gesture fling, gesture swipe, gesture rotate, or gesture transform."};if("gesture"!==e.command)return{ok:!0,platformCommand:e.command,dispatchRequest:e,recordedCommand:e.command};let[t,...r]=e.positionals??[],n=t?s_[t]:void 0;return n?{ok:!0,platformCommand:n,dispatchRequest:{...e,command:n,positionals:r},recordedCommand:e.command}:{ok:!1,message:eS}}(m);if(!y.ok)return{ok:!1,error:{code:"INVALID_ARGS",message:y.message}};let{platformCommand:S,dispatchRequest:_,recordedCommand:I}=y,b=await sA(h,S);if(b)return b;let A=await sb(h,S);if("response"in A)return A.response;let{resolvedPositionals:x,resolvedOut:N,recordedPositionals:M,recordedFlags:E}="screenshot"===(t=_).command?(c=(n=(r=t).positionals??[],i=r.meta?.cwd,(d=n[0])?[tK.expandHome(d,i),...n.slice(1)]:n),p=(u=(a=r.flags?.out,o=r.meta?.cwd,a?tK.expandHome(a,o):a))?{...r.flags??{},out:u}:r.flags??{},{resolvedPositionals:c,resolvedOut:u,recordedPositionals:c,recordedFlags:p}):{resolvedPositionals:f=(s=t).positionals??[],resolvedOut:s.flags?.out,recordedPositionals:f,recordedFlags:s.flags??{}},D=Date.now(),k={...v(m.flags,h.appBundleId,h.trace?.outPath),surface:h.surface},P=await sx({session:h,sessionName:e.sessionName,logPath:w,command:S,request:_,positionals:x,out:N,dispatchContext:k}),C=await sb(h,S,"after-command");if("response"in C)return C.response;"status"in A&&"recovered"===A.status&&(!P||"object"==typeof P)&&((P??={}).warning=A.warning);let R=Date.now(),O=I===S?M:m.positionals??[],T=I===S?E:m.flags??{};return function(e){let{session:t,sessionStore:r,command:n,recordedCommand:i,resolvedPositionals:a,recordedPositionals:o,recordedFlags:s,data:l,actionStartedAt:d,actionFinishedAt:c,flags:u}=e,p=function(e,t,r,n){if("scroll"!==t)return n;let i=si(e.snapshot),a={...n??{}},o=sm(a.direction)??sm(r[0]);if(!o)return n;let s=sh(a.amount)??sh(r[1]),l=sh(a.pixels),d=sv(a,[]),c=sh(a.referenceWidth),u=sh(a.referenceHeight),p=void 0!==c&&c>0&&void 0!==u&&u>0?{referenceWidth:c,referenceHeight:u}:i??so;if(d&&(d.x1!==d.x2||d.y1!==d.y2))return{...a,x1:d.x1,y1:d.y1,x2:d.x2,y2:d.y2,contentDirection:o,...void 0!==s?{amount:s}:{},...void 0!==l?{pixels:l}:{},referenceWidth:p.referenceWidth,referenceHeight:p.referenceHeight,durationMs:250};let f=eq({direction:o,amount:s,pixels:l,referenceWidth:p.referenceWidth,referenceHeight:p.referenceHeight});return{...a,x1:f.x1,y1:f.y1,x2:f.x2,y2:f.y2,contentDirection:o,...void 0!==s?{amount:s}:{},...void 0!==f.pixels?{pixels:f.pixels}:{},referenceWidth:p.referenceWidth,referenceHeight:p.referenceHeight,durationMs:250}}(t,n,a,l);ss(t,n,a,p,u,d,c),r.recordAction(t,{command:i,positionals:o,flags:s,result:l??{}})}({session:h,sessionStore:g,command:S,recordedCommand:I,resolvedPositionals:x,recordedPositionals:O,recordedFlags:T,data:P,actionStartedAt:D,actionFinishedAt:R,flags:m.flags??{}}),as(S)&&ai(h,S),ay(h.device.platform)&&("swipe"===(l=S)||"scroll"===l)&&(h.postGestureStabilization={action:S,markedAt:Date.now()}),{ok:!0,data:P??{}}}async function sb(e,t,r="before-command"){if("android"!==e.device.platform||!ey.androidBlockingDialogGuardedAction.has(t))return{status:"clear"};try{return await oE({session:e,command:t,phase:r})}catch(e){return{response:{ok:!1,error:T(e)}}}}async function sA(e,t){if(!io(t,e.device)){var r;let n=(r=e.device,ia[t]?.unsupportedHint?.(r));return{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:`${t} is not supported on this device`,...n?{hint:n}:{}}}}return"android"===e.device.platform&&e.recording&&"record"!==t&&await oM({session:e})==="failed"?{ok:!1,error:{code:"COMMAND_FAILED",message:"Android system dialog blocked the recording session"}}:null}async function sx(e){var t;let{session:r,command:n,request:i,positionals:a,out:o,dispatchContext:s}=e;if("screenshot"!==n)return await nz(r.device,n,a,o,{...s});let l=await a8({session:r,sessionName:e.sessionName,outPath:a[0]??o,outputPlacement:"screenshot"!==(t=i).command?"default":(t.positionals??[])[0]?"positional":t.flags?.out?"out":"default",dispatchContext:s});return i.flags?.overlayRefs&&"string"==typeof l?.path&&await sN(r,l,e.logPath),l}async function sN(e,t,r){let n={snapshotInteractiveOnly:!0,snapshotCompact:!0},i=aQ(await aK({device:e.device,session:e,flags:n,logPath:r,snapshotScope:void 0}),n);a4(e,i);let a=await oX({screenshotPath:t.path,snapshot:i});t.overlayRefs=a}let sM=sj(()=>import("./lease.js")),sE=sj(()=>import("./session.js").then(e=>e.session_namespaceObject)),sD=sj(()=>import("./snapshot.js").then(e=>e.snapshot_namespaceObject)),sk=sj(()=>import("./react-native.js")),sP=sj(()=>import("./record-trace.js").then(e=>e.record_trace_namespaceObject)),sC=sj(()=>import("./find.js")),sR=sj(()=>import("./interaction.js").then(e=>e.interaction_namespaceObject));async function sO(e){let{command:t}=e.req;return ey.leaseHandler.has(t)?await sT(e):ey.sessionHandler.has(t)?await sL(e):ey.snapshot.has(t)?await s$(e):ey.reactNativeHandler.has(t)?await sF(e):ey.recordTraceHandler.has(t)?await sU(e):ey.findHandler.has(t)?await sG(e):ey.interactionHandler.has(t)?await sq(e):null}async function sT(e){let{handleLeaseCommands:t}=await sM();return sV(e.req.command,"lease",await t({req:e.req,leaseRegistry:e.leaseRegistry}))}async function sL(e){let{handleSessionCommands:t}=await sE();return sV(e.req.command,"session",await t({req:e.req,sessionName:e.sessionName,logPath:e.logPath,sessionStore:e.sessionStore,invoke:e.invoke,invokeReplayAction:e.invokeReplayAction,androidAdbExecutor:e.androidAdbExecutor}))}async function s$(e){let{handleSnapshotCommands:t}=await sD();return sV(e.req.command,"snapshot",await t({req:e.req,sessionName:e.sessionName,logPath:e.logPath,sessionStore:e.sessionStore}))}async function sF(e){let{handleReactNativeCommands:t}=await sk();return sV(e.req.command,"react-native",await t({req:e.req,sessionName:e.sessionName,logPath:e.logPath,sessionStore:e.sessionStore,contextFromFlags:e.contextFromFlags}))}async function sU(e){let{handleRecordTraceCommands:t}=await sP();return sV(e.req.command,"record-trace",await t({req:e.req,sessionName:e.sessionName,sessionStore:e.sessionStore,logPath:e.logPath}))}async function sG(e){let{handleFindCommands:t}=await sC();return sV(e.req.command,"find",await t({req:e.req,sessionName:e.sessionName,logPath:e.logPath,sessionStore:e.sessionStore,invoke:e.invoke}))}async function sq(e){let{handleInteractionCommands:t}=await sR();return sV(e.req.command,"interaction",await t({req:e.req,sessionName:e.sessionName,logPath:e.logPath,sessionStore:e.sessionStore,contextFromFlags:e.contextFromFlags}))}function sj(e){let t;return()=>t??=e()}function sV(e,t,r){if(r)return r;throw new L("INTERNAL_ERROR",`Daemon handler routing mismatch: ${t} handler matched command "${e}" but returned no response.`)}let sB=new m;async function sH(e,t,r){let n=sB.getStore()??[];if(n.some(r=>r.locks===e&&r.key===t))return await r();let i=(e.get(t)??Promise.resolve()).catch(()=>{}).then(()=>sB.run([...n,{locks:e,key:t}],r));return e.set(t,i),i.finally(()=>{e.get(t)===i&&e.delete(t)})}function sK(e){let t=e.device.platform,r=e.device.name.trim(),n=e.device.id;return`${t} device "${r}" (${n})`}function sW(e,t){var r,n,i,a;let o,s,l,d,c,u;return e.recording?(r=e,n=t,o=z(r.name),s=`agent-device close --session ${o}`,l=`agent-device record stop --session ${o}`,d="selector-conflict"===n?`To keep using this device, rerun the command with --session ${o} and remove conflicting device selectors.`:`To keep using this device, reuse --session ${o} for commands that should attach to the recording session.`,`Recording session "${r.name}" owns this device. Run ${l}; if the session still appears in agent-device session list, run ${s}. ${d} Run agent-device session list to inspect active sessions.`):(i=e,a=t,c=z(i.name),u=`agent-device close --session ${c}`,"selector-conflict"===a?`Run agent-device session list to inspect active sessions. To reuse this device, rerun the command with --session ${c} and remove conflicting device selectors. To switch devices, first run ${u}, then open the desired device with a different --session name.`:`Run agent-device session list to inspect active sessions. To reuse this device, rerun the command with --session ${c}. To open a new session on this device, first run ${u}.`)}function sz(e,t){if(!t)return[];let r=[],n=e.device,i=rG(t.platform);if(i&&!rj(n.platform,i)&&r.push({key:"platform",value:t.platform}),t.target&&t.target!==(n.target??"mobile")&&r.push({key:"target",value:t.target}),t.udid&&("ios"!==n.platform||t.udid!==n.id)&&r.push({key:"udid",value:t.udid}),t.serial&&("android"!==n.platform||t.serial!==n.id)&&r.push({key:"serial",value:t.serial}),t.device&&t.device.trim().toLowerCase()!==n.name.trim().toLowerCase()&&r.push({key:"device",value:t.device}),t.iosSimulatorDeviceSet){let e=t.iosSimulatorDeviceSet.trim(),i=n.simulatorSetPath?.trim();("ios"!==n.platform||"simulator"!==n.kind||e!==i)&&r.push({key:"iosSimulatorDeviceSet",value:t.iosSimulatorDeviceSet})}if(t.androidDeviceAllowlist){let e=ec(t.androidDeviceAllowlist);"android"===n.platform&&e.has(n.id)||r.push({key:"androidDeviceAllowlist",value:t.androidDeviceAllowlist})}return r}function sJ(e){return`${function(e){switch(e){case"iosSimulatorDeviceSet":return"--ios-simulator-device-set";case"androidDeviceAllowlist":return"--android-device-allowlist";default:return`--${e}`}}(e.key)}=${e.value}`}let sX="default";function sZ(e){return e.session||sX}function sY(e){if(e.meta?.sessionExplicit===!0||(e.session||sX)!==sX||e.meta?.sessionIsolation==="tenant"||e.flags?.sessionIsolation==="tenant")return;let r=function(e){if(!e||0===e.trim().length)return;let t=function(e){let t=n.resolve(e);try{return i.realpathSync.native(t)}catch{return t}}(e);return function(e){let t=e;for(;;){if(i.existsSync(n.join(t,".git")))return t;let e=n.dirname(t);if(e===t)return;t=e}}(t)??t}(e.meta?.cwd);if(r){var a;return{kind:"cwd",id:(a=r,t.createHash("sha256").update(a).digest("hex").slice(0,16))}}}function sQ(e,t){return!t||e.sessionScope?.kind===t.kind&&e.sessionScope.id===t.id}function s0(e,t){let r=sY(e);return!!r&&!!t.sessionScope&&!sQ(t,r)}function s1(e){return{tenantId:e.meta?.tenantId??e.flags?.tenant,runId:e.meta?.runId??e.flags?.runId,leaseId:e.meta?.leaseId??e.flags?.leaseId,leaseTtlMs:e.meta?.leaseTtlMs,leaseBackend:e.meta?.leaseBackend}}let s2=ey.selectorValidationExempt,s3=ey.leaseAdmissionExempt,s4=new Set(s3),s5=new Set([ev.apps,ev.devices]);function s8(e,t){var r,n,i,a,o,s,l,d,c,u;let p,f,m,h=e.meta?.lockPolicy;if(!h)return e;let w={...e.flags??{}},g=s5.has(e.command),v=g?[]:t?sz(t,w):(r=w,n=e.meta?.lockPlatform,p=[],f=rG(n),void 0!==r.platform&&f&&(i=rG(r.platform),a=f,i&&a&&i!==a&&("apple"===i?!rq(a):"apple"!==a||!rq(i)))&&p.push({key:"platform",value:r.platform}),f&&(o=p,s=r,l=f,(m=s.target)&&function(e,t){switch(t){case"android":case"ios":return"desktop"===e;case"macos":case"linux":return"desktop"!==e;case"apple":return!1;default:return s9(t)}}(m,l)&&o.push({key:"target",value:m}),function(e,t,r){for(let n of function(e,t){switch(e){case"android":return["udid","iosSimulatorDeviceSet"];case"ios":return["serial","androidDeviceAllowlist"];case"apple":var r;return"desktop"===(r=t).target||"macos"===rG(r.platform)?["udid","serial","androidDeviceAllowlist","iosSimulatorDeviceSet"]:["serial","androidDeviceAllowlist"];case"macos":case"linux":return["udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist"];default:return s9(e)}}(r,t)){let r=t[n];r6(r)&&e.push({key:n,value:r})}}(p,r,f)),p),y=e.meta?.lockPlatform;if(0===v.length){return d=g,c=t,u=w,!y||c||void 0!==u.platform||d&&r9(u,r8)||(w.platform=y),{...e,flags:w}}if("strip"===h)return function(e,t,r,n){if(n){s6(e,t),e.platform=n.device.platform;return}s6(e,t),r&&void 0===e.platform&&(e.platform=r)}(w,v,y,t),{...e,flags:w};throw new L("INVALID_ARGS",function(e,t,r){let n=t.map(sJ).join(", ");if(r)return`${e.command} is already bound to session "${r.name}" on ${sK(r)}, but this request selected ${n}.`;let i=e.meta?.lockPlatform,a=i?` for ${i}`:"";return`${e.command} is using a bound-session lock${a}, but this request selected ${n}.`}(e,v,t),{session:e.session,conflicts:v.map(sJ),hint:function(e,t){if(t)return sW(t,"selector-conflict");let r=e.meta?.lockPlatform,n=e.session?` --session ${z(e.session)}`:"";return"Remove conflicting device selectors from this command, or use --session-lock strip to let agent-device ignore them. "+(r?`Run agent-device open <app>${n} --platform ${r} first if no session is active. `:`Run agent-device open <app>${n} first if no session is active. `)+"Run agent-device session list to inspect active sessions."}(e,t)})}function s6(e,t){for(let r of t)delete e[r.key]}function s9(e){throw Error(`Unhandled lock platform: ${String(e)}`)}async function s7(e){var t,r;let{req:n,sessionName:i,sessionStore:a}=e,o=a.get(i);if(o)return[le(o.device.id)];let s=new Set([(t=i,`session:${t}`)]),l=function(e){if(!e.meta?.lockPolicy)return e;try{return s8(e)}catch{return e}}(n);if("open"===(r=l).command||r9(r.flags,r5))try{let e=await rZ(l.flags??{});s.add(le(e.id))}catch{}return Array.from(s).sort((e,t)=>{let r=lt(e)-lt(t);return 0!==r?r:e.localeCompare(t)})}function le(e){return`device:${e}`}function lt(e){return+!e.startsWith("session:")}function lr(e,t={}){let r=ee(t.simulatorSetPath);return r?["simctl","--set",r,...e]:["simctl",...e]}function ln(e,t){return"ios"!==e.platform||"simulator"!==e.kind?["simctl",...t]:lr(t,{simulatorSetPath:e.simulatorSetPath})}function li(e,t,r){return i_(ln(e,t),r)}let la="If runner build products look stale or corrupted, run `pnpm clean:xcuitest` in a local checkout, or remove ~/.agent-device/ios-runner/derived, then retry.";function lo(e){if(!(e instanceof L)||"COMMAND_FAILED"!==e.code)return!1;let t=`${e.message??""}`.toLowerCase();return!(t.includes("xcodebuild exited early")||t.includes("device is busy")&&t.includes("connecting"))&&!!(t.includes("runner did not accept connection")||t.includes("fetch failed")||t.includes("econnrefused")||t.includes("socket hang up"))}function ls(e){return!(e instanceof L)||"COMMAND_FAILED"!==e.code||!String(e.message??"").toLowerCase().includes("xcodebuild exited early")}function ll(e){let{port:t,endpoints:r,logPath:n,lastError:i}=e,a="Runner did not accept connection";return new L("COMMAND_FAILED",a,{port:t,endpoints:r,logPath:n,lastError:i?String(i):void 0,reason:eo({error:i,message:a,context:{platform:"ios",phase:"connect"}}),hint:el("IOS_RUNNER_CONNECT_TIMEOUT")})}async function ld(e){var t,r;let n,{session:i,port:a,logPath:o}=e,s=await i.testPromise,l="Runner did not accept connection (xcodebuild exited early)",d=eo({message:l,stdout:s.stdout,stderr:s.stderr,context:{platform:"ios",phase:"connect"}});return new L("COMMAND_FAILED",l,{port:a,logPath:o,xcodebuild:{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr},reason:d,hint:(t=s.stdout,r=s.stderr,(n=`${l}
9
9
  ${t}
10
- ${r}`.toLowerCase()).includes("device is busy")&&n.includes("connecting")?"Target iOS device is still connecting. Keep it unlocked, wait for device trust/connection to settle, then retry.":`${el("IOS_RUNNER_CONNECT_TIMEOUT")} ${la}`)})}function lc(e){return"interactionFrame"===e||"snapshot"===e||"screenshot"===e||"findText"===e||"querySelector"===e||"readText"===e||"alert"===e||"status"===e||"uptime"===e}function lu(e){return"status"===e.command||e.commandId?.trim()?e:{...e,commandId:`runner-${t.randomUUID()}`}}function lp(e){if(t5(e))throw t6()}let lf=new Map;async function lm(e,t,r,n,i=45e3,a,o){let s=en.fromTimeoutMs(i),{getEndpoints:l}=lw(e,t),{endpoints:d}=await l(s.remainingMs()),c=null,u=Math.max(1,Math.ceil(i/250));try{return await eu(async({deadline:s})=>{if(s?.isExpired())throw new L("COMMAND_FAILED","Runner connection deadline exceeded",{port:t,timeoutMs:i});if(a&&null!==a.child.exitCode&&void 0!==a.child.exitCode)throw await ld({session:a,port:t,logPath:n});let u=!1;if("device"===e.kind){let e=await l(s?.remainingMs());d=e.endpoints,u=e.cached}let p=u?d[0]:null,f=await lg(d,{command:r,port:t,timeoutMs:i,signal:o,attemptDeadline:s,onError:(t,r)=>{var n;c=r,"device"===e.kind&&t===p&&(n=e.id,lf.delete(n))}});if(f)return f;if("device"===e.kind&&u){var m;m=e.id,lf.delete(m),d=(await l(s?.remainingMs(),!0)).endpoints;let n=await lg(d,{command:r,port:t,timeoutMs:i,signal:o,attemptDeadline:s,onError:(e,t)=>{c=t}});if(n)return n}if(o?.aborted)throw t6();throw new L("COMMAND_FAILED","Runner endpoint probe failed",{port:t,endpoints:d,lastError:c?String(c):void 0})},{maxAttempts:u,baseDelayMs:300,maxDelayMs:2e3,jitter:.2,shouldRetry:ls},{deadline:s,phase:"ios_runner_connect",signal:o})}catch(e){if(o?.aborted||t7(e))throw t6();c||(c=e)}if(o?.aborted)throw t6();if("simulator"===e.kind){let i=s.remainingMs();if(i<=0)throw ll({port:t,endpoints:d,logPath:n,lastError:c});let a=await l_(e,t,r,i,o);return new Response(a.body,{status:a.status})}throw ll({port:t,endpoints:d,logPath:n,lastError:c})}async function lh(e,t,r,n=45e3,i){if(i?.aborted)throw t6();let a=en.fromTimeoutMs(n),{getEndpoints:o}=lw(e,t),{endpoints:s}=await o(a.remainingMs()),l=s[0];if(!l)throw new L("COMMAND_FAILED","Runner command endpoint not available",{port:t,endpoints:s});let d=a.remainingMs();if(d<=0)throw new L("COMMAND_FAILED","Runner command deadline exceeded",{timeoutMs:n});return await ly(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},d,i)}function lw(e,t){let r;return{getEndpoints:async(n,i=!1)=>{var a,o,s;let l,d=await lv({device:e,timeoutBudgetMs:n,forceRefresh:i,requestTunnelIp:r,setRequestTunnelIp:e=>{r=e}});return{endpoints:(a=e,o=t,s=d.ip,l=[`http://127.0.0.1:${o}/command`],"device"!==a.kind||s&&l.unshift(`http://[${s}]:${o}/command`),l),cached:d.sharedCacheHit}}}}async function lg(e,t){let{command:r,port:n,timeoutMs:i,signal:a,attemptDeadline:o,onError:s}=t;for(let t of e)try{let e=o?.remainingMs()??i;if(e<=0)throw new L("COMMAND_FAILED","Runner connection deadline exceeded",{port:n,timeoutMs:i});return await ly(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},Math.min(2e4,e),a)}catch(e){if(a?.aborted||t7(e))throw t6();s(t,e)}return null}async function lv(e){var t,r,n;let{device:i,timeoutBudgetMs:a,forceRefresh:o,requestTunnelIp:s,setRequestTunnelIp:l}=e;if("device"!==i.kind)return{ip:null,sharedCacheHit:!1};if(!o){let e,r=(t=i.id,(e=lf.get(t))?e.expiresAt<=Date.now()?(lf.delete(t),null):e.ip:null);if(r)return{ip:r,sharedCacheHit:!0};if(void 0!==s)return{ip:s,sharedCacheHit:!1}}let d=await lS(i.id,a);return l(d),d&&(r=i.id,n=d,lf.set(r,{ip:n,expiresAt:Date.now()+3e4})),{ip:d,sharedCacheHit:!1}}async function ly(e,t,r,n){let i=AbortSignal.timeout(r),a=n?AbortSignal.any([n,i]):i;return await fetch(e,{...t,signal:a})}async function lS(e,t){if("number"==typeof t&&t<=0)return null;let r="number"==typeof t?Math.max(1,Math.min(1e4,t)):1e4,a=n.join(c.tmpdir(),`agent-device-devicectl-info-${process.pid}-${Date.now()}.json`);try{let t=Math.max(1,Math.ceil(r/1e3)),n=await i_(["devicectl","device","info","details","--device",e,"--json-output",a,"--timeout",String(t)],{allowFailure:!0,timeoutMs:r});if(0!==n.exitCode||!i.existsSync(a))return null;let o=JSON.parse(i.readFileSync(a,"utf8"));if(o.info?.outcome&&"success"!==o.info.outcome)return null;let s=(o.result?.connectionProperties?.tunnelIPAddress??o.result?.device?.connectionProperties?.tunnelIPAddress)?.trim();return s&&s.length>0?s:null}catch{return null}finally{lN(a)}}async function l_(e,t,r,n,i){let a=JSON.stringify(r),o=ln(e,["spawn",e.id,"/usr/bin/curl","-s","-X","POST","-H","Content-Type: application/json","--data",a,`http://127.0.0.1:${t}/command`]),s=await i_(o,{allowFailure:!0,timeoutMs:n,signal:i}),l=s.stdout;if(0!==s.exitCode){let e=eo({message:"Runner did not accept connection (simctl spawn)",stdout:s.stdout,stderr:s.stderr,context:{platform:"ios",phase:"connect"}});throw new L("COMMAND_FAILED","Runner did not accept connection (simctl spawn)",{port:t,stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode,reason:e,hint:el(e)})}return{status:200,body:l}}async function lI(){return await new Promise((e,t)=>{let r=w.createServer();r.listen(0,"127.0.0.1",()=>{let n=r.address();if("object"==typeof n&&n?.port){let t=n.port;r.close(()=>e(t))}else r.close(()=>t(new L("COMMAND_FAILED","Failed to allocate port")))}),r.on("error",t)})}function lb(e,t,r,n){t&&lx(t,e),r&&lx(r,e),n&&process.stderr.write(e)}let lA=new Map;function lx(e,t){let r=(lA.get(e)??Promise.resolve()).catch(()=>{}).then(()=>i.promises.appendFile(e,t)).catch(()=>{}).finally(()=>{lA.get(e)===r&&lA.delete(e)});lA.set(e,r)}function lN(e){try{i.existsSync(e)&&i.unlinkSync(e)}catch{}}let lM=new Set(["RUNNER_PRODUCT_MISSING","RUNNER_PRODUCT_REPAIR_FAILED"]);async function lE(e,t,r){if("macos"!==e.platform)return;if(0===t.length)throw new L("COMMAND_FAILED","Missing macOS runner product",{reason:"RUNNER_PRODUCT_MISSING",xctestrunPath:r});let n=Array.from(new Set(t)).sort((e,t)=>t.length-e.length);for(let e of n)if(!i.existsSync(e))throw new L("COMMAND_FAILED","Missing macOS runner product",{reason:"RUNNER_PRODUCT_MISSING",productPath:e,xctestrunPath:r});for(let e of n)if(!await lD(e)){await iS("codesign",["--remove-signature",e],{allowFailure:!0});try{await iS("codesign",["--force","--sign","-",e])}catch(n){let t=n instanceof L?n:new L("COMMAND_FAILED",String(n));throw new L("COMMAND_FAILED","Failed to repair macOS runner product signature",{reason:"RUNNER_PRODUCT_REPAIR_FAILED",productPath:e,xctestrunPath:r,error:t.message,details:t.details})}}}async function lD(e){return 0===(await iS("codesign",["--verify","--deep","--strict",e],{allowFailure:!0})).exitCode}let lk=new Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.:-"),lP=new Set([" "," ","\n","\r"]),lC=new Set(["__defineGetter__","__defineSetter__","__proto__","constructor","prototype"]);function lR(e,t={}){let r=t.maxDocumentChars??0x8000000;if(e.length>r)throw Error(`XML document exceeds maximum supported size of ${r} characters.`);return new lT(e).parse()}function lO(e,t){for(let r of e){if("dict"===r.name)for(let e=0;e<r.children.length-1;e+=1){let n=r.children[e],i=r.children[e+1];n?.name==="key"&&n.text&&i&&t(n.text,i)}lO(r.children,t)}}class lT{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(){"<"!==this.xml[this.index]?this.readText():this.resolveMarkupReader()()}resolveMarkupReader(){return this.startsWith("\x3c!--")?()=>this.skipUntil("--\x3e","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(){65279===this.xml.charCodeAt(0)&&(this.index=1)}readOpeningTag(){this.index+=1,this.skipWhitespace();let e=this.readRequiredName(`Missing XML tag name at offset ${this.index}.`),{attributes:t,selfClosing:r}=this.readOpeningTagBody(),n={name:e,attributes:t,text:null,children:[]};this.addNode(n),r||this.pushOpenNode(n)}readOpeningTagBody(){let e={};for(;;){this.skipWhitespace();let t=this.readOpeningTagEnd();if(t)return{attributes:e,selfClosing:"self-closing"===t};let r=this.readAttribute();e[r.name]=r.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(function(e){if(lC.has(e))throw Error(`Unsupported XML attribute name "${e}".`)}(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=-1===e?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(-1===t)throw Error("CDATA section is not closed.");this.appendText(this.xml.slice(e,t),!1),this.index=t+3}appendText(e,t){let r=e.trim();if(!r)return;let n=this.stack[this.stack.length-1];n&&(n.text=`${n.text??""}${t?lL(r):r}`)}addNode(e){let t=this.stack[this.stack.length-1];t?t.children.push(e):this.roots.push(e)}readName(){var e;let t=this.index;for(;this.index<this.xml.length&&void 0!==(e=this.xml[this.index])&&lk.has(e);)this.index+=1;return this.xml.slice(t,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 r=this.index,n=this.xml.indexOf(t,r);if(-1===n)throw Error(`XML attribute "${e}" is not closed.`);return this.index=n+1,lL(this.xml.slice(r,n).trim())}skipDeclaration(){let e={quote:null,bracketDepth:0};for(let t=this.index+2;t<this.xml.length;t+=1)if(function(e,t){var r,n,i;return!(void 0===t||(r=e,n=t,r.quote?(n===r.quote&&(r.quote=null),!0):('"'===n||"'"===n)&&(r.quote=n,!0)))&&(function(e,t){if("["===t){e.bracketDepth+=1;return}"]"===t&&e.bracketDepth>0&&(e.bracketDepth-=1)}(e,t),i=e,">"===t&&0===i.bracketDepth)}(e,this.xml[t])){this.index=t+1;return}throw Error("XML declaration is not closed.")}skipUntil(e,t){let r=this.xml.indexOf(e,this.index+e.length);if(-1===r)throw Error(t);this.index=r+e.length}skipWhitespace(){for(var e;this.index<this.xml.length&&void 0!==(e=this.xml[this.index])&&lP.has(e);)this.index+=1}startsWith(e){return this.xml.startsWith(e,this.index)}}function lL(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:var r=e,n=t;let i=n.startsWith("#x")?Number.parseInt(n.slice(2),16):Number(n.slice(1));if(!Number.isInteger(i)||i<0||i>1114111)return r;try{return String.fromCodePoint(i)}catch{return r}}})}let l$=new Set(["ProductPaths","DependentProductPaths","TestHostPath","TestBundlePath","UITargetAppPath"]);async function lF(e){var t;let r=await lU(e);if(!r||0===r.length)return null;let a=n.dirname(e),o=new Set,s=function(e,t){let r=[],i=new Set,a=[];for(let o of e){if(o.startsWith("__TESTHOST__/")){a.push(o.slice(13));continue}if(!o.startsWith("__TESTROOT__/"))continue;let e=o.slice(13);r.push(n.join(t,e));let s=function(e){let t=/\.app(?:\/|$)/.exec(e);return t&&void 0!==t.index?e.slice(0,t.index+4):null}(e);s&&i.add(n.join(t,s))}return{testRootPaths:r,hostRoots:Array.from(i),hostRelativePaths:a}}(r,a);for(let e of s.testRootPaths){if(!i.existsSync(e))return null;o.add(e)}for(let e of(t=s).hostRelativePaths.map(e=>{let r=t.hostRoots.find(t=>i.existsSync(n.join(t,e)));return r?n.join(r,e):null})){if(!e)return null;o.add(e)}return Array.from(o)}async function lU(e){let t=await iI(e);if(t){var r,n,a,o=t;let e=new Set;for(let t of[a=o,...function(e){let t=e.TestConfigurations;if(!Array.isArray(t))return[];let r=[];for(let e of t){if(!lG(e))continue;let t=e.TestTargets;Array.isArray(t)&&r.push(...t.filter(lG))}return r}(a),...Object.values(a).filter(e=>lG(e)&&"TestBundlePath"in e)])for(let r of function(e){let t=new Set;for(let[r,n]of Object.entries(e))if(l$.has(r)){if("string"==typeof n){t.add(n);continue}if(Array.isArray(n))for(let e of n)"string"==typeof e&&t.add(e)}return Array.from(t)}(t))e.add(r);return Array.from(e)}if("darwin"===process.platform)return null;try{let t;return r=i.readFileSync(e,"utf8"),n=lR(r),t=new Set,lO(n,(e,r)=>{if(l$.has(e)){if("string"===r.name&&r.text)return void t.add(r.text);if("array"===r.name)for(let e of r.children)"string"===e.name&&e.text&&t.add(e.text)}}),Array.from(t)}catch{return null}}function lG(e){return!!e&&"object"==typeof e}let lq=["CFBundleIcons","CFBundleIcons~ipad"];async function lj(e){let t=e.filter(lW);if(0===t.length)return;let r=e.filter(e=>lJ(e)&&!lz(e));for(let e of t){let t=function(e,t){let r=n.dirname(e);return t.find(e=>n.dirname(e)===r&&"AgentDeviceRunner.app"===n.basename(e))??t.find(t=>n.dirname(t)===r&&t!==e)??null}(e,r);t&&await lV(t,e)}}async function lV(e,t){var r;let a,o=function(e,t){let r=!1;for(let o of i.readdirSync(e,{withFileTypes:!0})){var a;if(o.isFile()&&(a=o.name,/^AppIcon.*\.png$/.test(a)||"Assets.car"===a))(function(e,t){if(i.existsSync(t)){let r=i.readFileSync(e),n=i.readFileSync(t);return!r.equals(n)&&(i.copyFileSync(e,t),!0)}return i.copyFileSync(e,t),!0})(n.join(e,o.name),n.join(t,o.name))&&(r=!0)}return r}(e,t),s=await lB(e,t);(o||s)&&(await lK(t),r=t,a=new Date,i.utimesSync(r,a,a))}async function lB(e,t){var r,i;let a=n.join(e,"Info.plist"),o=n.join(t,"Info.plist"),s=await iI(a),l=await iI(o);if(!s||!l)return!1;let d=(r=s,i=l,lq.flatMap(e=>{let t=r[e];return void 0===t||JSON.stringify(i[e])===JSON.stringify(t)?[]:[{key:e,value:t,shouldInsert:void 0===i[e]}]}));if(0===d.length)return!1;for(let e of d)await lH(o,e.key,e.value,e.shouldInsert);return!0}async function lH(e,t,r,n){let i=await iS("plutil",[n?"-insert":"-replace",t,"-json",JSON.stringify(r),e],{allowFailure:!0});if(0!==i.exitCode)throw new L("COMMAND_FAILED","Failed to update XCTest runner icon plist",{key:t,plistPath:e,stderr:i.stderr})}async function lK(e){let t=await iS("codesign",["--force","--sign","-","--timestamp=none","--generate-entitlement-der",e],{allowFailure:!0});if(0!==t.exitCode)throw new L("COMMAND_FAILED","Failed to sign XCTest runner app after icon update",{runnerAppPath:e,stderr:t.stderr})}function lW(e){return lJ(e)&&lz(e)&&(e.includes("Debug-iphonesimulator")||e.includes("Release-iphonesimulator")||e.includes("Debug-appletvsimulator")||e.includes("Release-appletvsimulator"))}function lz(e){return n.basename(e).endsWith("-Runner.app")}function lJ(e){return n.basename(e).endsWith(".app")}let lX="XCTestDevices",lZ=".agent-device-backup",lY=".agent-device-xctestdevices-backup-",lQ=n.join(c.homedir(),".agent-device","ios-runner"),l0=".agent-device-runner-cache.json",l1={PreferredScreenCaptureFormat:"screenshots",SystemAttachmentLifetime:"keepNever",UserAttachmentLifetime:"keepNever"},l2=new Map,l3=new Set;function l4(e){return e?.trim()??""}function l5(e=process.env){return l4(e.AGENT_DEVICE_IOS_BUNDLE_ID)||l4(e.AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID)||"com.callstack.agentdevice.runner"}function l8(e=process.env){let t=l4(e.AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID);return t||`${l5(e)}.uitests`}let l6=function(e=process.env){let t=l5(e),r=l8(e);return Array.from(new Set([l4(e.AGENT_DEVICE_IOS_RUNNER_CONTAINER_BUNDLE_ID),`${r}.xctrunner`,t].filter(e=>e.length>0)))}(process.env);function l9(e=c.homedir()){return n.join(e,"Library","Developer","XCTestDevices")}async function l7(e,t={}){if("ios"!==e.platform||"simulator"!==e.kind)return null;let r=ee(e.simulatorSetPath);if(!r)return null;let a=n.resolve(r),o=n.resolve(t.xctestDeviceSetPath??l9()),s=n.resolve(t.backupPath??function(e=l9()){return`${e}${lZ}`}(o)),l=n.resolve(t.lockDirPath??function(e=c.homedir()){return n.join(e,".agent-device","xctest-device-set.lock")}()),d=t.ownerStartTime??M(process.pid),u=await dr({lockDirPath:l,owner:{pid:t.ownerPid??process.pid,startTime:d,acquiredAtMs:t.nowMs??Date.now()}});try{if(de({xctestDeviceSetPath:o,backupPath:s}),function(e,t){if(n.resolve(e)===n.resolve(t))return!0;try{return i.realpathSync.native(e)===i.realpathSync.native(t)}catch{return!1}}(a,o))return await u(),null;i.mkdirSync(a,{recursive:!0}),i.existsSync(o)&&i.renameSync(o,s),function(e){let{requestedSetPath:t,xctestDeviceSetPath:r}=e,a=n.dirname(r),o=n.join(a,`${lX}.agent-device-link-${process.pid}-${Date.now()}`);i.mkdirSync(a,{recursive:!0});try{i.symlinkSync(t,o,"dir"),i.renameSync(o,r)}catch(e){throw i.existsSync(o)&&dt(o),e}}({requestedSetPath:a,xctestDeviceSetPath:o})}catch(e){throw de({xctestDeviceSetPath:o,backupPath:s}),await u(),new L("COMMAND_FAILED","Failed to redirect XCTest device set path",{requestedSetPath:a,xctestDeviceSetPath:o,backupPath:s,error:String(e)})}let p=!1;return{release:async()=>{if(!p){p=!0;try{de({xctestDeviceSetPath:o,backupPath:s})}finally{await u()}}}}}function de(e){let{xctestDeviceSetPath:t,backupPath:r}=e,a=[r,...function(e){let t=n.dirname(e),r=n.basename(e).replace(lZ,""),a=r===lX?lY:`${r}${lY}`;try{return i.readdirSync(t).filter(e=>e.startsWith(a)).sort().map(e=>n.join(t,e))}catch{return[]}}(r)],o=a.find(e=>i.existsSync(e)),s=i.existsSync(t)&&i.lstatSync(t).isSymbolicLink();if(o){if(s&&dt(t),i.existsSync(t))if(!s)return void N({level:"warn",phase:"ios_runner_xctest_device_set_restore_collision",data:{xctestDeviceSetPath:t,activeBackupPath:o}});else o!==r?i.rmSync(o,{recursive:!0,force:!0}):i.rmSync(r,{recursive:!0,force:!0});else i.mkdirSync(n.dirname(t),{recursive:!0}),i.renameSync(o,t);for(let e of a)e!==o&&i.existsSync(e)&&i.rmSync(e,{recursive:!0,force:!0});return}s&&(N({level:"warn",phase:"ios_runner_xctest_device_set_orphaned_symlink",data:{xctestDeviceSetPath:t}}),dt(t))}function dt(e){!i.existsSync(e)||i.lstatSync(e).isSymbolicLink()&&i.unlinkSync(e)}async function dr(e){let{lockDirPath:t,owner:r}=e,a=n.join(t,"owner.json"),o=Date.now()+(e.timeoutMs??3e4),s=e.pollMs??100,l=e.description??"XCTest device set lock";for(i.mkdirSync(n.dirname(t),{recursive:!0});Date.now()<o;)try{i.mkdirSync(t),function(e,t){let r=`${e}.${process.pid}.${Date.now()}.tmp`;i.writeFileSync(r,JSON.stringify(t),"utf8"),i.renameSync(r,e)}(a,r);let e=!1;return async()=>{e||(e=!0,i.rmSync(t,{recursive:!0,force:!0}))}}catch(e){if("EEXIST"!==e.code)throw e;if(function(e,t){let r=null;try{r=i.statSync(e)}catch{return!0}let n=di(t);if(n){var a;return!(Number.isInteger((a=n).pid)&&!(a.pid<=0)&&C(a.pid)&&(!a.startTime||M(a.pid)===a.startTime))&&(i.rmSync(e,{recursive:!0,force:!0}),!0)}return!(Date.now()-r.mtimeMs<5e3)&&(i.rmSync(e,{recursive:!0,force:!0}),!0)}(t,a))continue;await eV(s)}throw new L("COMMAND_FAILED",`Timed out waiting for ${l}`,{lockDirPath:t,...function(e,t){let r,n=Date.now(),a=di(t);try{r=Math.max(0,Math.round(n-i.statSync(e).mtimeMs))}catch{}return{...void 0!==r?{lockAgeMs:r}:{},...a?{ownerPid:a.pid,ownerStartTime:a.startTime,ownerAgeMs:Math.max(0,Math.round(n-a.acquiredAtMs))}:{}}}(t,a)})}async function dn(e){var t;return await dr({lockDirPath:(t=e,n.join(n.dirname(t),`${n.basename(t)}.lock`)),owner:{pid:process.pid,startTime:M(process.pid),acquiredAtMs:Date.now()},timeoutMs:6e5,description:"iOS runner cache lock"})}function di(e){try{return JSON.parse(i.readFileSync(e,"utf8"))}catch{return null}}async function da(e,r){let a=e6(),o=function(e,r=e6()){var a;let o;return{schemaVersion:1,packageVersion:e8(),runnerSourceFingerprint:function(e){let r=n.join(e,"ios-runner","AgentDeviceRunner"),a=function(e){if(!i.existsSync(e))return[];let t=[],r=[e];for(;r.length>0;){let e=r.pop();for(let s of i.readdirSync(e,{withFileTypes:!0})){var a,o;let i=n.join(e,s.name);if(s.isDirectory()){if("xcuserdata"===s.name)continue;r.push(i);continue}s.isFile()&&(a=s.name,o=i,"project.pbxproj"===a?o.includes(`${n.sep}.xcodeproj${n.sep}`):[".jpg",".json",".png",".swift",".plist",".entitlements",".xctestplan",".xcconfig",".storyboard",".xib"].includes(n.extname(a)))&&t.push(i)}}return t.sort((e,t)=>e.localeCompare(t))}(r),o=function(e,r){let a=t.createHash("sha256");for(let t of r){let r=n.relative(e,t),o=i.statSync(t);a.update(r),a.update("\0"),a.update(String(o.size)),a.update("\0"),a.update(String(Math.trunc(o.mtimeMs))),a.update("\0")}return a.digest("hex")}(r,a),s=dv.get(r);if(s?.fileStatsFingerprint===o)return s.sourceFingerprint;let l=t.createHash("sha256");for(let e of a){let t=n.relative(r,e);l.update(t),l.update("\0"),l.update(i.readFileSync(e)),l.update("\0")}let d=l.digest("hex");return dv.set(r,{fileStatsFingerprint:o,sourceFingerprint:d}),d}(r),platformName:dE(e),deviceKind:e.kind,target:e.target??"phone",buildDestinationFamily:"macOS"===(o=dE(a=e))?`platform=macOS,arch=${dD()}`:"simulator"===a.kind?`generic/platform=${o} Simulator`:`generic/platform=${o}`,runnerBundleBuildSettings:dC(process.env),runnerSigningBuildSettings:dP(process.env,"device"===e.kind,e.platform),runnerPerformanceBuildSettings:dR()}}(e,a),s=function(e,r){var i;let a,o=process.env.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim();if(o)return n.resolve(o);let s=(a=t.createHash("sha256").update(JSON.stringify(dp(r))).digest("hex"),`cache-${a.slice(0,16)}`),l="macos"===(i=e).platform?n.join(lQ,"derived","macos"):"tv"===i.target?n.join(lQ,"derived","simulator"===i.kind?"tvos-simulator":"tvos-device"):"simulator"===i.kind?n.join(lQ,"derived","ios-simulator"):n.join(lQ,"derived","ios-device");return n.join(l,s)}(e,o);return await sH(l2,s,async()=>{let t=await dn(s);try{return await ds({device:e,options:r,projectRoot:a,expectedCacheMetadata:o,derived:s})}finally{await t()}})}async function ds(e){let{device:t,options:r,projectRoot:a,expectedCacheMetadata:o,derived:s}=e;ei(process.env.AGENT_DEVICE_IOS_CLEAN_DERIVED)&&(dL("clean","forced_clean",{derived:s}),dO(s),dd(s));let l=await dT({derived:s,projectRoot:a,expectedCacheMetadata:o,findXctestrun:e=>dy(e,t),xctestrunReferencesProjectRoot:d_,resolveExistingXctestrunProductPaths:lF});if("reuse_ready"!==l.reason&&dL("rebuild",l.reason,{derived:s,xctestrunPath:l.xctestrunPath}),"reuse_ready"===l.reason){let e=await dl(t,s,o,l);if(e)return e}l.xctestrunPath&&(dO(s),dd(s));let d=n.join(a,"ios-runner","AgentDeviceRunner","AgentDeviceRunner.xcodeproj");if(!i.existsSync(d))throw new L("COMMAND_FAILED","iOS runner project not found",{projectPath:d});await dM(t,d,s,r);let c=dy(s,t);if(!c)throw new L("COMMAND_FAILED","Failed to locate .xctestrun after build");let u=await lF(c);if(!u)throw new L("COMMAND_FAILED","Runner build is missing expected products",{xctestrunPath:c});return await lE(t,u,c),await lj(u),du(s,df(o,c,u)),dL("build","built_new",{derived:s,xctestrunPath:c}),c}async function dl(e,t,r,n){try{var i,a,o,s;return await lE(e,n.productPaths,n.xctestrunPath),dL("reuse","reuse_ready",{derived:t,xctestrunPath:n.xctestrunPath}),i=t,a=r,o=n.xctestrunPath,s=n.productPaths,du(i,df(a,o,s)),n.xctestrunPath}catch(e){if(!function(e){if(!(e instanceof L))return!1;let t=e.details&&"object"==typeof e.details?e.details.reason:void 0;return"string"==typeof t&&lM.has(t)}(e))throw e;return dL("rebuild","repair_failed",{derived:t,xctestrunPath:n.xctestrunPath}),null}}function dd(e){try{if(!i.existsSync(e))return;if("derived"!==n.basename(e))return void i.rmSync(e,{recursive:!0,force:!0});for(let r of i.readdirSync(e,{withFileTypes:!0})){var t;t=r.name,dc.has(t)&&i.rmSync(n.join(e,r.name),{recursive:!0,force:!0})}}catch{}}let dc=new Set([l0,"Build","BuildCache.noindex","Index.noindex","Logs","ModuleCache.noindex","SDKStatCaches.noindex","SourcePackages","TextBasedInstallAPI","info.plist"]);function du(e,t){i.mkdirSync(e,{recursive:!0}),i.writeFileSync(n.join(e,l0),`${JSON.stringify(t,null,2)}
10
+ ${r}`.toLowerCase()).includes("device is busy")&&n.includes("connecting")?"Target iOS device is still connecting. Keep it unlocked, wait for device trust/connection to settle, then retry.":`${el("IOS_RUNNER_CONNECT_TIMEOUT")} ${la}`)})}function lc(e){return"interactionFrame"===e||"snapshot"===e||"screenshot"===e||"findText"===e||"querySelector"===e||"readText"===e||"alert"===e||"status"===e||"uptime"===e}function lu(e){return"status"===e.command||e.commandId?.trim()?e:{...e,commandId:`runner-${t.randomUUID()}`}}function lp(e){if(t5(e))throw t6()}let lf=new Map;async function lm(e,t,r,n,i=45e3,a,o){let s=en.fromTimeoutMs(i),{getEndpoints:l}=lw(e,t),{endpoints:d}=await l(s.remainingMs()),c=null,u=Math.max(1,Math.ceil(i/250));try{return await eu(async({deadline:s})=>{if(s?.isExpired())throw new L("COMMAND_FAILED","Runner connection deadline exceeded",{port:t,timeoutMs:i});if(a&&null!==a.child.exitCode&&void 0!==a.child.exitCode)throw await ld({session:a,port:t,logPath:n});let u=!1;if("device"===e.kind){let e=await l(s?.remainingMs());d=e.endpoints,u=e.cached}let p=u?d[0]:null,f=await lg(d,{command:r,port:t,timeoutMs:i,signal:o,attemptDeadline:s,onError:(t,r)=>{var n;c=r,"device"===e.kind&&t===p&&(n=e.id,lf.delete(n))}});if(f)return f;if("device"===e.kind&&u){var m;m=e.id,lf.delete(m),d=(await l(s?.remainingMs(),!0)).endpoints;let n=await lg(d,{command:r,port:t,timeoutMs:i,signal:o,attemptDeadline:s,onError:(e,t)=>{c=t}});if(n)return n}if(o?.aborted)throw t6();throw new L("COMMAND_FAILED","Runner endpoint probe failed",{port:t,endpoints:d,lastError:c?String(c):void 0})},{maxAttempts:u,baseDelayMs:300,maxDelayMs:2e3,jitter:.2,shouldRetry:ls},{deadline:s,phase:"ios_runner_connect",signal:o})}catch(e){if(o?.aborted||t7(e))throw t6();c||(c=e)}if(o?.aborted)throw t6();if("simulator"===e.kind){let i=s.remainingMs();if(i<=0)throw ll({port:t,endpoints:d,logPath:n,lastError:c});let a=await l_(e,t,r,i,o);return new Response(a.body,{status:a.status})}throw ll({port:t,endpoints:d,logPath:n,lastError:c})}async function lh(e,t,r,n=45e3,i){if(i?.aborted)throw t6();let a=en.fromTimeoutMs(n),{getEndpoints:o}=lw(e,t),{endpoints:s}=await o(a.remainingMs()),l=s[0];if(!l)throw new L("COMMAND_FAILED","Runner command endpoint not available",{port:t,endpoints:s});let d=a.remainingMs();if(d<=0)throw new L("COMMAND_FAILED","Runner command deadline exceeded",{timeoutMs:n});return await ly(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},d,i)}function lw(e,t){let r;return{getEndpoints:async(n,i=!1)=>{var a,o,s;let l,d=await lv({device:e,timeoutBudgetMs:n,forceRefresh:i,requestTunnelIp:r,setRequestTunnelIp:e=>{r=e}});return{endpoints:(a=e,o=t,s=d.ip,l=[`http://127.0.0.1:${o}/command`],"device"!==a.kind||s&&l.unshift(`http://[${s}]:${o}/command`),l),cached:d.sharedCacheHit}}}}async function lg(e,t){let{command:r,port:n,timeoutMs:i,signal:a,attemptDeadline:o,onError:s}=t;for(let t of e)try{let e=o?.remainingMs()??i;if(e<=0)throw new L("COMMAND_FAILED","Runner connection deadline exceeded",{port:n,timeoutMs:i});return await ly(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},Math.min(2e4,e),a)}catch(e){if(a?.aborted||t7(e))throw t6();s(t,e)}return null}async function lv(e){var t,r,n;let{device:i,timeoutBudgetMs:a,forceRefresh:o,requestTunnelIp:s,setRequestTunnelIp:l}=e;if("device"!==i.kind)return{ip:null,sharedCacheHit:!1};if(!o){let e,r=(t=i.id,(e=lf.get(t))?e.expiresAt<=Date.now()?(lf.delete(t),null):e.ip:null);if(r)return{ip:r,sharedCacheHit:!0};if(void 0!==s)return{ip:s,sharedCacheHit:!1}}let d=await lS(i.id,a);return l(d),d&&(r=i.id,n=d,lf.set(r,{ip:n,expiresAt:Date.now()+3e4})),{ip:d,sharedCacheHit:!1}}async function ly(e,t,r,n){let i=AbortSignal.timeout(r),a=n?AbortSignal.any([n,i]):i;return await fetch(e,{...t,signal:a})}async function lS(e,t){if("number"==typeof t&&t<=0)return null;let r="number"==typeof t?Math.max(1,Math.min(1e4,t)):1e4,a=n.join(c.tmpdir(),`agent-device-devicectl-info-${process.pid}-${Date.now()}.json`);try{let t=Math.max(1,Math.ceil(r/1e3)),n=await i_(["devicectl","device","info","details","--device",e,"--json-output",a,"--timeout",String(t)],{allowFailure:!0,timeoutMs:r});if(0!==n.exitCode||!i.existsSync(a))return null;let o=JSON.parse(i.readFileSync(a,"utf8"));if(o.info?.outcome&&"success"!==o.info.outcome)return null;let s=(o.result?.connectionProperties?.tunnelIPAddress??o.result?.device?.connectionProperties?.tunnelIPAddress)?.trim();return s&&s.length>0?s:null}catch{return null}finally{lN(a)}}async function l_(e,t,r,n,i){let a=JSON.stringify(r),o=ln(e,["spawn",e.id,"/usr/bin/curl","-s","-X","POST","-H","Content-Type: application/json","--data",a,`http://127.0.0.1:${t}/command`]),s=await i_(o,{allowFailure:!0,timeoutMs:n,signal:i}),l=s.stdout;if(0!==s.exitCode){let e=eo({message:"Runner did not accept connection (simctl spawn)",stdout:s.stdout,stderr:s.stderr,context:{platform:"ios",phase:"connect"}});throw new L("COMMAND_FAILED","Runner did not accept connection (simctl spawn)",{port:t,stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode,reason:e,hint:el(e)})}return{status:200,body:l}}async function lI(){return await new Promise((e,t)=>{let r=w.createServer();r.listen(0,"127.0.0.1",()=>{let n=r.address();if("object"==typeof n&&n?.port){let t=n.port;r.close(()=>e(t))}else r.close(()=>t(new L("COMMAND_FAILED","Failed to allocate port")))}),r.on("error",t)})}function lb(e,t,r,n){t&&lx(t,e),r&&lx(r,e),n&&process.stderr.write(e)}let lA=new Map;function lx(e,t){let r=(lA.get(e)??Promise.resolve()).catch(()=>{}).then(()=>i.promises.appendFile(e,t)).catch(()=>{}).finally(()=>{lA.get(e)===r&&lA.delete(e)});lA.set(e,r)}function lN(e){try{i.existsSync(e)&&i.unlinkSync(e)}catch{}}let lM=new Set(["RUNNER_PRODUCT_MISSING","RUNNER_PRODUCT_REPAIR_FAILED"]);async function lE(e,t,r){if("macos"!==e.platform)return;if(0===t.length)throw new L("COMMAND_FAILED","Missing macOS runner product",{reason:"RUNNER_PRODUCT_MISSING",xctestrunPath:r});let n=Array.from(new Set(t)).sort((e,t)=>t.length-e.length);for(let e of n)if(!i.existsSync(e))throw new L("COMMAND_FAILED","Missing macOS runner product",{reason:"RUNNER_PRODUCT_MISSING",productPath:e,xctestrunPath:r});for(let e of n)if(!await lD(e)){await iS("codesign",["--remove-signature",e],{allowFailure:!0});try{await iS("codesign",["--force","--sign","-",e])}catch(n){let t=n instanceof L?n:new L("COMMAND_FAILED",String(n));throw new L("COMMAND_FAILED","Failed to repair macOS runner product signature",{reason:"RUNNER_PRODUCT_REPAIR_FAILED",productPath:e,xctestrunPath:r,error:t.message,details:t.details})}}}async function lD(e){return 0===(await iS("codesign",["--verify","--deep","--strict",e],{allowFailure:!0})).exitCode}let lk=new Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.:-"),lP=new Set([" "," ","\n","\r"]),lC=new Set(["__defineGetter__","__defineSetter__","__proto__","constructor","prototype"]);function lR(e,t={}){let r=t.maxDocumentChars??0x8000000;if(e.length>r)throw Error(`XML document exceeds maximum supported size of ${r} characters.`);return new lT(e).parse()}function lO(e,t){for(let r of e){if("dict"===r.name)for(let e=0;e<r.children.length-1;e+=1){let n=r.children[e],i=r.children[e+1];n?.name==="key"&&n.text&&i&&t(n.text,i)}lO(r.children,t)}}class lT{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(){"<"!==this.xml[this.index]?this.readText():this.resolveMarkupReader()()}resolveMarkupReader(){return this.startsWith("\x3c!--")?()=>this.skipUntil("--\x3e","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(){65279===this.xml.charCodeAt(0)&&(this.index=1)}readOpeningTag(){this.index+=1,this.skipWhitespace();let e=this.readRequiredName(`Missing XML tag name at offset ${this.index}.`),{attributes:t,selfClosing:r}=this.readOpeningTagBody(),n={name:e,attributes:t,text:null,children:[]};this.addNode(n),r||this.pushOpenNode(n)}readOpeningTagBody(){let e={};for(;;){this.skipWhitespace();let t=this.readOpeningTagEnd();if(t)return{attributes:e,selfClosing:"self-closing"===t};let r=this.readAttribute();e[r.name]=r.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(function(e){if(lC.has(e))throw Error(`Unsupported XML attribute name "${e}".`)}(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=-1===e?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(-1===t)throw Error("CDATA section is not closed.");this.appendText(this.xml.slice(e,t),!1),this.index=t+3}appendText(e,t){let r=e.trim();if(!r)return;let n=this.stack[this.stack.length-1];n&&(n.text=`${n.text??""}${t?lL(r):r}`)}addNode(e){let t=this.stack[this.stack.length-1];t?t.children.push(e):this.roots.push(e)}readName(){var e;let t=this.index;for(;this.index<this.xml.length&&void 0!==(e=this.xml[this.index])&&lk.has(e);)this.index+=1;return this.xml.slice(t,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 r=this.index,n=this.xml.indexOf(t,r);if(-1===n)throw Error(`XML attribute "${e}" is not closed.`);return this.index=n+1,lL(this.xml.slice(r,n).trim())}skipDeclaration(){let e={quote:null,bracketDepth:0};for(let t=this.index+2;t<this.xml.length;t+=1)if(function(e,t){var r,n,i;return!(void 0===t||(r=e,n=t,r.quote?(n===r.quote&&(r.quote=null),!0):('"'===n||"'"===n)&&(r.quote=n,!0)))&&(function(e,t){if("["===t){e.bracketDepth+=1;return}"]"===t&&e.bracketDepth>0&&(e.bracketDepth-=1)}(e,t),i=e,">"===t&&0===i.bracketDepth)}(e,this.xml[t])){this.index=t+1;return}throw Error("XML declaration is not closed.")}skipUntil(e,t){let r=this.xml.indexOf(e,this.index+e.length);if(-1===r)throw Error(t);this.index=r+e.length}skipWhitespace(){for(var e;this.index<this.xml.length&&void 0!==(e=this.xml[this.index])&&lP.has(e);)this.index+=1}startsWith(e){return this.xml.startsWith(e,this.index)}}function lL(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:var r=e,n=t;let i=n.startsWith("#x")?Number.parseInt(n.slice(2),16):Number(n.slice(1));if(!Number.isInteger(i)||i<0||i>1114111)return r;try{return String.fromCodePoint(i)}catch{return r}}})}let l$=new Set(["ProductPaths","DependentProductPaths","TestHostPath","TestBundlePath","UITargetAppPath"]);async function lF(e){var t;let r=await lU(e);if(!r||0===r.length)return null;let a=n.dirname(e),o=new Set,s=function(e,t){let r=[],i=new Set,a=[];for(let o of e){if(o.startsWith("__TESTHOST__/")){a.push(o.slice(13));continue}if(!o.startsWith("__TESTROOT__/"))continue;let e=o.slice(13);r.push(n.join(t,e));let s=function(e){let t=/\.app(?:\/|$)/.exec(e);return t&&void 0!==t.index?e.slice(0,t.index+4):null}(e);s&&i.add(n.join(t,s))}return{testRootPaths:r,hostRoots:Array.from(i),hostRelativePaths:a}}(r,a);for(let e of s.testRootPaths){if(!i.existsSync(e))return null;o.add(e)}for(let e of(t=s).hostRelativePaths.map(e=>{let r=t.hostRoots.find(t=>i.existsSync(n.join(t,e)));return r?n.join(r,e):null})){if(!e)return null;o.add(e)}return Array.from(o)}async function lU(e){let t=await iI(e);if(t){var r,n,a,o=t;let e=new Set;for(let t of[a=o,...function(e){let t=e.TestConfigurations;if(!Array.isArray(t))return[];let r=[];for(let e of t){if(!lG(e))continue;let t=e.TestTargets;Array.isArray(t)&&r.push(...t.filter(lG))}return r}(a),...Object.values(a).filter(e=>lG(e)&&"TestBundlePath"in e)])for(let r of function(e){let t=new Set;for(let[r,n]of Object.entries(e))if(l$.has(r)){if("string"==typeof n){t.add(n);continue}if(Array.isArray(n))for(let e of n)"string"==typeof e&&t.add(e)}return Array.from(t)}(t))e.add(r);return Array.from(e)}if("darwin"===process.platform)return null;try{let t;return r=i.readFileSync(e,"utf8"),n=lR(r),t=new Set,lO(n,(e,r)=>{if(l$.has(e)){if("string"===r.name&&r.text)return void t.add(r.text);if("array"===r.name)for(let e of r.children)"string"===e.name&&e.text&&t.add(e.text)}}),Array.from(t)}catch{return null}}function lG(e){return!!e&&"object"==typeof e}let lq=["CFBundleIcons","CFBundleIcons~ipad"];async function lj(e){let t=e.filter(lW);if(0===t.length)return;let r=e.filter(e=>lJ(e)&&!lz(e));for(let e of t){let t=function(e,t){let r=n.dirname(e);return t.find(e=>n.dirname(e)===r&&"AgentDeviceRunner.app"===n.basename(e))??t.find(t=>n.dirname(t)===r&&t!==e)??null}(e,r);t&&await lV(t,e)}}async function lV(e,t){var r;let a,o=function(e,t){let r=!1;for(let o of i.readdirSync(e,{withFileTypes:!0})){var a;if(o.isFile()&&(a=o.name,/^AppIcon.*\.png$/.test(a)||"Assets.car"===a))(function(e,t){if(i.existsSync(t)){let r=i.readFileSync(e),n=i.readFileSync(t);return!r.equals(n)&&(i.copyFileSync(e,t),!0)}return i.copyFileSync(e,t),!0})(n.join(e,o.name),n.join(t,o.name))&&(r=!0)}return r}(e,t),s=await lB(e,t);(o||s)&&(await lK(t),r=t,a=new Date,i.utimesSync(r,a,a))}async function lB(e,t){var r,i;let a=n.join(e,"Info.plist"),o=n.join(t,"Info.plist"),s=await iI(a),l=await iI(o);if(!s||!l)return!1;let d=(r=s,i=l,lq.flatMap(e=>{let t=r[e];return void 0===t||JSON.stringify(i[e])===JSON.stringify(t)?[]:[{key:e,value:t,shouldInsert:void 0===i[e]}]}));if(0===d.length)return!1;for(let e of d)await lH(o,e.key,e.value,e.shouldInsert);return!0}async function lH(e,t,r,n){let i=await iS("plutil",[n?"-insert":"-replace",t,"-json",JSON.stringify(r),e],{allowFailure:!0});if(0!==i.exitCode)throw new L("COMMAND_FAILED","Failed to update XCTest runner icon plist",{key:t,plistPath:e,stderr:i.stderr})}async function lK(e){let t=await iS("codesign",["--force","--sign","-","--timestamp=none","--generate-entitlement-der",e],{allowFailure:!0});if(0!==t.exitCode)throw new L("COMMAND_FAILED","Failed to sign XCTest runner app after icon update",{runnerAppPath:e,stderr:t.stderr})}function lW(e){return lJ(e)&&lz(e)&&(e.includes("Debug-iphonesimulator")||e.includes("Release-iphonesimulator")||e.includes("Debug-appletvsimulator")||e.includes("Release-appletvsimulator"))}function lz(e){return n.basename(e).endsWith("-Runner.app")}function lJ(e){return n.basename(e).endsWith(".app")}let lX="XCTestDevices",lZ=".agent-device-backup",lY=".agent-device-xctestdevices-backup-",lQ=n.join(c.homedir(),".agent-device","ios-runner"),l0=".agent-device-runner-cache.json",l1={PreferredScreenCaptureFormat:"screenshots",SystemAttachmentLifetime:"keepNever",UserAttachmentLifetime:"keepNever"},l2=new Map,l3=new Set;function l4(e){return e?.trim()??""}function l5(e=process.env){return l4(e.AGENT_DEVICE_IOS_BUNDLE_ID)||l4(e.AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID)||"com.callstack.agentdevice.runner"}function l8(e=process.env){let t=l4(e.AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID);return t||`${l5(e)}.uitests`}let l6=function(e=process.env){let t=l5(e),r=l8(e);return Array.from(new Set([l4(e.AGENT_DEVICE_IOS_RUNNER_CONTAINER_BUNDLE_ID),`${r}.xctrunner`,t].filter(e=>e.length>0)))}(process.env);function l9(e=c.homedir()){return n.join(e,"Library","Developer","XCTestDevices")}async function l7(e,t={}){if("ios"!==e.platform||"simulator"!==e.kind)return null;let r=ee(e.simulatorSetPath);if(!r)return null;let a=n.resolve(r),o=n.resolve(t.xctestDeviceSetPath??l9()),s=n.resolve(t.backupPath??function(e=l9()){return`${e}${lZ}`}(o)),l=n.resolve(t.lockDirPath??function(e=c.homedir()){return n.join(e,".agent-device","xctest-device-set.lock")}()),d=t.ownerStartTime??M(process.pid),u=await dr({lockDirPath:l,owner:{pid:t.ownerPid??process.pid,startTime:d,acquiredAtMs:t.nowMs??Date.now()}});try{if(de({xctestDeviceSetPath:o,backupPath:s}),function(e,t){if(n.resolve(e)===n.resolve(t))return!0;try{return i.realpathSync.native(e)===i.realpathSync.native(t)}catch{return!1}}(a,o))return await u(),null;i.mkdirSync(a,{recursive:!0}),i.existsSync(o)&&i.renameSync(o,s),function(e){let{requestedSetPath:t,xctestDeviceSetPath:r}=e,a=n.dirname(r),o=n.join(a,`${lX}.agent-device-link-${process.pid}-${Date.now()}`);i.mkdirSync(a,{recursive:!0});try{i.symlinkSync(t,o,"dir"),i.renameSync(o,r)}catch(e){throw i.existsSync(o)&&dt(o),e}}({requestedSetPath:a,xctestDeviceSetPath:o})}catch(e){throw de({xctestDeviceSetPath:o,backupPath:s}),await u(),new L("COMMAND_FAILED","Failed to redirect XCTest device set path",{requestedSetPath:a,xctestDeviceSetPath:o,backupPath:s,error:String(e)})}let p=!1;return{release:async()=>{if(!p){p=!0;try{de({xctestDeviceSetPath:o,backupPath:s})}finally{await u()}}}}}function de(e){let{xctestDeviceSetPath:t,backupPath:r}=e,a=[r,...function(e){let t=n.dirname(e),r=n.basename(e).replace(lZ,""),a=r===lX?lY:`${r}${lY}`;try{return i.readdirSync(t).filter(e=>e.startsWith(a)).sort().map(e=>n.join(t,e))}catch{return[]}}(r)],o=a.find(e=>i.existsSync(e)),s=i.existsSync(t)&&i.lstatSync(t).isSymbolicLink();if(o){if(s&&dt(t),i.existsSync(t))if(!s)return void N({level:"warn",phase:"ios_runner_xctest_device_set_restore_collision",data:{xctestDeviceSetPath:t,activeBackupPath:o}});else o!==r?i.rmSync(o,{recursive:!0,force:!0}):i.rmSync(r,{recursive:!0,force:!0});else i.mkdirSync(n.dirname(t),{recursive:!0}),i.renameSync(o,t);for(let e of a)e!==o&&i.existsSync(e)&&i.rmSync(e,{recursive:!0,force:!0});return}s&&(N({level:"warn",phase:"ios_runner_xctest_device_set_orphaned_symlink",data:{xctestDeviceSetPath:t}}),dt(t))}function dt(e){!i.existsSync(e)||i.lstatSync(e).isSymbolicLink()&&i.unlinkSync(e)}async function dr(e){let{lockDirPath:t,owner:r}=e,a=n.join(t,"owner.json"),o=Date.now()+(e.timeoutMs??3e4),s=e.pollMs??100,l=e.description??"XCTest device set lock";for(i.mkdirSync(n.dirname(t),{recursive:!0});Date.now()<o;)try{i.mkdirSync(t),function(e,t){let r=`${e}.${process.pid}.${Date.now()}.tmp`;i.writeFileSync(r,JSON.stringify(t),"utf8"),i.renameSync(r,e)}(a,r);let e=!1;return async()=>{e||(e=!0,i.rmSync(t,{recursive:!0,force:!0}))}}catch(e){if("EEXIST"!==e.code)throw e;if(function(e,t){let r=null;try{r=i.statSync(e)}catch{return!0}let n=di(t);if(n){var a;return!(Number.isInteger((a=n).pid)&&!(a.pid<=0)&&C(a.pid)&&(!a.startTime||M(a.pid)===a.startTime))&&(i.rmSync(e,{recursive:!0,force:!0}),!0)}return!(Date.now()-r.mtimeMs<5e3)&&(i.rmSync(e,{recursive:!0,force:!0}),!0)}(t,a))continue;await eV(s)}throw new L("COMMAND_FAILED",`Timed out waiting for ${l}`,{lockDirPath:t,...function(e,t){let r,n=Date.now(),a=di(t);try{r=Math.max(0,Math.round(n-i.statSync(e).mtimeMs))}catch{}return{...void 0!==r?{lockAgeMs:r}:{},...a?{ownerPid:a.pid,ownerStartTime:a.startTime,ownerAgeMs:Math.max(0,Math.round(n-a.acquiredAtMs))}:{}}}(t,a)})}async function dn(e){var t;return await dr({lockDirPath:(t=e,n.join(n.dirname(t),`${n.basename(t)}.lock`)),owner:{pid:process.pid,startTime:M(process.pid),acquiredAtMs:Date.now()},timeoutMs:6e5,description:"iOS runner cache lock"})}function di(e){try{return JSON.parse(i.readFileSync(e,"utf8"))}catch{return null}}async function da(e,r){let a=e6(),o=function(e,r=e6()){var a;let o;return{schemaVersion:1,packageVersion:e8(),runnerSourceFingerprint:function(e){let r=n.join(e,"ios-runner","AgentDeviceRunner"),a=function(e){if(!i.existsSync(e))return[];let t=[],r=[e];for(;r.length>0;){let e=r.pop();for(let s of i.readdirSync(e,{withFileTypes:!0})){var a,o;let i=n.join(e,s.name);if(s.isDirectory()){if("xcuserdata"===s.name)continue;r.push(i);continue}s.isFile()&&(a=s.name,o=i,"project.pbxproj"===a?o.includes(`${n.sep}.xcodeproj${n.sep}`):[".jpg",".json",".png",".swift",".plist",".entitlements",".xctestplan",".xcconfig",".storyboard",".xib"].includes(n.extname(a)))&&t.push(i)}}return t.sort((e,t)=>e.localeCompare(t))}(r),o=function(e,r){let a=t.createHash("sha256");for(let t of r){let r=n.relative(e,t),o=i.statSync(t);a.update(r),a.update("\0"),a.update(String(o.size)),a.update("\0"),a.update(String(Math.trunc(o.mtimeMs))),a.update("\0")}return a.digest("hex")}(r,a),s=dv.get(r);if(s?.fileStatsFingerprint===o)return s.sourceFingerprint;let l=t.createHash("sha256");for(let e of a){let t=n.relative(r,e);l.update(t),l.update("\0"),l.update(i.readFileSync(e)),l.update("\0")}let d=l.digest("hex");return dv.set(r,{fileStatsFingerprint:o,sourceFingerprint:d}),d}(r),platformName:dE(e),deviceKind:e.kind,target:e.target??"mobile",buildDestinationFamily:"macOS"===(o=dE(a=e))?`platform=macOS,arch=${dD()}`:"simulator"===a.kind?`generic/platform=${o} Simulator`:`generic/platform=${o}`,runnerBundleBuildSettings:dC(process.env),runnerSigningBuildSettings:dP(process.env,"device"===e.kind,e.platform),runnerPerformanceBuildSettings:dR()}}(e,a),s=function(e,r){var i;let a,o=process.env.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim();if(o)return n.resolve(o);let s=(a=t.createHash("sha256").update(JSON.stringify(dp(r))).digest("hex"),`cache-${a.slice(0,16)}`),l="macos"===(i=e).platform?n.join(lQ,"derived","macos"):"tv"===i.target?n.join(lQ,"derived","simulator"===i.kind?"tvos-simulator":"tvos-device"):"simulator"===i.kind?n.join(lQ,"derived","ios-simulator"):n.join(lQ,"derived","ios-device");return n.join(l,s)}(e,o);return await sH(l2,s,async()=>{let t=await dn(s);try{return await ds({device:e,options:r,projectRoot:a,expectedCacheMetadata:o,derived:s})}finally{await t()}})}async function ds(e){let{device:t,options:r,projectRoot:a,expectedCacheMetadata:o,derived:s}=e;ei(process.env.AGENT_DEVICE_IOS_CLEAN_DERIVED)&&(dL("clean","forced_clean",{derived:s}),dO(s),dd(s));let l=await dT({derived:s,projectRoot:a,expectedCacheMetadata:o,findXctestrun:e=>dy(e,t),xctestrunReferencesProjectRoot:d_,resolveExistingXctestrunProductPaths:lF});if("reuse_ready"!==l.reason&&dL("rebuild",l.reason,{derived:s,xctestrunPath:l.xctestrunPath}),"reuse_ready"===l.reason){let e=await dl(t,s,o,l);if(e)return e}l.xctestrunPath&&(dO(s),dd(s));let d=n.join(a,"ios-runner","AgentDeviceRunner","AgentDeviceRunner.xcodeproj");if(!i.existsSync(d))throw new L("COMMAND_FAILED","iOS runner project not found",{projectPath:d});await dM(t,d,s,r);let c=dy(s,t);if(!c)throw new L("COMMAND_FAILED","Failed to locate .xctestrun after build");let u=await lF(c);if(!u)throw new L("COMMAND_FAILED","Runner build is missing expected products",{xctestrunPath:c});return await lE(t,u,c),await lj(u),du(s,df(o,c,u)),dL("build","built_new",{derived:s,xctestrunPath:c}),c}async function dl(e,t,r,n){try{var i,a,o,s;return await lE(e,n.productPaths,n.xctestrunPath),dL("reuse","reuse_ready",{derived:t,xctestrunPath:n.xctestrunPath}),i=t,a=r,o=n.xctestrunPath,s=n.productPaths,du(i,df(a,o,s)),n.xctestrunPath}catch(e){if(!function(e){if(!(e instanceof L))return!1;let t=e.details&&"object"==typeof e.details?e.details.reason:void 0;return"string"==typeof t&&lM.has(t)}(e))throw e;return dL("rebuild","repair_failed",{derived:t,xctestrunPath:n.xctestrunPath}),null}}function dd(e){try{if(!i.existsSync(e))return;if("derived"!==n.basename(e))return void i.rmSync(e,{recursive:!0,force:!0});for(let r of i.readdirSync(e,{withFileTypes:!0})){var t;t=r.name,dc.has(t)&&i.rmSync(n.join(e,r.name),{recursive:!0,force:!0})}}catch{}}let dc=new Set([l0,"Build","BuildCache.noindex","Index.noindex","Logs","ModuleCache.noindex","SDKStatCaches.noindex","SourcePackages","TextBasedInstallAPI","info.plist"]);function du(e,t){i.mkdirSync(e,{recursive:!0}),i.writeFileSync(n.join(e,l0),`${JSON.stringify(t,null,2)}
11
11
  `)}function dp(e){let{artifacts:t,...r}=e;return r}function df(e,t,r){let n=function(e,t){let r=dh(e);if(null===r||0===t.length)return null;let n=[];for(let e of t){let t=dh(e);if(null===t)return null;n.push({path:e,...t})}return{xctestrunPath:e,xctestrunMtimeMs:r.mtimeMs,xctestrunSize:r.size,productPaths:n}}(t,r);return n?{...e,artifacts:n}:e}function dm(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"string"==typeof e.path&&Number.isInteger(e.mtimeMs)&&Number.isInteger(e.size)}function dh(e){try{let t=i.statSync(e);return{mtimeMs:Math.trunc(t.mtimeMs),size:t.size}}catch{return null}}function dw(e,t){let r=dh(e);return r?.mtimeMs===t.mtimeMs&&r.size===t.size}function dg(e,t){let r=n.relative(n.resolve(t),n.resolve(e));return""!==r&&!r.startsWith("..")&&!n.isAbsolute(r)}let dv=new Map;function dy(e,t){if(!i.existsSync(e))return null;let r=[],a=[e];for(;a.length>0;){let e=a.pop();for(let t of i.readdirSync(e,{withFileTypes:!0})){let o=n.join(e,t.name);if(t.isDirectory()){a.push(o);continue}if(t.isFile()&&t.name.endsWith(".xctestrun"))try{let e=i.statSync(o);r.push({path:o,mtimeMs:e.mtimeMs})}catch{}}}return 0===r.length?null:(r.sort((e,r)=>{if(t){let n=dS(r.path,t)-dS(e.path,t);if(0!==n)return n}return r.mtimeMs-e.mtimeMs||e.path.localeCompare(r.path)}),r[0]?.path??null)}function dS(e,t){var r;let i=0,a=e.toLowerCase();n.basename(a).startsWith("agentdevicerunner.env.")&&(i-=1e3),a.includes(`${n.sep}macos${n.sep}`)&&(i-=5e3);let o="macos"===(r=t).platform?{preferred:["macos"],disallowed:["iphoneos","iphonesimulator","appletvos","appletvsimulator"]}:"tv"===r.target?"simulator"===r.kind?{preferred:["appletvsimulator"],disallowed:["appletvos","iphoneos","iphonesimulator","macos"]}:{preferred:["appletvos"],disallowed:["appletvsimulator","iphoneos","iphonesimulator","macos"]}:"simulator"===r.kind?{preferred:["iphonesimulator"],disallowed:["iphoneos","appletvos","appletvsimulator","macos"]}:{preferred:["iphoneos"],disallowed:["iphonesimulator","appletvos","appletvsimulator","macos"]};return o.preferred.length>0&&(o.preferred.some(e=>a.includes(e))?i+=2e3:i-=500),o.disallowed.some(e=>a.includes(e))&&(i-=2500),i}function d_(e,t){try{let r=i.readFileSync(e,"utf8"),n=new Set([t]);try{n.add(i.realpathSync(t))}catch{}for(let e of n)if(r.includes(e))return!0;return!1}catch{return!1}}async function dI(e,t,r){let i=n.dirname(e),a=r.replace(/[^a-zA-Z0-9._-]/g,"_"),o=n.join(i,`AgentDeviceRunner.env.${a}.json`),s=n.join(i,`AgentDeviceRunner.env.${a}.xctestrun`),l=await db(e);return dx(l,e=>{var r,n;return r=e,n=t,void(r.EnvironmentVariables={...r.EnvironmentVariables??{},...n},r.UITestEnvironmentVariables={...r.UITestEnvironmentVariables??{},...n},r.UITargetAppEnvironmentVariables={...r.UITargetAppEnvironmentVariables??{},...n},r.TestingEnvironmentVariables={...r.TestingEnvironmentVariables??{},...n})}),dx(l,e=>Object.assign(e,l1),{requireTestBundlePath:!0}),await dA(l,o,s),{xctestrunPath:s,jsonPath:o}}async function db(e){let t=await iS("plutil",["-convert","json","-o","-",e],{allowFailure:!0});if(0!==t.exitCode||!t.stdout.trim())throw new L("COMMAND_FAILED","Failed to read xctestrun plist",{xctestrunPath:e,stderr:t.stderr});try{let e=JSON.parse(t.stdout);if(!e||"object"!=typeof e||Array.isArray(e))throw Error("Root must be an object");return e}catch(t){throw new L("COMMAND_FAILED","Failed to parse xctestrun JSON",{xctestrunPath:e,error:String(t)})}}async function dA(e,t,r){i.writeFileSync(t,JSON.stringify(e,null,2));let n=await iS("plutil",["-convert","xml1","-o",r,t],{allowFailure:!0});if(0!==n.exitCode)throw new L("COMMAND_FAILED","Failed to write xctestrun plist",{tmpXctestrunPath:r,stderr:n.stderr})}function dx(e,t,r={}){let n=e.TestConfigurations;if(Array.isArray(n))for(let e of n)e&&"object"==typeof e&&function(e,t,r){if(Array.isArray(e))for(let n of e){let e=dN(n,r);e&&t(e)}}(e.TestTargets,t,r);for(let r of Object.values(e)){let e=dN(r,{requireTestBundlePath:!0});e&&t(e)}}function dN(e,t){return!e||"object"!=typeof e||Array.isArray(e)||t.requireTestBundlePath&&!e.TestBundlePath?null:e}async function dM(e,t,r,n){let i=dC(process.env),a=dP(process.env,"device"===e.kind,e.platform),o="device"===e.kind?["-allowProvisioningUpdates"]:[],s=dR(),l=await l7(e);try{var d;let l;await F("xcodebuild",["build-for-testing","-project",t,"-scheme","AgentDeviceRunner","-parallel-testing-enabled","NO",dk(e),"1","-destination",(d=e,l=dE(d),"macOS"===l?`platform=macOS,arch=${dD()}`:"simulator"===d.kind?`platform=${l} Simulator,id=${d.id}`:`generic/platform=${l}`),"-derivedDataPath",r,...s,...i,...o,...a],{detached:!0,onSpawn:e=>{l3.add(e),e.on("close",()=>{l3.delete(e)})},onStdoutChunk:e=>{lb(e,n.logPath,n.traceLogPath,n.verbose)},onStderrChunk:e=>{lb(e,n.logPath,n.traceLogPath,n.verbose)}})}catch(a){let e,t,r=a instanceof L?a:new L("COMMAND_FAILED",String(a)),i=(e=r.details?JSON.stringify(r.details):"",((t=`${r.message}
12
12
  ${e}`.toLowerCase()).includes("failed registering bundle identifier")||t.includes("app identifier")&&t.includes("not available")?"Set AGENT_DEVICE_IOS_BUNDLE_ID to a unique reverse-DNS value (for example, com.yourname.agentdevice.runner), then retry.":t.includes("requires a development team")?"Configure signing in Xcode or set AGENT_DEVICE_IOS_TEAM_ID for physical-device runs.":t.includes("no profiles for")||t.includes("provisioning profile")?"Install/select a valid iOS provisioning profile, or set AGENT_DEVICE_IOS_PROVISIONING_PROFILE.":t.includes("code signing")?"Enable Automatic Signing in Xcode or provide AGENT_DEVICE_IOS_TEAM_ID and optional AGENT_DEVICE_IOS_SIGNING_IDENTITY.":void 0)??la);throw new L("COMMAND_FAILED","xcodebuild build-for-testing failed",{error:r.message,details:r.details,logPath:n.logPath,hint:i})}finally{await l?.release()}}function dE(e){var t;if("ios"!==e.platform&&"macos"!==e.platform)throw new L("UNSUPPORTED_PLATFORM",`Unsupported platform for iOS runner: ${e.platform}`);return"macos"===e.platform?"macOS":"macos"===(t=e.target)||"desktop"===t?"macOS":"tv"===t?"tvOS":"iOS"}function dD(){return"arm64"===process.arch?"arm64":"x86_64"}function dk(e){return"macos"===e.platform||"device"===e.kind?"-maximum-concurrent-test-device-destinations":"-maximum-concurrent-test-simulator-destinations"}function dP(e=process.env,t=!1,r="ios"){if("macos"===r)return["CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO","CODE_SIGN_IDENTITY=","DEVELOPMENT_TEAM="];if(!t)return[];let n=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 n&&o.push(`DEVELOPMENT_TEAM=${n}`),i&&o.push(`CODE_SIGN_IDENTITY=${i}`),a&&o.push(`PROVISIONING_PROFILE_SPECIFIER=${a}`),o}function dC(e=process.env){let t=l5(e),r=l8(e);return[`AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID=${t}`,`AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID=${r}`]}function dR(){return["COMPILER_INDEX_STORE_ENABLE=NO","ENABLE_CODE_COVERAGE=NO"]}function dO(e,t=process.env){if(t.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim()){var r;let t,i;if(r=e,t=n.resolve(e6(),".tmp"),""===(i=n.relative(t,n.resolve(r)))||i.startsWith("..")||n.isAbsolute(i))throw new L("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 ${n.join(e6(),".tmp")}.`})}}async function dT(e){var t,r;let a,o=(t=e.derived,r=e.expectedCacheMetadata,(a=function(e){try{let t=JSON.parse(i.readFileSync(n.join(e,l0),"utf8"));if(!t||"object"!=typeof t||Array.isArray(t))return null;return t}catch{return null}}(t))?JSON.stringify(dp(a))!==JSON.stringify(dp(r))?{ok:!1,reason:"cache_metadata_mismatch"}:{ok:!0,metadata:a}:{ok:!1,reason:"cache_metadata_missing"}),s=o.ok?function(e,t){var r;let n=t?.artifacts;if(!(!(!(r=n)||"object"!=typeof r||Array.isArray(r))&&"string"==typeof r.xctestrunPath&&Number.isInteger(r.xctestrunMtimeMs)&&Number.isInteger(r.xctestrunSize)&&Array.isArray(r.productPaths)&&r.productPaths.length>0&&r.productPaths.every(dm))||!dg(n.xctestrunPath,e)||!dw(n.xctestrunPath,{mtimeMs:n.xctestrunMtimeMs,size:n.xctestrunSize}))return null;let i=[];for(let t of n.productPaths){if(!dg(t.path,e)||!dw(t.path,t))return null;i.push(t.path)}return{xctestrunPath:n.xctestrunPath,productPaths:i}}(e.derived,o.metadata):null,l=s?.xctestrunPath??e.findXctestrun(e.derived);if(!l)return{reason:"missing_xctestrun",xctestrunPath:null};let d=s?.xctestrunPath===l,c=d?s.productPaths:await e.resolveExistingXctestrunProductPaths(l);return c?e.xctestrunReferencesProjectRoot(l,e.projectRoot)||d?o.ok?{reason:"reuse_ready",xctestrunPath:l,productPaths:c}:{reason:o.reason,xctestrunPath:l,productPaths:c}:{reason:"project_root_mismatch",xctestrunPath:l,productPaths:c}:{reason:"missing_products",xctestrunPath:l,productPaths:[]}}function dL(e,t,r){N({level:"rebuild"===e?"warn":"info",phase:"runner_xctestrun_cache",data:{action:e,reason:t,...r}})}let d$=new Map,dF=new Map;async function dU(e,t){return await sH(dF,e.id,async()=>{let r,n,i=d$.get(e.id);if(i){if(dW(i.child.pid))return N({level:"debug",phase:"ios_runner_session_reuse",data:{deviceId:e.id,sessionId:i.sessionId,ready:i.ready}}),i;await dQ({},"stop_stale_session",async()=>{await dV(e.id,i)})}let a={};await dQ(a,"ensure_booted",async()=>{var t;await ("simulator"!==(t=e).kind?Promise.resolve():t.booted?(N({level:"debug",phase:"ios_runner_startup_ensure_booted_skipped",data:{deviceId:t.id}}),Promise.resolve()):dJ(t))}),t.cleanStaleBundles?await dQ(a,"cleanup_stale_bundles",async()=>{await dG(e)}):(a.cleanup_stale_bundles=0,N({level:"debug",phase:"ios_runner_startup_cleanup_stale_bundles_skipped"}));let o=await dQ(a,"ensure_xctestrun",async()=>await da(e,t)),s=await dQ(a,"allocate_port",async()=>await lI()),{xctestrunPath:l,jsonPath:d}=await dQ(a,"prepare_xctestrun_env",async()=>await dI(o,{AGENT_DEVICE_RUNNER_PORT:String(s)},`session-${e.id}-${s}`)),c=await dQ(a,"simulator_set_redirect",async()=>await l7(e));try{({child:r,wait:n}=await dQ(a,"launch_xcodebuild",()=>{let t;return $("xcodebuild",["test-without-building","-only-testing","AgentDeviceRunnerUITests/RunnerTests/testCommand","-parallel-testing-enabled","NO","-test-timeouts-enabled","NO","-collect-test-diagnostics","never",dk(e),"1","-destination-timeout",String(20),"-xctestrun",l,"-destination",(t=dE(e),"macOS"===t?`platform=macOS,arch=${dD()}`:"simulator"===e.kind?`platform=${t} Simulator,id=${e.id}`:`platform=${t},id=${e.id}`)],{allowFailure:!0,env:{...process.env,AGENT_DEVICE_RUNNER_PORT:String(s)},detached:!0})}))}catch(e){throw await c?.release(),e}r.stdout?.on("data",e=>{lb(e,t.logPath,t.traceLogPath,t.verbose)}),r.stderr?.on("data",e=>{lb(e,t.logPath,t.traceLogPath,t.verbose)});let u={sessionId:`${e.id}:${s}:${Date.now()}`,device:e,deviceId:e.id,port:s,xctestrunPath:l,jsonPath:d,testPromise:n,child:r,ready:!1,startupTimings:a,simulatorSetRedirect:c??void 0};return d$.set(e.id,u),u})}async function dG(e){if("simulator"===e.kind)for(let t of l6){let r=await i_(ln(e,["uninstall",e.id,t]),{allowFailure:!0});if(0!==r.exitCode){let e=`${r.stdout}
13
13
  ${r.stderr}`.toLowerCase();if(!e.includes("not installed")&&!e.includes("found nothing")&&!e.includes("no such file")&&!e.includes("invalid device")&&!e.includes("could not find"))continue}}}function dq(e){let t=d$.get(e);return t?{sessionId:t.sessionId,alive:dW(t.child.pid)}:null}async function dj(e,t){await sH(dF,e.deviceId,async()=>{d$.get(e.deviceId)===e&&(N({level:"warn",phase:"ios_runner_session_invalidated",data:{deviceId:e.deviceId,sessionId:e.sessionId,reason:t}}),await dV(e.deviceId,e,{graceful:!1,waitTimeoutMs:1e3}))})}async function dV(e,t,r={}){let n=t??d$.get(e);if(n){var i;if(!1!==r.graceful)try{await lm(n.device,n.port,lu({command:"shutdown"}),void 0,15e3)}catch{await dz(n.child.pid,"SIGTERM")}else await dz(n.child.pid,"SIGTERM");try{await Promise.race([n.testPromise,new Promise(e=>setTimeout(e,r.waitTimeoutMs??1e4))])}catch{}(i=n.child.pid)&&(dW(i)||k(i))&&await dz(n.child.pid,"SIGKILL"),lN(n.xctestrunPath),lN(n.jsonPath),await n.simulatorSetRedirect?.release(),d$.get(e)===n&&d$.delete(e)}}async function dB(e){await sH(dF,e,async()=>{await dV(e)})}async function dH(){let e=Array.from(d$.values()),t=Array.from(l3);await Promise.allSettled(e.map(async e=>{await dz(e.child.pid,"SIGINT")})),await Promise.allSettled(t.map(async e=>{await dz(e.pid,"SIGINT")})),await Promise.allSettled(e.map(async e=>{await dz(e.child.pid,"SIGTERM")})),await Promise.allSettled(t.map(async e=>{await dz(e.pid,"SIGTERM")})),await Promise.allSettled(e.map(async e=>{await dz(e.child.pid,"SIGKILL")})),await Promise.allSettled(t.map(async e=>{await dz(e.pid,"SIGKILL"),l3.delete(e)})),await Promise.allSettled(e.map(async e=>{await e.simulatorSetRedirect?.release()}))}async function dK(){await dH();let e=Array.from(d$.keys());await Promise.allSettled(e.map(async e=>{await dB(e)}));let t=Array.from(l3);await Promise.allSettled(t.map(async e=>{try{await dz(e.pid,"SIGTERM"),await dz(e.pid,"SIGKILL")}finally{l3.delete(e)}}))}function dW(e){return!!e&&C(e)}async function dz(e,t){if(!e||e<=0)return;try{process.kill(-e,t)}catch{}try{process.kill(e,t)}catch{}let r="SIGINT"===t?"INT":"SIGTERM"===t?"TERM":"KILL";try{await iS("pkill",[`-${r}`,"-P",String(e)],{allowFailure:!0})}catch{}}async function dJ(e){await i_(ln(e,["bootstatus",e.id,"-b"]),{timeoutMs:45e3})}async function dX(e,t,r,n,i,a){var o,s;o=t,s=r.command,o.startupTimingsReported||!o.startupTimings||(o.startupTimingsReported=!0,N({level:"info",phase:"ios_runner_session_startup_timings",durationMs:Object.values(o.startupTimings).reduce((e,t)=>e+t,0),data:{command:s,sessionId:o.sessionId,ready:o.ready,timings:o.startupTimings}}));let l=lu(r);if(lc(l.command)){let r=await x("ios_runner_command_send",async()=>await lm(e,t.port,l,n,i,t,a),{command:l.command,commandId:l.commandId,readOnly:!0,sessionReady:t.ready,timeoutMs:i});return await dZ(r,t,n)}let d=en.fromTimeoutMs(i),c=function(e,t){if(!e.ready)return{action:"run",reason:"startup"};if("tap"!==t.command&&"tapSeries"!==t.command)return{action:"run",reason:"conservative_command"};let r=e.lastSuccessfulRunnerResponseAtMs;if(void 0===r)return{action:"run",reason:"no_successful_response"};let n=Date.now()-r;return n>1e4?{action:"run",reason:"successful_response_stale",lastSuccessfulRunnerResponseAgeMs:n}:{action:"skip",reason:"recent_successful_response",lastSuccessfulRunnerResponseAgeMs:n}}(t,l);if("run"===c.action){let r=t.ready?Math.min(5e3,d.remainingMs()):Math.min(45e3,d.remainingMs());try{let i=await x("ios_runner_readiness_preflight",async()=>await lm(e,t.port,lu({command:"uptime"}),n,r,t,a),{command:l.command,commandId:l.commandId,lastSuccessfulRunnerResponseAgeMs:c.lastSuccessfulRunnerResponseAgeMs,reason:c.reason,sessionReady:t.ready,timeoutMs:r});await dZ(i,t,n)}catch(e){throw dY(e,{runnerReadinessPreflightFailed:!0})}}else N({level:"debug",phase:"ios_runner_readiness_preflight_skipped",data:{command:r.command,commandId:l.commandId,lastSuccessfulRunnerResponseAgeMs:c.lastSuccessfulRunnerResponseAgeMs,reason:c.reason,sessionReady:t.ready}});let u=d.remainingMs();if(u<=0)throw new L("COMMAND_FAILED","Runner command deadline exceeded",{timeoutMs:i});let p=await x("ios_runner_command_send",async()=>await lh(e,t.port,l,u,a),{command:l.command,commandId:l.commandId}).catch(e=>{if("skip"===c.action){var t;throw dY(e,{runnerReadinessPreflightSkipped:!0,runnerReadinessPreflightSkipReason:(t=c).reason,runnerReadinessPreflightSkippedAgeMs:t.lastSuccessfulRunnerResponseAgeMs})}throw e});return await dZ(p,t,n)}async function dZ(e,t,r){let n,i=await e.text();try{let e=JSON.parse(i);n=e&&"object"==typeof e?e:{}}catch{throw new L("COMMAND_FAILED","Invalid runner response",{text:i})}if(!n.ok){let e=n.error?.code,t="string"==typeof e&&e.trim().length>0?R(e):"COMMAND_FAILED",i="string"==typeof n.error?.message?n.error.message:void 0,a="string"==typeof n.error?.hint?n.error.hint:void 0;throw new L(t,i??"Runner error",{runner:n,xcodebuild:{exitCode:1,stdout:"",stderr:""},hint:a,logPath:r})}if(t.ready=!0,t.lastSuccessfulRunnerResponseAtMs=Date.now(),n.data&&"object"==typeof n.data&&!Array.isArray(n.data)){var a;let e,t=n.data;return"string"==typeof(e=(a=t).gestureFallback)&&0!==e.length&&N({level:"debug",phase:"ios_runner_gesture_fallback",data:{fallback:e,message:"string"==typeof a.gestureFallbackMessage?a.gestureFallbackMessage:void 0,hint:"string"==typeof a.gestureFallbackHint?a.gestureFallbackHint:void 0}}),t}return{}}function dY(e,t){let r=e instanceof L?e:new L("COMMAND_FAILED",e instanceof Error?e.message:String(e),void 0,e);return new L(r.code,r.message,{...r.details??{},...t},r.cause??e)}async function dQ(e,t,r){let n=Date.now();try{return await r()}finally{let r=Date.now()-n;e[t]=r,N({level:"debug",phase:`ios_runner_startup_${t}`,durationMs:r})}}let d0=new m;function d1(e){return{runCommand:e}}function d2(e,t,r,n={}){if(r)return d8(r);let i=d4(e,n);return i?d8(i.provider):d8(t)}function d3(e,t={}){return void 0!==d4(e,t)}function d4(e,t={}){let r=d0.getStore();return r&&r.deviceId===e.id&&(r.requestId?r.requestId===t.requestId:!t.requestId)?r:void 0}async function d5(e,t,r){if(!e)return await r();let n={provider:d8(e),deviceId:t.deviceId,requestId:t.requestId};return await d0.run(n,r)}function d8(e){return"function"==typeof e?{runCommand:e}:e}async function d6(e,t,r={}){if("ios"!==e.platform&&"macos"!==e.platform)throw new L("UNSUPPORTED_PLATFORM",`Unsupported platform for iOS runner: ${e.platform}`);if("simulator"!==e.kind&&"device"!==e.kind)throw new L("UNSUPPORTED_OPERATION",`Unsupported iOS device kind for runner: ${e.kind}`);lp(r.requestId);let n=lu(t),i=d2(e,d1(d7),void 0,{requestId:r.requestId});return lc(n.command)?er(()=>(lp(r.requestId),i.runCommand(e,n,r)),{shouldRetry:e=>(lp(r.requestId),lo(e))}):i.runCommand(e,n,r)}function d9(e,t={}){return"ios"!==e.platform?void 0:d3(e,{requestId:t.requestId})?void N({level:"debug",phase:"ios_runner_session_prewarm_skipped_scoped_provider",data:{deviceId:e.id}}):dU(e,t).then(()=>{}).catch(t=>{N({level:"warn",phase:"ios_runner_session_prewarm_failed",data:{deviceId:e.id,error:t instanceof Error?t.message:String(t)}})})}async function d7(e,t,r){let n;lp(r.requestId);let i=t8(r.requestId);try{let a=((n=await dU(e,r)).ready,45e3);return await dX(e,n,t,r.logPath,a,i)}catch(o){let a=o instanceof L?o:new L("COMMAND_FAILED",String(o));if("COMMAND_FAILED"===a.code&&"string"==typeof a.message&&a.message.includes("Runner did not accept connection")&&ls(a)&&n){lp(r.requestId),await dj(n,"runner_connect_failed_before_command_send"),n=await dU(e,{...r,cleanStaleBundles:!0});try{return await dX(e,n,t,r.logPath,45e3,i)}catch(o){let a=o instanceof L?o:new L("COMMAND_FAILED",String(o));if(lo(a))return await ce(e,n,t,a,r,i,"transport_error_after_retry_command_send");throw o}}if(n&&function(e){let t;return e.details?.runnerReadinessPreflightFailed===!0&&(lo(e)||(t=e.message.toLowerCase()).includes("timeout")||t.includes("timed out"))}(a)){lp(r.requestId),await dj(n,"runner_readiness_preflight_failed_before_command_send"),n=await dU(e,{...r,cleanStaleBundles:!0});try{let a=await dX(e,n,t,r.logPath,45e3,i);return N({level:"debug",phase:"ios_runner_readiness_preflight_recovered",data:{command:t.command,commandId:t.commandId,recovery:"session_restarted",sessionId:n.sessionId}}),a}catch(o){let a=o instanceof L?o:new L("COMMAND_FAILED",String(o));if(lo(a))return await ce(e,n,t,a,r,i,"transport_error_after_retry_command_send");throw o}}if(!n&&a.message.includes("Runner did not accept connection")&&await dB(e.id),n&&lo(a))return await ce(e,n,t,a,r,i,"transport_error_after_command_send");throw o}}async function ce(e,t,r,n,i,a,o){let s=await cn(e,t,r,n,i,a);return await ct(s,{command:r,session:t,transportError:n,invalidationReason:o})}async function ct(e,t){var r,n,i,a;if(!e)return await cr(t,"status_recovery_unavailable");if("recovered"===e.type){return r=e,ca({command:(n=t).command,session:n.session,transportError:n.transportError,decision:"skipped",reason:r.reason,lifecycleState:r.lifecycleState}),r.data}if("skipInvalidation"===e.type){throw i=e,ca({command:(a=t).command,session:a.session,transportError:a.transportError,decision:"skipped",reason:i.reason,lifecycleState:i.lifecycleState}),i.error}return await cr(t,e.reason,e.lifecycleState,e.error)}async function cr(e,t,r,n){throw ca({command:e.command,session:e.session,transportError:e.transportError,decision:"retained",reason:t,lifecycleState:r}),await dj(e.session,e.invalidationReason),n??e.transportError}async function cn(e,t,r,n,i,a){var o,s,l,d,c,u,p,f,m,h;let w,g,v,y,S;if("status"===r.command||!r.commandId?.trim())return;let _=co(n);try{w=await dX(e,t,{command:"status",statusCommandId:r.commandId},i.logPath,3e3,a)}catch(e){return N({level:"debug",phase:"ios_runner_command_status_recovery_failed",data:{command:r.command,commandId:r.commandId,error:e instanceof Error?e.message:String(e),..._}}),{type:"retainInvalidation",reason:"status_probe_failed"}}let I="string"==typeof w.lifecycleState?w.lifecycleState:"";return N({level:"debug",phase:"ios_runner_command_status_recovery",data:{command:r.command,commandId:r.commandId,lifecycleState:I,..._}}),o=w,s=I,l=r,d=n,c=i,"completed"===s?function(e,t,r,n){let i=function(e){if("string"!=typeof e||0===e.trim().length)return;let t=function(e){try{let t=JSON.parse(e);if(t&&"object"==typeof t)return t}catch{}return{}}(e);if(t.ok)return t.data&&"object"==typeof t.data&&!Array.isArray(t.data)?t.data:{}}(e.lifecycleResponseJson);if(i)return{type:"recovered",data:i,reason:"completed_with_retained_response",lifecycleState:"completed"};if(lc(t.command))return{type:"skipInvalidation",error:r,reason:"read_only_completed_without_retained_response",lifecycleState:"completed"};let a=co(r);return{type:"skipInvalidation",reason:"completed_without_retained_response",lifecycleState:"completed",error:new L("COMMAND_FAILED",`Runner command "${t.command}" completed after the transport response was lost, but no recoverable response was retained.`,{command:t.command,commandId:t.commandId,lifecycleState:"completed",recovery:"completed_without_retained_response",...a,hint:function(e,t={}){return`${ci(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.`}(t.command,a),logPath:n.logPath,transportError:r.message},r)}}(o,l,d,c):"failed"===s?{type:"skipInvalidation",reason:"runner_reported_failure",lifecycleState:s,error:(u=o,p=l,f=d,m=c,g="string"==typeof u.lifecycleErrorCode?u.lifecycleErrorCode:void 0,v="string"==typeof u.lifecycleErrorMessage?u.lifecycleErrorMessage:"Runner command failed",y="string"==typeof u.lifecycleErrorHint?u.lifecycleErrorHint:void 0,S=co(f),new L(R(g),v,{command:p.command,commandId:p.commandId,lifecycleState:"failed",recovery:"runner_reported_failure",...S,hint:y??function(e,t={}){return`${ci(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.`}(p.command,S),logPath:m.logPath,transportError:f.message},f))}:"accepted"===s||"started"===s?{type:"skipInvalidation",reason:"command_still_in_flight",lifecycleState:s,error:function(e,t,r,n){if(lc(t.command))return r;let i=co(r);return new L("COMMAND_FAILED",`Runner command "${t.command}" is still ${e} after the transport response was lost.`,{command:t.command,commandId:t.commandId,lifecycleState:e,recovery:"command_still_in_flight",...i,hint:function(e,t,r={}){return`${ci(r)}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.`}(t.command,e,i),logPath:n.logPath,transportError:r.message},r)}(s,l,d,c)}:{type:"retainInvalidation",reason:s?"unknown_lifecycle_state":"missing_lifecycle_state",lifecycleState:s,error:new L("COMMAND_FAILED",`Runner command "${l.command}" lost its transport response and lifecycle status was ${s?`"${s}"`:"missing"}, so agent-device invalidated the runner session instead of replaying the command.`,{command:l.command,commandId:l.commandId,lifecycleState:s,recovery:"lifecycle_state_not_recoverable",hint:(h=l.command,`The runner did not confirm that "${h}" reached a safe terminal state, so agent-device kept the conservative invalidation path. Run snapshot -i before retrying if the UI may have changed.`),logPath:c.logPath,transportError:d.message},d)}}function ci(e){return!0!==e.readinessPreflightSkipped?"":"This hot command skipped the uptime preflight because the runner had just responded; status recovery confirmed the runner still observed it. "}function ca(e){let{command:t,session:r,transportError:n,decision:i,reason:a,lifecycleState:o}=e;N({level:"retained"===i?"warn":"debug",phase:"ios_runner_command_invalidation_decision",data:{command:t.command,commandId:t.commandId,decision:i,reason:a,lifecycleState:o,runnerReachable:void 0!==o,sessionId:r.sessionId,transportError:n.message}})}function co(e){let t,r,n,i={},a="boolean"==typeof(t=e.details?.runnerReadinessPreflightSkipped)?t:void 0;void 0!==a&&(i.readinessPreflightSkipped=a);let o="string"==typeof(r=e.details?.runnerReadinessPreflightSkipReason)?r:void 0;void 0!==o&&(i.readinessPreflightSkipReason=o);let s="number"==typeof(n=e.details?.runnerReadinessPreflightSkippedAgeMs)?n:void 0;return void 0!==s&&(i.readinessPreflightSkippedAgeMs=s),i}let cs=new WeakMap;async function cl(e){var t,r;let n,i,a,{sessionStore:o,leaseRegistry:s}=e,l=(n={...(t=function(e){let t=W(e.meta?.sessionIsolation??e.flags?.sessionIsolation),r=e.meta?.tenantId??e.flags?.tenant,n=B(r);if(r&&!n)throw new L("INVALID_ARGS","Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");if("tenant"!==t)return e;if(!n)throw new L("INVALID_ARGS","session isolation mode tenant requires --tenant (or meta.tenantId).");let i=e.session||"default";return i.startsWith(`${n}:`)?{...e,meta:{...e.meta,tenantId:n,sessionIsolation:t}}:{...e,session:`${n}:${i}`,meta:{...e.meta,tenantId:n,sessionIsolation:t}}}(e.req)).flags??{}},((i=td(t.command,n))||!t.flags)&&i?{...t,flags:n}:t);N({level:"info",phase:"request_start",data:{session:l.session,command:l.command,tenant:l.meta?.tenantId,isolation:l.meta?.sessionIsolation}});let d=l.command;!function(e,t){if(s3.has(e.command)||e.meta?.sessionIsolation!=="tenant")return;let r=s1(e);t.assertLeaseAdmission({tenantId:r.tenantId,runId:r.runId,leaseId:r.leaseId,backend:r.leaseBackend})}(l,s);let c=function(e){var t,r;let n=e.session||sX;if(function(e){if(e.meta?.sessionExplicit===!0)return!0;let t=e.flags?.session;return"string"==typeof t&&t.trim().length>0}(e))return n;let i=sY(e);return i?(t=i.id,r=n,`cwd:${t}:${r}`):n}(l),u=s4.has(d)?[]:await s7({req:l,sessionName:c,sessionStore:o}),p=(r=s,(a=cs.get(r))||(a=new Map,cs.set(r,a)),a);return{req:l,command:d,sessionName:c,throwIfCanceled:()=>t9(l.meta?.requestId),runLocked:async e=>(t9(l.meta?.requestId),0===u.length)?await e():await cd(p,u,async()=>(t9(l.meta?.requestId),await e()))}}async function cd(e,t,r){let[n,...i]=t;return n?await sH(e,n,async()=>await cd(e,i,r)):await r()}function cc(e){var t,r,i;let a,{scope:o,logPath:s,sessionStore:l,trackDownloadableArtifact:d}=e;o.throwIfCanceled();let c=l.get(o.sessionName);c&&(!function(e){var t;let r;if(!((r=(t=e).recording)&&"ios"===t.device.platform&&"ios"!==r.platform&&!1!==r.showTouches))return;let n=e.recording,i=dq(e.device.id);if(!n.runnerSessionId){i?.alive&&(n.runnerSessionId=i.sessionId);return}if(!i?.alive){n.invalidatedReason??="iOS runner session exited during recording";return}i.sessionId!==n.runnerSessionId&&(n.invalidatedReason??="iOS runner session restarted during recording")}(c),l.set(o.sessionName,c));let u=(a=(t={req:o.req,sessionName:o.sessionName,sessionStore:l}).sessionStore.get(t.sessionName),{req:s8(t.req,a),existingSession:a}),p=u.req;c=u.existingSession;let f=e=>(function(e,t,r){let i=b();if(!t.ok){N({level:"error",phase:"request_failed",data:{code:t.error.code,message:t.error.message}});let e=A({force:!0})??void 0;return{ok:!1,error:T(new L(R(t.error.code),t.error.message,{...t.error.details??{},hint:t.error.hint??("string"==typeof t.error.details?.hint?t.error.details.hint:void 0),diagnosticId:t.error.diagnosticId,logPath:t.error.logPath}),{diagnosticId:i.diagnosticId,logPath:e})}}return N({level:"info",phase:"request_success"}),A(),{ok:!0,data:function(e,t,r){var i,a;let o;if(!t)return t;let s=(i=e,o=Array.isArray((a=t).artifacts)?[...a.artifacts]:[],"screenshot"!==i.command||o.some(e=>e?.field==="path")||"string"!=typeof a.path||o.push({field:"path",path:a.path,localPath:i.meta?.clientArtifactPaths?.path,fileName:n.basename(i.meta?.clientArtifactPaths?.path??a.path)}),o.filter(e=>!!(e&&"string"==typeof e.field&&"string"==typeof e.path&&"string"==typeof e.localPath&&e.localPath.length>0)));return 0===s.length?t:{...t,artifacts:s.map(t=>{let n=t.path;return{field:t.field,artifactId:r({artifactPath:n,tenantId:e.meta?.tenantId,fileName:t.fileName}),fileName:t.fileName,localPath:t.localPath}})}}(e,t.data,r)}})(p,e,d);if(c?.recording?.invalidatedReason&&"record"!==(r=o.command)&&"close"!==r)return{type:"response",response:f({ok:!1,error:{code:"COMMAND_FAILED",message:c.recording.invalidatedReason}})};!c||p.meta?.lockPolicy||(i=o.command,s2.has(i))||function(e,t){let r=sz(e,t);if(0!==r.length)throw new L("INVALID_ARGS",`Session "${e.name}" is already bound to ${sK(e)}, but this request selected ${r.map(sJ).join(", ")}.`,{session:e.name,conflicts:r.map(sJ),hint:sW(e,"selector-conflict")})}(c,p.flags);let m=(e,t,r)=>{let n;return{...ad(s,e,t,r,n=b().requestId),requestId:n}};return{type:"scope",scope:{req:p,sessionName:o.sessionName,existingSession:c,finalize:f,contextFromFlags:m,handlerContextFromFlags:(e,t,r)=>({...m(e,t,r),surface:l.get(o.sessionName)?.surface})}}}async function cu(e){let{lockedScope:t,logPath:r,sessionStore:n}=e,i=n.get(t.sessionName);if(!i)return t.finalize({ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session. Run open first."}});let a=await sI({req:t.req,session:i,sessionName:t.sessionName,logPath:r,sessionStore:n,contextFromFlags:t.contextFromFlags});return t.finalize(a)}function cp(e){N({level:"error",phase:"request_failed",data:{error:e instanceof Error?e.message:String(e)}});let t=b(),r=A({force:!0})??void 0;return{ok:!1,error:T(e,{diagnosticId:t.diagnosticId,logPath:r})}}async function cf(e,t=2e3){await Promise.race([e.then(()=>void 0).catch(()=>void 0),new Promise(e=>setTimeout(e,t))])}function cm(e,t){let r=t.includeTokens?.filter(e=>e.length>0)??[],n="",i=n=>{(!(r.length>0)||r.some(e=>n.includes(e)))&&e.write(function(e,t){if(0===t.length)return e;let r=e;for(let e of t)r=r.replace(e,"[REDACTED]");return r}(n,t.redactionPatterns))};return{onChunk:e=>{let t=`${n}${e}`.split("\n");for(let e of(n=t.pop()??"",t))i(`${e}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-device",
3
- "version": "0.16.11",
3
+ "version": "0.16.12",
4
4
  "description": "Agent-native CLI for AI mobile testing and app automation across iOS, Android, tvOS, Android TV, macOS, and Linux.",
5
5
  "mcpName": "io.github.callstackincubator/agent-device",
6
6
  "license": "MIT",
package/server.json CHANGED
@@ -7,12 +7,12 @@
7
7
  "url": "https://github.com/callstackincubator/agent-device",
8
8
  "source": "github"
9
9
  },
10
- "version": "0.16.11",
10
+ "version": "0.16.12",
11
11
  "packages": [
12
12
  {
13
13
  "registryType": "npm",
14
14
  "identifier": "agent-device",
15
- "version": "0.16.11",
15
+ "version": "0.16.12",
16
16
  "transport": {
17
17
  "type": "stdio"
18
18
  }
@@ -1 +0,0 @@
1
- 2b408efdce7368b2a0f8d7ca0cf1fdec6165330919a09e7276ec0704653f7bb3 agent-device-android-multitouch-helper-0.16.11.apk
@@ -1 +0,0 @@
1
- df75ea0154748d4c06368a62808b7b071b86de7e322c96c756076114b6611416 agent-device-android-snapshot-helper-0.16.11.apk