agent-device 0.17.5 → 0.17.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +5 -5
  2. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.5.apk → agent-device-android-multitouch-helper-0.17.7.apk} +0 -0
  3. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.7.apk.sha256 +1 -0
  4. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.5.manifest.json → agent-device-android-multitouch-helper-0.17.7.manifest.json} +4 -4
  5. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.5.apk → agent-device-android-snapshot-helper-0.17.7.apk} +0 -0
  6. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.7.apk.sha256 +1 -0
  7. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.5.manifest.json → agent-device-android-snapshot-helper-0.17.7.manifest.json} +6 -6
  8. package/dist/src/2133.js +1 -0
  9. package/dist/src/2748.js +1 -0
  10. package/dist/src/{4012.js → 2892.js} +1 -1
  11. package/dist/src/2948.js +1 -0
  12. package/dist/src/2954.js +2 -0
  13. package/dist/src/{7651.js → 3006.js} +1 -1
  14. package/dist/src/314.js +1 -0
  15. package/dist/src/{8806.js → 3340.js} +5 -5
  16. package/dist/src/368.js +1 -0
  17. package/dist/src/4291.js +1 -0
  18. package/dist/src/{7599.js → 432.js} +1 -1
  19. package/dist/src/4418.js +1 -0
  20. package/dist/src/4428.js +3 -0
  21. package/dist/src/4723.js +1 -0
  22. package/dist/src/{113.js → 5448.js} +1 -1
  23. package/dist/src/5484.js +1 -0
  24. package/dist/src/5628.js +1 -0
  25. package/dist/src/587.js +1 -0
  26. package/dist/src/5910.js +2 -0
  27. package/dist/src/6311.js +27 -0
  28. package/dist/src/6918.js +1 -0
  29. package/dist/src/7244.js +1 -0
  30. package/dist/src/7394.js +6 -0
  31. package/dist/src/8184.js +1 -0
  32. package/dist/src/8225.js +1 -0
  33. package/dist/src/{1974.js → 8275.js} +1 -1
  34. package/dist/src/8875.js +1 -0
  35. package/dist/src/9581.js +11 -0
  36. package/dist/src/9624.js +1 -0
  37. package/dist/src/9722.js +38 -0
  38. package/dist/src/9836.js +1 -0
  39. package/dist/src/9873.js +1 -0
  40. package/dist/src/9919.js +6 -0
  41. package/dist/src/android-adb.d.ts +3 -3
  42. package/dist/src/android-adb.js +1 -1
  43. package/dist/src/android-snapshot-helper.js +1 -1
  44. package/dist/src/android.js +1 -1
  45. package/dist/src/apple.js +1 -1
  46. package/dist/src/apps.js +6 -6
  47. package/dist/src/artifacts.js +1 -1
  48. package/dist/src/batch.d.ts +5 -5
  49. package/dist/src/batch.js +1 -1
  50. package/dist/src/{args.js → cli-help.js} +135 -36
  51. package/dist/src/cli-output.js +4 -30
  52. package/dist/src/cli.js +18 -17
  53. package/dist/src/command-surface.js +1 -1
  54. package/dist/src/contracts.d.ts +7 -7
  55. package/dist/src/contracts.js +1 -1
  56. package/dist/src/devices.js +1 -1
  57. package/dist/src/find.js +1 -1
  58. package/dist/src/finders.d.ts +1 -1
  59. package/dist/src/finders.js +1 -1
  60. package/dist/src/generic.js +8 -14
  61. package/dist/src/index.d.ts +34 -28
  62. package/dist/src/index.js +1 -1
  63. package/dist/src/input-actions.js +1 -1
  64. package/dist/src/input-actions~1.js +1 -1
  65. package/dist/src/install-source.js +1 -1
  66. package/dist/src/interaction.js +1 -1
  67. package/dist/src/internal/bin.js +5 -5
  68. package/dist/src/internal/companion-tunnel.js +1 -1
  69. package/dist/src/internal/daemon.js +1 -1
  70. package/dist/src/internal/png-worker.js +1 -1
  71. package/dist/src/internal/update-check-entry.js +1 -1
  72. package/dist/src/io.js +1 -1
  73. package/dist/src/lease.js +1 -1
  74. package/dist/src/linux.js +1 -1
  75. package/dist/src/metro.js +1 -1
  76. package/dist/src/notifications.js +1 -1
  77. package/dist/src/provider.js +1 -0
  78. package/dist/src/react-native.js +1 -1
  79. package/dist/src/record-trace-recording.js +3 -3
  80. package/dist/src/record-trace.js +1 -1
  81. package/dist/src/recording-provider.js +1 -1
  82. package/dist/src/remote-config.d.ts +6 -6
  83. package/dist/src/remote-config.js +1 -1
  84. package/dist/src/rslib-runtime.js +1 -1
  85. package/dist/src/selector-runtime.js +1 -1
  86. package/dist/src/selectors.d.ts +2 -2
  87. package/dist/src/selectors.js +1 -1
  88. package/dist/src/server.js +1 -1
  89. package/dist/src/session.js +8 -8
  90. package/dist/src/snapshot.js +2 -2
  91. package/dist/src/web.js +1 -0
  92. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +6 -6
  93. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +1 -1
  94. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift +9 -5
  95. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +5 -2
  96. package/ios-runner/AgentDeviceRunner/RecordingScripts/recording-overlay.swift +44 -8
  97. package/ios-runner/AgentDeviceRunner/RecordingScripts/recording-resize.swift +59 -16
  98. package/ios-runner/RUNNER_PROTOCOL.md +1 -1
  99. package/package.json +18 -14
  100. package/server.json +3 -3
  101. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.5.apk.sha256 +0 -1
  102. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.5.apk.sha256 +0 -1
  103. package/dist/src/1010.js +0 -1
  104. package/dist/src/123.js +0 -1
  105. package/dist/src/1231.js +0 -1
  106. package/dist/src/1352.js +0 -1
  107. package/dist/src/208.js +0 -1
  108. package/dist/src/221.js +0 -6
  109. package/dist/src/2403.js +0 -3
  110. package/dist/src/2415.js +0 -38
  111. package/dist/src/3675.js +0 -1
  112. package/dist/src/5611.js +0 -1
  113. package/dist/src/5827.js +0 -1
  114. package/dist/src/6088.js +0 -1
  115. package/dist/src/6133.js +0 -1
  116. package/dist/src/6629.js +0 -1
  117. package/dist/src/7556.js +0 -1
  118. package/dist/src/7719.js +0 -1
  119. package/dist/src/7847.js +0 -1
  120. package/dist/src/8133.js +0 -1
  121. package/dist/src/8656.js +0 -1
  122. package/dist/src/9010.js +0 -1
  123. package/dist/src/9471.js +0 -1
  124. package/dist/src/9542.js +0 -6
  125. package/dist/src/9616.js +0 -2
  126. package/dist/src/9639.js +0 -2
  127. package/dist/src/9671.js +0 -1
  128. package/dist/src/9818.js +0 -1
  129. package/dist/src/989.js +0 -1
  130. /package/dist/src/{2301.js → 4069.js} +0 -0
  131. /package/dist/src/{4829.js → 5560.js} +0 -0
  132. /package/dist/src/{4778.js → 6024.js} +0 -0
  133. /package/dist/src/{9152.js → 733.js} +0 -0
  134. /package/dist/src/{3267.js → 9612.js} +0 -0
@@ -0,0 +1 @@
1
+ import{AppError as e}from"./733.js";import{normalizeText as t}from"./587.js";function n(e){var t;let n=i(e.label),r=i(e.value),l=i(e.identifier),u=(t=l)&&!/^[\w.]+:id\/[\w.-]+$/i.test(t)&&!/^_?NS:\d+$/i.test(t)?l:"";return o(e.type??"")?r||n||u:n||r||u}function r(e){let t=e.replace(/\s+/g," ").trim();return t.length<=48?t:`${t.slice(0,45)}...`}function l(e,t){var r;let l=n(e),i=function(e,t){if("text-view"===t||"text-field"===t||"search"===t)return!0;let n=u(e.type??""),r=`${e.role??""} ${e.subrole??""}`.toLowerCase();return n.includes("textview")||n.includes("textarea")||n.includes("textfield")||n.includes("securetextfield")||n.includes("searchfield")||n.includes("edittext")||r.includes("text area")||r.includes("text field")}(e,t);return{text:l,isLargeSurface:i,shouldSummarize:i&&!!(r=l)&&(r.length>80||/[\r\n]/.test(r))}}function i(e){return"string"==typeof e?e.trim():""}function u(e){let t=e.trim().replace(/XCUIElementType/gi,"").replace(/^AX/,"").toLowerCase(),n=Math.max(t.lastIndexOf("."),t.lastIndexOf("/"));return -1!==n&&(t=t.slice(n+1)),t}function o(e){let t=u(e);return t.includes("textfield")||t.includes("securetextfield")||t.includes("searchfield")||t.includes("edittext")||t.includes("textview")||t.includes("textarea")}let a=new Set(["id","role","text","label","value","appname","windowtitle"]),c=new Set(["visible","hidden","editable","selected","enabled","hittable"]),s=new Set([...a,...c]),f=new Map([['"','"'],["'","'"],["\\","\\"],["/","/"],["b","\b"],["f","\f"],["n","\n"],["r","\r"],["t"," "]]);function d(t){let n=t.trim();if(!n)throw new e("INVALID_ARGS","Selector expression cannot be empty");let r=function(t){let n=[],r="",l=null;for(let i=0;i<t.length;i+=1){let u=t[i];if(('"'===u||"'"===u)&&!g(t,i)){l=w(l,u),r+=u;continue}if(!l&&"|"===u&&"|"===t[i+1]){let l=r.trim();if(!l)throw new e("INVALID_ARGS",`Invalid selector fallback expression: ${t}`);n.push(l),r="",i+=1;continue}r+=u}let i=r.trim();if(!i)throw new e("INVALID_ARGS",`Invalid selector fallback expression: ${t}`);return n.push(i),n}(n);if(0===r.length)throw new e("INVALID_ARGS","Selector expression cannot be empty");return{raw:n,selectors:r.map(t=>(function(t){let n=t.trim();if(!n)throw new e("INVALID_ARGS","Selector segment cannot be empty");let r=function(t){let n=[],r="",l=null;for(let e=0;e<t.length;e+=1){let i=t.charAt(e);if(('"'===i||"'"===i)&&!g(t,e)){l=w(l,i),r+=i;continue}if(!l&&/\s/.test(i)){r.trim()&&n.push(r.trim()),r="";continue}r+=i}if(l)throw new e("INVALID_ARGS",`Unclosed quote in selector: ${t}`);return r.trim()&&n.push(r.trim()),n}(n);if(0===r.length)throw new e("INVALID_ARGS",`Invalid selector segment: ${t}`);return{raw:n,terms:r.map(b)}})(t))}}function h(e){try{return d(e)}catch{return null}}function p(e){let t=e.trim();if(!t)return!1;if("||"===t)return!0;let n=t.indexOf("=");if(-1!==n){let e=t.slice(0,n).trim().toLowerCase();return s.has(e)}return s.has(t.toLowerCase())}function m(e,t={}){if(0===e.length)return null;let n=t.preferTrailingValue??!1,r=0,l=[];for(;r<e.length;){let t=e[r];if(void 0===t||!p(t))break;r+=1;let n=e.slice(0,r).join(" ").trim();n&&h(n)&&l.push(r)}if(0===l.length)return null;let i=l.at(-1);if(void 0===i)return null;let u=i;if(n)for(let t=l.length-1;t>=0;t-=1){let n=l[t];if(void 0!==n&&n<e.length){u=n;break}}let o=e.slice(0,u).join(" ").trim();return o?{selectorExpression:o,rest:e.slice(u)}:null}function b(t){let n=t.trim();if(!n)throw new e("INVALID_ARGS","Empty selector term");let r=n.indexOf("=");if(-1===r){let r=n.toLowerCase();if(!c.has(r))throw new e("INVALID_ARGS",`Invalid selector term "${t}", expected key=value`);return{key:r,value:!0}}let l=n.slice(0,r).trim().toLowerCase(),i=n.slice(r+1).trim();if(!s.has(l))throw new e("INVALID_ARGS",`Unknown selector key: ${l}`);if(!i)throw new e("INVALID_ARGS",`Missing selector value for key: ${l}`);if(c.has(l)){let t,n="true"===(t=x(i).toLowerCase())||"false"!==t&&null;if(null===n)throw new e("INVALID_ARGS",`Invalid boolean value for ${l}: ${i}`);return{key:l,value:n}}return{key:l,value:x(i)}}function w(e,t){return e?e===t?null:e:t}function x(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?function(e){let t="",n=0;for(;n<e.length;){var r;let l=e.charAt(n);if("\\"!==l){t+=l,n+=1;continue}let i=e.charAt(n+1);if(!i){t+=l,n+=1;continue}let u=(r=i,f.get(r)??null);if(null!==u){t+=u,n+=2;continue}if("u"===i){let r=e.slice(n+2,n+6);if(/^[0-9a-fA-F]{4}$/.test(r)){t+=String.fromCharCode(Number.parseInt(r,16)),n+=6;continue}}t+=l,n+=1}return t}(t.slice(1,-1)):t}function g(e,t){let n=0;for(let r=t-1;r>=0&&"\\"===e[r];r-=1)n+=1;return n%2==1}function v(e){let t=e[0]??"",n=m(e.slice(1),{preferTrailingValue:"text"===t});return{predicate:t,split:n}}function S(e,t){let n=t.toLowerCase();return e.find(e=>{let t=(e.label??"").toLowerCase(),r=(e.value??"").toLowerCase(),l=(e.identifier??"").toLowerCase();return t.includes(n)||r.includes(n)||l.includes(n)})??null}function I(e,t){let n=[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0);return n&&A(n)?n:function(e,t){if(!e.rect)return;let n=e.rect.y+e.rect.height/2,r=null;for(let e of t){if(!e.rect)continue;let t=[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0);if(!t||!A(t))continue;let l=Math.abs(e.rect.y+e.rect.height/2-n);(!r||l<r.distance)&&(r={label:t,distance:l})}return r?.label}(e,t)??(n&&A(n)?n:void 0)}function A(e){let t=e.trim();return!(!t||/^(true|false)$/i.test(t)||/^\d+$/.test(t))}function $(e){let t=[],n=[];for(let r of e){let e=r.depth??0;for(;t.length>0&&e<=t[t.length-1];)t.pop();let l=u(r.type??""),i=[r.label,r.value,r.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0),o=!!i&&A(i);if(("group"===l||"ioscontentgroup"===l)&&!o){t.push(e);continue}let a=Math.max(0,e-t.length);n.push({...r,depth:a})}return n}function y(e,t){let n=u(e);return!n||("android"===t?n.includes("edittext")||n.includes("autocompletetextview"):n.includes("textfield")||n.includes("securetextfield")||n.includes("searchfield")||n.includes("textview")||n.includes("textarea")||"search"===n)}function N(e,t){return t.hittable?t:R(e,t,e=>!0===e.hittable)}function L(e){return new Map(e.map(e=>[e.index,e]))}function C(e,t,n,r){let l=t,i=new Set;for(;"number"==typeof l.parentIndex&&!i.has(l.index)&&(i.add(l.index),l=n.get(l.parentIndex)??e[l.parentIndex]);){let e=r(l);if(null!==e)return e}return null}function _(e,t,n,r){return!!C(e,t,r,e=>e===n||e.index===n.index?e:null)}function R(e,t,n){let r=L(e);return C(e,t,r,e=>n(e)?e:null)}function V(e){return[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").filter(e=>e.length>0)[0]??""}function T(e){return n(e)}function D(e){return!0===e.hittable||!!e.rect&&e.rect.width>0&&e.rect.height>0}function G(e,t){return y(e.type??"",t)&&!1!==e.enabled}function k(e,t,n){return t.terms.every(t=>(function(e,t,n){switch(t.key){case"id":return M(e.identifier,String(t.value));case"role":return M(u(e.type??""),String(t.value));case"label":return M(e.label,String(t.value));case"value":return M(e.value,String(t.value));case"text":return M(V(e),String(t.value));case"appname":return M(e.appName,String(t.value));case"windowtitle":return M(e.windowTitle,String(t.value));case"visible":return D(e)===!!t.value;case"hidden":return!D(e)==!!t.value;case"editable":return G(e,n)===!!t.value;case"selected":return!0===e.selected==!!t.value;case"enabled":return!1!==e.enabled==!!t.value;case"hittable":return!0===e.hittable==!!t.value;default:return!1}})(e,t,n))}function M(e,n){return t(e??"")===t(n)}function q(e,t,n){let r=n.requireRect??!1,l=n.requireUnique??!0,i=[];for(let[u,o]of t.selectors.entries()){let t=function(e,t,n,r){let l=0,i=null,u=null,o=!1;for(let a of e){if(r&&!a.rect||!k(a,t,n))continue;if(l+=1,i??=a,!u){u=a;continue}let e=function(e,t){let n=e.depth??0,r=t.depth??0;if(n!==r)return n>r?1:-1;let l=U(e),i=U(t);return l!==i?l<i?1:-1:0}(a,u);e>0?(u=a,o=!1):0===e&&(o=!0)}return{count:l,firstNode:i,disambiguated:o?null:u}}(e,o,n.platform,r);if(i.push({selector:o.raw,matches:t.count}),0!==t.count&&t.firstNode){if(l&&1!==t.count){if(!n.disambiguateAmbiguous||!t.disambiguated)continue;return{node:t.disambiguated,selector:o,selectorIndex:u,matches:t.count,diagnostics:i}}return{node:t.firstNode,selector:o,selectorIndex:u,matches:t.count,diagnostics:i}}}return null}function F(e,t,n){let r=n.requireRect??!1,l=[];for(let[i,u]of t.selectors.entries()){let t=function(e,t,n,r){let l=0;for(let i of e)(!r||i.rect)&&k(i,t,n)&&(l+=1);return l}(e,u,n.platform,r);if(l.push({selector:u.raw,matches:t}),t>0)return{selectorIndex:i,selector:u,matches:t,diagnostics:l}}return null}function O(e,t,n){if(0===t.length)return`Selector did not match: ${e.raw}`;let r=t.map(e=>`${e.selector} -> ${e.matches}`).join(", ");return n.unique??!0?`Selector did not resolve uniquely (${r})`:`Selector did not match (${r})`}function U(e){return e.rect?e.rect.width*e.rect.height:1/0}function E(e,t,n={}){let r=[],l=u(e.type??""),i=P(e.identifier),o=P(e.label),a=P(e.value),c=P(V(e)),s="fill"===n.action;i&&r.push(`id=${K(i)}`),l&&o&&r.push(s?`role=${K(l)} label=${K(o)} editable=true`:`role=${K(l)} label=${K(o)}`),o&&r.push(s?`label=${K(o)} editable=true`:`label=${K(o)}`),a&&r.push(s?`value=${K(a)} editable=true`:`value=${K(a)}`),c&&c!==o&&c!==a&&r.push(s?`text=${K(c)} editable=true`:`text=${K(c)}`),l&&s&&!r.some(e=>e.includes("editable=true"))&&r.push(`role=${K(l)} editable=true`);let f=Array.from(new Set(r));return 0===f.length&&l&&f.push(s?`role=${K(l)} editable=true`:`role=${K(l)}`),0===f.length&&D(e)&&f.push("visible=true"),f}function K(e){return JSON.stringify(e)}function P(e){if(!e)return null;let t=e.trim();return t||null}export{E as buildSelectorChainForNode,L as buildSnapshotNodeByIndex,r as buildTextPreview,l as describeTextSurface,T as extractNodeReadText,V as extractNodeText,n as extractReadableText,R as findNearestAncestor,N as findNearestHittableAncestor,S as findNodeByLabel,F as findSelectorChainMatch,C as findSnapshotAncestor,O as formatSelectorFailure,_ as isDescendantOfSnapshotNode,y as isFillableType,G as isNodeEditable,D as isNodeVisible,p as isSelectorToken,k as matchesSelector,u as normalizeType,d as parseSelectorChain,o as prefersValueForReadableText,$ as pruneGroupNodes,I as resolveRefLabel,q as resolveSelectorChain,v as splitIsSelectorArgs,m as splitSelectorFromArgs,i as trimText,h as tryParseSelectorChain};
@@ -0,0 +1 @@
1
+ var e;import{findNodeByRef as t,centerOfRect as r,normalizeRef as n,NETWORK_INCLUDE_MODES as i}from"./4291.js";import{intersectArea as a,isScrollableNodeLike as s}from"./6024.js";import{PLATFORM_SELECTORS as o,DEVICE_TARGETS as l}from"./5910.js";import{splitSelectorFromArgs as c,findNearestHittableAncestor as u,tryParseSelectorChain as p,buildSelectorChainForNode as d,parseSelectorChain as m,findNodeByLabel as f,resolveRefLabel as h,resolveSelectorChain as g,formatSelectorFailure as y,normalizeType as b}from"./9836.js";import{AppError as v}from"./733.js";import{STRUCTURED_BATCH_COMMAND_NAMES as w,readStructuredBatchCommandName as x,INTERNAL_COMMANDS as S,GESTURE_KINDS as k,PUBLIC_COMMANDS as D}from"./2133.js";import{FIND_LOCATORS as A}from"./587.js";import{DEFAULT_APPS_FILTER as I,assertResolvedAppsFilter as M}from"./2748.js";function L(e){let t=new Map;for(let[r,n]of e.entries())t.set(n.index,r);let r=[],n=[];for(let[i,a]of e.entries()){let e=Math.max(0,a.depth??0);for(;n.length>0&&e<=n[n.length-1].depth;)n.pop();let s="number"==typeof a.parentIndex?t.get(a.parentIndex):void 0,o="number"==typeof s&&s<i?s:n[n.length-1]?.index;r.push({...a,index:i,depth:e,parentIndex:o}),n.push({depth:e,index:i})}return r}function N(e){return new Map(e.map(e=>[e.index,e]))}function R(e){return e.label?.trim()||e.value?.trim()||e.identifier?.trim()||""}function O(e){let t=e.trim().toLowerCase();return!!t&&/^(vertical|horizontal)\s+scroll\s+bar(?:,?\s*\d+\s+pages?)?$/.test(t)}function E(e,t){if(!(e?.trim().toLowerCase()??"").includes("vertical scroll bar"))return null;let r=function(e){if(!e)return null;let t=/^(\d{1,3})%$/.exec(e.trim());if(!t)return null;let r=Number(t[1]);return Number.isFinite(r)?Math.max(0,Math.min(100,r)):null}(t);return null===r?null:r<=1?{above:!1,below:!0}:r>=99?{above:!0,below:!1}:{above:!0,below:!0}}function P(e,t,r){return t>=e.x&&t<=e.x+e.width&&r>=e.y&&r<=e.y+e.height}function _(e){let t=null,r=-1;for(let n of e){let e=n.width*n.height;e>r&&(t=n,r=e)}return t}function C(e,t,r,n){return Math.max(e,r)<=Math.min(t,n)}function T(e){if(0===e.length)return{nodes:e,hiddenCount:0,summaryLines:[]};let{byIndex:t,visibleNodeIndexes:r,offscreenNodes:n,hintedContainers:i}=$(e),a=0===r.size?e:e.filter(e=>r.has(e.index));return{nodes:a.map(e=>(function(e,t){let r=t.get(e.index);if(!r||0===r.size)return e;let n=!!(!0===e.hiddenContentAbove||r.has("above"))||void 0,i=!!(!0===e.hiddenContentBelow||r.has("below"))||void 0;return{...e,hiddenContentAbove:n,hiddenContentBelow:i}})(e,i.directionsByContainer)),hiddenCount:0===r.size?0:e.length-a.length,summaryLines:function(e,t,r){let n=new Map;for(let i of e){let e=function(e,t,r){if(!e.rect)return null;let n=j(e,t,r);return n?V(e.rect,n):null}(i,t,r);if(!e)continue;let a=n.get(e)??[];a.push(i),n.set(e,a)}return["above","below"].flatMap(e=>{let t=n.get(e);if(!t||0===t.length)return[];let r=(function(e){let t=new Set,r=[];for(let n of e){let e=R(n);!e||t.has(e)||(t.add(e),r.push(e))}return r})(t).slice(0,3).map(e=>`"${e}"`),i=1===t.length?"interactive item":"interactive items",a=r.length>0?`: ${r.join(", ")}`:"";return[`[off-screen ${e}] ${t.length} ${i}${a}`]})}(n.filter(e=>!i.coveredNodeIndexes.has(e.index)&&function(e){if(!0===e.hittable)return!0;let t=(e.type??"").toLowerCase();return t.includes("button")||t.includes("link")||t.includes("textfield")||t.includes("edittext")||t.includes("searchfield")||t.includes("checkbox")||t.includes("radio")||t.includes("switch")||t.includes("menuitem")||!!R(e)}(e)),e,t)}}function F(e){if(0===e.length)return new Map;let{hintedContainers:t}=$(e);var r=t.directionsByContainer;let n=new Map;for(let[e,t]of r){let r={};t.has("above")&&(r.hiddenContentAbove=!0),t.has("below")&&(r.hiddenContentBelow=!0),(r.hiddenContentAbove||r.hiddenContentBelow)&&n.set(e,r)}return n}function $(e){let t=N(e),r=new Set,n=[];for(let i of e){if(U(i,e,t)){!function(e,t,r){let n=e,i=new Set;for(;n&&!i.has(n.index);)i.add(n.index),t.add(n.index),n="number"==typeof n.parentIndex?r.get(n.parentIndex):void 0}(i,r,t);continue}n.push(i)}let i=function(e,t,r,n){let i=new Map,a=new Map,s=new Set;for(let e of t){if(!e.rect)continue;let t=q(e,r,n);if(!t?.rect)continue;let o=V(e.rect,t.rect);if(!o)continue;let l=i.get(t.index)??new Set;l.add(o),i.set(t.index,l);let c=a.get(t.index)??new Set;c.add(o),a.set(t.index,c),s.add(e.index)}return function(e,t,r,n,i){for(let a of e){let e=function(e){let t=E(e.label,e.value);if(!t)return null;let r=new Set;return t.above&&r.add("above"),t.below&&r.add("below"),r.size>0?r:null}(a);if(!e||0===e.size)continue;let s=q(a,t,r);if(!s)continue;let o=n.get(s.index)??new Set,l=i.get(s.index);for(let t of e)(!l||!(l.size>0)||l.has(t))&&o.add(t);n.set(s.index,o)}}(e,r,n,i,a),{directionsByContainer:i,coveredNodeIndexes:s}}(e,n,r,t);return{byIndex:t,visibleNodeIndexes:r,offscreenNodes:n,hintedContainers:i}}function U(e,t,r=N(t)){var n;if(!e.rect)return!0;let i=j(e,t,r);return!i||(n=e.rect,C(n.x,n.x+n.width,i.x,i.x+i.width)&&C(n.y,n.y+n.height,i.y,i.y+i.height))}function j(e,t,n=N(t)){var i,a;let s=(i=e,a=n,G(i,a,e=>!!e.rect)?.rect??null);return s||function(e,t){let n=r(t),i=e.filter(e=>{var t;return!!(t=e.rect)&&Number.isFinite(t.x)&&Number.isFinite(t.y)&&Number.isFinite(t.width)&&Number.isFinite(t.height)}),a=i.filter(e=>{let t=(e.type??"").toLowerCase();return t.includes("application")||t.includes("window")}),s=_(a.map(e=>e.rect).filter(e=>P(e,n.x,n.y)));if(s)return s;let o=_(a.map(e=>e.rect));if(o)return o;let l=_(i.map(e=>e.rect).filter(e=>P(e,n.x,n.y)));return l||null}(t,e.rect??{x:0,y:0,width:0,height:0})}function V(e,t){return e.y+e.height<=t.y?"above":e.y>=t.y+t.height?"below":null}function q(e,t,r){return G(e,r,e=>t.has(e.index))}function G(e,t,r){let n="number"==typeof e.parentIndex?t.get(e.parentIndex):void 0,i=new Set;for(;n&&!i.has(n.index);){if(i.add(n.index),r(n)&&s(n))return n;n="number"==typeof n.parentIndex?t.get(n.parentIndex):void 0}return null}let z=["ref","selector","point"];function B(e){return{type:"string",...e?{description:e}:{}}}function H(e){return{type:"boolean",...e?{description:e}:{}}}function X(e){return{type:"object",additionalProperties:!0,...e?{description:e}:{}}}function W(e){return{...e,required:!0}}function K(e){return eD(B(e),ed)}function J(e){return eD({type:"number",...e?{description:e}:{}},ef)}function Y(e,t={}){return eD(function(e,t){return{...{type:"integer",...e?{description:e}:{}},...void 0===t.min?{}:{minimum:t.min},...void 0===t.max?{}:{maximum:t.max}}}(e,t),(e,r)=>eh(e,r,t))}function Q(e){return eD(H(e),eg)}function Z(e,t){return eD({type:"string",enum:e,...t?{description:t}:{}},(t,r)=>eb(t,r,e))}function ee(e){return eD({type:"array",items:{type:"string"},...e?{description:e}:{}},eA)}function et(e){return eD(e,(e,t)=>e[t])}function er(){return eD({oneOf:[...eI(),{type:"object",properties:{kind:{type:"string",const:"point"},x:{type:"number"},y:{type:"number"}},required:["kind","x","y"],additionalProperties:!1}],description:"UI target. This is separate from deviceTarget, which selects the device form."},(e,t)=>void 0===e[t]?void 0:function(e,t){let r=eM(e,t),n=ey(r,"kind",z);switch(n){case"ref":return{kind:n,ref:ep(r,"ref"),label:ed(r,"label")};case"selector":return{kind:n,selector:ep(r,"selector")};case"point":return{kind:n,x:em(r,"x"),y:em(r,"y")}}}(e,t))}function en(e){return eD({type:"object",description:e,properties:{x:{type:"number"},y:{type:"number"}},required:["x","y"],additionalProperties:!1},(e,t)=>void 0===e[t]?void 0:eu(e,t))}function ei(){return{depth:Y("Snapshot traversal depth.",{min:0}),scope:K("Snapshot scope selector used before resolution."),raw:Q("Use raw snapshot data during selector resolution.")}}function ea(){return{count:Y("Number of press/click repetitions.",{min:1}),intervalMs:Y("Delay between repeated press/click actions.",{min:0}),holdMs:Y("Hold duration for each action.",{min:0}),jitterPx:Y("Randomization radius in pixels.",{min:0}),doubleTap:Q("Request a double-tap action.")}}function es(e){return function(e,t=[]){return{type:"object",properties:{session:{type:"string",description:"Agent-device session name."},platform:{type:"string",enum:o,description:"Platform selector used to resolve a device."},deviceTarget:{type:"string",enum:l,description:"Device target form. Maps to the CLI --target flag."},target:{type:"string",enum:l,description:"Alias for deviceTarget on commands without a UI target field. Interaction commands reserve target for the UI element."},device:{type:"string",description:"Device name selector."},udid:{type:"string",description:"iOS device UDID selector."},serial:{type:"string",description:"Android serial selector."},iosSimulatorDeviceSet:{type:"string",description:"iOS simulator device-set path used for device resolution."},iosXctestrunFile:{type:"string",description:"Externally built iOS XCTest runner .xctestrun artifact path."},iosXctestDerivedDataPath:{type:"string",description:"Derived data path for external iOS XCTest runner execution."},iosXctestEnvDir:{type:"string",description:"Writable directory for iOS XCTest runner env overlays."},androidDeviceAllowlist:{type:"string",description:"Android serial allowlist used for device resolution."},daemonBaseUrl:{type:"string",description:"Remote daemon base URL."},daemonAuthToken:{type:"string",description:"Remote daemon auth token."},tenant:{type:"string",description:"Remote tenant identifier."},runId:{type:"string",description:"Lease run identifier."},leaseId:{type:"string",description:"Existing lease identifier."},cwd:{type:"string",description:"Working directory for command execution."},debug:{type:"boolean",description:"Enable debug diagnostics."},...e},...t.length>0?{required:t}:{},additionalProperties:!1}}(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.schema])),Object.entries(e).flatMap(([e,t])=>t.required?[e]:[]))}function eo(e,t){let r=el(e),n=Object.fromEntries(Object.entries(t).flatMap(([e,t])=>{let n=t.read(r,e);if(t.required&&void 0===n)throw Error(`Expected ${e} to be set.`);return void 0===n?[]:[[e,n]]})),i=ec(r,{readTargetAlias:!Object.hasOwn(t,"target")});return ek({...i,...ev(i),...n})}function el(e){if(null==e)return{};if(!e||"object"!=typeof e||Array.isArray(e))throw Error("Expected object arguments.");return e}function ec(e,t={}){return{session:ed(e,"session"),platform:eb(e,"platform",o),deviceTarget:function(e,t){let r=eb(e,"deviceTarget",l);if(!1===t.readTargetAlias||void 0===e.target)return r;let n=eb(e,"target",l);if(void 0!==r&&n!==r)throw Error("Expected target alias to match deviceTarget when both are set.");return r??n}(e,t),device:ed(e,"device"),udid:ed(e,"udid"),serial:ed(e,"serial"),iosSimulatorDeviceSet:ed(e,"iosSimulatorDeviceSet"),iosXctestrunFile:ed(e,"iosXctestrunFile"),iosXctestDerivedDataPath:ed(e,"iosXctestDerivedDataPath"),iosXctestEnvDir:ed(e,"iosXctestEnvDir"),androidDeviceAllowlist:ed(e,"androidDeviceAllowlist"),daemonBaseUrl:ed(e,"daemonBaseUrl"),daemonAuthToken:ed(e,"daemonAuthToken"),tenant:ed(e,"tenant"),runId:ed(e,"runId"),leaseId:ed(e,"leaseId"),cwd:ed(e,"cwd"),debug:eg(e,"debug")}}function eu(e,t){let r=eM(e,t);return{x:em(r,"x"),y:em(r,"y")}}function ep(e,t){let r=e[t];if("string"!=typeof r||0===r.length)throw Error(`Expected ${t} to be a non-empty string.`);return r}function ed(e,t){let r=e[t];if(void 0!==r){if("string"!=typeof r||0===r.length)throw Error(`Expected ${t} to be a non-empty string.`);return r}}function em(e,t){let r=e[t];if("number"!=typeof r||!Number.isFinite(r))throw Error(`Expected ${t} to be a finite number.`);return r}function ef(e,t){let r=e[t];if(void 0!==r){if("number"!=typeof r||!Number.isFinite(r))throw Error(`Expected ${t} to be a finite number.`);return r}}function eh(e,t,r={}){let n=e[t];if(void 0!==n){if(!Number.isInteger(n))throw Error(`Expected ${t} to be an integer.`);if(void 0!==r.min&&n<r.min)throw Error(`Expected ${t} to be at least ${r.min}.`);if(void 0!==r.max&&n>r.max)throw Error(`Expected ${t} to be at most ${r.max}.`);return n}}function eg(e,t){let r=e[t];if(void 0!==r){if("boolean"!=typeof r)throw Error(`Expected ${t} to be a boolean.`);return r}}function ey(e,t,r){let n=e[t];if("string"!=typeof n||!r.includes(n))throw Error(`Expected ${t} to be one of: ${r.join(", ")}.`);return n}function eb(e,t,r){let n=e[t];if(void 0!==n){if("string"!=typeof n||!r.includes(n))throw Error(`Expected ${t} to be one of: ${r.join(", ")}.`);return n}}function ev(e){return ek({session:e.session,platform:e.platform,target:e.deviceTarget,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,iosXctestrunFile:e.iosXctestrunFile,iosXctestDerivedDataPath:e.iosXctestDerivedDataPath,iosXctestEnvDir:e.iosXctestEnvDir,androidDeviceAllowlist:e.androidDeviceAllowlist,daemonBaseUrl:e.daemonBaseUrl,daemonAuthToken:e.daemonAuthToken,tenant:e.tenant,runId:e.runId,leaseId:e.leaseId,cwd:e.cwd,debug:e.debug})}function ew(e){switch(e.kind){case"ref":return{ref:e.ref,label:e.label};case"selector":return{selector:e.selector};case"point":return{x:e.x,y:e.y}}}function ex(e){return{count:e.count,intervalMs:e.intervalMs,holdMs:e.holdMs,jitterPx:e.jitterPx,doubleTap:e.doubleTap}}function eS(e){return{depth:e.depth,scope:e.scope,raw:e.raw}}function ek(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e))}function eD(e,t){return{schema:e,required:!1,read:t}}function eA(e,t){let r=e[t];if(void 0!==r){if(!Array.isArray(r)||r.some(e=>"string"!=typeof e))throw Error(`Expected ${t} to be an array of strings.`);return r}}function eI(){return[{type:"object",properties:{kind:{type:"string",const:"ref"},ref:{type:"string",description:"Snapshot element ref such as @e12."},label:{type:"string",description:"Optional human label for the ref."}},required:["kind","ref"],additionalProperties:!1},{type:"object",properties:{kind:{type:"string",const:"selector"},selector:{type:"string",description:"Agent-device selector expression."}},required:["kind","selector"],additionalProperties:!1}]}function eM(e,t){let r=e[t];if(!r||"object"!=typeof r||Array.isArray(r))throw Error(`Expected ${t} to be an object.`);return r}function eL(e,t){return r=>eN(e,t?t(r):[],r)}function eN(e,t,r){return{command:e,positionals:t,options:function(e){var t;let r="mobile"===(t=e.deviceTarget??e.target)||"tv"===t||"desktop"===t?t:void 0;if(void 0===r&&void 0===e.target)return e;let{target:n,...i}=e;return void 0===r?i:{...i,target:r}}(r)}}function eR(e){return ek({session:e.session,platform:e.platform,deviceTarget:e.target,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,iosXctestrunFile:e.iosXctestrunFile,iosXctestDerivedDataPath:e.iosXctestDerivedDataPath,iosXctestEnvDir:e.iosXctestEnvDir,androidDeviceAllowlist:e.androidDeviceAllowlist})}function eO(e){return{platform:e.platform,target:e.target,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,androidDeviceAllowlist:e.androidDeviceAllowlist}}function eE(e){return ek({depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw})}function eP(e){return{depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}}function e_(e){return ek({count:e.count,intervalMs:e.intervalMs,holdMs:e.holdMs,jitterPx:e.jitterPx,doubleTap:e.doubleTap})}function eC(e){return"ref"in e&&void 0!==e.ref?ek({kind:"ref",ref:e.ref,label:e.label}):"selector"in e&&void 0!==e.selector?{kind:"selector",selector:e.selector}:{kind:"point",x:e.x,y:e.y}}function eT(e){let t=eF(e);if("string"==typeof t.ref)return[t.ref,...eU(t.label)];if("string"==typeof t.selector)return[t.selector];if("point"===t.kind||void 0!==t.x||void 0!==t.y)return[String(e$(t.x,"x")),String(e$(t.y,"y"))];throw new v("INVALID_ARGS","interaction requires @ref, selector, or point target")}function eF(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new v("INVALID_ARGS","Expected target object.");let t=e.target;return t&&"object"==typeof t&&!Array.isArray(t)?t:e}function e$(e,t){if("number"!=typeof e||!Number.isFinite(e))throw new v("INVALID_ARGS",`point target requires numeric ${t}.`);return e}function eU(e){return"string"==typeof e&&e.length>0?[e]:[]}function ej(...e){return new Set(e)}function eV(e,t){return void 0!==e&&t.has(e)}function eq(e){return void 0!==e&&""!==e.trim()&&Number.isFinite(Number(e))}function eG(e){return void 0===e?void 0:Number(e)}function ez(e){return void 0===e?[]:[e]}function eB(e){return void 0===e?[]:[String(e)]}function eH(e,t){if(void 0===e||""===e)throw new v("INVALID_ARGS",t);return e}function eX(e,t){if("string"!=typeof e||0===e.length)throw new v("INVALID_ARGS",t);return e}function eW(e,t){return{...e,run:t,invoke:async(r,n)=>await t(r,e.readInput(n))}}let eK=["screenshotFullscreen","screenshotMaxSize","screenshotNoStabilize"];function eJ(e){return e0({overlayRefs:e?.overlayRefs,fullscreen:e?.screenshotFullscreen,maxSize:e?.screenshotMaxSize,stabilize:!e?.screenshotNoStabilize&&void 0})}function eY(e={}){return e0({overlayRefs:e.overlayRefs,screenshotFullscreen:e.screenshotFullscreen??e.fullscreen,screenshotMaxSize:e.screenshotMaxSize??e.maxSize,screenshotNoStabilize:e.screenshotNoStabilize??(!1===e.stabilize||void 0)})}function eQ(e,t){t?.screenshotFullscreen&&e.push("--fullscreen"),"number"==typeof t?.screenshotMaxSize&&e.push("--max-size",String(t.screenshotMaxSize)),t?.screenshotNoStabilize&&e.push("--no-stabilize")}function eZ(e){let{args:t,flags:r,index:n}=e,i=t[n];if("--fullscreen"===i)return r.screenshotFullscreen=!0,{handled:!0,nextIndex:n};if("--no-stabilize"===i)return r.screenshotNoStabilize=!0,{handled:!0,nextIndex:n};if("--max-size"===i){let e=t[n+1],i=void 0===e?NaN:Number(e);if(!Number.isInteger(i)||i<1)throw new v("INVALID_ARGS","screenshot --max-size requires a positive integer");return r.screenshotMaxSize=i,{handled:!0,nextIndex:n+1}}return{handled:!1}}function e0(e){return Object.fromEntries(Object.entries(e).filter(e=>void 0!==e[1]))}let e1=new Set(["healthy","recovered","sparse"]),e2=new Set(["tree","queries","private-ax"]),e3=new Set(["ax-rejected","sparse-tree","budget","no-nodes","capture-failed"]);function e5(e){if(e&&"object"==typeof e){if("string"==typeof e.state&&e1.has(e.state)&&"string"==typeof e.backend&&e2.has(e.backend))return{state:e.state,backend:e.backend,reason:"string"==typeof e.reason?e.reason:void 0,reasonCode:"string"==typeof e.reasonCode&&e3.has(e.reasonCode)?e.reasonCode:void 0,effectiveDepth:"number"==typeof e.effectiveDepth?e.effectiveDepth:void 0,collapsedLeafIndexes:Array.isArray(e.collapsedLeafIndexes)?e.collapsedLeafIndexes.filter(e=>"number"==typeof e):void 0}}}function e8(e){return e?.state==="sparse"}function e4(e,t){var r;return[...function(e){if("recovered"===e.state){let t="budget"===e.reasonCode?" The primary capture ran out of its time budget (busy app or simulator); the recovered tree is authoritative for this screen.":" This usually means the app publishes an unhealthy accessibility tree — fixing the app's accessibility is the real cure. Treat screenshot as visual truth when this warning appears.";return[`Recovered this snapshot with the ${e.backend} accessibility backend`+(e.reason?` after: ${e.reason}.`:".")+t]}return"sparse"===e.state?["No snapshot backend could read this screen"+(e.reason?` (${e.reason})`:"")+". Use screenshot as visual truth and coordinate taps; retry snapshot after navigating."]:[]}(e),...void 0===(r=e).effectiveDepth?[]:[`The accessibility server rejected deeper requests; this tree is capped at depth ${r.effectiveDepth} — re-run with --depth ${r.effectiveDepth} --scope <container> for deeper content.`],...function(e,t){let r=[];for(let n of e.collapsedLeafIndexes??[]){let e=t.find(e=>e.index===n);if(!e)continue;let i=e.identifier?` (${e.identifier})`:"";r.push(`@${e.ref} [${e.type??"element"}]${i} merges many labels into a single accessibility element. The app likely marks a container as accessible, which hides every descendant from assistive tech and automation — the children cannot be addressed individually. Fix the app's accessibility (mark the rows, not the container); until then use screenshot as visual truth and coordinate taps.`)}return r}(e,t)]}function e6(e){let t=e5(e.quality);return{...e.analysis?{analysis:e.analysis}:{},...e.androidSnapshot?{androidSnapshot:e.androidSnapshot}:{},...e.freshness?{freshness:e.freshness}:{},...t?{quality:t}:{},...e.warnings?{warnings:e.warnings}:{}}}function e9(e){return{...e.androidSnapshot?{androidSnapshot:e.androidSnapshot}:{},...e.quality?{snapshotQuality:e.quality}:{},...e.warnings&&e.warnings.length>0?{warnings:e.warnings}:{}}}function e7(e){var t;let r="object"==typeof(t=e.androidSnapshot)&&null!==t?t:void 0,n=Array.isArray(e.warnings)?e.warnings.filter(e=>"string"==typeof e):void 0,i=e5(e.snapshotQuality);return e9({...r?{androidSnapshot:r}:{},...i?{quality:i}:{},...n?{warnings:n}:{}})}function te(e){return e?{message:e}:{}}function tt(e,t){return t?{...e,message:t}:e}function tr(e){return"string"==typeof e?.message&&e.message.length>0?e.message:null}function tn(e){let t=e.appId??e.bundleId??e.packageName;return{session:e.session,appId:t,appBundleId:e.bundleId,package:e.packageName}}function ti(e,t,r){return{deviceId:t,deviceName:r,..."android"===e?{serial:t}:"ios"===e?{udid:t}:{}}}function ta(e,t={}){let r=t.includeAndroidSerial??!0;return{platform:e.platform,target:e.target,device:e.name,id:e.id,..."ios"===e.platform?{device_udid:e.ios?.udid??e.id,ios_simulator_device_set:e.ios?.simulatorSetPath??null}:{},..."android"===e.platform&&r?{serial:e.android?.serial??e.id}:{}}}function ts(e){return{name:e.name,...e.sessionStateDir?{sessionStateDir:e.sessionStateDir}:{},...e.runnerLogPath?{runnerLogPath:e.runnerLogPath}:{},...ta(e.device,{includeAndroidSerial:!1}),createdAt:e.createdAt}}function to(e){return{platform:e.platform,id:e.id,name:e.name,kind:e.kind,target:e.target,..."boolean"==typeof e.booted?{booted:e.booted}:{}}}function tl(e){return e.bundleId??e.package??e.app}function tc(e){return tt({app:e.app,appPath:e.appPath,platform:e.platform,...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.package?{package:e.package}:{}},`Installed: ${tl(e)}`)}function tu(e){return e.appName??e.bundleId??e.packageName??e.launchTarget}function tp(e){return tt({launchTarget:e.launchTarget,...e.appName?{appName:e.appName}:{},...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.packageName?{package:e.packageName}:{},...e.installablePath?{installablePath:e.installablePath}:{},...e.archivePath?{archivePath:e.archivePath}:{},...e.materializationId?{materializationId:e.materializationId}:{},...e.materializationExpiresAt?{materializationExpiresAt:e.materializationExpiresAt}:{}},`Installed: ${tu(e)}`)}function td(e){let t=e.appName??e.appBundleId??e.session;return tt({session:e.session,...e.sessionStateDir?{sessionStateDir:e.sessionStateDir}:{},...e.runnerLogPath?{runnerLogPath:e.runnerLogPath}:{},...e.requestLogPath?{requestLogPath:e.requestLogPath}:{},...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.startup?{startup:e.startup}:{},...e.runtime?{runtime:e.runtime}:{},...e.device?ta(e.device):{}},t?`Opened: ${t}`:"Opened")}function tm(e){return{session:e.session,...e.shutdown?{shutdown:e.shutdown}:{},...te(e.session?`Closed: ${e.session}`:"Closed")}}function tf(e){var t;return{nodes:e.nodes,truncated:e.truncated,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.visibility?{visibility:e.visibility}:{},...e9({...t=e,...t.snapshotQuality?{quality:t.snapshotQuality}:{}}),...e.unchanged?{unchanged:e.unchanged}:{},...e.snapshotDiagnostics?{snapshotDiagnostics:e.snapshotDiagnostics}:{}}}function th(e,t,r,n){let i=r(e[t]);if(void 0===i)throw new v("COMMAND_FAILED",n,{response:e});return i}function tg(e,t){return th(e,t,tk,`Daemon response is missing "${t}".`)}function ty(e,t){return tk(e[t])}function tb(e,t){var r;let n;return r=tk,null===(n=e[t])?null:r(n)}function tv(e,t){return th(e,t,tA,`Daemon response has invalid "${t}".`)}function tw(e,t){return function(e){return"tv"===e||"mobile"===e||"desktop"===e?e:void 0}(e[t])??"mobile"}function tx(e,t){let r=e[t];if(!tM(r))return;let n=tS(r,"x"),i=tS(r,"y"),a=tS(r,"width"),s=tS(r,"height");if(void 0!==n&&void 0!==i&&void 0!==a&&void 0!==s)return{x:n,y:i,width:a,height:s}}function tS(e,t){let r=e[t];return"number"==typeof r?r:void 0}function tk(e){return"string"==typeof e&&e.length>0?e:void 0}function tD(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function tA(e){return"ios"===e||"macos"===e||"android"===e||"linux"===e||"web"===e?e:void 0}function tI(e){return"simulator"===e||"emulator"===e||"device"===e?e:void 0}function tM(e){return"object"==typeof e&&null!==e}function tL(e){let t={};for(let[r,n]of Object.entries(e))void 0!==n&&(t[r]=n);return t}function tN(e){return e.split("\n").map(e=>e.trim()).filter(e=>e.length>0)}function tR(e,t){let r=ty(e,"bundleId"),n=ty(e,"package");return{app:tg(e,"app"),appPath:tg(e,"appPath"),platform:tv(e,"platform"),appId:r??n,bundleId:r,package:n,identifiers:tn({session:t,bundleId:r,packageName:n})}}function tO(e,t){let r=ty(e,"bundleId"),n=ty(e,"packageName"),i=r??n??ty(e,"appId"),a=ty(e,"launchTarget")??n??r??i;if(!a)throw new v("COMMAND_FAILED",'Daemon response is missing "launchTarget".',{response:e});return{appName:ty(e,"appName"),appId:i,bundleId:r,packageName:n,launchTarget:a,installablePath:ty(e,"installablePath"),archivePath:ty(e,"archivePath"),materializationId:ty(e,"materializationId"),materializationExpiresAt:ty(e,"materializationExpiresAt"),identifiers:tn({session:t,bundleId:r,packageName:n,appId:i})}}function tE(e){return{released:!0===e.released,materializationId:tg(e,"materializationId"),identifiers:{}}}function tP(e){let{record:t,platform:r,id:n,name:i,target:a}=tC(e,"name");return{platform:r,target:a,kind:th(t,"kind",tI,'Daemon response has invalid "kind".'),id:n,name:i,booted:"boolean"==typeof t.booted?t.booted:void 0,identifiers:ti(r,n,i),...tT(r,n)}}function t_(e){let{record:t,platform:r,id:n,name:i,target:a}=tC(e,"name"),s=tg(t,"device"),o={session:i,...ti(r,n,s)};return{name:i,createdAt:th(t,"createdAt",tD,'Daemon response is missing numeric "createdAt".'),sessionStateDir:ty(t,"sessionStateDir"),runnerLogPath:ty(t,"runnerLogPath"),device:{platform:r,target:a,id:n,name:s,identifiers:o,...tT(r,n,tb(t,"ios_simulator_device_set"))},identifiers:o}}function tC(e,t){let r=function(e){if(!tM(e))throw new v("COMMAND_FAILED","Daemon returned an unexpected response shape.",{value:e});return e}(e);return{record:r,platform:tv(r,"platform"),id:tg(r,"id"),name:tg(r,t),target:tw(r,"target")}}function tT(e,t,r){return{ios:"ios"===e?{udid:t,...void 0!==r?{simulatorSetPath:r}:{}}:void 0,android:"android"===e?{serial:t}:void 0}}function tF(e){if(!tM(e))return;let t=e.platform,r=ty(e,"metroHost"),n="number"==typeof e.metroPort?e.metroPort:void 0;return{platform:"ios"===t||"android"===t?t:void 0,metroHost:r,metroPort:n,bundleUrl:ty(e,"bundleUrl"),launchUrl:ty(e,"launchUrl")}}function t$(e){let t=e.platform,r=ty(e,"id"),n=ty(e,"device");if("ios"!==t&&"macos"!==t&&"android"!==t&&"linux"!==t&&"web"!==t||!r||!n)return;let i=tw(e,"target"),a=ti(t,r,n);return{platform:t,target:i,id:r,name:n,identifiers:a,ios:"ios"===t?{udid:ty(e,"device_udid")??r,simulatorSetPath:tb(e,"ios_simulator_device_set")}:void 0,android:"android"===t?{serial:ty(e,"serial")??r}:void 0}}function tU(e){if(tM(e)&&"number"==typeof e.durationMs&&"string"==typeof e.measuredAt&&"string"==typeof e.method)return{durationMs:e.durationMs,measuredAt:e.measuredAt,method:e.method,appTarget:ty(e,"appTarget"),appBundleId:ty(e,"appBundleId")}}function tj(e){return Array.isArray(e)?e:[]}function tV(e){let t=e.overlayRefs;if(!Array.isArray(t))return;let r=[];for(let e of t){if(!tM(e))continue;let t=ty(e,"ref"),n=tx(e,"rect"),i=tx(e,"overlayRect"),a=function(e,t){let r=e[t];if(!tM(r))return;let n=tS(r,"x"),i=tS(r,"y");if(void 0!==n&&void 0!==i)return{x:n,y:i}}(e,"center");t&&n&&i&&a&&r.push({ref:t,label:ty(e,"label"),rect:n,overlayRect:i,center:a})}return r}function tq(e){return tL({stateDir:e.stateDir,daemonBaseUrl:e.daemonBaseUrl,daemonAuthToken:e.daemonAuthToken,daemonTransport:e.daemonTransport,daemonServerMode:e.daemonServerMode,tenant:e.tenant,sessionIsolation:e.sessionIsolation,runId:e.runId,leaseId:e.leaseId,leaseBackend:e.leaseBackend,platform:e.platform,target:e.target,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,iosXctestrunFile:e.iosXctestrunFile,iosXctestDerivedDataPath:e.iosXctestDerivedDataPath,iosXctestEnvDir:e.iosXctestEnvDir,androidDeviceAllowlist:e.androidDeviceAllowlist,surface:e.surface,activity:e.activity,launchConsole:e.launchConsole,launchArgs:e.launchArgs,relaunch:e.relaunch,shutdown:e.shutdown,saveScript:e.saveScript,deviceHub:e.deviceHub,noRecord:e.noRecord,backMode:e.backMode,metroHost:e.metroHost,metroPort:e.metroPort,bundleUrl:e.bundleUrl,launchUrl:e.launchUrl,snapshotInteractiveOnly:e.interactiveOnly,snapshotDepth:e.depth,snapshotScope:e.scope,snapshotRaw:e.raw,snapshotForceFull:e.forceFull,...eY(e),appsFilter:e.appsFilter,kind:e.kind,out:e.out,count:e.count,fps:e.fps,screenshotMaxSize:e.maxSize,quality:e.quality,hideTouches:e.hideTouches,intervalMs:e.intervalMs,delayMs:e.delayMs,holdMs:e.holdMs,jitterPx:e.jitterPx,pixels:e.pixels,doubleTap:e.doubleTap,clickButton:e.clickButton,pauseMs:e.pauseMs,pattern:e.pattern,headless:e.headless,restart:e.restart,replayUpdate:e.replayUpdate,replayBackend:e.replayBackend,replayEnv:e.replayEnv,replayShellEnv:e.replayShellEnv,failFast:e.failFast,timeoutMs:e.timeoutMs,retries:e.retries,recordVideo:e.recordVideo,artifactsDir:e.artifactsDir,reportJunit:e.reportJunit,shardAll:e.shardAll,shardSplit:e.shardSplit,findFirst:e.findFirst,findLast:e.findLast,networkInclude:e.networkInclude,batchOnError:e.batchOnError,batchMaxSteps:e.batchMaxSteps,batchSteps:e.batchSteps,verbose:e.debug})}function tG(e){return tL({requestId:e.requestId,cwd:e.cwd,sessionExplicit:void 0!==e.session,debug:e.debug,lockPolicy:e.lockPolicy,lockPlatform:e.lockPlatform,tenantId:e.tenant,runId:e.runId,leaseId:e.leaseId,leaseBackend:e.leaseBackend,leaseTtlMs:e.leaseTtlMs,sessionIsolation:e.sessionIsolation,installSource:e.installSource,retainMaterializedPaths:e.retainMaterializedPaths,materializedPathRetentionMs:e.materializedPathRetentionMs,materializationId:e.materializationId})}function tz(e){return e??"default"}function tB(e){return t=>eN(D.batch,[],{...t,batchSteps:function(e,t){if(!Array.isArray(e)||0===e.length)throw new v("INVALID_ARGS","batch requires a non-empty steps array.");return e.map((e,r)=>{var n,i,a,s,o;let l,c,u,p,d,m;return n=e,i=r+1,a=t,u=(s=c=function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw new v("INVALID_ARGS",`Invalid batch step ${t}.`);return e}(n,i),o=i,x(s.command,o)),p=function(e,t){let r=e.input;if(!r||"object"!=typeof r||Array.isArray(r))throw new v("INVALID_ARGS",`Batch step ${t} input must be an object.`);return r}(c,i),d=function(e,t){let r=e.runtime;if(void 0!==r&&(!r||"object"!=typeof r||Array.isArray(r)))throw new v("INVALID_ARGS",`Batch step ${t} runtime must be an object.`);return r}(c,i),{...m={command:(l=a(u,p)).command,positionals:l.positionals,flags:tq(l.options),runtime:l.options.runtime},runtime:d??m.runtime}})}(t.steps,e),batchOnError:t.onError,batchMaxSteps:t.maxSteps})}let tH=function(e=w){var t;let r={steps:W(eD({type:"array",description:"Structured batch steps. Each step uses a command name and the same input object as that command tool.",items:{type:"object",properties:{command:{type:"string",enum:t=e,description:"Command name to run with structured input."},input:{type:"object",additionalProperties:!0,description:"Structured command input for the nested command. Use the matching MCP tool schema for this object."},runtime:{type:"object",additionalProperties:!0,description:"Optional per-step runtime payload."}},required:["command","input"],additionalProperties:!1}},(e,r)=>(function(e,t){if(!Array.isArray(e))throw Error("Expected steps to be an array.");return e.map((e,r)=>{var n,i,a;let s;return n=e,i=r+1,a=t,!function(e,t,r){let n=new Set(t),i=Object.keys(e).filter(e=>!n.has(e));if(i.length>0)throw Error(`${r} has unknown field(s): ${i.join(", ")}.`)}(s=function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`Invalid batch step ${t}.`);return e}(n,i),["command","input","runtime"],`Batch step ${i}`),{command:function(e,t,r){if(r===w)return x(e.command,t);let n=e.command;if("string"!=typeof n||!r.includes(n))throw Error(`Expected command to be one of: ${r.join(", ")}.`);return n}(s,i,a),input:function(e,t){let r=e.input;if(!r||"object"!=typeof r||Array.isArray(r))throw Error(`Batch step ${t} input must be an object.`);return r}(s,i),...function(e,t){let r=e.runtime;if(void 0!==r&&(!r||"object"!=typeof r||Array.isArray(r)))throw Error(`Batch step ${t} runtime must be an object.`);return void 0===r?{}:{runtime:r}}(s,i)}})})(e[r],t))),onError:Z(["stop"],"Batch failure policy."),maxSteps:Y("Maximum number of steps accepted for this batch.",{min:1,max:1e3}),out:K("Optional output path for command artifacts.")};return{name:"batch",description:"Run multiple structured command steps in one daemon request.",inputSchema:es(r),readInput:e=>(function(e,t){let r=eo(e,t),n=r.maxSteps??100;if(!Number.isInteger(n)||n<1||n>1e3)throw Error(`Invalid batch maxSteps: ${String(r.maxSteps)}`);if(r.steps.length>n)throw Error(`batch has ${r.steps.length} steps; max allowed is ${n}.`);return{...r}})(e,r)}}(),tX=eW(tH,(e,t)=>{var r;return e.batch.run({...ev(r=t),steps:r.steps,onError:r.onError,maxSteps:r.maxSteps,out:r.out})}),tW={batch:{usageOverride:"batch [--steps <json> | --steps-file <path>]",listUsageOverride:"batch --steps <json> | --steps-file <path>",helpDescription:"Execute multiple commands in one daemon request",summary:"Run multiple commands",allowedFlags:["steps","stepsFile","batchOnError","batchMaxSteps","out"]}},tK={batch:(e,t)=>({...eR(t),steps:t.batchSteps??[],onError:t.batchOnError,maxSteps:t.batchMaxSteps,out:t.out})};function tJ(e){if(!e)return null;let t=Number(e);return Number.isFinite(t)?t:null}function tY(e){let t=e[0];if(void 0===t)return null;let r=tJ(t);if(null!==r)return{kind:"sleep",durationMs:r};let n=tJ(e[e.length-1]);if("text"===t)return{kind:"text",text:(null!==n?e.slice(1,-1).join(" "):e.slice(1).join(" ")).trim(),timeoutMs:n};if(t.startsWith("@"))return{kind:"ref",rawRef:t,timeoutMs:n};let i=c(null!==n?e.slice(0,-1):e.slice());return i&&0===i.rest.length&&p(i.selectorExpression)?{kind:"selector",selectorExpression:i.selectorExpression,timeoutMs:n}:{kind:"text",text:(null!==n?e.slice(0,-1).join(" "):e.join(" ")).trim(),timeoutMs:n}}function tQ(e,t){return e.includes(t)}function tZ(e,t,r={}){let n=void 0===t?void 0:r.normalize?.(t)??t;if(void 0!==n&&tQ(e,n))return n;throw new v("INVALID_ARGS",("function"==typeof r.message?r.message(t):r.message)??`Invalid value: ${t}. Use ${e.join("|")}.`)}function t0(e,t={}){return{values:e,is:t=>tQ(e,t),parse:r=>tZ(e,r,t)}}let t1=["app","frontmost-app","desktop","menubar"],t2=t0(t1,{normalize:e=>e.trim().toLowerCase(),message:e=>`Invalid surface: ${e}. Use ${t1.join("|")}.`});function t3(e){return t2.parse(e)}let t5=["metrics","frames","memory","cpu","trace"],t8=["sample","snapshot","start","stop","report"],t4=["profile"],t6=["xctrace","simpleperf","perfetto","android-hprof","memgraph"],t9=t0(t5),t7=t0(t8),re=t0(t4),rt=t0(t6),rr=t0(["android-hprof","memgraph"]),rn="perf area must be metrics, frames, memory, cpu, or trace",ri="perf action must be sample, snapshot, start, stop, or report",ra="perf cpu requires profile",rs="perf --kind must be xctrace, simpleperf, perfetto, android-hprof, or memgraph",ro="perf memory snapshot --kind must be android-hprof or memgraph",rl=t9.is,rc=t7.is,ru=re.is,rp=rt.is,rd=rr.is,rm="https://github.com/callstack/agent-device/issues/558",rf="https://github.com/callstack/agent-device/issues/new";function rh(...e){return e}let rg=rh("snapshotInteractiveOnly","snapshotDepth","snapshotScope","snapshotRaw"),ry=rh("snapshotDepth","snapshotScope","snapshotRaw"),rb=rh("metroProjectRoot","kind","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"),rv=rh("metroHost","metroPort","bundleUrl"),rw=rh("count","intervalMs","holdMs","jitterPx","doubleTap"),rx=rh("replayUpdate","replayEnv"),rS=[{key:"config",names:["--config"],type:"string",usageLabel:"--config <path>",usageDescription:"Load CLI defaults from a specific config file"},{key:"remoteConfig",names:["--remote-config"],type:"string",usageLabel:"--remote-config <path>",usageDescription:"Load remote host + Metro workflow settings from a specific profile file"},{key:"stateDir",names:["--state-dir"],type:"string",usageLabel:"--state-dir <path>",usageDescription:"Daemon state directory (defaults to ~/.agent-device for packages, or a worktree-scoped dev dir from source)"},{key:"daemonBaseUrl",names:["--daemon-base-url"],type:"string",usageLabel:"--daemon-base-url <url>",usageDescription:"Explicit remote HTTP daemon base URL (skip local daemon discovery/startup)"},{key:"daemonAuthToken",names:["--daemon-auth-token"],type:"string",usageLabel:"--daemon-auth-token <token>",usageDescription:"Remote HTTP daemon auth token (sent as request token and bearer header)"},{key:"daemonTransport",names:["--daemon-transport"],type:"enum",enumValues:["auto","socket","http"],usageLabel:"--daemon-transport auto|socket|http",usageDescription:"Daemon client transport preference"},{key:"daemonServerMode",names:["--daemon-server-mode"],type:"enum",enumValues:["socket","http","dual"],usageLabel:"--daemon-server-mode socket|http|dual",usageDescription:"Daemon server mode used when spawning daemon"},{key:"tenant",names:["--tenant"],type:"string",usageLabel:"--tenant <id>",usageDescription:"Tenant scope identifier for isolated daemon sessions"},{key:"sessionIsolation",names:["--session-isolation"],type:"enum",enumValues:["none","tenant"],usageLabel:"--session-isolation none|tenant",usageDescription:"Session isolation strategy (tenant prefixes session namespace)"},{key:"runId",names:["--run-id"],type:"string",usageLabel:"--run-id <id>",usageDescription:"Run identifier used for tenant lease admission checks"},{key:"leaseId",names:["--lease-id"],type:"string",usageLabel:"--lease-id <id>",usageDescription:"Lease identifier bound to tenant/run admission scope"},{key:"leaseBackend",names:["--lease-backend"],type:"enum",enumValues:["ios-simulator","ios-instance","android-instance"],usageLabel:"--lease-backend ios-simulator|ios-instance|android-instance",usageDescription:"Lease backend for remote tenant connection admission"},{key:"force",names:["--force"],type:"boolean",usageLabel:"--force",usageDescription:"Force connection state replacement when reconnecting"},{key:"noLogin",names:["--no-login"],type:"boolean",usageLabel:"--no-login",usageDescription:"Connect: fail instead of starting implicit cloud login"},{key:"sessionLock",names:["--session-lock"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock reject|strip",usageDescription:"Lock bound-session device routing for this CLI invocation and nested batch steps"},{key:"sessionLocked",names:["--session-locked"],type:"boolean",usageLabel:"--session-locked",usageDescription:"Deprecated alias for --session-lock reject"},{key:"sessionLockConflicts",names:["--session-lock-conflicts"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock-conflicts reject|strip",usageDescription:"Deprecated alias for --session-lock"},{key:"platform",names:["--platform"],type:"enum",enumValues:["ios","macos","android","linux","web","apple"],usageLabel:"--platform ios|macos|android|linux|web|apple",usageDescription:"Platform to target (`apple` aliases the Apple automation backend)"},{key:"target",names:["--target"],type:"enum",enumValues:["mobile","tv","desktop"],usageLabel:"--target mobile|tv|desktop",usageDescription:"Device target class to match"},{key:"device",names:["--device"],type:"string",usageLabel:"--device <name>",usageDescription:"Device name to target"},{key:"udid",names:["--udid"],type:"string",usageLabel:"--udid <udid>",usageDescription:"iOS device UDID"},{key:"serial",names:["--serial"],type:"string",usageLabel:"--serial <serial>",usageDescription:"Android device serial"},{key:"surface",names:["--surface"],type:"enum",enumValues:t1,usageLabel:"--surface app|frontmost-app|desktop|menubar",usageDescription:"macOS session surface for open (defaults to app)"},{key:"headless",names:["--headless"],type:"boolean",usageLabel:"--headless",usageDescription:"Boot: launch Android emulator without a GUI window"},{key:"metroHost",names:["--metro-host"],type:"string",usageLabel:"--metro-host <host>",usageDescription:"Session-scoped Metro/debug host hint"},{key:"metroPort",names:["--metro-port"],type:"int",min:1,max:65535,usageLabel:"--metro-port <port>",usageDescription:"Session-scoped Metro/debug port hint"},{key:"metroProjectRoot",names:["--project-root"],type:"string",usageLabel:"--project-root <path>",usageDescription:"metro prepare: React Native project root (default: cwd)"},{key:"kind",names:["--kind"],type:"enum",enumValues:["auto","react-native","expo",...t6],usageLabel:"--kind <kind>",usageDescription:"Kind selector for commands that support it, such as metro prepare or perf artifact collectors"},{key:"perfTemplate",names:["--template"],type:"string",usageLabel:"--template <name>",usageDescription:"Perf xctrace template name, for example Time Profiler"},{key:"metroKind",names:["--metro-kind"],type:"enum",enumValues:["auto","react-native","expo"],usageLabel:"--metro-kind auto|react-native|expo",usageDescription:"metro prepare: detect or force the Metro launcher kind"},{key:"metroPublicBaseUrl",names:["--public-base-url"],type:"string",usageLabel:"--public-base-url <url>",usageDescription:"metro prepare: public base URL used for direct bundle hints"},{key:"metroProxyBaseUrl",names:["--proxy-base-url"],type:"string",usageLabel:"--proxy-base-url <url>",usageDescription:"metro prepare: optional bridge origin for remote Metro access"},{key:"metroBearerToken",names:["--bearer-token"],type:"string",usageLabel:"--bearer-token <token>",usageDescription:"metro prepare: host bridge bearer token (or AGENT_DEVICE_METRO_BEARER_TOKEN; falls back to AGENT_DEVICE_DAEMON_AUTH_TOKEN)"},{key:"metroPreparePort",names:["--port"],type:"int",min:1,max:65535,usageLabel:"--port <port>",usageDescription:"metro prepare: local Metro port (default: 8081)"},{key:"metroListenHost",names:["--listen-host"],type:"string",usageLabel:"--listen-host <host>",usageDescription:"metro prepare: host Metro listens on (default: 0.0.0.0)"},{key:"metroStatusHost",names:["--status-host"],type:"string",usageLabel:"--status-host <host>",usageDescription:"metro prepare: host used for local /status polling (default: 127.0.0.1)"},{key:"metroStartupTimeoutMs",names:["--startup-timeout-ms"],type:"int",min:1,usageLabel:"--startup-timeout-ms <ms>",usageDescription:"metro prepare: timeout while waiting for Metro to become ready"},{key:"metroProbeTimeoutMs",names:["--probe-timeout-ms"],type:"int",min:1,usageLabel:"--probe-timeout-ms <ms>",usageDescription:"metro prepare: timeout for /status and proxy bridge calls"},{key:"metroRuntimeFile",names:["--runtime-file"],type:"string",usageLabel:"--runtime-file <path>",usageDescription:"metro prepare: optional file path to persist the JSON result"},{key:"metroNoReuseExisting",names:["--no-reuse-existing"],type:"boolean",usageLabel:"--no-reuse-existing",usageDescription:"metro prepare: always start a fresh Metro process"},{key:"metroNoInstallDeps",names:["--no-install-deps"],type:"boolean",usageLabel:"--no-install-deps",usageDescription:"metro prepare: skip package-manager install when node_modules is missing"},{key:"bundleUrl",names:["--bundle-url"],type:"string",usageLabel:"--bundle-url <url>",usageDescription:"Session-scoped bundle URL hint"},{key:"launchUrl",names:["--launch-url"],type:"string",usageLabel:"--launch-url <url>",usageDescription:"Session-scoped deep link / launch URL hint"},{key:"iosSimulatorDeviceSet",names:["--ios-simulator-device-set"],type:"string",usageLabel:"--ios-simulator-device-set <path>",usageDescription:"Scope iOS simulator discovery/commands to this simulator device set"},{key:"iosXctestrunFile",names:["--ios-xctestrun-file"],type:"string",usageLabel:"--ios-xctestrun-file <path>",usageDescription:"Use an externally built iOS XCTest runner .xctestrun artifact"},{key:"iosXctestDerivedDataPath",names:["--ios-xctest-derived-data-path"],type:"string",usageLabel:"--ios-xctest-derived-data-path <path>",usageDescription:"Derived data path for external iOS XCTest runner execution"},{key:"iosXctestEnvDir",names:["--ios-xctest-env-dir"],type:"string",usageLabel:"--ios-xctest-env-dir <path>",usageDescription:"Writable directory for per-session iOS XCTest runner env overlays"},{key:"deviceHub",names:["--device-hub"],type:"boolean",usageLabel:"--device-hub",usageDescription:"open: use Xcode Device Hub when surfacing Apple simulators"},{key:"androidDeviceAllowlist",names:["--android-device-allowlist"],type:"string",usageLabel:"--android-device-allowlist <serials>",usageDescription:"Comma/space separated Android serial allowlist for discovery/selection"},{key:"activity",names:["--activity"],type:"string",usageLabel:"--activity <component>",usageDescription:"Android app launch activity (package/Activity); not for URL opens"},{key:"launchConsole",names:["--launch-console"],type:"string",usageLabel:"--launch-console <path>",usageDescription:"open: capture the initial iOS simulator launch console window to a file"},{key:"launchArgs",names:["--launch-args"],type:"string",multiple:!0,usageLabel:"--launch-args <arg>",usageDescription:"open: repeatable launch argument forwarded verbatim to the platform launch command (iOS app process args; Android adb shell am start args). Linux and macOS reject the flag."},{key:"header",names:["--header"],type:"string",multiple:!0,usageLabel:"--header <name:value>",usageDescription:"install-from-source: repeatable HTTP header for URL downloads"},{key:"githubActionsArtifact",names:["--github-actions-artifact"],type:"string",usageLabel:"--github-actions-artifact <owner/repo:artifact>",usageDescription:"install-from-source: GitHub Actions artifact resolved by a remote daemon"},{key:"installSource",names:[],type:"string"},{key:"session",names:["--session"],type:"string",usageLabel:"--session <name>",usageDescription:"Named session"},{key:"count",names:["--count"],type:"int",min:1,max:200,usageLabel:"--count <n>",usageDescription:"Repeat count for press/swipe series"},{key:"fps",names:["--fps"],type:"int",min:1,max:120,usageLabel:"--fps <n>",usageDescription:"Record: target frames per second (iOS physical device runner)"},{key:"quality",names:["--quality"],type:"string",usageLabel:"--quality <medium|high>",usageDescription:"Record: output quality preset; Android maps this to screenrecord bitrate, Apple targets use it for export/encoding. Legacy numeric values 5-7 map to medium; 8-10 map to high"},{key:"hideTouches",names:["--hide-touches"],type:"boolean",usageLabel:"--hide-touches",usageDescription:"Record: skip touch-overlay post-processing for faster raw benchmark videos"},{key:"intervalMs",names:["--interval-ms"],type:"int",min:0,max:1e4,usageLabel:"--interval-ms <ms>",usageDescription:"Delay between press iterations"},{key:"delayMs",names:["--delay-ms"],type:"int",min:0,max:1e4,usageLabel:"--delay-ms <ms>",usageDescription:"Delay between typed characters"},{key:"holdMs",names:["--hold-ms"],type:"int",min:0,max:1e4,usageLabel:"--hold-ms <ms>",usageDescription:"Press hold duration for each iteration"},{key:"jitterPx",names:["--jitter-px"],type:"int",min:0,max:100,usageLabel:"--jitter-px <n>",usageDescription:"Deterministic coordinate jitter radius for press"},{key:"pixels",names:["--pixels"],type:"int",min:1,max:1e5,usageLabel:"--pixels <n>",usageDescription:"Scroll: explicit gesture distance in pixels"},{key:"doubleTap",names:["--double-tap"],type:"boolean",usageLabel:"--double-tap",usageDescription:"Use double-tap gesture per press iteration"},{key:"clickButton",names:["--button"],type:"enum",enumValues:["primary","secondary","middle"],usageLabel:"--button primary|secondary|middle",usageDescription:"Click: choose mouse button (middle reserved for future macOS support)"},{key:"backMode",names:["--in-app"],type:"enum",enumValues:["in-app","system"],setValue:"in-app",usageLabel:"--in-app",usageDescription:"Back: use app-provided back UI when available"},{key:"backMode",names:["--system"],type:"enum",enumValues:["in-app","system"],setValue:"system",usageLabel:"--system",usageDescription:"Back: use system back input or gesture when available"},{key:"pauseMs",names:["--pause-ms"],type:"int",min:0,max:1e4,usageLabel:"--pause-ms <ms>",usageDescription:"Delay between swipe iterations"},{key:"pattern",names:["--pattern"],type:"enum",enumValues:["one-way","ping-pong"],usageLabel:"--pattern one-way|ping-pong",usageDescription:"Swipe repeat pattern"},{key:"verbose",names:["--debug","--verbose","-v"],type:"boolean",usageLabel:"--debug, --verbose, -v",usageDescription:"Enable debug diagnostics; test --verbose prints per-test step timings without debug logs"},{key:"json",names:["--json"],type:"boolean",usageLabel:"--json",usageDescription:"JSON output"},{key:"help",names:["--help","-h"],type:"boolean",usageLabel:"--help, -h",usageDescription:"Print help and exit"},{key:"version",names:["--version","-V"],type:"boolean",usageLabel:"--version, -V",usageDescription:"Print version and exit"},{key:"snapshotDiff",names:["--diff"],type:"boolean",usageLabel:"--diff",usageDescription:"Snapshot: show structural diff against the previous session baseline"},{key:"saveScript",names:["--save-script"],type:"booleanOrString",usageLabel:"--save-script [path]",usageDescription:"Save session script (.ad) on close; optional custom output path"},{key:"networkInclude",names:["--include"],type:"enum",enumValues:["summary","headers","body","all"],usageLabel:"--include summary|headers|body|all",usageDescription:"Network: include headers, bodies, or both in output"},{key:"shutdown",names:["--shutdown"],type:"boolean",usageLabel:"--shutdown",usageDescription:"close: shutdown associated simulator/emulator after ending session"},{key:"relaunch",names:["--relaunch"],type:"boolean",usageLabel:"--relaunch",usageDescription:"open: terminate app process before launching it"},{key:"restart",names:["--restart"],type:"boolean",usageLabel:"--restart",usageDescription:"logs clear: stop active stream, clear logs, then start streaming again"},{key:"retainPaths",names:["--retain-paths"],type:"boolean",usageLabel:"--retain-paths",usageDescription:"install-from-source: keep materialized artifact paths after install"},{key:"retentionMs",names:["--retention-ms"],type:"int",min:1,usageLabel:"--retention-ms <ms>",usageDescription:"install-from-source: retention TTL for materialized artifact paths"},{key:"noRecord",names:["--no-record"],type:"boolean",usageLabel:"--no-record",usageDescription:"Do not record this action"},{key:"replayUpdate",names:["--update","-u"],type:"boolean",usageLabel:"--update, -u",usageDescription:"Replay: update selectors and rewrite replay file in place"},{key:"replayMaestro",names:["--maestro"],type:"boolean",usageLabel:"--maestro",usageDescription:`Replay: treat input as a Maestro YAML compatibility flow. Supported subset: ${(e=["app launch with Apple-platform launch arguments and Android/iOS simulator clearState","runFlow file/inline with when.platform, when.visible, when.notVisible, and limited when.true boolean/platform expressions","onFlowStart and onFlowComplete hooks","deterministic repeat.times","tapOn including optional, index, childOf, label, and absolute/percentage point taps","doubleTapOn and longPressOn","inputText, focused-field eraseText, and pasteText","openLink","visibility assertions and extendedWaitUntil","scroll and scrollUntilVisible","absolute/percentage swipe and swipe.label","screenshots","keyboard dismiss","basic pressKey, back, animation waits, and stopApp","ordered trusted runScript file/env scripts with http.post, json, and output variables"]).length>1?`${e.slice(0,-1).join(", ")}, and ${e.at(-1)}`:e[0]??""}. Unsupported syntax fails loudly with a link to ${rm}`},{key:"replayExportFormat",names:["--format"],type:"enum",enumValues:["maestro"],usageLabel:"--format maestro",usageDescription:"Replay export: output format"},{key:"replayEnv",names:["-e","--env"],type:"string",multiple:!0,usageLabel:"-e KEY=VALUE, --env KEY=VALUE",usageDescription:"Replay/Test: inject or override a ${KEY} variable for the script (repeatable)"},{key:"failFast",names:["--fail-fast"],type:"boolean",usageLabel:"--fail-fast",usageDescription:"Test: stop the suite after the first failing script; with sharding, each shard stops independently"},{key:"timeoutMs",names:["--timeout"],type:"int",min:1,usageLabel:"--timeout <ms>",usageDescription:"Prepare/Replay/Snapshot/Test: maximum wall-clock time for the command or attempt"},{key:"retries",names:["--retries"],type:"int",min:0,max:3,usageLabel:"--retries <n>",usageDescription:"Test: retry each failed script up to n additional times"},{key:"recordVideo",names:["--record-video"],type:"boolean",usageLabel:"--record-video",usageDescription:"Test: record each replay attempt to recording.mp4 in its attempt artifacts"},{key:"artifactsDir",names:["--artifacts-dir"],type:"string",usageLabel:"--artifacts-dir <path>",usageDescription:"Test: root directory for suite artifacts"},{key:"reportJunit",names:["--report-junit"],type:"string",usageLabel:"--report-junit <path>",usageDescription:"Test: write a JUnit XML report for the replay suite"},{key:"shardAll",names:["--shard-all"],type:"int",min:1,usageLabel:"--shard-all <n>",usageDescription:"Test: run the full suite on each of n devices; combine with --device id1,id2 for explicit connected devices; AD_SHARD_INDEX is zero-based"},{key:"shardSplit",names:["--shard-split"],type:"int",min:1,usageLabel:"--shard-split <n>",usageDescription:"Test: split runnable suite entries across n devices; AD_SHARD_INDEX is zero-based"},{key:"steps",names:["--steps"],type:"string",usageLabel:"--steps <json>",usageDescription:"Batch: JSON array of steps"},{key:"stepsFile",names:["--steps-file"],type:"string",usageLabel:"--steps-file <path>",usageDescription:"Batch: read steps JSON from file"},{key:"batchOnError",names:["--on-error"],type:"enum",enumValues:["stop"],usageLabel:"--on-error stop",usageDescription:"Batch: stop when a step fails"},{key:"batchMaxSteps",names:["--max-steps"],type:"int",min:1,max:1e3,usageLabel:"--max-steps <n>",usageDescription:"Batch: maximum number of allowed steps"},{key:"appsFilter",names:["--all"],type:"enum",enumValues:["user-installed","all"],setValue:"all",usageLabel:"--all",usageDescription:"Apps: include system/OEM apps"},{key:"snapshotInteractiveOnly",names:["-i"],type:"boolean",usageLabel:"-i",usageDescription:"Snapshot: interactive elements only"},{key:"snapshotDepth",names:["--depth","-d"],type:"int",min:0,usageLabel:"--depth, -d <depth>",usageDescription:"Snapshot: limit snapshot depth"},{key:"snapshotScope",names:["--scope","-s"],type:"string",usageLabel:"--scope, -s <scope>",usageDescription:"Snapshot: scope snapshot to label/identifier"},{key:"snapshotRaw",names:["--raw"],type:"boolean",usageLabel:"--raw",usageDescription:"Snapshot: raw node output"},{key:"snapshotForceFull",names:["--force-full"],type:"boolean",usageLabel:"--force-full",usageDescription:"Snapshot: re-emit the full tree even when unchanged"},{key:"findFirst",names:["--first"],type:"boolean",usageLabel:"--first",usageDescription:"Find: pick the first match when ambiguous"},{key:"findLast",names:["--last"],type:"boolean",usageLabel:"--last",usageDescription:"Find: pick the last match when ambiguous"},{key:"out",names:["--out"],type:"string",usageLabel:"--out <path>",usageDescription:"Output path"},{key:"artifact",names:["--artifact"],type:"string",usageLabel:"--artifact <path>",usageDescription:"Debug symbols: Apple crash artifact path (.ips, .crash, or .log)"},{key:"dsym",names:["--dsym"],type:"string",usageLabel:"--dsym <path>",usageDescription:"Debug symbols: matching .dSYM bundle path"},{key:"searchPath",names:["--search-path"],type:"string",usageLabel:"--search-path <dir>",usageDescription:"Debug symbols: directory to scan for matching .dSYM bundles"},{key:"overlayRefs",names:["--overlay-refs"],type:"boolean",usageLabel:"--overlay-refs",usageDescription:"Screenshot: draw current snapshot refs and target rectangles onto the saved PNG; diff screenshot: also write a separate current-screen overlay guide"},{key:"screenshotFullscreen",names:["--fullscreen"],type:"boolean",usageLabel:"--fullscreen",usageDescription:"Screenshot: capture the full screen instead of the app window"},{key:"screenshotMaxSize",names:["--max-size"],type:"int",min:1,usageLabel:"--max-size <px>",usageDescription:"Screenshot/record: downscale so the longest edge is at most <px>"},{key:"screenshotNoStabilize",names:["--no-stabilize"],type:"boolean",usageLabel:"--no-stabilize",usageDescription:"Screenshot: skip Android demo-mode/status-bar stabilization and settle delay for low-latency capture loops"},{key:"baseline",names:["--baseline","-b"],type:"string",usageLabel:"--baseline, -b <path>",usageDescription:"Diff screenshot: path to baseline image file"},{key:"threshold",names:["--threshold"],type:"string",usageLabel:"--threshold <0-1>",usageDescription:"Diff screenshot: color distance threshold (default 0.1)"}],rk=rh("remoteConfig","stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","leaseBackend","sessionLock","sessionLocked","sessionLockConflicts","platform","target","device","udid","serial","iosSimulatorDeviceSet","iosXctestrunFile","iosXctestDerivedDataPath","iosXctestEnvDir","androidDeviceAllowlist","session","noRecord"),rD=new Set(["json","config","help","version","verbose"]),rA=new Map;for(let e of rS)for(let t of e.names)rA.set(t,e);function rI(e){return rA.get(e)}function rM(){return rS}function rL(e,t,r){return{name:e,description:t,inputSchema:es(r),readInput:e=>eo(e,r)}}let rN=["duration","text","ref","selector"],rR="<wifi|airplane|location> <on|off>",rO="location set <lat> <lon>",rE="animations <on|off>",rP="appearance <light|dark|toggle>",r_="faceid <match|nonmatch|enroll|unenroll>",rC="touchid <match|nonmatch|enroll|unenroll>",rT="fingerprint <match|nonmatch>",rF="clear-app-state [app-id]",r$="permission <grant|deny|reset> <camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri> [full|limited]",rU="permission <grant|reset> <accessibility|screen-recording|input-monitoring>",rj=`macOS supports only settings ${rP} and settings ${rU}. wifi|airplane|location|animations remain unsupported on macOS.`,rV=`settings ${rR} | settings ${rO} | settings ${rE} | settings ${rP} | settings ${r_} | settings ${rC} | settings ${rT} | settings ${rF} | settings ${r$} | settings ${rU}`,rq=`settings requires ${rR}, ${rO}, ${rE}, ${rP}, ${r_}, ${rC}, ${rT}, ${rF}, ${r$}, or ${rU}`;function rG(e){let t=e.trim().toLowerCase();return"appearance"===t||"permission"===t}function rz(e){return`Unsupported macOS setting: ${e}. ${rj}`}function rB(e,t){if(void 0===e||""===e.trim())throw new v("INVALID_ARGS",`settings location set requires ${t}`);return rX(Number(e),t)}function rH(e){return{latitude:rX(e?.latitude,"latitude"),longitude:rX(e?.longitude,"longitude")}}function rX(e,t){let r="latitude"===t?-90:-180,n="latitude"===t?90:180;if("number"!=typeof e||!Number.isFinite(e)||e<r||e>n)throw new v("INVALID_ARGS",`${t} must be a number from ${r} to ${n}`);return e}let rW="settings",rK=rL(rW,"Change OS settings and app permissions.",{setting:W(K()),state:W(K()),app:K(),latitude:J(),longitude:J(),permission:K(),mode:Z(["full","limited"])}),rJ=eW(rK,(e,t)=>e.settings.update(t)),rY=eL(D.settings,e=>{var t;return"clear-app-state"===(t=e).setting?[t.setting,...ez(t.app)]:"location"===t.setting&&"set"===t.state?[t.setting,t.state,String(t.latitude),String(t.longitude)]:"permission"===t.setting?[t.setting,t.state,t.permission,...ez(t.mode)]:[t.setting,t.state]}),rQ=ej("wifi","airplane","location","animations"),rZ=ej("on","off"),r0=ej("light","dark","toggle"),r1=ej("faceid","touchid"),r2=ej("match","nonmatch","enroll","unenroll"),r3=ej("match","nonmatch"),r5=ej("grant","deny","reset"),r8=ej("camera","microphone","photos","contacts","contacts-limited","notifications","calendar","location","location-always","media-library","motion","reminders","siri","accessibility","screen-recording","input-monitoring"),r4="snapshot",r6="screenshot",r9="diff",r7="wait",ne="alert",nt=rL(r4,"Capture an accessibility snapshot.",{interactiveOnly:Q(),depth:Y(),scope:K(),raw:Q(),forceFull:Q(),timeoutMs:Y("Maximum wall-clock time for the snapshot command.")}),nr=rL(r6,"Capture a screenshot.",{path:K("Output path."),overlayRefs:Q(),fullscreen:Q(),maxSize:Y(),stabilize:Q(),surface:Z(t1)}),nn=rL(r9,"Diff accessibility snapshots.",{kind:W(et({type:"string",const:"snapshot"})),out:K(),interactiveOnly:Q(),depth:Y(),scope:K(),raw:Q()}),ni=rL(r7,"Wait for duration, text, ref, or selector.",{kind:Z(rN),durationMs:Y(),text:K(),ref:K(),selector:K(),timeoutMs:Y(),depth:Y(),scope:K(),raw:Q()}),na=rL(ne,"Inspect or handle platform alerts.",{action:Z(["get","accept","dismiss","wait"]),timeoutMs:Y()}),ns=[nt,nr,nn,ni,na,rK],no=[eW(nt,(e,t)=>e.capture.snapshot(t)),eW(nr,(e,t)=>e.capture.screenshot(t)),eW(nn,(e,t)=>e.capture.diff(t)),eW(ni,(e,t)=>{var r;let n;return e.command.wait((eb(r=t,"kind",rN),n={...r},delete n.kind,n))}),eW(na,(e,t)=>e.command.alert(t)),rJ],nl={[r4]:{usageOverride:"snapshot [--diff] [-i] [-d <depth>] [-s <scope>] [--raw] [--force-full] [--timeout <ms>]",helpDescription:"Capture accessibility tree or diff against the previous session baseline. For iOS raw-coordinate fallback after a no-op ref press, inspect rects with snapshot -i --json, press the rect center, then verify with diff snapshot -i or snapshot --diff.",summary:"Capture accessibility tree or diff against the previous session baseline",allowedFlags:["snapshotDiff",...rg,"snapshotForceFull","timeoutMs"]},[r6]:{helpDescription:"Capture screenshot (macOS app sessions default to the app window; use --fullscreen for full desktop, --max-size to downscale, --overlay-refs to annotate current refs, or --no-stabilize for low-latency Android capture loops)",summary:"Capture screenshot with optional desktop, downscale, or ref overlay modes",positionalArgs:["path?"],allowedFlags:["out","overlayRefs","screenshotFullscreen","screenshotMaxSize","screenshotNoStabilize"]},[r9]:{usageOverride:"diff snapshot | diff screenshot --baseline <path> [current.png] [--out <diff.png>] [--threshold <0-1>] [--overlay-refs]",helpDescription:"Diff accessibility snapshot or compare screenshots pixel-by-pixel",summary:"Diff snapshot or screenshot",positionalArgs:["kind","current?"],allowedFlags:[...rg,"baseline","threshold","out","overlayRefs"]},[r7]:{usageOverride:"wait <ms>|text <text>|@ref|<selector> [timeoutMs]",positionalArgs:["durationOrSelector","timeoutMs?"],allowsExtraPositionals:!0,allowedFlags:[...ry]},[ne]:{usageOverride:"alert [get|accept|dismiss|wait] [timeout]",positionalArgs:["action?","timeout?"]},[rW]:{usageOverride:rV,listUsageOverride:"settings [area] [options]",helpDescription:"Toggle OS settings, animation scales, appearance, and app permissions (macOS supports only settings appearance <light|dark|toggle> and settings permission <grant|reset> <accessibility|screen-recording|input-monitoring>; wifi|airplane|location|animations remain unsupported on macOS; mobile permission actions use the active session app)",summary:"Change OS settings and app permissions",positionalArgs:["setting","state","target?","mode?"]}},nc={snapshot:(e,t)=>({...eR(t),interactiveOnly:t.snapshotInteractiveOnly,depth:t.snapshotDepth,scope:t.snapshotScope,raw:t.snapshotRaw,forceFull:t.snapshotForceFull,timeoutMs:t.timeoutMs}),screenshot:(e,t)=>({...eR(t),path:e[0]??t.out,...eJ(t)}),diff:(e,t)=>{if("snapshot"!==e[0])throw new v("INVALID_ARGS","Only diff snapshot is available through this parser.");return{...eR(t),kind:"snapshot",out:t.out,interactiveOnly:t.snapshotInteractiveOnly,depth:t.snapshotDepth,scope:t.snapshotScope,raw:t.snapshotRaw}},wait:(e,t)=>(function(e,t){let r=tY(e);if(!r)throw new v("INVALID_ARGS","wait requires <ms>, text <text>, @ref, or <selector> [timeoutMs].");let n={...eO(t),...eP(t)};if("sleep"===r.kind)return{...n,durationMs:r.durationMs};if("text"===r.kind){if(!r.text)throw new v("INVALID_ARGS","wait requires text.");return{...n,text:r.text,...np(r.timeoutMs)}}return"ref"===r.kind?{...n,ref:r.rawRef,...np(r.timeoutMs)}:{...n,selector:r.selectorExpression,...np(r.timeoutMs)}})(e,t),alert:(e,t)=>({...eR(t),...function(e){if(e.length>2)throw new v("INVALID_ARGS","alert accepts at most action and timeout arguments.");return ek({action:function(e){let t=e?.toLowerCase();if(void 0===t||"get"===t||"accept"===t||"dismiss"===t||"wait"===t)return t;throw new v("INVALID_ARGS","alert action must be get, accept, dismiss, or wait.")}(e[0]),timeoutMs:function(e,t){if(void 0===e)return;let r=Number(e);if(Number.isFinite(r))return r;throw new v("INVALID_ARGS",`${t} must be a finite number.`)}(e[1],"alert timeout")})}(e)}),settings:(e,t)=>(function(e,t){let r=eO(t),n=e[0],i=e[1];if(eV(n,rQ)&&eV(i,rZ))return{...r,setting:n,state:i};if("location"===n&&"set"===i)return{...r,setting:n,state:i,latitude:rB(e[2],"latitude"),longitude:rB(e[3],"longitude")};if("appearance"===n&&eV(i,r0)||eV(n,r1)&&eV(i,r2)||"fingerprint"===n&&eV(i,r3))return{...r,setting:n,state:i};if("permission"===n&&eV(i,r5))return{...r,setting:n,state:i,permission:function(e){if(eV(e,r8))return e;throw new v("INVALID_ARGS","settings permission requires a permission target.")}(e[2]),mode:function(e){if(void 0===e||"full"===e||"limited"===e)return e;throw new v("INVALID_ARGS","settings permission mode must be full or limited.")}(e[3])};if("clear-app-state"===n){let t="clear"===i?e[2]:i;return{...r,setting:n,state:"clear",app:t}}throw new v("INVALID_ARGS","Invalid settings arguments.")})(e,t)};nc.snapshot,nc.screenshot,nc.diff,nc.wait,nc.alert,nc.settings;let nu={snapshot:eL(D.snapshot),screenshot:e=>eN(D.screenshot,ez(e.path),{...e,...eY(e)}),diff:eL(D.diff,e=>[eX(e.kind,"diff requires kind")]),wait:eL(D.wait,e=>(function(e){if(1!==[void 0!==e.durationMs?"durationMs":void 0,void 0!==e.text?"text":void 0,void 0!==e.ref?"ref":void 0,void 0!==e.selector?"selector":void 0].filter(Boolean).length)throw new v("INVALID_ARGS","wait command requires exactly one of durationMs, text, ref, or selector.");if(void 0!==e.durationMs)return[String(e.durationMs)];let t=eB(e.timeoutMs);if(void 0!==e.text)return["text",e.text,...t];if(void 0!==e.ref)return[e.ref,...t];let r=e.selector;if(!p(r))throw new v("INVALID_ARGS",`Invalid wait selector: ${r}`);return[r,...t]})(e)),alert:eL(D.alert,e=>{var t;return[(t=e).action??"get",...eB(t.timeoutMs)]}),settings:rY};function np(e){return null===e?{}:{timeoutMs:e}}function nd(e){return e?.clickButton??"primary"}function nm(e){return"primary"===e.button?null:"click"!==e.commandLabel?new v("INVALID_ARGS","--button is supported only for click"):"macos"!==e.platform&&"linux"!==e.platform?new v("UNSUPPORTED_OPERATION",`click --button ${e.button} is supported only on macOS and Linux`):"macos"===e.platform&&"middle"===e.button?new v("UNSUPPORTED_OPERATION","click --button middle is not supported by the macOS runner yet"):"number"==typeof e.count||"number"==typeof e.intervalMs||"number"==typeof e.holdMs||"number"==typeof e.jitterPx||!0===e.doubleTap?new v("INVALID_ARGS",`click --button ${e.button} does not support repeat or gesture modifier flags`):null}function nf(e){return"primary"===e?{}:{button:e}}nu.screenshot,nu.wait,nu.alert,nu.settings;let nh=["up","down","left","right"],ng=["left","right","left-edge","right-edge"],ny=["one-way","ping-pong"],nb=t0(ng,{message:"gesture swipe requires left, right, left-edge, or right-edge"}),nv=t0(nh,{message:e=>`Unknown direction: ${e}`});function nw(e){let t=e.direction,r="up"===t||"down"===t?e.referenceHeight:e.referenceWidth,n=nR(e.amount),i=void 0!==e.pixels?nO(e.pixels):Math.round(r*n),a=Math.max(1,Math.round(.05*r)),s=Math.max(1,Math.min(i,Math.max(1,r-2*a))),o=Math.round(s/2),l=Math.round(e.referenceWidth/2),c=Math.round(e.referenceHeight/2),u=(r,n,i,a)=>({direction:t,x1:r,y1:n,x2:i,y2:a,referenceWidth:e.referenceWidth,referenceHeight:e.referenceHeight,amount:e.amount,pixels:s});switch(t){case"up":return u(l,c-o,l,c+o);case"down":return u(l,c+o,l,c-o);case"left":return u(l-o,c,l+o,c);case"right":return u(l+o,c,l-o,c)}}function nx(e){nR(e.amount),void 0!==e.pixels&&nO(e.pixels)}function nS(e){return{...nw({...e,direction:function(e){switch(e){case"up":return"down";case"down":return"up";case"left":return"right";case"right":return"left"}}(e.direction)}),direction:e.direction}}function nk(e,t,r={}){let n=r.marginPx??8,[i,a,s]="left"===e?[85,15,50]:"right"===e?[15,85,50]:"left-edge"===e?[99,15,50]:[1,85,50],o=nI(t,i,s,{marginPx:n}),l=nI(t,a,s,{marginPx:n});return{preset:e,x1:o.x,y1:o.y,x2:l.x,y2:l.y,referenceWidth:t.referenceWidth,referenceHeight:t.referenceHeight}}function nD(e){return nb.parse(e)}function nA(e){let t=function(e){let t=e.filter(e=>(function(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("application")||t.includes("window")})(e.type)&&nN(e.rect)).map(e=>e.rect).sort((e,t)=>(t?.width??0)*(t?.height??0)-(e?.width??0)*(e?.height??0))[0];if(t)return t;let r=e.map(e=>e.rect).filter(nN);if(0===r.length)return;let n=Math.max(...r.map(e=>e.x+e.width)),i=Math.max(...r.map(e=>e.y+e.height));if(!(n<=0)&&!(i<=0))return{x:0,y:0,width:n,height:i}}(e);if(t)return{referenceWidth:t.width,referenceHeight:t.height}}function nI(e,t,r,n={}){let i={x:Math.round(e.referenceWidth*t/100),y:Math.round(e.referenceHeight*r/100)};return void 0===n.marginPx?i:nM(i,e,n.marginPx)}function nM(e,t,r){return{x:nE(e.x,r,t.referenceWidth),y:nE(e.y,r,t.referenceHeight)}}function nL(e){return nv.parse(e)}function nN(e){return!!e&&e.width>0&&e.height>0}function nR(e){if(void 0===e)return .6;if(!Number.isFinite(e)||e<=0)throw new v("INVALID_ARGS","scroll amount must be a positive number");return e}function nO(e){if(!Number.isFinite(e)||e<=0)throw new v("INVALID_ARGS","scroll pixels must be a positive integer");return Math.max(1,Math.round(e))}function nE(e,t,r){let n=Math.max(t,r-t);return nP(e,t,n)}function nP(e,t,r){return Math.min(Math.round(r),Math.max(Math.round(t),Math.round(e)))}function n_(e,t,r,n){if(!Number.isFinite(e)||!Number.isInteger(e)||e<r||e>n)throw new v("INVALID_ARGS",`${t} must be an integer between ${r} and ${n}`);return e}async function nC(e){let{edge:t,target:r={},scope:n,captureNodes:i}=e;try{let e=await i(n),a=function(e,t,r={}){var n,i,a;let o,l=(e??[]).map((e,t)=>({...e,ref:"ref"in e&&e.ref?e.ref:`e${t+1}`}));if(0===l.length)return{canScroll:!1,emptySnapshot:!0,signature:""};let c=F(l),u=function(e,t,r,n){let i=new Map(e.map(e=>[e.index,e])),a=e.filter(e=>s(e)&&nG(e.rect));if(0===a.length)return null;let o=function(e,t){if(void 0===e)return null;let r=t.get(e);for(;r;){if(s(r)&&nG(r.rect))return r;r=void 0===r.parentIndex?void 0:t.get(r.parentIndex)}return null}(n.nodeIndex,i);if(o)return o;let l=n.point;if(l){let e=a.filter(e=>{var t,r;return e.rect&&(t=e.rect,(r=l).x>=t.x&&r.x<=t.x+t.width&&r.y>=t.y&&r.y<=t.y+t.height)}).sort(nj);if(e.length>0)return e.find(e=>n$(e,t.get(e.index),r))??e[0]??null}let c=a.filter(e=>n$(e,t.get(e.index),r)).sort(nV);return c.length>0?c[0]??null:a.filter(t=>U(t,e)).sort(nV)[0]??a.sort(nV)[0]??null}(l,c,t,r),p=(u?(n=l,i=u.index,o=new Map(n.map(e=>[e.index,e])),n.filter(e=>e.index===i||function(e,t,r){let n=void 0===e.parentIndex?void 0:r.get(e.parentIndex);for(;n;){if(n.index===t)return!0;n=void 0===n.parentIndex?void 0:r.get(n.parentIndex)}return!1}(e,i,o))):l).map(e=>{let t=e.rect?["x","y","width","height"].map(t=>{var r;return r=e.rect?.[t],"number"==typeof r&&Number.isFinite(r)?r.toFixed(1):""}).join(","):"";return[String(e.index??""),String(e.parentIndex??""),String(e.type??""),String(e.label??""),String(e.value??""),t].join("|")}).join("\n");return u?{canScroll:n$(u,c.get(u.index),t),emptySnapshot:!1,signature:p,scope:[(a=u).identifier,a.label,a.value].map(e=>"string"==typeof e?e.trim():"").find(nU)}:{canScroll:!1,emptySnapshot:!1,signature:p}}(e,t,r);if(n&&a.emptySnapshot)return await nC({edge:t,target:r,captureNodes:i});return a}catch(e){var a,o,l;throw a=t,o=n,l=e,o?new v("COMMAND_FAILED",`Failed to verify scroll ${a} state for scoped container`,{scope:o,hint:`scroll ${a} could not verify the scoped scroll container. Run snapshot -i for the current screen and retry with a visible scroll target.`},l):new v("COMMAND_FAILED",`Failed to verify scroll ${a} state`,{hint:`scroll ${a} needs a snapshot showing hidden content ${"bottom"===a?"below":"above"} before it will move.`},l)}}async function nT(e){let t,{edge:r,captureState:n,scroll:i}=e,a=await n();a.scope&&(a=await n(a.scope));let s=0;for(;a.canScroll;){if(s>=40)throw new v("COMMAND_FAILED",`scroll ${r} reached the safety limit before the snapshot showed the edge`,{hint:"The scoped scroll container still reports hidden content. Use a smaller manual scroll + snapshot loop to inspect the current state."});t=await i(),s+=1,a=await n(a.scope)}return{passes:s,result:t}}function nF(e,t,r,n,i){return t&&0===r?`Already at ${t}; no hidden content ${"bottom"===t?"below":"above"} detected`:t?`Scrolled to ${t} with ${r} ${e} passes`:void 0!==i?`Scrolled ${e} by ${i}px`:void 0!==n?`Scrolled ${e} by ${n}`:`Scrolled ${e}`}function n$(e,t,r){return"bottom"===r?!0===e.hiddenContentBelow||t?.hiddenContentBelow===!0:!0===e.hiddenContentAbove||t?.hiddenContentAbove===!0}function nU(e){return e.length>0&&e.length<=80&&!/^(true|false)$/i.test(e)&&!/^\d+$/.test(e)&&!/^\d+%$/.test(e)}function nj(e,t){return nq(e.rect)-nq(t.rect)}function nV(e,t){return nq(t.rect)-nq(e.rect)}function nq(e){return e?e.width*e.height:0}function nG(e){return!!(e&&e.width>0&&e.height>0)}function nz(e,t){return{session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata}}function nB(e){return e.clock?.now()??Date.now()}async function nH(e,t){e.clock?await e.clock.sleep(t):await new Promise(e=>setTimeout(e,t))}function nX(e){return e&&"object"==typeof e?e:void 0}let nW=["x","y","width","height"];function nK(e){let t=nJ(e);if(!t)return null;let n=r(t);return Number.isFinite(n.x)&&Number.isFinite(n.y)?n:null}function nJ(e){if(!e)return null;let t=Number(e.x),r=Number(e.y),n=Number(e.width),i=Number(e.height);return Number.isFinite(t)&&Number.isFinite(r)&&Number.isFinite(n)&&Number.isFinite(i)&&!(n<0)&&!(i<0)?{x:t,y:r,width:n,height:i}:null}function nY(e,t){return!!e&&!!t&&nW.every(r=>.5>=Math.abs(e[r]-t[r]))}function nQ(e){return{x:nZ(e.x,e.width),y:nZ(e.y,e.height)}}function nZ(e,t){if(t<=1)return Math.floor(e);let r=Math.ceil(e);return Math.round(Math.min(Math.floor(e+t-1),Math.max(r,e+t/2)))}let n0=["tabbar","toolbar","navigationbar","bottomnavigation","bottomnavigationview","sheet","dialog","alert","popover","menu"],n1=["button","link","menuitem","tabitem","textfield","searchfield","edittext","checkbox","radio","switch","cell"];function n2(e){if(e.length<2)return e;let t=[...e],n={nodes:t,byIndex:new Map(t.map(e=>[e.index,e]))},i=!1;for(let[e,a]of t.entries()){if(!function(e){return!!n6(e.rect)&&(!!(!0===e.hittable||n5(e,n1))||!!(e.label?.trim()||e.value?.trim()||e.identifier?.trim()))}(a)||!function e(t,n,i){let a=n6(i.rect);if(!a)return null;let s=r(a);for(let r=n+1;r<t.nodes.length;r+=1){let n=t.nodes[r];if(n&&function(t,r,n,i,a){if(!t.nodes[r])return!1;let s=function(t,r,n,i){var a,s,o,l;let c=t.nodes[r];if(!c||!(!(!n6((a=c).rect)||function(e){let t=n8(e);return t.includes("application")||t.includes("window")}(a))&&n5(a,n0))||n4(s=n,o=c,l=t.byIndex)||n4(o,s,l))return null;let u=n6(c.rect);return!u||nY(i,u)||e(t,r,c)?null:u}(t,r,n,i);return!!(s&&P(s,a.x,a.y))}(t,r,i,a,s))return n}return null}(n,e,a))continue;i=!0;let s={...a,hittable:!1,interactionBlocked:"covered",presentationHints:Array.from(new Set([...a.presentationHints??[],"covered"]))};t[e]=s,n.byIndex.set(s.index,s)}return i?t:e}function n3(e){return void 0!==e.interactionBlocked}function n5(e,t){let r=n8(e);return t.some(e=>r.includes(e))}function n8(e){return[e.type,e.role,e.subrole].map(e=>b(e??"")).join(" ")}function n4(e,t,r){let n="number"==typeof t.parentIndex?r.get(t.parentIndex):void 0,i=new Set;for(;n&&!i.has(n.index);){if(n.index===e.index)return!0;i.add(n.index),n="number"==typeof n.parentIndex?r.get(n.parentIndex):void 0}return!1}function n6(e){let t=nJ(e);return t&&t.width>0&&t.height>0?t:null}let n9=["button","link","menuitem","tabitem","textfield","searchfield","securetextfield","checkbox","radio","switch","cell"];function n7(e,t){return ie(e,t).node}function ie(e,t){var n;if(n3(t))return{node:t,reason:"covered"};let i=function(e,t){let r=nJ(t.rect);if(!r)return null;let n=t,i=new Set;for(;!i.has(n.ref);){i.add(n.ref);let t=e.filter(e=>{if(e.parentIndex!==n.index||!e.hittable||n3(e))return!1;let t=nJ(e.rect);return!!t&&nY(t,r)});if(1!==t.length)break;n=t[0]}return n===t?null:n}(e,t);if(i?.rect&&nK(i.rect))return{node:i,reason:"same-rect-descendant"};if([(n=t).type,n.role,n.subrole].map(e=>b(e??"")).some(it)&&t.rect&&nK(t.rect))return{node:t,reason:"semantic-target"};let s=u(e,t);return s?.rect&&!n3(s)&&nK(s.rect)?!function(e,t,n){var i,s;let o,l,c,u=nJ(e.rect),p=nJ(t.rect);if(!u||!p)return!1;let d=function(e,t){let n=r(t),i=e.filter(e=>{let t=(e.type??"").toLowerCase();return t.includes("application")||t.includes("window")}).map(e=>nJ(e.rect)).filter(e=>null!==e);if(0===i.length)return null;let a=i.filter(e=>P(e,n.x,n.y));return _(a.length>0?a:i)}(n,u);return!!d&&(o=a(i=p,s=d),l=i.width*i.height,c=s.width*s.height,!(o<=0)&&!(l<=0)&&!(c<=0)&&!!(o/c>=.9)&&!!(o/l>=.8))&&!nY(u,p)}(t,s,e)?{node:s,reason:"hittable-ancestor"}:{node:t,reason:"overly-broad-ancestor"}:{node:t,reason:"original"}}function it(e){return"tab"===e||n9.some(t=>e.includes(t))}async function ir(e,t,r){var n;return(await ip(e,t,r.action),"point"===t.target.kind)?{kind:"point",point:{x:(n=t.target).x,y:n.y}}:"ref"===t.target.kind?await ii(e,t,t.target,r):await ia(e,t,t.target,r)}async function ii(e,t,r,i){let a=await im(e,t,r),s=a.resolved,o=i.promoteToHittableAncestor?io(a.snapshot.nodes,s.node,{action:i.action,label:`Ref ${r.ref}`}):s.node;return il(o,`Ref ${r.ref}`,i.action),function(e,t,r,i){let a=e.rect?j(e,t):null;if(!(!e.rect||!a||U(e,t)))throw new v("COMMAND_FAILED",`Ref ${r} is off-screen and not safe to ${i}`,{reason:"offscreen_ref",ref:n(r),rect:e.rect,viewport:a,hint:`Use scroll with the direction from the off-screen summary, take a fresh snapshot, then retry ${i} with the new ref or a selector.`})}(o,a.snapshot.nodes,r.ref,i.action),{kind:"ref",point:ig(o,`Ref ${r.ref} not found or has invalid bounds`),target:{kind:"ref",ref:`@${s.ref}`},node:o,selectorChain:d(o,e.backend.platform,{action:"fill"===i.action?"fill":"click"}),refLabel:h(o,a.snapshot.nodes)}}async function ia(e,t,r,n){let i=m(r.selector),a=await iu(e,t,n.requireInteractive),s=g(is(a.snapshot.nodes),i,{platform:e.backend.platform,requireRect:!0,requireUnique:!0,disambiguateAmbiguous:!0});if(s&&s.node.rect||!n.requireInteractive||(s=g(is((a=await iu(e,t,!1)).snapshot.nodes),i,{platform:e.backend.platform,requireRect:!0,requireUnique:!0,disambiguateAmbiguous:!0})),!s||!s.node.rect){let t=g(a.snapshot.nodes,i,{platform:e.backend.platform,requireRect:!0,requireUnique:!1});if(t?.node&&n3(t.node))throw ic({label:`Selector ${t.selector.raw}`,node:t.node,action:n.action,selector:t.selector.raw});throw new v("COMMAND_FAILED",y(i,s?.diagnostics??[],{unique:!0}))}let o=n.promoteToHittableAncestor?io(a.snapshot.nodes,s.node,{action:n.action,label:`Selector ${s.selector.raw}`}):s.node;return il(o,`Selector ${s.selector.raw}`,n.action),{kind:"selector",point:ig(o,`Selector ${s.selector.raw} resolved to invalid bounds`),target:{kind:"selector",selector:s.selector.raw},node:o,selectorChain:d(o,e.backend.platform,{action:"fill"===n.action?"fill":"click"}),refLabel:h(o,a.snapshot.nodes)}}function is(e){return e.filter(e=>!n3(e))}function io(e,t,r){let n=ie(e,t);if("covered"===n.reason)throw ic({label:r.label,node:t,action:r.action});return n.node}function il(e,t,r){if(n3(e))throw ic({label:t,node:e,action:r})}function ic(e){return new v("COMMAND_FAILED",`${e.label} is covered by another visible element and cannot ${function(e){switch(e){case"fill":return"be filled";case"focus":return"be focused";case"longPress":return"be long-pressed";default:return"be tapped"}}(e.action)} safely`,{hint:"Use a different visible target, scroll it clear of the overlay, or inspect with snapshot/screenshot before retrying.",...e.selector?{selector:e.selector}:{},ref:`@${e.node.ref}`,interactionBlocked:e.node.interactionBlocked})}async function iu(e,t,r){if(!e.backend.captureSnapshot)throw new v("UNSUPPORTED_OPERATION","snapshot is not supported by this backend");let n=t.session??"default",i=await e.sessions.get(n);if(!i)throw new v("SESSION_NOT_FOUND","No active session. Run open first.");let a=await e.backend.captureSnapshot(nz(e,t),{interactiveOnly:r}),s=a.snapshot??{nodes:a.nodes??[],truncated:a.truncated,backend:a.backend,createdAt:nB(e)};return await e.sessions.set({...i,snapshot:s}),{snapshot:s}}async function ip(e,t,r){if("macos"!==e.backend.platform)return;let n=await id(e,t);if(("desktop"===n||"menubar"===n)&&("menubar"!==n||"click"!==r&&"press"!==r))throw new v("UNSUPPORTED_OPERATION",`${r} is not supported on macOS ${n} sessions yet. Open an app session to act, or use the ${n} surface to inspect.`)}async function id(e,t){let r=await e.sessions.get(t.session??"default");return r?.metadata?.surface}async function im(e,t,r){let n=t.session??"default",i=await e.sessions.get(n);if(!i)throw new v("SESSION_NOT_FOUND","No active session. Run open first.");if(!i.snapshot)throw new v("INVALID_ARGS","No snapshot in session. Run snapshot first.");let a=r.fallbackLabel??"",s=ih(i.snapshot.nodes,r.ref,{fallbackLabel:a});if(s)return{snapshot:i.snapshot,resolved:s};let o=await iu(e,t,!0),l=ih(o.snapshot.nodes,r.ref,{fallbackLabel:a});if(!l)throw new v("COMMAND_FAILED",`Ref ${r.ref} not found or has no bounds`);return{...o,resolved:l}}function ih(e,r,i){let a=n(r);if(!a)throw new v("INVALID_ARGS",`Invalid ref: ${r}`);let s=t(e,a);if(iy(s))return{ref:a,node:s};let o=i.fallbackLabel.length>0?f(e,i.fallbackLabel):null;return iy(o)?{ref:a,node:o}:null}function ig(e,t){let r=nK(e.rect);if(!r)throw new v("COMMAND_FAILED",t);return r}function iy(e){return!!e&&null!==nK(e.rect)}let ib=async(e,t)=>{let r=await ir(e,t,{action:"focus",requireInteractive:!0,promoteToHittableAncestor:!1});if(!e.backend.focus)throw new v("UNSUPPORTED_OPERATION","focus is not supported by this backend");let n=nX(await e.backend.focus(nz(e,t),r.point));return{...r,...n?{backendResult:n}:{},...te(`Focused (${r.point.x}, ${r.point.y})`)}},iv=async(e,t)=>{let r=await ir(e,t,{action:"longPress",requireInteractive:!0,promoteToHittableAncestor:!0});if(!e.backend.longPress)throw new v("UNSUPPORTED_OPERATION","longPress is not supported by this backend");let n=void 0===t.durationMs?void 0:n_(t.durationMs,"durationMs",0,12e4),i=nX(await e.backend.longPress(nz(e,t),r.point,{durationMs:n}));return{...r,...void 0!==n?{durationMs:n}:{},...i?{backendResult:i}:{},...te(`Long pressed (${r.point.x}, ${r.point.y})`)}},iw=async(e,t)=>{var r,n,i,a;let s;if(!e.backend.scroll)throw new v("UNSUPPORTED_OPERATION","scroll is not supported by this backend");let o="bottom"===(r=t.direction)?{direction:"down",edge:"bottom"}:"top"===r?{direction:"up",edge:"top"}:{direction:iM(r,"scroll direction")},l=(n=t.amount,i="scroll amount",void 0===n?void 0:iN(n,i)),c=function(e,t){if(void 0!==e){if(!Number.isFinite(e)||!Number.isInteger(e)||e<=0)throw new v("INVALID_ARGS",`${t} must be a positive integer`);return e}}(t.pixels,"scroll pixels");if(void 0!==l&&void 0!==c)throw new v("INVALID_ARGS","scroll accepts either amount or pixels, not both");let u=await iD(e,t),p="viewport"===u.kind?{kind:"viewport"}:{kind:"point",point:u.point},d=e.backend.scroll,m=async()=>await d(nz(e,t),p,{direction:o.direction,...void 0!==l?{amount:l}:{},...void 0!==c?{pixels:c}:{}}),f=0;if(o.edge){let r=o.edge,n="viewport"===(a=u).kind?{}:{point:a.point,nodeIndex:"node"in a?a.node.index:void 0},i=await nT({edge:r,captureState:async i=>await iI(e,t,r,n,i),scroll:m});s=i.result,f=i.passes}else s=await m(),f=1;let h=nX(s);return{...u,direction:o.direction,...o.edge?{edge:o.edge,passes:f}:{},...void 0!==l?{amount:l}:{},...void 0!==c?{pixels:c}:{},...h?{backendResult:h}:{},...te(nF(o.direction,o.edge,f,l,c))}},ix=async(e,t)=>{if(!e.backend.swipe)throw new v("UNSUPPORTED_OPERATION","swipe is not supported by this backend");if(t.preset)return await iS(e,t,e.backend.swipe);let r=await iA(e,t),n=function(e,t){if(t.to)return{point:iL(t.to,"to")};let r=iM(t.direction,"swipe direction"),n=iN(t.distance??200,"swipe distance");switch(r){case"up":return{point:{x:e.x,y:e.y-n},direction:r,distance:n};case"down":return{point:{x:e.x,y:e.y+n},direction:r,distance:n};case"left":return{point:{x:e.x-n,y:e.y},direction:r,distance:n};case"right":return{point:{x:e.x+n,y:e.y},direction:r,distance:n}}}(r.point,t),i=void 0===t.durationMs?void 0:n_(t.durationMs,"durationMs",16,1e4),a=nX(await e.backend.swipe(nz(e,t),r.point,n.point,{durationMs:i}));return{kind:"swipe",from:r.point,to:n.point,...n.direction?{direction:n.direction}:{},...void 0!==n.distance?{distance:n.distance}:{},...void 0!==i?{durationMs:i}:{},...r.target?{fromTarget:r.target}:{},...a?{backendResult:a}:{},...te("Swiped")}};async function iS(e,t,r){let n;if(t.from||t.to||t.direction||void 0!==t.distance)throw new v("INVALID_ARGS","gesture swipe preset cannot be combined with from, to, direction, or distance");let i=nD(t.preset);await ip(e,t,"swipe");let a=nk(i,{referenceWidth:(n=iR((await iu(e,t,!1)).snapshot.nodes)).width,referenceHeight:n.height},{platform:e.backend.platform}),s=void 0===t.durationMs?void 0:n_(t.durationMs,"durationMs",16,1e4),o={x:a.x1,y:a.y1},l={x:a.x2,y:a.y2},c=nX(await r(nz(e,t),o,l,{durationMs:s}));return{kind:"swipe",from:o,to:l,preset:i,...void 0!==s?{durationMs:s}:{},fromTarget:{kind:"viewport"},...c?{backendResult:c}:{},...te(`Swiped ${i}`)}}let ik=async(e,t)=>{if(!e.backend.pinch)throw new v("UNSUPPORTED_OPERATION","pinch is not supported by this backend");await ip(e,t,"pinch");let r=iN(t.scale,"pinch scale"),n=t.center?await ir(e,{...t,target:t.center},{action:"pinch",requireInteractive:!1,promoteToHittableAncestor:!1}):void 0,i=nX(await e.backend.pinch(nz(e,t),{scale:r,...n?{center:n.point}:{}}));return{kind:"pinch",scale:r,...n?{center:n.point,centerTarget:n}:{},...i?{backendResult:i}:{},...te(`Pinched to scale ${r}`)}};async function iD(e,t){let r=t.target??{kind:"viewport"};return"viewport"===r.kind?(await ip(e,t,"scroll"),{kind:"viewport"}):await ir(e,{...t,target:r},{action:"scroll",requireInteractive:!1,promoteToHittableAncestor:!1})}async function iA(e,t){if(t.from){var n;if("x"in(n=t.from)&&"y"in n)return await ip(e,t,"swipe"),{point:iL(t.from,"from")};let r=await ir(e,{...t,target:t.from},{action:"swipe",requireInteractive:!1,promoteToHittableAncestor:!1});return{point:r.point,target:r}}if(!t.direction)throw new v("INVALID_ARGS","swipe requires from+to or a direction");return await ip(e,t,"swipe"),{point:r(iR((await iu(e,t,!1)).snapshot.nodes)),target:{kind:"viewport"}}}async function iI(e,t,r,n,i){if(!e.backend.captureSnapshot)throw new v("UNSUPPORTED_OPERATION",`scroll ${r} requires snapshot support to verify hidden content before scrolling`);let{captureSnapshot:a}=e.backend;return await nC({edge:r,target:n,scope:i,captureNodes:async r=>{let n=await a(nz(e,t),{scope:r});return n.snapshot?.nodes??n.nodes??[]}})}function iM(e,t){switch(e){case"up":case"down":case"left":case"right":return e;default:throw new v("INVALID_ARGS",`${t} must be up, down, left, or right`)}}function iL(e,t){let r=Number(e.x),n=Number(e.y);if(!Number.isFinite(r)||!Number.isFinite(n))throw new v("INVALID_ARGS",`${t} point requires finite x and y`);return{x:r,y:n}}function iN(e,t){if(!Number.isFinite(e)||e<=0)throw new v("INVALID_ARGS",`${t} must be a positive number`);return e}function iR(e){let t=e.filter(t=>U(t,e)).map(e=>e.rect).filter(iO),r=t.length>0?t:e.map(e=>e.rect).filter(iO);if(0===r.length)throw new v("COMMAND_FAILED","Cannot infer viewport for directional swipe");let n=Math.min(...r.map(e=>e.x)),i=Math.min(...r.map(e=>e.y));return{x:n,y:i,width:Math.max(...r.map(e=>e.x+e.width))-n,height:Math.max(...r.map(e=>e.y+e.height))-i}}function iO(e){return!!(e&&e.width>0&&e.height>0)}let iE={click:"Click or tap a semantic UI target by ref, selector, or point.",press:"Press a semantic UI target by ref, selector, or point.",fill:"Fill text into a semantic UI target by ref, selector, or point.",longpress:"Long press by ref, selector, or point.",swipe:"Swipe between two points.",focus:"Focus input at coordinates.",type:"Type text in the focused field.",scroll:"Scroll in a direction or to an edge.",get:"Get element text or attributes.",is:"Assert UI state.",find:"Find an element and optionally act on it.",gesture:"Run a structured gesture."},iP={target:W(er()),button:Z(["primary","secondary","middle"],"Pointer button for platforms that support mouse buttons."),...ei(),...ea()},i_={target:W(er()),...ei(),...ea()},iC={target:W(er()),text:W(K("Text to enter into the target.")),delayMs:Y("Delay between typed characters.",{min:0}),...ei()},iT={target:W(er()),durationMs:Y("Long press duration in milliseconds.",{min:0}),...ei()},iF={from:W(en("Swipe start point.")),to:W(en("Swipe end point.")),durationMs:Y("Swipe duration in milliseconds.",{min:0}),count:Y("Number of swipe repetitions.",{min:1}),pauseMs:Y("Pause between repeated swipes.",{min:0}),pattern:Z(ny)},i$={x:W(J("X coordinate.")),y:W(J("Y coordinate."))},iU={text:W(K("Text to type.")),delayMs:Y("Delay between typed characters.",{min:0})},ij={direction:W(Z(["up","down","left","right","top","bottom"])),amount:J("Platform scroll amount."),pixels:Y("Pixel scroll amount.",{min:0})},iV={format:W(Z(["text","attrs"])),target:W(eD({oneOf:eI(),description:"UI element target by snapshot ref or selector expression."},(e,t)=>{let r,n;return void 0===e[t]?void 0:"ref"===(n=ey(r=eM(e,t),"kind",["ref","selector"]))?{kind:n,ref:ep(r,"ref"),label:ed(r,"label")}:{kind:n,selector:ep(r,"selector")}})),...ei()},iq={predicate:W(Z(["visible","hidden","exists","editable","selected","text"])),selector:W(K()),value:K(),...ei()},iG={locator:Z(A),query:W(K()),action:Z(["click","focus","exists","getText","getAttrs","wait","fill","type"]),value:K(),timeoutMs:Y(),first:Q(),last:Q(),depth:Y(),raw:Q()},iz={kind:W(Z(k,"Gesture variant.")),direction:Z(nh,"Fling direction."),preset:Z(ng,"Swipe preset."),origin:en("Gesture origin point."),delta:en("Movement delta for pan or transform gestures."),distance:Y("Fling distance.",{min:0}),scale:J("Pinch or transform scale."),degrees:J("Rotation in degrees."),velocity:Y("Rotate gesture velocity.",{min:0}),durationMs:Y("Gesture duration in milliseconds.",{min:0})},iB=[{name:"click",description:iE.click,inputSchema:es(iP),readInput:e=>eo(e,iP)},{name:"press",description:iE.press,inputSchema:es(i_),readInput:e=>eo(e,i_)},{name:"fill",description:iE.fill,inputSchema:es(iC),readInput:e=>eo(e,iC)},iH("longpress",iT),iH("swipe",iF),iH("focus",i$),iH("type",iU),iH("scroll",ij),iH("get",iV),iH("is",iq),iH("find",iG),{name:"gesture",description:iE.gesture,inputSchema:es(iz),readInput:function(e){let t=el(e),r=ec(t),n=ey(t,"kind",k);return"pan"===n?{...r,kind:n,origin:eu(t,"origin"),delta:eu(t,"delta"),durationMs:eh(t,"durationMs",{min:0})}:"fling"===n?{...r,kind:n,direction:ey(t,"direction",nh),origin:eu(t,"origin"),distance:eh(t,"distance",{min:0}),durationMs:eh(t,"durationMs",{min:0})}:"swipe"===n?{...r,kind:n,preset:ey(t,"preset",ng),durationMs:eh(t,"durationMs",{min:0})}:"pinch"===n?{...r,kind:n,scale:em(t,"scale"),origin:iX(t,"origin")}:"rotate"===n?{...r,kind:n,degrees:em(t,"degrees"),origin:iX(t,"origin"),velocity:eh(t,"velocity",{min:0})}:{...r,kind:n,origin:eu(t,"origin"),delta:eu(t,"delta"),scale:em(t,"scale"),degrees:em(t,"degrees"),durationMs:eh(t,"durationMs",{min:0})}}}];function iH(e,t){return rL(e,iE[e],t)}function iX(e,t){return void 0===e[t]?void 0:eu(e,t)}let iW={gesture:function(e,t){let r=e[0],n=e.slice(1),i=eR(t);switch(r){case"pan":return{...i,kind:r,origin:{x:Number(n[0]),y:Number(n[1])},delta:{x:Number(n[2]),y:Number(n[3])},durationMs:eG(n[4])};case"fling":return{...i,kind:r,direction:n[0],origin:{x:Number(n[1]),y:Number(n[2])},distance:eG(n[3]),durationMs:eG(n[4])};case"swipe":return{...i,kind:r,preset:n[0],durationMs:eG(n[1])};case"pinch":return{...i,kind:r,scale:Number(n[0]),origin:void 0===n[1]||void 0===n[2]?void 0:{x:Number(n[1]),y:Number(n[2])}};case"rotate":return{...i,kind:r,degrees:Number(n[0]),origin:void 0===n[1]||void 0===n[2]?void 0:{x:Number(n[1]),y:Number(n[2])},velocity:eG(n[3])};case"transform":return{...i,kind:r,origin:{x:Number(n[0]),y:Number(n[1])},delta:{x:Number(n[2]),y:Number(n[3])},scale:Number(n[4]),degrees:Number(n[5]),durationMs:eG(n[6])};default:throw new v("INVALID_ARGS","gesture requires pan, fling, swipe, pinch, rotate, or transform")}}},iK={gesture:eL(D.gesture,function(e){switch(e.kind){case"pan":return["pan",String(e.origin?.x),String(e.origin?.y),String(e.delta?.x),String(e.delta?.y),...eB(e.durationMs)];case"fling":return["fling",eX(e.direction,"gesture fling requires direction"),String(e.origin?.x),String(e.origin?.y),...eB(e.distance),...eB(e.durationMs)];case"swipe":return iJ(e);case"pinch":return["pinch",String(e.scale),...eB(e.origin?.x),...eB(e.origin?.y)];case"rotate":return["rotate",String(e.degrees),...eB(e.origin?.x),...eB(e.origin?.y),...eB(e.velocity)];case"transform":return["transform",String(e.origin?.x),String(e.origin?.y),String(e.delta?.x),String(e.delta?.y),String(e.scale),String(e.degrees),...eB(e.durationMs)];default:throw new v("INVALID_ARGS","gesture requires pan, fling, swipe, pinch, rotate, or transform")}}),"gesture-pan":eL(D.gesture,function(e){return["pan",String(e.x),String(e.y),String(e.dx),String(e.dy),...eB(e.durationMs)]}),"gesture-fling":eL(D.gesture,e=>{var t;let r;return r=void 0!==(t=e).durationMs?t.distance??180:t.distance,["fling",t.direction,String(t.x),String(t.y),...eB(r),...eB(t.durationMs)]}),"gesture-swipe":eL(D.gesture,iJ),"gesture-pinch":eL(D.gesture,function(e){return["pinch",String(e.scale),...eB(e.x),...eB(e.y)]}),"gesture-rotate":eL(D.gesture,e=>(function(e){var t=e;if(void 0===t.x&&void 0!==t.y||void 0!==t.x&&void 0===t.y)throw new v("INVALID_ARGS","gesture rotate center requires both x and y");let r=void 0===e.x||void 0===e.y?[]:[String(e.x),String(e.y)];return["rotate",String(e.degrees),...r,...eB(e.velocity)]})(e)),"gesture-transform":eL(D.gesture,function(e){return["transform",String(e.x),String(e.y),String(e.dx),String(e.dy),String(e.scale),String(e.degrees),...eB(e.durationMs)]})};function iJ(e){return["swipe",eX(e.preset,"gesture swipe requires preset"),...eB(e.durationMs)]}function iY(e){if(e[0]?.startsWith("@")){let t=iZ(e.slice(1));return{ref:e[0],...void 0===t?{}:{label:t}}}let t=c(e);return t?{selector:t.selectorExpression}:{x:Number(e[0]),y:Number(e[1])}}function iQ(e){let t=e[0];if(t?.startsWith("@")){let r=e.length>=3?e.slice(2).join(" "):e.slice(1).join(" ");return{kind:"ref",target:{ref:t,label:e.length>=3?iZ(e.slice(1,2)):void 0},text:r}}let r=c(e,{preferTrailingValue:!0});return r?{kind:"selector",target:{selector:r.selectorExpression},text:r.rest.join(" ")}:{kind:"point",target:{x:Number(e[0]),y:Number(e[1])},text:e.slice(2).join(" ")}}function iZ(e){return e.join(" ").trim()||void 0}let i0={click:(e,t)=>({...eR(t),...eE(t),...e_(t),target:eC(iY(e)),button:t.clickButton}),press:(e,t)=>({...eR(t),...eE(t),...e_(t),target:eC(iY(e))}),longpress:(e,t)=>{let r,n={...iY((r=function(e){if(eq(e[0])&&eq(e[1]))return{target:e.slice(0,2),...void 0!==e[2]?{durationMs:Number(e[2])}:{}};let t=e.at(-1);return e.length>1&&eq(t)?{target:e.slice(0,-1),durationMs:Number(t)}:{target:e}}(e)).target),...void 0!==r.durationMs?{durationMs:r.durationMs}:{}};return{...eR(t),...eE(t),target:eC(n),durationMs:n.durationMs}},swipe:(e,t)=>({...eR(t),from:{x:Number(e[0]),y:Number(e[1])},to:{x:Number(e[2]),y:Number(e[3])},durationMs:eG(e[4]),count:t.count,pauseMs:t.pauseMs,pattern:t.pattern}),focus:(e,t)=>({...eR(t),x:Number(e[0]),y:Number(e[1])}),type:(e,t)=>({...eR(t),text:e.join(" "),delayMs:t.delayMs}),fill:(e,t)=>{let r=iQ(e);return{...eR(t),...eE(t),target:eC(r.target),text:r.text,delayMs:t.delayMs}},scroll:(e,t)=>({...eR(t),direction:function(e){if("up"===e||"down"===e||"left"===e||"right"===e||"top"===e||"bottom"===e)return e;throw new v("INVALID_ARGS",`Unknown direction: ${String(e)}`)}(e[0]),amount:eG(e[1]),pixels:t.pixels}),get:(e,t)=>({...eR(t),...eE(t),format:function(e){if("text"===e||"attrs"===e)return e;throw new v("INVALID_ARGS","get only supports text or attrs")}(e[0]),target:eC(function(e){if(e[0]?.startsWith("@"))return{ref:e[0],label:e.slice(1).join(" ").trim()||void 0};let t=e.join(" ").trim();if(!t)throw new v("INVALID_ARGS","get requires @ref or selector expression");return{selector:t}}(e.slice(1)))})},i1={click:e=>eN(D.click,eT(e),{...e,clickButton:e.button}),press:eL(D.press,e=>eT(e)),longpress:eL(D.longPress,e=>{var t;return[...eT(t=e),...eB(t.durationMs)]}),swipe:eL(D.swipe,function(e){return[String(e.from?.x),String(e.from?.y),String(e.to?.x),String(e.to?.y),...eB(e.durationMs)]}),focus:eL(D.focus,e=>[String(e.x),String(e.y)]),type:eL(D.type,e=>[e.text]),fill:eL(D.fill,e=>{var t;return[...eT(t=e),t.text]}),scroll:eL(D.scroll,e=>[eX(e.direction,"scroll requires direction"),...eB(e.amount)]),get:eL(D.get,e=>[eX(e.format,"get requires format"),...function(e){let t=eF(e);if("string"==typeof t.ref)return[t.ref,...eU(t.label)];if("string"==typeof t.selector)return[t.selector];throw new v("INVALID_ARGS","element command requires @ref or selector target")}(e)])},i2={find:(e,t)=>(function(e,t){var r;let n={...{depth:(r=t).snapshotDepth,raw:r.snapshotRaw},...eO(t),first:t.findFirst,last:t.findLast},i=function(e){if("text"===e||"label"===e||"value"===e||"role"===e||"id"===e)return e}(e[0]),a=void 0!==i,s=a?e[1]:e[0],o=a?2:1,l=e[o];if(void 0===l)return{...n,locator:i,query:i5(s)};if("get"===l){let t=e[o+1];if("text"===t)return{...n,locator:i,query:i5(s),action:"getText"};if("attrs"===t)return{...n,locator:i,query:i5(s),action:"getAttrs"};throw new v("INVALID_ARGS","find get only supports text or attrs")}if("wait"===l)return{...n,locator:i,query:i5(s),action:"wait",timeoutMs:eG(e[o+1])};if("fill"===l||"type"===l)return{...n,locator:i,query:i5(s),action:l,value:e.slice(o+1).join(" ")};if("click"===l||"focus"===l||"exists"===l)return{...n,locator:i,query:i5(s),action:l};throw new v("INVALID_ARGS",`Unsupported find action: ${l}`)})(e,t),is:(e,t)=>(function(e,t){let r={...eP(t),...eO(t)},n=e[0],i=function(e,t={}){let r=c(e,t);if(!r)throw new v("INVALID_ARGS","is requires a selector expression");return r}(e.slice(1),{preferTrailingValue:"text"===n});if("text"===n)return{...r,predicate:n,selector:i.selectorExpression,value:i.rest.join(" ")};if("visible"===n||"hidden"===n||"exists"===n||"editable"===n||"selected"===n)return{...r,predicate:n,selector:i.selectorExpression};throw new v("INVALID_ARGS","is requires predicate: visible|hidden|exists|editable|selected|text")})(e,t)},i3={is:eL(D.is,e=>{var t;return[(t=e).predicate,t.selector,..."text"===t.predicate?[t.value]:[]]}),find:e=>eN(D.find,function(e){let t=e.locator&&"any"!==e.locator?[e.locator,e.query]:[e.query];switch(e.action){case void 0:case"click":case"focus":case"exists":return e.action?[...t,e.action]:t;case"getText":return[...t,"get","text"];case"getAttrs":return[...t,"get","attrs"];case"wait":return[...t,"wait",...eB(e.timeoutMs)];case"fill":case"type":return[...t,e.action,e.value]}}(e),{...e,findFirst:e.first,findLast:e.last})};function i5(e){if(void 0===e||""===e)throw new v("INVALID_ARGS","find requires query");return e}let i8={get:{usageOverride:"get text|attrs <@ref|selector>",positionalArgs:["subcommand","target"],allowedFlags:[...ry]},find:{usageOverride:"find <locator|text> <action> [value] [--first|--last]",helpDescription:"Find by text/label/value/role/id and run action",summary:"Find an element and act",positionalArgs:["query","action","value?"],allowsExtraPositionals:!0,allowedFlags:["snapshotDepth","snapshotRaw","findFirst","findLast"]},is:{positionalArgs:["predicate","selector","value?"],allowsExtraPositionals:!0,allowedFlags:[...ry]},click:{usageOverride:"click <x y|@ref|selector>",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:[...rw,"clickButton",...ry]},press:{usageOverride:"press <x y|@ref|selector>",helpDescription:"Short press a semantic UI target by ref, selector, or point. For native context menus or hold gestures, use longpress <target> <durationMs> instead of press --hold-ms.",positionalArgs:["targetOrX","y?"],allowsExtraPositionals:!0,allowedFlags:[...rw,...ry]},longpress:{usageOverride:"longpress <x y|@ref|selector> [durationMs]",helpDescription:"Open native context menus or long-press targets by ref, selector, or point. Duration is positional, for example longpress @e12 800 or longpress 300 500 800.",positionalArgs:["targetOrX","yOrDurationMs?","durationMs?"],allowsExtraPositionals:!0,allowedFlags:[...ry]},swipe:{helpDescription:"Swipe coordinates with optional repeat pattern",positionalArgs:["x1","y1","x2","y2","durationMs?"],allowedFlags:["count","pauseMs","pattern"]},gesture:{usageOverride:"gesture <pan|fling|swipe|pinch|rotate|transform> ...",listUsageOverride:"gesture <pan|fling|swipe|pinch|rotate|transform> ...",helpDescription:'Run touch gestures: pan <x> <y> <dx> <dy> [durationMs], fling <up|down|left|right> <x> <y> [distance] [durationMs], swipe <left|right|left-edge|right-edge> [durationMs], pinch <scale> [x] [y], rotate <degrees> [x] [y] [velocity], or transform <x> <y> <dx> <dy> <scale> <degrees> [durationMs]. For command plans, output only command lines. Android transform verification should use all app-observable effects, for example wait text "pan changed yes", wait text "pinch changed yes", and wait text "rotate changed yes", not exact transform values.',summary:"Run pan, fling, swipe, pinch, rotate, or transform gestures",positionalArgs:["pan|fling|swipe|pinch|rotate|transform","args?"],allowsExtraPositionals:!0},focus:{positionalArgs:["x","y"]},type:{positionalArgs:["text"],allowsExtraPositionals:!0,allowedFlags:["delayMs"]},fill:{usageOverride:"fill <x> <y> <text> | fill <@ref|selector> <text>",positionalArgs:["targetOrX","yOrText","text?"],allowsExtraPositionals:!0,allowedFlags:[...ry,"delayMs"]},scroll:{usageOverride:"scroll <direction|top|bottom> [amount] [--pixels <n>]",helpDescription:"Scroll in a direction, or toward the top/bottom edge of scrollable content.",summary:"Scroll in a direction or to an edge",positionalArgs:["directionOrEdge","amount?"],allowedFlags:["pixels"]}},i4=[eW(i6("click"),(e,t)=>{var r;return e.interactions.click({...ev(r=t),...ew(r.target),...eS(r),...ex(r),button:r.button})}),eW(i6("press"),(e,t)=>{var r;return e.interactions.press({...ev(r=t),...ew(r.target),...eS(r),...ex(r)})}),eW(i6("fill"),(e,t)=>{var r;return e.interactions.fill({...ev(r=t),...ew(r.target),...eS(r),text:r.text,delayMs:r.delayMs})}),eW(i6("longpress"),(e,t)=>{var r;return e.interactions.longPress({...ev(r=t),...ew(r.target),...eS(r),durationMs:r.durationMs})}),eW(i6("swipe"),(e,t)=>e.interactions.swipe(t)),eW(i6("focus"),(e,t)=>e.interactions.focus(t)),eW(i6("type"),(e,t)=>e.interactions.type(t)),eW(i6("scroll"),(e,t)=>e.interactions.scroll(t)),eW(i6("get"),(e,t)=>{var r;return e.interactions.get({...ev(r=t),...function(e){switch(e.kind){case"ref":return{ref:e.ref,label:e.label};case"selector":return{selector:e.selector}}}(r.target),...eS(r),format:r.format})}),eW(i6("is"),(e,t)=>e.interactions.is(t)),eW(i6("find"),(e,t)=>e.interactions.find(t)),eW(i6("gesture"),async(e,t)=>{var r,n,i,a,s,o;switch(t.kind){case"pan":return await e.interactions.pan({...ev(r=t),x:r.origin.x,y:r.origin.y,dx:r.delta.x,dy:r.delta.y,durationMs:r.durationMs});case"fling":return await e.interactions.fling({...ev(n=t),direction:n.direction,x:n.origin.x,y:n.origin.y,distance:n.distance,durationMs:n.durationMs});case"swipe":return await e.interactions.swipeGesture({...ev(i=t),preset:i.preset,durationMs:i.durationMs});case"pinch":return await e.interactions.pinch({...ev(a=t),scale:a.scale,x:a.origin?.x,y:a.origin?.y});case"rotate":return await e.interactions.rotateGesture({...ev(s=t),degrees:s.degrees,x:s.origin?.x,y:s.origin?.y,velocity:s.velocity});case"transform":return await e.interactions.transformGesture({...ev(o=t),x:o.origin.x,y:o.origin.y,dx:o.delta.x,dy:o.delta.y,scale:o.scale,degrees:o.degrees,durationMs:o.durationMs})}})];function i6(e){let t=iB.find(t=>t.name===e);if(!t)throw Error(`Missing interaction command metadata for ${e}`);return t}function i9(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw new v("INVALID_ARGS",`${t} installSource must be an object.`);if("github-actions-artifact"!==at(e.type,`${t} installSource.type`))throw new v("INVALID_ARGS",`${t} installSource.type must be "github-actions-artifact".`);let{owner:r,repo:n}=ae(at(e.repo,`${t} installSource.repo`),`${t} installSource.repo`);return i7(r,n,e.artifact,`${t} installSource.artifact`)}function i7(e,t,r,n){var i;return"number"==typeof r||"string"==typeof(i=r)&&/^\d+$/.test(i.trim())?{kind:"github-actions-artifact",owner:e,repo:t,artifactId:function(e,t){let r="number"==typeof e?e:"string"==typeof e?Number(e):NaN;if(!Number.isInteger(r))throw new v("INVALID_ARGS",`${t} must be an integer.`);return r}(r,n)}:{kind:"github-actions-artifact",owner:e,repo:t,artifactName:at(r,n)}}function ae(e,t){let r=e.indexOf("/");if(r<=0||r===e.length-1||-1!==e.indexOf("/",r+1))throw new v("INVALID_ARGS",`${t} must use owner/repo.`);let n={owner:e.slice(0,r).trim(),repo:e.slice(r+1).trim()};if(!n.owner||!n.repo)throw new v("INVALID_ARGS",`${t} must use owner/repo.`);return n}function at(e,t){let r="string"==typeof e&&e.trim().length>0?e.trim():void 0;if(!r)throw new v("INVALID_ARGS",`${t} must be a non-empty string.`);return r}let ar=[rL("devices","List available devices.",{}),rL("boot","Boot or prepare a selected device without using CLI positional arguments.",{headless:Q("Boot without showing simulator UI when supported.")}),rL("shutdown","Shutdown a selected simulator or emulator.",{}),rL("prepare","Prepare platform helper infrastructure.",{action:W(Z(["ios-runner"])),timeoutMs:Y("Maximum wall-clock time for the prepare command.")}),rL("apps","List installed apps.",{appsFilter:Z(["user-installed","all"])}),rL("session","List active sessions or print daemon state directory.",{action:Z(["list","state-dir"],"list shows active sessions; state-dir prints the resolved daemon state directory without contacting the daemon.")}),rL("open","Open an app, deep link, URL, or platform surface.",{app:K("App name, bundle id, package, or URL."),url:K("Optional URL passed with an app shell."),surface:Z(t1),activity:K("Android activity name."),launchConsole:K("Launch console mode."),launchArgs:ee("Launch arguments forwarded verbatim to the platform launch command."),relaunch:Q("Force relaunch."),saveScript:et({oneOf:[H(),B()]}),deviceHub:Q("Use Xcode Device Hub when surfacing Apple simulators."),noRecord:Q("Do not record this action.")}),rL("close","Close an app or end the active session.",{app:K("Optional app to close."),shutdown:Q("Shutdown the session/device where supported."),saveScript:et({oneOf:[H(),B()]})}),rL("install","Install an app binary.",{app:W(K()),appPath:W(K("Path to app binary."))}),rL("reinstall","Reinstall an app binary.",{app:W(K()),appPath:W(K("Path to app binary."))}),rL("install-from-source","Install an app from a structured source.",{source:W(et(X("Install source object."))),retainPaths:Q(),retentionMs:Y()}),rL("push","Deliver a push payload.",{app:W(K()),payload:W(et({oneOf:[B(),X()]}))}),rL("trigger-app-event","Trigger an app-defined event.",{event:W(K()),payload:eD(X(void 0),function(e,t){let r=e[t];if(void 0!==r){if(!r||"object"!=typeof r||Array.isArray(r))throw Error(`Expected ${t} to be an object.`);return r}})})],an=[eW(aa("devices"),(e,t)=>e.devices.list(t)),eW(aa("boot"),(e,t)=>e.devices.boot(t)),eW(aa("shutdown"),(e,t)=>e.devices.shutdown(t)),eW(aa("apps"),(e,t)=>e.apps.list(t)),eW(aa("session"),async(e,{action:t,...r})=>"state-dir"===t?{stateDir:await e.sessions.stateDir(r)}:{sessions:await e.sessions.list(r)}),eW(aa("open"),(e,t)=>e.apps.open(t)),eW(aa("close"),(e,t)=>t.app?e.apps.close(t):e.sessions.close(function(e){let{app:t,...r}=e;return r}(t))),eW(aa("install"),(e,t)=>e.apps.install(t)),eW(aa("reinstall"),(e,t)=>e.apps.reinstall(t)),eW(aa("install-from-source"),(e,t)=>e.apps.installFromSource(t)),eW(aa("push"),(e,t)=>e.apps.push(t)),eW(aa("trigger-app-event"),(e,t)=>e.apps.triggerEvent(t)),eW(aa("prepare"),(e,t)=>e.command.prepare(t))],ai={boot:{summary:"Boot target device/simulator",allowedFlags:["headless"]},shutdown:{summary:"Shutdown target simulator/emulator"},prepare:{usageOverride:"prepare ios-runner --platform ios|macos [--timeout <ms>]",listUsageOverride:"prepare",helpDescription:"Prepare platform helper infrastructure. ios-runner builds/reuses, starts, and health-checks the XCTest runner so later Apple snapshots and interactions do not pay first-use startup cost. In CI, run it after boot/install and before replay/test; if replay/test starts a separate daemon, run clean:daemon after prepare to release the prepared runner lease. Runner build/start output is written to the session runner.log; daemon.log is for daemon lifecycle/startup issues.",summary:"Pre-warm platform helpers, especially the iOS/macOS XCTest runner before Apple automation",positionalArgs:["ios-runner"],allowedFlags:["timeoutMs"]},open:{helpDescription:'Boot device/simulator; optionally launch app or deep link URL. Use --platform to bind URL/deep-link opens to the target platform. For iOS simulator initial stdout/stderr, put --launch-console <path> on this open command, for example agent-device open "Agent Device Tester" --platform ios --launch-console artifacts/launch-console.log. Expo Go/dev-client shells accept host + URL, for example agent-device open "Expo Go" exp://127.0.0.1:8081 --platform ios. macOS also supports --surface app|frontmost-app|desktop|menubar.',summary:"Open an app, deep link or URL, save replays",positionalArgs:["appOrUrl?","url?"],allowedFlags:["activity","launchConsole","launchArgs","deviceHub","saveScript","noRecord","relaunch","surface"]},close:{positionalArgs:["app?"],allowedFlags:["saveScript","shutdown"]},reinstall:{positionalArgs:["app","path"]},install:{positionalArgs:["app","path"]},"install-from-source":{usageOverride:"install-from-source <url> | install-from-source --github-actions-artifact <owner/repo:artifact>",listUsageOverride:"install-from-source",helpDescription:"Install app builds from URLs, remote source specs, or CI artifacts resolved by a remote daemon.",summary:"Install app builds from URLs, remote source specs, or CI artifacts",positionalArgs:["url?"],allowedFlags:["header","githubActionsArtifact","installSource","retainPaths","retentionMs"]},apps:{helpDescription:"List user-installed apps; use --all to include system/OEM apps",summary:"List installed apps",allowedFlags:["appsFilter"],defaults:{appsFilter:I}},push:{listUsageOverride:"push",helpDescription:"Deliver push notification payloads to an installed app.",summary:"Deliver push notification payloads to an installed app",positionalArgs:["bundleOrPackage","payloadOrJson"]},"trigger-app-event":{usageOverride:"trigger-app-event <event> [payloadJson]",listUsageOverride:"trigger-app-event",helpDescription:"Invoke app-defined automation or test events with an optional structured payload.",summary:"Invoke app-defined automation/test events with optional structured payloads",positionalArgs:["event","payloadJson?"]},session:{usageOverride:"session list | session state-dir",listUsageOverride:"session",helpDescription:"List active sessions or print the effective daemon state directory",positionalArgs:["list|state-dir?"]}};function aa(e){let t=ar.find(t=>t.name===e);if(!t)throw Error(`Missing management command metadata for ${e}`);return t}let as={devices:(e,t)=>eR(t),apps:(e,t)=>({...eR(t),appsFilter:M(t.appsFilter)}),session:(e,t)=>({...eR(t),action:function(e){let t=e??"list";if("list"===t||"state-dir"===t)return t;throw new v("INVALID_ARGS","session only supports list or state-dir")}(e[0])}),boot:(e,t)=>({...eR(t),headless:t.headless}),shutdown:(e,t)=>eR(t),prepare:(e,t)=>({...eR(t),action:eH(e[0],"prepare requires subcommand"),timeoutMs:t.timeoutMs}),open:(e,t)=>({...eR(t),app:e[0],url:e[1],surface:t.surface,activity:t.activity,launchConsole:t.launchConsole,launchArgs:t.launchArgs,relaunch:t.relaunch,saveScript:t.saveScript,deviceHub:t.deviceHub,noRecord:t.noRecord}),close:(e,t)=>({...eR(t),app:e[0],shutdown:t.shutdown,saveScript:t.saveScript}),install:al,reinstall:al,"install-from-source":(e,t)=>({...eR(t),source:function(e,t){let r=e[0]?.trim();if(e.length>1)throw new v("INVALID_ARGS","install-from-source accepts either one <url> positional or --github-actions-artifact");let n=t.githubActionsArtifact?function(e,t="--github-actions-artifact"){let r=e.indexOf(":");if(r<=0||r===e.length-1)throw new v("INVALID_ARGS",`${t} must use owner/repo:artifact, for example thymikee/RNCLI83:6635342232`);let{owner:n,repo:i}=ae(e.slice(0,r),t);return i7(n,i,e.slice(r+1),`${t} artifact`)}(t.githubActionsArtifact):void 0,i=t.installSource;if(1!=+!!r+ +!!n+ +!!i)throw new v("INVALID_ARGS","install-from-source requires exactly one source: <url>, --github-actions-artifact, or config installSource");if(!r&&t.header&&t.header.length>0)throw new v("INVALID_ARGS","install-from-source --header is only supported for URL sources");return n||i||{kind:"url",url:r,headers:function(e){if(!e||0===e.length)return;let t={};for(let r of e){let e=r.indexOf(":");if(e<=0)throw new v("INVALID_ARGS",`Invalid --header value "${r}". Expected "name:value".`);let n=r.slice(0,e).trim(),i=r.slice(e+1).trim();if(!n)throw new v("INVALID_ARGS",`Invalid --header value "${r}". Header name cannot be empty.`);t[n]=i}return t}(t.header)}}(e,t),retainPaths:t.retainPaths,retentionMs:t.retentionMs}),push:(e,t)=>({...eR(t),app:eH(e[0],"push requires bundleOrPackage"),payload:eH(e[1],"push requires payloadOrJson")}),"trigger-app-event":(e,t)=>({...eR(t),event:eH(e[0],"trigger-app-event requires event"),payload:e[1]?function(e,t){try{let t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return t}catch{}throw new v("INVALID_ARGS",`${t} must be a JSON object`)}(e[1],"trigger-app-event payload"):void 0})},ao={devices:eL(D.devices),boot:eL(D.boot),shutdown:eL(D.shutdown),prepare:eL(D.prepare,e=>[eX(e.action,"prepare requires subcommand")]),apps:eL(D.apps),open:eL(D.open,function(e){return e.app?e.url?[e.app,e.url]:[e.app]:[]}),close:eL(D.close,e=>ez(e.app)),install:eL(D.install,e=>ac(e.app,e.appPath)),reinstall:eL(D.reinstall,e=>ac(e.app,e.appPath)),"install-from-source":e=>eN(S.installSource,[],{...e,installSource:e.source,retainMaterializedPaths:e.retainPaths,materializedPathRetentionMs:e.retentionMs}),push:eL(D.push,e=>{var t;return[(t=e).app,"string"==typeof t.payload?t.payload:JSON.stringify(t.payload)]}),"trigger-app-event":eL(D.triggerAppEvent,e=>{var t;return[(t=e).event,...t.payload?[JSON.stringify(t.payload)]:[]]})};function al(e,t,r="install"){return{...eR(t),app:eH(e[0],`${r} requires app`),appPath:eH(e[1],`${r} requires path`)}}function ac(e,t){return[eX(e,"missing first positional"),eX(t,"missing second positional")]}let au=["path","start","stop","doctor","mark","clear"],ap="logs",ad="network",am=rL(ap,"Manage session app logs.",{action:Z(au),message:K(),restart:Q()}),af=rL(ad,"Show recent HTTP traffic.",{action:Z(["dump","log"]),limit:Y(),include:Z(i)}),ah=[am,af],ag=[eW(am,(e,t)=>e.observability.logs(t)),eW(af,(e,t)=>e.observability.network(t))],ay={[ap]:{usageOverride:"logs path | logs start | logs stop | logs clear [--restart] | logs doctor | logs mark [message...]",helpDescription:"Session app log info, start/stop streaming, diagnostics, and markers",summary:"Manage session app logs",positionalArgs:["path|start|stop|clear|doctor|mark","message?"],allowsExtraPositionals:!0,allowedFlags:["restart"]},[ad]:{usageOverride:"network dump [limit] [summary|headers|body|all] [--include summary|headers|body|all] | network log [limit] [summary|headers|body|all] [--include summary|headers|body|all]",listUsageOverride:"network",helpDescription:"Dump recent HTTP(s) traffic parsed from the session app log",summary:"Inspect HTTP(S) traffic parsed from session app logs, including summaries, headers, and bodies",positionalArgs:["dump|log","limit?","include?"],allowedFlags:["networkInclude"]}},ab={logs:(e,t)=>({...eR(t),action:function(e){if(void 0!==e)return tZ(au,e,{message:"logs requires path, start, stop, doctor, mark, or clear"})}(e[0]),message:e.slice(1).join(" ")||void 0,restart:t.restart}),network:(e,t)=>({...eR(t),action:function(e){if(void 0!==e){if("dump"===e||"log"===e)return e;throw new v("INVALID_ARGS","network requires dump or log")}}(e[0]),limit:eG(e[1]),include:t.networkInclude??function(e){if(void 0!==e)return tZ(i,e,{message:"network include must be summary, headers, body, or all"})}(e[2])})},av={logs:eL(ap,e=>{var t;return[(t=e).action??"path",...ez(t.message)]}),network:e=>{var t;return eN(ad,[...(t=e).action?[t.action]:[],...eB(t.limit)],{...e,networkInclude:e.include})}},aw="perf",ax=rL(aw,"Show session performance, frame health, and memory diagnostics.",{area:Z(t5),subject:Z(t4),action:Z(t8),kind:Z(t6),template:K("xctrace template name, for example Time Profiler."),out:K("Output artifact path."),tracePath:K("Existing .trace path to report, defaults to the latest session trace.")}),aS=[ax],ak=[eW(ax,(e,t)=>e.observability.perf(t))],aD={[aw]:{usageOverride:"perf metrics --json\n agent-device perf frames --json\n agent-device perf memory sample --json\n agent-device perf memory snapshot [--kind android-hprof|memgraph] [--out <path>]\n agent-device perf cpu profile start --kind xctrace [--template <name>] --out <profile.trace>\n agent-device perf cpu profile stop --kind xctrace --out <profile.trace>\n agent-device perf cpu profile report --kind xctrace --out <report.json>\n agent-device perf trace start|stop --kind xctrace [--template <name>] --out <path>\n agent-device perf cpu profile start --kind simpleperf --out <cpu.perf.data>\n agent-device perf cpu profile stop --kind simpleperf\n agent-device perf cpu profile report --kind simpleperf --out <cpu-report.json>\n agent-device perf trace start|stop --kind perfetto [--out <path>]",listUsageOverride:"perf",helpDescription:"Show session performance metrics, focused frame/jank health, memory diagnostics artifacts, Apple xctrace artifacts, or Android native Simpleperf/Perfetto artifacts. Prefer explicit perf metrics --json for first-pass startup/CPU/memory data. For CPU profiles, start/stop write the raw artifact and report writes a compact .json summary; include report after simpleperf stop when the task needs agent-readable native CPU evidence. Bare perf and metrics remain aliases. Native perf output is agent evidence: compact state, artifact path, and size only; raw profiles/traces stay on disk.",summary:"Check runtime metrics, frames, memory, CPU profiles, or native trace artifacts",positionalArgs:["area?","subjectOrAction?","action?"],allowedFlags:["kind","perfTemplate","out"]}},aA={perf:(e,t)=>{var r;return{...eR(t),...function(e,t={}){if(void 0!==e[0]&&void 0===e[1]){let r=aL(e[0],{allowUndefined:!0});if(r)return{action:r,kind:aN(t.kind),out:t.out}}let r=function(e){if(void 0===e)return;let t=e.toLowerCase();if(rl(t))return t;throw new v("INVALID_ARGS",rn)}(e[0]);return"cpu"===r?{area:r,subject:function(e){let t=e?.toLowerCase();if(void 0!==t&&ru(t))return t;throw new v("INVALID_ARGS",ra)}(e[1]),action:aL(e[2]),kind:aN(t.kind),template:t.template,out:t.out}:"trace"===r?{area:r,action:aL(e[1]),kind:aN(t.kind),template:t.template,out:t.out}:{area:r,action:aL(e[1]),kind:aN(t.kind),out:t.out}}(e,{kind:"string"==typeof(r=t.kind)?aN(r):void 0,template:t.perfTemplate,out:t.out})}}},aI={perf:eL(aw,e=>{var t;let r;return"cpu"===(r=(t=e).area??(t.action?"metrics":void 0))?aM([...ez(r),...ez(t.subject),...ez(t.action),...ez(t.kind)],t):"trace"===r?aM([...ez(r),...ez(t.action),...ez(t.kind)],t):[...ez(r),...ez(t.action)]})};function aM(e,t){let r=[...e];return(t.template||t.out||t.tracePath)&&r.push(t.template??""),(t.out||t.tracePath)&&r.push(t.out??""),t.tracePath&&r.push(t.tracePath),r}function aL(e,t={}){if(void 0===e)return;let r=e.toLowerCase();if(rc(r))return r;if(!t.allowUndefined)throw new v("INVALID_ARGS",ri)}function aN(e){if(void 0===e)return;let t=e.toLowerCase();if(rp(t))return t;throw new v("INVALID_ARGS",rs)}let aR=/\b(logbox|redbox|reload js|copy stack|component stack|call stack|runtime error|open debugger to view warnings)\b/,aO=/\b(redbox|runtime error|reload js|copy stack|component stack|call stack)\b/,aE=[/\b[\w.$<>/-]+\.(?:tsx?|jsx?):\d+(?::\d+)?\b/,/\b[\w.$<>/-]+\.(?:tsx?|jsx?)\s+\(\d+:\d+\)/],aP=[/^!,\s+/,/^(warn|warning|error):\s+/,/\b(?:possible\s+)?unhandled (?:promise )?rejection\b/],a_=["open debugger to view warnings","getsnapshot should be cached to avoid an infinite loop",'unique "key" prop',"unique 'key' prop","virtualizedlists should never be nested","failed prop type"],aC=new Set(["x","\xd7","✕","✖","⨯"]);function aT(e){if(a$(e).detected)return"Hint: React Native warning/error overlay detected. It overlays part of the app and should be handled before interacting.\nRun: agent-device react-native dismiss-overlay\nThe command verifies the overlay is gone. Run agent-device snapshot -i afterward only when you need fresh refs for the next action."}function aF(e){return a$(e)}function a$(e){var t,n,i,a,s,o,l,c,u,p;let d,m,f,h,g,y,b,v,w=(d=(t=e).map(aq).join("\n").toLowerCase(),m=aQ(t,aH),f=aQ(t,aW),h=aQ(t,az,aK),g=aQ(t,aB),y=(n=d,aE.some(e=>e.test(n))),b=aG(d),v=(i=d,a=m,s=f,a.length>0||s.length>0||/\b(reload js|copy stack)\b/.test(i)),{dismissNodes:m,minimizeNodes:f,collapsedNodes:h,redBox:(o=d,l=y,c=v,aO.test(o)||aG(o)||l&&c),detected:(u={text:d,hasReactNativeStackFrame:y,hasOverlayControl:v,hasControllessRedBoxText:b,collapsedNodes:h,openDebuggerWarningNodes:g}).collapsedNodes.length>0||u.openDebuggerWarningNodes.length>0||u.hasControllessRedBoxText||u.hasOverlayControl&&(p=u.text,aR.test(p)||u.hasReactNativeStackFrame)}),x=w.detected?function(e){let t=a0(e.dismissNodes,aZ);if(t){let e;var n,i=t,a=(n=t,(e=a2(n)?.trim().toLowerCase())&&aX(e)?"dismiss":"close");if(!i.rect)throw Error("React Native overlay target node must have rect");return{action:a,point:r(i.rect),rect:i.rect,ref:i.ref,label:a2(i)}}let s=a0(e.collapsedNodes.filter(aJ),a1);return s?.rect?{action:"close-collapsed-banner",point:function(e){var t,r;if(!e.rect)throw Error("Collapsed React Native warning node must have rect");let n=Math.min(e.rect.height,52),i=Math.min(36,Math.max(18,.45*n));return{x:Math.round((t=e.rect.x+e.rect.width-i,r=e.rect.x+1,Math.min(e.rect.x+e.rect.width-1,Math.max(r,t)))),y:Math.round(e.rect.y+n/2)}}(s),rect:s.rect,ref:s.ref,label:a2(s)}:null}(w):null;return{detected:w.detected,redBox:w.redBox,dismissNodes:w.dismissNodes,minimizeNodes:w.minimizeNodes,collapsedNodes:w.collapsedNodes,primaryAction:x}}function aU(e){return[...e.dismissNodes,...e.minimizeNodes,...e.collapsedNodes]}function aj(e){var t;return az(e.label?.trim())&&!!(t=e.rect)&&t.x<=1&&t.y<=1&&t.width>=300&&t.height>=600}function aV(e,t){let r=e.label?.trim();return!!r&&!!aj(e)&&t.some(e=>e.label?.trim()===r&&aY(e))}function aq(e){return[e.label,e.value,e.identifier,e.type,e.role].filter(Boolean).join(" ")}function aG(e){return/\buncaught\b/.test(e)&&/unable to download asset/.test(e)}function az(e){let t=e?.trim().toLowerCase();return!!t&&(a_.some(e=>t.includes(e))||aP.some(e=>e.test(t)))}function aB(e){return e.includes("open debugger to view warnings")||/^!,\s+open debugger\b/.test(e)}function aH(e){var t,r;return aX(e)||(t=e,/^close(?:\s*\([^)]*\))?$/i.test(t))||(r=e,aC.has(r))}function aX(e){return/^dismiss(?:\s*\([^)]*\))?$/i.test(e)}function aW(e){return/^minimi[sz]e(?:\b|\s|\()/i.test(e)}function aK(e){return!e.rect||e.rect.height<=180}function aJ(e){let t=a2(e)?.trim().toLowerCase()??"";return(aB(t)||/^!,\s+/.test(t))&&aY(e)}function aY(e){return!!e.rect&&e.rect.width>=120&&e.rect.height>=36&&e.rect.height<=180}function aQ(e,t,r=()=>!0){let n=[];for(let i of e)i.ref&&r(i)&&[i.label,i.value,i.identifier].map(e=>e?.trim().toLowerCase()).filter(e=>!!e).some(e=>t(e))&&n.push(i);return n}function aZ(e){var t;let r;return[+(!0===(r=[e.type,e.role,e.subrole].join(" ").toLowerCase(),/\b(button|menuitem|link)\b/.test(r))),+(!0===e.hittable),-((t=e.rect)?t.width*t.height:1/0)]}function a0(e,t){let r=e.filter(e=>e.rect);return 0===r.length?null:r.sort((e,r)=>(function(e,t){for(let r=0;r<e.length;r+=1){let n=e[r]-t[r];if(0!==n)return n}return 0})(t(r),t(e)))[0]??null}function a1(e){return[+(!0===e.hittable),e.rect?.width??0,e.rect?.y??0]}function a2(e){return e.label??e.value??e.identifier}let a3="react-native",a5=rL(a3,"Run supported React Native app automation helpers.",{action:W(Z(["dismiss-overlay"]))}),a8=eW(a5,(e,t)=>e.command.reactNative(t)),a4={[a3]:{usageOverride:"react-native dismiss-overlay",listUsageOverride:"react-native dismiss-overlay",positionalArgs:["dismiss-overlay"]}},a6={"react-native":(e,t)=>({...eR(t),action:function(e){if("dismiss-overlay"===e)return e;throw new v("INVALID_ARGS","react-native supports only: dismiss-overlay")}(e[0])})},a9={"react-native":eL(a3,e=>[eX(e.action,"react-native requires action")])},a7=["medium","high"];function se(e){var t;let r;if(a7.includes(e))return e;let n=void 0!==(r="number"==typeof e?e:"string"==typeof(t=e)&&/^\d+$/.test(t)?Number(t):void 0)&&Number.isInteger(r)&&r>=5&&r<=10?r:void 0;if(void 0!==n)return n<=7?"medium":"high"}let st="record",sr="trace",sn=["start","stop"],si=rL(st,"Start or stop screen recording.",{action:W(Z(sn)),path:K(),fps:Y(),maxSize:Y(),quality:Z(a7),hideTouches:Q()}),sa=rL(sr,"Start or stop trace capture.",{action:W(Z(sn)),path:K()}),ss=[si,sa],so=[eW(si,(e,t)=>e.recording.record(t)),eW(sa,(e,t)=>e.recording.trace(t))],sl={[st]:{usageOverride:"record start [path] [--fps <n>] [--max-size <px>] [--quality <medium|high>] [--hide-touches] | record stop",listUsageOverride:"record start [path] | record stop",helpDescription:"Start/stop screen recording; Android recordings longer than the 180s adb screenrecord limit are returned as multiple MP4 chunks. Use --max-size to limit dimensions and --quality to choose medium or high export quality",summary:"Start or stop screen recording",positionalArgs:["start|stop","path?"],allowedFlags:["fps","screenshotMaxSize","quality","hideTouches"]},[sr]:{usageOverride:"trace start <path> | trace stop <path>",listUsageOverride:"trace start <path> | trace stop <path>",helpDescription:"Start/stop trace log capture; when an artifact path is requested, pass the same positional path to start and stop",summary:"Start or stop trace capture",positionalArgs:["start|stop","path?"]}},sc={record:(e,t)=>({...eR(t),action:sd(e[0],st),path:e[1],fps:t.fps,maxSize:t.screenshotMaxSize,quality:t.quality,hideTouches:t.hideTouches}),trace:(e,t)=>({...eR(t),action:sd(e[0],sr),path:e[1]})},su={record:eL(st,e=>sp(e)),trace:eL(sr,e=>sp(e))};function sp(e){return[e.action,...ez(e.path)]}function sd(e,t){if("start"===e||"stop"===e)return e;throw new v("INVALID_ARGS",`${t} requires start|stop`)}let sm="replay",sf="test",sh="Replay a recorded session.",sg=rL(sm,sh,{path:W(K()),update:Q(),backend:K(),maestro:Q(),env:ee()}),sy=rL(sf,"Run one or more replay scripts.",{paths:W(ee()),update:Q(),backend:K(),maestro:Q(),env:ee(),failFast:Q(),timeoutMs:Y(),retries:Y(),recordVideo:Q(),artifactsDir:K(),reportJunit:K(),shardAll:Y(),shardSplit:Y()}),sb=[sg,sy],sv=[eW(sg,(e,t)=>e.replay.run(t)),eW(sy,(e,t)=>e.replay.test(t))],sw={[sm]:{usageOverride:"replay <path> | replay export <file.ad> [--format maestro] [--out <path>]",helpDescription:"Replay a recorded session. For Maestro YAML compatibility flows, use replay <flow.yaml> --maestro and keep the target binding such as --platform ios on the replay command.",summary:sh,positionalArgs:["path"],allowsExtraPositionals:!0,allowedFlags:["replayMaestro","replayExportFormat",...rx,"timeoutMs","out"]},[sf]:{usageOverride:"test <path-or-glob>...",listUsageOverride:"test <path-or-glob>...",helpDescription:"Run one or more replay scripts as a serial test suite",summary:"Run replay test suites",positionalArgs:["pathOrGlob"],allowsExtraPositionals:!0,allowedFlags:["replayMaestro",...rx,"failFast","timeoutMs","retries","recordVideo","artifactsDir","reportJunit","shardAll","shardSplit"]}},sx={replay:(e,t)=>({...eR(t),path:eH(e[0],"replay requires path"),update:t.replayUpdate,backend:t.replayMaestro?"maestro":void 0,env:t.replayEnv}),test:(e,t)=>({...eR(t),paths:e,update:t.replayUpdate,backend:t.replayMaestro?"maestro":void 0,env:t.replayEnv,failFast:t.failFast,timeoutMs:t.timeoutMs,retries:t.retries,recordVideo:t.recordVideo,artifactsDir:t.artifactsDir,reportJunit:t.reportJunit,shardAll:t.shardAll,shardSplit:t.shardSplit})},sS={replay:e=>eN(sm,[eX(e.path,"replay requires path")],{...e,replayUpdate:e.update,replayBackend:sk(e),replayEnv:e.env,replayShellEnv:sD(process.env)}),test:e=>eN(sf,e.paths??[],{...e,replayUpdate:e.update,replayBackend:sk(e),replayEnv:e.env,replayShellEnv:sD(process.env)})};function sk(e){return e.backend??(!0===e.maestro?"maestro":void 0)}function sD(e){let t={};for(let[r,n]of Object.entries(e))"string"==typeof n&&r.startsWith("AD_VAR_")&&(t[r]=n);return t}function sA(e){if(void 0===e)throw new v("INVALID_ARGS","rotate requires an orientation argument. Use portrait|portrait-upside-down|landscape-left|landscape-right.");switch(e?.trim().toLowerCase()){case"portrait":return"portrait";case"portrait-upside-down":case"upside-down":return"portrait-upside-down";case"landscape-left":case"left":return"landscape-left";case"landscape-right":case"right":return"landscape-right";default:throw new v("INVALID_ARGS",`Invalid rotation: ${e}. Use portrait|portrait-upside-down|landscape-left|landscape-right.`)}}let sI="appstate",sM="back",sL="home",sN="rotate",sR="app-switcher",sO="keyboard",sE="clipboard",sP=rL(sI,"Show foreground app or activity.",{}),s_=rL(sM,"Navigate back.",{mode:Z(["in-app","system"])}),sC=rL(sL,"Go to the home screen.",{}),sT=rL(sN,"Rotate device orientation.",{orientation:W(Z(["portrait","portrait-upside-down","landscape-left","landscape-right"]))}),sF=rL(sR,"Open the app switcher.",{}),s$=rL(sO,"Inspect or dismiss the keyboard.",{action:Z(["status","dismiss"])}),sU=rL(sE,"Read or write clipboard text.",{action:W(Z(["read","write"])),text:K()}),sj=[sP,s_,sC,sT,sF,s$,sU],sV=[eW(sP,(e,t)=>e.command.appState(t)),eW(s_,(e,t)=>e.command.back(t)),eW(sC,(e,t)=>e.command.home(t)),eW(sT,(e,t)=>e.command.rotate(t)),eW(sF,(e,t)=>e.command.appSwitcher(t)),eW(s$,(e,t)=>e.command.keyboard(t)),eW(sU,(e,t)=>e.command.clipboard(t))],sq={[sI]:{helpDescription:"Show foreground app/activity"},[sM]:{usageOverride:"back [--in-app|--system]",allowedFlags:["backMode"]},[sN]:{usageOverride:"rotate <portrait|portrait-upside-down|landscape-left|landscape-right>",helpDescription:"Rotate device orientation on iOS and Android",positionalArgs:["orientation"]},[sO]:{usageOverride:"keyboard [status|get|dismiss|enter|return]",helpDescription:"Inspect Android keyboard visibility/type or press/dismiss the device keyboard. For iOS toolbar Done dismissal, focus the field by id/ref first, then run keyboard dismiss; do not manually press Done unless keyboard dismiss reports unsupported.",summary:"Inspect, press, or dismiss the device keyboard",positionalArgs:["action?"]},[sE]:{usageOverride:"clipboard read | clipboard write <text>",listUsageOverride:"clipboard read | clipboard write <text>",helpDescription:"Read or write device clipboard text",positionalArgs:["read|write","text?"],allowsExtraPositionals:!0}},sG={appstate:(e,t)=>eR(t),home:(e,t)=>eR(t),"app-switcher":(e,t)=>eR(t),back:(e,t)=>({...eR(t),mode:t.backMode}),rotate:(e,t)=>({...eR(t),orientation:sA(e[0])}),keyboard:(e,t)=>({...eR(t),...function(e){if(e.length>1)throw new v("INVALID_ARGS","keyboard accepts at most one action argument.");return ek({action:function(e){let t=e?.toLowerCase();if("get"===t)return"status";if(void 0===t||"status"===t||"dismiss"===t||"enter"===t||"return"===t)return t;throw new v("INVALID_ARGS","keyboard action must be status, get, dismiss, enter, or return.")}(e[0])})}(e)}),clipboard:(e,t)=>({...eR(t),...function(e){let t=e[0]?.toLowerCase();if("read"!==t&&"write"!==t)throw new v("INVALID_ARGS","clipboard requires a subcommand: read or write.");if("read"===t){if(1!==e.length)throw new v("INVALID_ARGS","clipboard read does not accept additional arguments.");return{action:t}}if(e.length<2)throw new v("INVALID_ARGS","clipboard write requires text.");return{action:t,text:e.slice(1).join(" ")}}(e)})},sz={appstate:eL(sI),back:e=>{var t;return eN(sM,[],{...e,backMode:"in-app"===(t=e.mode)||"system"===t?t:void 0})},home:eL(sL),rotate:eL(sN,e=>[eX(e.orientation,"rotate requires orientation")]),"app-switcher":eL(sR),keyboard:eL(sO,e=>ez(e.action)),clipboard:eL(sE,e=>{var t;return"read"===(t=e).action?["read"]:["write",t.text]})};export{rk as COMMON_COMMAND_SUPPORTED_FLAG_KEYS,rD as GLOBAL_FLAG_KEYS,au as LOG_ACTION_VALUES,rm as MAESTRO_COMPAT_TRACKER_URL,rf as MAESTRO_NEW_ISSUE_URL,rb as METRO_PREPARE_FLAGS,rv as METRO_RELOAD_FLAGS,ri as PERF_ACTION_ERROR_MESSAGE,rn as PERF_AREA_ERROR_MESSAGE,rs as PERF_KIND_ERROR_MESSAGE,ro as PERF_MEMORY_KIND_ERROR_MESSAGE,ra as PERF_SUBJECT_ERROR_MESSAGE,a7 as RECORDING_EXPORT_QUALITIES,eK as SCREENSHOT_ACTION_FLAG_KEYS,nh as SCROLL_DIRECTIONS,rq as SETTINGS_INVALID_ARGS_MESSAGE,ny as SWIPE_PATTERNS,a$ as analyzeReactNativeOverlay,n2 as annotateCoveredSnapshotNodes,as as appCliReaders,ao as appDaemonWriters,eQ as appendScreenshotScriptFlags,nY as areRectsApproximatelyEqual,nx as assertScrollGestureInput,tK as batchCliReaders,tW as batchCliSchemas,tX as batchCommandDefinition,tH as batchCommandMetadata,Q as booleanField,tq as buildFlags,tG as buildMeta,T as buildMobileSnapshotPresentation,nw as buildScrollGesturePlan,nS as buildSwipeGesturePlan,nk as buildSwipePresetGesturePlan,nf as buttonTag,nc as captureCliReaders,nl as captureCliSchemas,no as captureCommandDefinitions,ns as captureCommandMetadata,nu as captureDaemonWriters,nC as captureScrollEdgeState,nM as clampGesturePoint,nP as clampToRange,eR as commonInputFromFlags,tB as createBatchDaemonWriter,eW as defineExecutableCommand,rL as defineFieldCommandMetadata,F as deriveMobileSnapshotHiddenContentHints,aF as detectReactNativeOverlay,R as displayNodeLabel,Z as enumField,ib as focusCommand,aT as formatReactNativeOverlayWarning,nF as formatScrollEdgeMessage,iW as gestureCliReaders,iK as gestureDaemonWriters,nm as getClickButtonValidationError,rI as getFlagDefinition,rM as getFlagDefinitions,rz as getUnsupportedMacOsSettingMessage,nA as inferGestureReferenceFrame,E as inferVerticalScrollIndicatorDirections,Y as integerField,i0 as interactionCliReaders,i8 as interactionCliSchemas,i4 as interactionCommandDefinitions,iB as interactionCommandMetadata,i1 as interactionDaemonWriters,rG as isMacOsSettingSupported,U as isNodeVisibleInEffectiveViewport,rc as isPerfAction,rl as isPerfArea,rp as isPerfKind,rd as isPerfMemoryKind,ru as isPerfSubject,aj as isReactNativeCollapsedWarningWrapperCandidate,aV as isReactNativeCollapsedWarningWrapperWithVisibleBanner,n3 as isSnapshotNodeInteractionBlocked,e8 as isSparseSnapshotQualityVerdict,tQ as isStringMember,O as isSystemScrollIndicatorLabel,et as jsonSchemaField,iv as longPressCommand,ai as managementCliSchemas,an as managementCommandDefinitions,ar as managementCommandMetadata,tR as normalizeDeployResult,tP as normalizeDevice,tO as normalizeInstallFromSourceResult,tE as normalizeMaterializationReleaseResult,t$ as normalizeOpenDevice,tF as normalizeRuntimeHints,t_ as normalizeSession,L as normalizeSnapshotTree,tU as normalizeStartupSample,nB as now,ab as observabilityCliReaders,ay as observabilityCliSchemas,ag as observabilityCommandDefinitions,ah as observabilityCommandMetadata,av as observabilityDaemonWriters,sA as parseDeviceRotation,i9 as parseInstallSourceConfig,nL as parseScrollDirection,t3 as parseSessionSurface,tZ as parseStringMember,nD as parseSwipePreset,tJ as parseTimeout,tY as parseWaitPositionals,tL as parsing_stripUndefined,aA as perfCliReaders,aD as perfCliSchemas,ak as perfCommandDefinitions,aS as perfCommandMetadataList,aI as perfDaemonWriters,ik as pinchCommand,nI as pointFromPercent,nQ as pointInsideRect,e9 as publicSnapshotCaptureAnnotations,a6 as reactNativeCliReaders,a4 as reactNativeCliSchemas,a8 as reactNativeCommandDefinition,a5 as reactNativeCommandMetadata,a9 as reactNativeDaemonWriters,tr as readCommandMessage,iQ as readFillTargetFromPositionals,rB as readLocationCoordinate,ty as readOptionalString,aU as readReactNativeOverlayActionNodes,tg as readRequiredString,tV as readScreenshotOverlayRefs,eZ as readScreenshotScriptFlag,e7 as readSerializedSnapshotCaptureAnnotations,tj as readSnapshotNodes,e5 as readSnapshotQualityVerdict,sc as recordingCliReaders,sl as recordingCliSchemas,so as recordingCommandDefinitions,ss as recordingCommandMetadata,su as recordingDaemonWriters,se as recordingQualityInputToExportQuality,e4 as renderSnapshotQualityWarnings,sx as replayCliReaders,sw as replayCliSchemas,sv as replayCommandDefinitions,sb as replayCommandMetadataList,sS as replayDaemonWriters,n_ as requireIntInRange,rH as requireLocationCoordinates,W as requiredField,n7 as resolveActionableTouchNode,ie as resolveActionableTouchResolution,nd as resolveClickButton,tl as resolveDeployResultTarget,tu as resolveInstallFromSourceResultTarget,ir as resolveInteractionTarget,nK as resolveRectCenter,tz as resolveSessionName,nT as runScrollEdgePasses,eY as screenshotFlagsFromOptions,eJ as screenshotOptionsFromFlags,iw as scrollCommand,i2 as selectorCliReaders,i3 as selectorDaemonWriters,tm as serializeCloseResult,tc as serializeDeployResult,to as serializeDevice,tp as serializeInstallFromSourceResult,td as serializeOpenResult,ts as serializeSessionListEntry,tf as serializeSnapshotResult,nH as sleep,e6 as snapshotCaptureAnnotationsFrom,tN as splitNonEmptyTrimmedLines,K as stringField,B as stringSchema,te as successText,ix as swipeCommand,sG as systemCliReaders,sq as systemCliSchemas,sV as systemCommandDefinitions,sj as systemCommandMetadata,sz as systemDaemonWriters,nz as toBackendContext,nX as toBackendResult,tt as withSuccessText};
@@ -0,0 +1,6 @@
1
+ import e from"node:fs";import t from"node:http";import a from"node:https";import r from"node:path";import{pipeline as n}from"node:stream/promises";import i from"node:os";import{createHash as o,randomUUID as s}from"node:crypto";import{Writable as l}from"node:stream";import d from"node:net";import c from"node:fs/promises";import{toAppErrorCode as u,AppError as f}from"./733.js";import{runCmdDetachedMonitored as p,runCmd as m,runCmdSync as h}from"./8875.js";import{createRequestId as y,withDiagnosticTimer as w,emitDiagnostic as g}from"./432.js";import{isAgentDeviceDaemonProcess as I,stopProcessForTakeover as v}from"./5628.js";import{readSnapshotDiagnosticsSummary as b,consumeTextLines as A,shellQuote as S,shouldStreamRequestProgress as _,isDaemonResponseEnvelope as M,isDaemonProgressEnvelope as D,resolveDaemonPaths as P,resolveDaemonServerMode as k,computeDaemonCodeSignature as x,resolveDaemonTransportPreference as E}from"./2892.js";import{colorize as N,supportsColor as $}from"./6311.js";import{INTERNAL_COMMANDS as T,PUBLIC_COMMANDS as C}from"./2133.js";import{readVersion as U,findProjectRoot as L}from"./7244.js";import{sleep as R}from"./5560.js";import{normalizeSession as O,readRequiredString as F,readSerializedSnapshotCaptureAnnotations as B,readOptionalString as j,normalizeMaterializationReleaseResult as q,readSnapshotNodes as K,normalizeDeployResult as V,appDaemonWriters as G,observabilityDaemonWriters as H,normalizeOpenDevice as z,replayDaemonWriters as Y,buildMeta as W,systemDaemonWriters as J,resolveSessionName as X,buildFlags as Q,reactNativeDaemonWriters as Z,interactionDaemonWriters as ee,captureDaemonWriters as et,perfDaemonWriters as ea,gestureDaemonWriters as er,selectorDaemonWriters as en,createBatchDaemonWriter as ei,normalizeRuntimeHints as eo,normalizeDevice as es,recordingDaemonWriters as el,readScreenshotOverlayRefs as ed,normalizeStartupSample as ec,normalizeInstallFromSourceResult as eu}from"./9873.js";import{reloadMetro as ef,prepareMetroRuntime as ep}from"./8275.js";function em(e){return new Promise((t,a)=>{let r="";e.setEncoding("utf8"),e.on("data",e=>{r+=e}),e.on("end",()=>t(r)),e.on("error",a)})}let eh="sha256";async function ey(e){let t=await ew(e.localPath,e.platform),a=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;try{let r=await eb({normalizedBase:a,token:e.token,artifact:t});if(r?.kind==="cache-hit")return r.uploadId;if(r?.kind==="direct-upload")try{return await eA(t.payloadPath,r),await eD({normalizedBase:a,token:e.token,uploadId:r.uploadId})}catch{}return await ev({normalizedBase:a,token:e.token,artifact:t})}finally{t.cleanup()}}async function ew(t,a){var n,i,o;let s,l=e.statSync(t),d=r.basename(t),c=l.isDirectory(),u=("ios"===(n=a)||"android"===n?n:void 0)??(i=t,o=l,s=i.toLowerCase(),o.isDirectory()&&s.endsWith(".app")||s.endsWith(".ipa")?"ios":s.endsWith(".apk")||s.endsWith(".aab")?"android":void 0),f=[];try{let a=c?await eg(t,f):t,r=e.statSync(a);return{payloadPath:a,fileName:d,artifactType:c?"app-bundle":"file",platform:u,contentType:c?"application/gzip":"application/octet-stream",sha256:await eP(a),sizeBytes:r.size,cleanup:()=>eI(f)}}catch(e){throw eI(f),e}}async function eg(t,a){let n=e.mkdtempSync(r.join(i.tmpdir(),`agent-device-upload-${s()}-`));a.push(n);let o=r.join(n,`${r.basename(t)}.tar.gz`);return await m("tar",["czf",o,"-C",r.dirname(t),r.basename(t)],{env:{...process.env,COPYFILE_DISABLE:"1"}}),o}function eI(t){for(let a of t)e.rmSync(a,{recursive:!0,force:!0})}async function ev(e){let{normalizedBase:t,token:a,artifact:r}=e,n=new URL("upload",t),i={"content-type":r.contentType,"x-artifact-type":r.artifactType,"x-artifact-filename":r.fileName,"x-artifact-hash":r.sha256,"x-artifact-hash-algorithm":eh,"transfer-encoding":"chunked"};a&&(i.authorization=`Bearer ${a}`,i["x-agent-device-token"]=a);let o=await eS({url:n,method:"POST",headers:i,payloadPath:r.payloadPath,timeoutMessage:"Artifact upload timed out",timeoutHint:"The upload to the remote daemon exceeded the 5-minute timeout.",errorMessage:"Failed to upload artifact to remote daemon",errorHint:"Verify the remote daemon is reachable and supports artifact uploads."});try{let e=JSON.parse(o.body);if(!e.ok||!e.uploadId)throw new f("COMMAND_FAILED",`Upload failed: ${o.body}`);return e.uploadId}catch(e){if(e instanceof f)throw e;throw new f("COMMAND_FAILED",`Invalid upload response: ${o.body}`)}}async function eb(e){let t=new URL("upload/preflight",e.normalizedBase),a={"content-type":"application/json"};e.token&&(a.authorization=`Bearer ${e.token}`,a["x-agent-device-token"]=e.token);let r=await fetch(t,{method:"POST",headers:a,signal:AbortSignal.timeout(3e4),body:JSON.stringify({sha256:e.artifact.sha256,fileName:e.artifact.fileName,sizeBytes:e.artifact.sizeBytes,artifactType:e.artifact.artifactType,...e.artifact.platform?{platform:e.artifact.platform}:{},contentType:e.artifact.contentType})}).catch(()=>void 0);if(r?.ok)return function(e){var t;if(!e||"object"!=typeof e||!0!==e.ok||"string"!=typeof e.uploadId)return;if(!0===e.cacheHit)return{kind:"cache-hit",uploadId:e.uploadId};let a=e.upload;if(!a||"string"!=typeof a.url)return;let r=a.headers??{};if(!(!(t=r)||"object"!=typeof t||Array.isArray(t))&&Object.values(t).every(e=>"string"==typeof e))return{kind:"direct-upload",uploadId:e.uploadId,url:a.url,headers:r}}(await r.json().catch(()=>void 0))}async function eA(e,t){let a=await eS({url:new URL(t.url),method:"PUT",headers:t.headers,payloadPath:e,timeoutMessage:"Direct artifact upload timed out",timeoutHint:"The direct upload ticket did not accept the artifact within the timeout.",errorMessage:"Failed to upload artifact with direct upload ticket"});if(a.statusCode<200||a.statusCode>=300)throw new f("COMMAND_FAILED","Direct artifact upload failed",{statusCode:a.statusCode,statusMessage:a.statusMessage})}async function eS(e){return await e_({...e,url:e.url,redirectCount:0,startOffset:0})}async function e_(r){var i,o,s;let l="https:"===r.url.protocol?a:t,d=e.statSync(r.payloadPath).size,c=(i=r.headers,o=r.startOffset,s=d,o<=0?i:{...i,"content-length":Math.max(s-o,0),"content-range":`bytes ${o}-${s-1}/${s}`});return await new Promise((t,a)=>{let i=!1,o=l.request({protocol:r.url.protocol,host:r.url.hostname,port:r.url.port,method:r.method,path:r.url.pathname+r.url.search,headers:c},e=>{i=!0,em(e).then(n=>{clearTimeout(s);let i=e.statusCode??500,o=e.headers.location;if(o&&[301,302,303,307,308].includes(i)){if(r.redirectCount>=5)return void a(new f("COMMAND_FAILED","Artifact upload exceeded redirect limit",{maxRedirects:5,url:r.url.toString()}));let e=new URL(o,r.url);return void e_({...r,url:e,redirectCount:r.redirectCount+1}).then(t,a)}let l=308===i?function(e,t){let a=function(e){let t=eM(e);if(void 0===t)return;let a=Number(t);return Number.isSafeInteger(a)&&a>=0?a:void 0}(e["x-upload-offset"]??e["upload-offset"]);if(void 0!==a)return Math.min(a,t);let r=eM(e.range),n=r?.match(/^bytes=0-(\d+)$/);if(!n)return;let i=Number(n[1]);if(Number.isSafeInteger(i)&&!(i<0))return Math.min(i+1,t)}(e.headers,d):void 0;void 0!==l?l>=d?t({statusCode:200,statusMessage:"Upload already complete",body:""}):l<=r.startOffset?a(new f("COMMAND_FAILED","Artifact upload resume did not advance",{offset:l,previousOffset:r.startOffset,url:r.url.toString()})):e_({...r,startOffset:l}).then(t,a):t({statusCode:i,statusMessage:e.statusMessage,body:n})}).catch(a)}),s=setTimeout(()=>{o.destroy(),a(new f("COMMAND_FAILED",r.timeoutMessage,{timeoutMs:3e5,...r.timeoutHint?{hint:r.timeoutHint}:{}}))},3e5);o.on("error",e=>{i||(clearTimeout(s),a(new f("COMMAND_FAILED",r.errorMessage,r.errorHint?{hint:r.errorHint}:{},e)))}),o.on("close",()=>clearTimeout(s)),n(e.createReadStream(r.payloadPath,{start:r.startOffset}),o).catch(e=>{i||(o.destroy(),a(new f("COMMAND_FAILED","Failed to read local artifact",{},e instanceof Error?e:Error(String(e)))))})})}function eM(e){return Array.isArray(e)?e[0]:e}async function eD(e){let t=new URL("upload/finalize",e.normalizedBase),a={"content-type":"application/json"};e.token&&(a.authorization=`Bearer ${e.token}`,a["x-agent-device-token"]=e.token);let r=await fetch(t,{method:"POST",headers:a,signal:AbortSignal.timeout(3e4),body:JSON.stringify({uploadId:e.uploadId})}).catch(e=>{throw new f("COMMAND_FAILED","Failed to finalize direct artifact upload",{},e)});if(!r.ok)throw new f("COMMAND_FAILED","Direct artifact upload finalize failed",{status:r.status,statusText:r.statusText});let n=await r.json().catch(()=>void 0);if(!n?.ok||!n.uploadId)throw new f("COMMAND_FAILED","Invalid upload finalize response");return n.uploadId}async function eP(t){let a=o(eh),r=new l({write(e,t,r){a.update(e),r()}});return await n(e.createReadStream(t),r).catch(e=>{throw new f("COMMAND_FAILED","Failed to read local artifact",{},e instanceof Error?e:void 0)}),a.digest("hex")}async function ek(e,t){var a;let n,i=[...e.positionals??[]],o=e.flags?{...e.flags}:void 0,s=e.meta?.installSource,l={};if(!("string"==typeof(a=t).baseUrl&&a.baseUrl.length>0))return eE({positionals:i,flags:o,installSource:s,uploadedArtifactId:n,clientArtifactPaths:l});o=function(e,t,a,n){var i,o;let s=function(e,t){if("screenshot"===e.command){let a=e$(e,"path",".png");return t[0]?{field:"path",localPath:a,positionalIndex:0,positionalPath:eT("screenshot",".png")}:{field:"path",localPath:a,positionalIndex:0,flagPath:eT("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=e$(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:eT("recording",r.extname(t)||".mp4")}}return null}(e,t);if(!s)return a;void 0!==s.positionalPath&&(t[s.positionalIndex]=s.positionalPath);let l=(i=a,void 0===(o=s.flagPath)?i:{...i??{},out:o});return n[s.field]=s.localPath,l}(e,i,o,l);let d=await eN(e,t);d&&(s=d.installSource,n=d.uploadedArtifactId??n);let c=()=>eE({positionals:i,flags:o,installSource:s,uploadedArtifactId:n,clientArtifactPaths:l});return"install"!==e.command&&"reinstall"!==e.command||(n=await ex(e,t,i)??n),c()}async function ex(t,a,n){var i,o;let s,l=n[1];if(void 0===l)return;if(l.startsWith("remote:")){n[1]=l.slice(7);return}let d=(i=l,o=t.meta?.cwd,s=r.isAbsolute(i)?i:r.resolve(o??process.cwd(),i),e.existsSync(s)?s:void 0);if(d)return await ey({localPath:d,baseUrl:a.baseUrl,token:a.token,platform:t.flags?.platform})}function eE(e){return{positionals:e.positionals,flags:e.flags,installSource:e.installSource,uploadedArtifactId:e.uploadedArtifactId,...Object.keys(e.clientArtifactPaths).length>0?{clientArtifactPaths:e.clientArtifactPaths}:{}}}async function eN(t,a){let n=t.meta?.installSource;if("install_source"!==t.command||!n||"path"!==n.kind)return null;let i=n.path.trim();if(!i)return{installSource:n};if(i.startsWith("remote:"))return{installSource:{...n,path:i.slice(7)}};let o=r.isAbsolute(i)?i:r.resolve(t.meta?.cwd??process.cwd(),i);if(!e.existsSync(o))return{installSource:{...n,path:o}};let s=await ey({localPath:o,baseUrl:a.baseUrl,token:a.token,platform:t.flags?.platform});return{installSource:{...n,path:o},uploadedArtifactId:s}}function e$(e,t,a,n=0){let i=e.positionals?.[n]??e.flags?.out,o=`${"path"===t?"screenshot":"recording"}-${Date.now()}${a}`,s=i&&i.trim().length>0?i:o;return r.isAbsolute(s)?s:r.resolve(e.meta?.cwd??process.cwd(),s)}function eT(e,t){let a=t.startsWith(".")?t:`.${t}`;return r.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${a}`)}async function eC(e,t,a){let n=Array.isArray(a.data?.artifacts)?a.data.artifacts:[];if(0===n.length||!e.baseUrl)return a;let i=a.data?{...a.data}:{},o=[];for(let a of n){if(!a||"object"!=typeof a||"string"!=typeof a.artifactId){o.push(a);continue}let n=function(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let a=t.meta?.clientArtifactPaths?.[e.field];if(a&&a.trim().length>0)return a;let n=e.fileName?.trim()||`${e.field}-${Date.now()}`;return r.resolve(t.meta?.cwd??process.cwd(),n)}(a,t);await eU({baseUrl:e.baseUrl,token:e.token,artifactId:a.artifactId,destinationPath:n,requestId:t.meta?.requestId}),i[a.field]=n,o.push({...a,localPath:n})}return i.artifacts=o,{ok:!0,data:i}}async function eU(i){var o,s;let l,d=new URL((o=i.baseUrl,s=i.artifactId,l=o.endsWith("/")?o:`${o}/`,new URL(`artifacts/${encodeURIComponent(s)}`,l).toString())),c="https:"===d.protocol?a:t;await e.promises.mkdir(r.dirname(i.destinationPath),{recursive:!0}),await new Promise((t,a)=>{let r=!1,o=i.timeoutMs??9e4,s=n=>{if(!r){if(r=!0,clearTimeout(u),n)return void e.promises.rm(i.destinationPath,{force:!0}).finally(()=>a(n));t()}},l=c.request({protocol:d.protocol,host:d.hostname,port:d.port,method:"GET",path:d.pathname+d.search,headers:i.token?{authorization:`Bearer ${i.token}`,"x-agent-device-token":i.token}:void 0},t=>{if((t.statusCode??500)>=400){let e="";t.setEncoding("utf8"),t.on("data",t=>{e+=t}),t.on("end",()=>{s(new f("COMMAND_FAILED","Failed to download remote artifact",{artifactId:i.artifactId,statusCode:t.statusCode,requestId:i.requestId,body:e}))});return}t.on("aborted",()=>{s(new f("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:i.artifactId,requestId:i.requestId}))}),n(t,e.createWriteStream(i.destinationPath)).then(()=>s(),e=>s(e instanceof Error?e:Error(String(e))))}),u=setTimeout(()=>{let e=new f("COMMAND_FAILED","Remote artifact download timed out",{artifactId:i.artifactId,requestId:i.requestId,timeoutMs:o});s(e),l.destroy(e)},o);l.on("error",e=>{e instanceof f?s(e):s(new f("COMMAND_FAILED","Failed to download remote artifact",{artifactId:i.artifactId,requestId:i.requestId,timeoutMs:o},e instanceof Error?e:void 0))}),l.end()})}function eL(e){var t,a,r;let n,i,o=eG(e);if(!o||"object"!=typeof o)return null;let s="string"==typeof(t=o).token&&t.token.length>0?t.token:null;if(!s)return null;let l=(n=eO((a=o).port),i=eO(a.httpPort),void 0===n&&void 0===i?null:{port:n,httpPort:i});return l?{token:s,...l,transport:"socket"===(r=o.transport)||"http"===r||"dual"===r?r:void 0,pid:eO(o.pid)??0,version:eR(o.version),codeSignature:eR(o.codeSignature),processStartTime:eR(o.processStartTime)}:null}function eR(e){return"string"==typeof e?e:void 0}function eO(e){return Number.isInteger(e)&&Number(e)>0?Number(e):void 0}function eF(e){let t=eG(e);return t&&"object"==typeof t&&Number.isInteger(t.pid)&&Number(t.pid)>0?{pid:Number(t.pid),processStartTime:"string"==typeof t.processStartTime?t.processStartTime:void 0,startedAt:"number"==typeof t.startedAt?t.startedAt:void 0}:null}async function eB(t,a,r={}){let n=r.stopLiveProcesses??!0,i={reason:a,removedInfo:!1,removedLock:!1,stoppedInfoProcess:!1,stoppedLockProcess:!1};try{var o,s,l,d;let a=e.existsSync(t.infoPath),r=eL(t.infoPath);if(r){let e=I(r.pid,r.processStartTime);e&&!n?i.retainedInfoProcess=!0:(e&&(await eK(r),i.stoppedInfoProcess=!0),o=t.infoPath,eH(o),i.removedInfo=!0)}else a&&(s=t.infoPath,eH(s),i.removedInfo=!0);let c=e.existsSync(t.lockPath),u=eF(t.lockPath);if(u){let e=I(u.pid,u.processStartTime);e&&!n?i.retainedLockProcess=!0:(e&&(await v(u.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:u.processStartTime}),i.stoppedLockProcess=!0),l=t.lockPath,eH(l),i.removedLock=!0)}else c&&(d=t.lockPath,eH(d),i.removedLock=!0)}catch(e){i.error=e instanceof Error?e.message:String(e)}return g({level:i.error?"warn":"info",phase:"daemon_startup_metadata_cleanup",data:i}),i}function ej(t){return{hasInfo:e.existsSync(t.infoPath),hasLock:e.existsSync(t.lockPath)}}async function eq(e){let t=ej(e);if(!t.hasLock||t.hasInfo)return!1;let a=eF(e.lockPath);return!(a&&I(a.pid,a.processStartTime))&&(eH(e.lockPath),!0)}async function eK(e){await v(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function eV(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function eG(t){if(!e.existsSync(t))return null;try{return JSON.parse(e.readFileSync(t,"utf8"))}catch{return null}}function eH(t){try{e.existsSync(t)&&e.unlinkSync(t)}catch{}}function ez(e){let t=Math.max(0,e)/1e3;return t>=10?`${t.toFixed(1)}s`:t>=1?`${t.toFixed(2)}s`:`${t.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}s`}function eY(e){let t=eW(e),a=t.findIndex(({stop:e})=>!1===e.ok);if(a<0)return[];let r=t.slice(Math.max(0,a-2),a+1);return[e.attempts>1?`steps (attempt ${e.attempts}):`:"steps:",...r.map(({stop:e,start:t})=>eZ(e,t))]}function eW(t){var a,n;let i=(a=t).artifactsDir?r.join(a.artifactsDir,`attempt-${a.attempts}`,"replay-timing.ndjson"):void 0;if(!i)return[];let o=function(t){try{return e.readFileSync(t,"utf8").split(/\r?\n/).filter(e=>e.trim().length>0).flatMap(e=>{try{let t=JSON.parse(e);return e1(t)?[t]:[]}catch{return[]}})}catch{return[]}}(i);if(0===o.length)return[];let s=[],l=[];for(let e of o){if("replay_action_start"===(n=e).type&&eJ(n)&&eX(n,"line")&&eQ(n,"command")&&(void 0===n.positionals||Array.isArray(n.positionals))){s.push(e);continue}(function(e){var t;return["replay_action_stop"===e.type&&eJ(e)&&eX(e,"line")&&eQ(e,"command"),void 0===(t=e).ok||"boolean"==typeof t.ok,eX(e,"durationMs"),eQ(e,"errorCode"),void 0===e.resultTiming||e1(e.resultTiming)].every(Boolean)})(e)&&l.push({stop:e,start:function(e,t){let a=t.command,r=e.findIndex(e=>e.step===t.step&&(void 0===a||void 0===e.command||e.command===a));if(!(r<0))return e.splice(r,1)[0]}(s,e)})}return l}function eJ(e){return"number"==typeof e.step}function eX(e,t){return void 0===e[t]||"number"==typeof e[t]}function eQ(e,t){return void 0===e[t]||"string"==typeof e[t]}function eZ(e,t){var a,r,n,i;let o,s,l=!1===e.ok?"[FAIL] ":!0===e.ok?"":"[info] ";return` ${l}${a=t,r=e,[function(e){if(!e)return"unknown";if(!e.startsWith("__maestro"))return e;let t=e.slice(9);return t.length>0?t[0].toLowerCase()+t.slice(1):e}(a?.command??r.command),...(a?.positionals??[]).map(e0)].join(" ")}${n=e,i=t,(s=["number"==typeof(o=i?.line??n.line)?`line ${o}`:"","number"==typeof n.durationMs?ez(n.durationMs):"",n.errorCode??"",n.resultTiming?`timing ${JSON.stringify(n.resultTiming)}`:""].filter(Boolean)).length>0?` (${s.join(", ")})`:""}`}function e0(e){return"string"==typeof e?JSON.stringify(e):"number"==typeof e||"boolean"==typeof e?String(e):JSON.stringify(e)}function e1(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function e3(e,t){return N(e,t,{validateStream:!1})}function e2(e){if("number"!=typeof e.shardIndex)return"";let t="number"==typeof e.shardCount?e.shardCount:"?",a="string"==typeof e.deviceId?` ${e.deviceId}`:"";return` [shard ${e.shardIndex+1}/${t}${a}]`}function e5(e){return`\r\x1b[2K${e}`}function e4(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?Math.floor(e):80}function e6(e,t){let a=e4(t);return e.length<=a?e:a<=0?"":a<=3?".".repeat(a):`${e.slice(0,a-3)}...`}function e8(e){return{file:e.file,title:e.title,durationMs:e.durationMs??0,attempts:e.attempt??1,artifactsDir:e.artifactsDir,session:e.session??""}}function e7(e){return function(e={}){let t=new Set,a=!1;return{render(n){var i,o;if("replay-test-suite"===n.type){t.clear(),a=!1;return}if("replay-test"!==n.type)return;if("progress"===n.status){if(!e.liveProgress)return;return a=!0,{text:e5(function(e,t){let a=e.title?.trim(),n=r.basename(e.file),i=e2(e),o=e.stepIndex??0,s=e.stepTotal??0,l=`${i} [${o}/${s}]`,d="⊙ ";if(!a)return e6(`${d}${n}${l}`,t.columns);let c=`${d}"`,u=`" in ${n}${l}`,f=e6(a,Math.max(0,e4(t.columns)-c.length-u.length));return e6(`${c}${f}${u}`,t.columns)}(n,e)),newline:!1}}if("pass"===(i=n).status||"skip"===i.status||"fail"===i.status&&!i.retrying){let e,a=(e="number"==typeof(o=n).shardIndex?o.shardIndex:"",[o.status,o.index,o.total,o.file,o.title??"",e].join("\0"));if(t.has(a))return;t.add(a)}let s=function(e,t={}){if("replay-test"===e.type)return function(e,t){var a,n,i,o;let s,l,d,c,u,f;if("start"===e.status||"progress"===e.status||"fail"===e.status&&e.retrying)return;let p=[(d=function(e){let t=$(process.stderr);if("pass"===e.status){let a=e.attempt&&e.attempt>1?"yellow":"green";return t?e3("✓",a):"✓"}return"fail"===e.status?t?e3("⨯","red"):"⨯":"progress"===e.status?"⊙":t?e3("-","dim"):"-"}(a=e),c=(n=a,s=n.title?.trim(),l=r.basename(n.file),s?`${JSON.stringify(s)} in ${l}`:l),u=e2(a),f=void 0!==a.durationMs?` (${ez(a.durationMs??0)})`:"",`${d} ${c}${u}${f}`)];return function(e,t,a){if(a.verbose&&"fail"===t.status)return;let r=t.message?.replace(/\s+/g," ").trim();r&&e.push(` ${"fail"===t.status?`failed at: ${r}`:r}`),"fail"===t.status&&!t.retrying&&(t.session&&e.push(` session: ${t.session}`),t.artifactsDir&&e.push(` artifacts: ${t.artifactsDir}`))}(p,e,t),t.verbose&&p.push(...("pass"===(i=e).status||"fail"===i.status)&&i.artifactsDir&&i.attempt?(function(e){if("skipped"===e.status)return[];let t=eW(e);return 0===t.length?[]:[e.attempts>1?`steps (attempt ${e.attempts}):`:"steps:",...t.map(({stop:e,start:t})=>eZ(e,t))]})("pass"===i.status?{...e8(i),status:"passed",replayed:0,healed:0}:{...e8(o=i),status:"failed",error:{code:"COMMAND_FAILED",message:o.message??"Unknown test failure"}}).map(e=>` ${e}`):[]),p.join("\n")}(e,t)}(n,e);if(!s)return;let l=a?e5(s):s;return a=!1,{text:l,newline:!0}}}}({verbose:!!(e.flags?.verbose||e.meta?.debug),liveProgress:!0===process.stderr.isTTY&&!process.env.CI,columns:process.stderr.columns})}function e9(e,t){let a=t.render(e);a&&process.stderr.write(a.newline?`${a.text}
2
+ `:a.text)}function te(e,t){let{info:a,req:r,resolve:n,reject:i}=t;try{var o,s,l;let t=(o=e,JSON.parse(o));if(t.error){let e;return void i((s=t.error,l=r.meta?.requestId,e=s.data??{},new f(u(null!=e.code?String(e.code):void 0,"COMMAND_FAILED"),String(e.message??s.message??"Daemon RPC request failed"),{..."object"==typeof e.details&&e.details?e.details:{},hint:"string"==typeof e.hint?e.hint:void 0,diagnosticId:"string"==typeof e.diagnosticId?e.diagnosticId:void 0,logPath:"string"==typeof e.logPath?e.logPath:void 0,requestId:l})))}if(!t.result||"object"!=typeof t.result)return void i(new f("COMMAND_FAILED","Invalid daemon RPC response",{requestId:r.meta?.requestId}));tt(a,r,t.result,n,i)}catch(t){i(new f("COMMAND_FAILED","Invalid daemon response",{requestId:r.meta?.requestId,line:e},t instanceof Error?t:void 0))}}async function tt(e,t,a,r,n){try{r(e.baseUrl&&a.ok?await eC(e,t,a):a)}catch(e){n(e)}}let ta=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"];function tr(e,t,a,r,n,i){let o=n?{terminated:0}:function(){let e=0;try{for(let t of ta){let a=h("pkill",["-f",t],{allowFailure:!0});0===a.exitCode&&(e+=1)}return{terminated:e}}catch(t){return{terminated:e,error:t instanceof Error?t.message:String(t)}}}(),s=!n&&"snapshot"!==r,l=s?function(e,t){let a=!1;try{I(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),a=!0)}catch{eK(e)}finally{eH(t.infoPath),eH(t.lockPath)}return{forcedKill:a}}(e,t):{forcedKill:!1};return g({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:i,requestId:a,command:r,timedOutRunnerPidsTerminated:o.terminated,timedOutRunnerCleanupError:o.error,daemonPidReset:s?e.pid:void 0,daemonPidForceKilled:s?l.forcedKill:void 0,daemonPreservedAfterTimeout:!n&&!s,daemonBaseUrl:e.baseUrl}}),new f("COMMAND_FAILED","Daemon request timed out",{timeoutMs:i,requestId:a,hint:function(e){let{remote:t,resetDaemon:a,command:r}=e;if(t)return"Retry with --debug and verify the remote daemon URL, auth token, and remote host logs.";if(!a){let e=r===C.snapshot?" If this was the first Apple-platform snapshot on the device, run agent-device prepare ios-runner with the same --platform before snapshot/test so runner startup is handled explicitly.":"";return`Retry with --debug and check daemon diagnostics logs. The timed-out ${r??"request"} request was canceled and Apple runner work was aborted when detected; the daemon was kept alive so the session can still be closed or inspected.${e}`}return"Retry with --debug and check daemon diagnostics logs. Timed-out Apple runner xcodebuild processes were terminated when detected."}({remote:n,resetDaemon:s,command:r})})}async function tn(e,t){let a=tl(e,t);if(await ti(e,a))return!0;let r=tc(e,t,a);return!!r&&await ti(e,r)}async function ti(e,r){var n;return"http"===r?await function(e){let r=e.baseUrl?tm(e.baseUrl,"health"):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!r)return Promise.resolve(!1);let n=new URL(r),i="https:"===n.protocol?a:t,o=e.baseUrl?3e3:500;return new Promise(e=>{let t=i.request({protocol:n.protocol,host:n.hostname,port:n.port,path:n.pathname+n.search,method:"GET",timeout:o},t=>{t.resume(),e((t.statusCode??500)<500)});t.on("timeout",()=>{t.destroy(),e(!1)}),t.on("error",()=>{e(!1)}),t.end()})}(e):await ((n=e.port)?new Promise(e=>{let t=!1,a=d.createConnection({host:"127.0.0.1",port:n},()=>{r(!0)}),r=r=>{t||(t=!0,a.destroy(),e(r))};a.setTimeout(500),a.on("timeout",()=>{r(!1)}),a.on("error",()=>{r(!1)})}):Promise.resolve(!1))}async function to(e,t,a,r,n){let i=tl(e,a);try{return await ts(e,t,r,n,i)}catch(l){var o;let s=tc(e,a,i);if(!s||(o=l,"socket"!==i||!(o instanceof f)||"COMMAND_FAILED"!==o.code||"Failed to communicate with daemon"!==o.message||o.details?.daemonSocketRequestWritten!==!1))throw l;return await ts(e,t,r,n,s)}}async function ts(e,t,a,r,n){return"http"===n?await tp(e,t,a,r):await tf(e,t,a,r)}function tl(e,t){if(e.baseUrl){if("socket"===t)throw new f("COMMAND_FAILED","Remote daemon endpoint only supports HTTP transport",{daemonBaseUrl:e.baseUrl});return"http"}if("http"===t||"socket"===t){var a=e,r=t;if(td(a,r))return r;throw new f("COMMAND_FAILED","http"===r?"Daemon HTTP endpoint is unavailable":"Daemon socket endpoint is unavailable")}let n=("socket"===e.transport||"dual"===e.transport?["socket","http"]:["http","socket"]).find(t=>td(e,t));if(n)return n;throw new f("COMMAND_FAILED","Daemon metadata has no reachable transport")}function td(e,t){return"http"===t?!!e.httpPort:!!e.port}function tc(e,t,a){if("auto"!==t||e.baseUrl)return null;let r="socket"===a?"http":"socket";return td(e,r)?r:null}function tu(e,t,a,r={}){return g({level:"error",phase:"daemon_request_socket_error",data:{requestId:t,message:e instanceof Error?e.message:String(e)}}),new f("COMMAND_FAILED","Failed to communicate with daemon",{...r,requestId:t,hint:a?"Retry command. If this persists, verify the remote daemon URL, auth token, and remote host reachability.":"Retry command. If this persists, clean stale daemon metadata and start a fresh session."},e instanceof Error?e:void 0)}async function tf(e,t,a,r){let n=e.port;if(!n)throw new f("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((i,o)=>{let s=!1,l=d.createConnection({host:"127.0.0.1",port:n},()=>{s=!0,l.write(`${JSON.stringify(t)}
3
+ `)}),c=!1,u="number"==typeof r?setTimeout(()=>{c=!0,l.destroy(),o(tr(e,a,t.meta?.requestId,t.command,!1,r))},r):void 0;!function(e,t){let{req:a,isSettled:r,resolve:n,reject:i,clearTimeout:o}=t,s="",l=e7(a),d=(e,t)=>{o(),i(new f("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:e},t instanceof Error?t:void 0))};e.setEncoding("utf8"),e.on("data",t=>{if(r())return;let a=A(s,t);for(let t of(s=a.buffer,a.lines))try{let a=JSON.parse(t);if(D(a)){e9(a.event,l);continue}let r=M(a)?a.response:a;o(),n(r),e.end();return}catch(e){d(t,e);return}})}(l,{req:t,isSettled:()=>c,clearTimeout:()=>{u&&clearTimeout(u)},resolve:e=>{c=!0,i(e)},reject:e=>{c=!0,o(e)}}),l.on("error",e=>{c||(c=!0,u&&clearTimeout(u),o(tu(e,t.meta?.requestId,!1,{daemonSocketRequestWritten:s})))})})}async function tp(e,r,n,i){var o,s;let l,d=e.baseUrl?new URL(tm(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!d)throw new f("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let c=JSON.stringify((o={includeTokenParam:!e.baseUrl},l=r.meta?.requestId??y(),"lease_allocate"!==(s=r.command)&&"lease_heartbeat"!==s&&"lease_release"!==s?{jsonrpc:"2.0",id:l,method:"agent_device.command",params:r}:{jsonrpc:"2.0",id:l,method:function(e){switch(e){case"lease_allocate":return"agent_device.lease.allocate";case"lease_heartbeat":return"agent_device.lease.heartbeat";case"lease_release":return"agent_device.lease.release"}}(r.command),params:function(e,t,a){let r={...a.includeTokenParam?{token:e.token}:{},session:e.session,tenantId:e.meta?.tenantId,runId:e.meta?.runId};switch(t){case"lease_allocate":return{...r,ttlMs:e.meta?.leaseTtlMs,backend:e.meta?.leaseBackend};case"lease_heartbeat":return{...r,leaseId:e.meta?.leaseId,ttlMs:e.meta?.leaseTtlMs};case"lease_release":return{...r,leaseId:e.meta?.leaseId}}}(r,r.command,o)})),u={"content-type":"application/json","content-length":Buffer.byteLength(c)};return e.baseUrl&&e.token&&(u.authorization=`Bearer ${e.token}`,u["x-agent-device-token"]=e.token),await new Promise((o,s)=>{let l=("https:"===d.protocol?a:t).request({protocol:d.protocol,host:d.hostname,port:d.port,method:"POST",path:d.pathname+d.search,headers:u},t=>{var a;(a=t.headers?.["content-type"],_(r)&&String(Array.isArray(a)?a.join(","):a??"").includes("application/x-ndjson"))?function(e,t){let{req:a,handleResponseBody:r,reject:n,clearTimeout:i}=t,o="",s=!1,l=e7(a),d=e=>{try{let t=JSON.parse(e);if(D(t))return e9(t.event,l),!1;if(M(t))return s=!0,i(),r(JSON.stringify(t.response)),!0;throw Error("Missing daemon progress response envelope")}catch(t){return s=!0,i(),n(new f("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:e},t instanceof Error?t:void 0)),!0}};e.setEncoding("utf8"),e.on("data",e=>{if(s)return;let t=A(o,e);for(let e of(o=t.buffer,t.lines))if(e&&d(e))return}),e.on("end",()=>{if(s)return;let e=o.trim();e&&d(e)||(s=!0,i(),n(new f("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:e})))}),e.on("error",e=>{s||(s=!0,i(),n(new f("COMMAND_FAILED","Failed to read daemon response",{requestId:a.meta?.requestId},e instanceof Error?e:void 0)))})}(t,{req:r,reject:s,clearTimeout:()=>{m&&clearTimeout(m)},handleResponseBody:t=>te(t,{info:e,req:r,resolve:o,reject:s})}):em(t).then(t=>{m&&clearTimeout(m),te(t,{info:e,req:r,resolve:o,reject:s})}).catch(e=>{m&&clearTimeout(m),s(new f("COMMAND_FAILED","Failed to read daemon response",{requestId:r.meta?.requestId},e instanceof Error?e:void 0))})}),p=eV(e),m="number"==typeof i?setTimeout(()=>{l.destroy(),s(tr(e,n,r.meta?.requestId,r.command,p,i))},i):void 0;l.on("error",e=>{m&&clearTimeout(m),s(tu(e,r.meta?.requestId,p))}),l.write(c),l.end()})}function tm(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}let th=new d.BlockList;async function ty(e){if(e.remoteBaseUrl)return await tw(e);let t=await tg(e);return t?{info:t,startedByClient:!1}:(!function(e){let t=ej(e);if(!t.hasLock||t.hasInfo)return;let a=eF(e.lockPath);if(!a)return eH(e.lockPath);I(a.pid,a.processStartTime)||eH(e.lockPath)}(e.paths),await tI(e))}async function tw(e){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await tn(t,"http"))return{info:t,startedByClient:!1};throw new f("COMMAND_FAILED","Remote daemon is unavailable",{daemonBaseUrl:e.remoteBaseUrl,hint:"Verify AGENT_DEVICE_DAEMON_BASE_URL points to a reachable daemon with GET /health and POST /rpc."})}async function tg(e){var t,a;let r=eL(e.paths.infoPath);if(!r)return null;let n=await tn(r,e.transportPreference);return(t=r,a=n,t.version===U()&&t.codeSignature===t_()&&a)?r:(function(e,t,a){try{var r,n;let i=e.version?`pid ${e.pid}, v${e.version}`:`pid ${e.pid}`,o=(r=e,n=t,r.version!==U()?`version mismatch (client v${U()})`:r.codeSignature!==t_()?"code-signature mismatch":n?"not reusable":"unreachable");process.stderr.write(`Replacing daemon (${i}) in ${a}: ${o}
4
+ `)}catch{}}(r,n,e.paths.baseDir),await eK(r),eH(e.paths.infoPath),null)}async function tI(t){let a,r,n=0,i=[];for(let o=1;o<=2;o+=1){let s;try{r={pid:(s=function(t){let a=tS(),r=a.useSrc?["--experimental-strip-types",a.srcPath]:[a.distPath],n={...process.env,AGENT_DEVICE_STATE_DIR:t.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:t.serverMode};e.mkdirSync(t.paths.baseDir,{recursive:!0});let i=e.openSync(t.paths.logPath,"a"),o=e.openSync(t.paths.logPath,"a");try{return p(process.execPath,r,{env:n,stdio:["ignore",i,o]})}finally{e.closeSync(i),e.closeSync(o)}}(t)).pid}}catch(e){if(a=e instanceof Error?e.message:String(e),i.push(await eB(t.paths,"start_error")),o<2){await R(150);continue}break}let l=await tA(15e3,t,s);if("ready"===l.kind)return{info:l.info,startedByClient:!0};if("early_exit"===l.kind){if(r=l.exit,a=tM(l.exit),i.push(await eB(t.paths,"start_error")),o<2){await R(150);continue}break}if(await eq(t.paths)){n+=1;continue}let d=ej(t.paths),c=o<2,u=await eB(t.paths,"startup_timeout",{stopLiveProcesses:!1});if(i.push(u),u.retainedInfoProcess||u.retainedLockProcess){let e=await tA(15e3,t,s);if("ready"===e.kind)return{info:e.info,startedByClient:!0};"early_exit"===e.kind&&(r=e.exit,a=tM(e.exit));break}if(!c)break;d.hasInfo||d.hasLock||await R(150)}let o=ej(t.paths),s=function(t){try{if(!e.existsSync(t))return;let a=e.statSync(t);if(a.size<=0)return;let r=Math.min(a.size,64e3),n=e.openSync(t,"r");try{let t=Buffer.alloc(r);e.readSync(n,t,0,r,a.size-r);let i=t.toString("utf8").trim();return i.length>0?i:void 0}finally{e.closeSync(n)}}catch{return}}(t.paths.logPath);throw new f("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",stateDir:t.paths.baseDir,infoPath:t.paths.infoPath,lockPath:t.paths.lockPath,logPath:t.paths.logPath,startupTimeoutMs:15e3,startupAttempts:2,lockRecoveryCount:n,cleanupResults:i,startError:a,daemonProcess:r,...s?{daemonLogTail:s}:{},metadataState:o,hint:function(e,t=P(process.env.AGENT_DEVICE_STATE_DIR)){var a;let r=(a=t,`rm -f ${S(a.infoPath)} ${S(a.lockPath)}`);return e.hasLock&&!e.hasInfo?`agent-device attempted to clean stale daemon metadata automatically, but ${t.lockPath} still exists without ${t.infoPath}. Retry with --debug; if this persists after confirming no agent-device daemon process is running, run: ${r}`:e.hasLock&&e.hasInfo?`agent-device attempted to clean stale daemon metadata automatically, but ${t.infoPath} and ${t.lockPath} still remain. Retry with --debug; if this persists after confirming no agent-device daemon process is running, run: ${r}`:e.hasInfo?`agent-device did not observe reachable daemon metadata after retrying, and ${t.infoPath} still remains. Stale metadata was cleaned automatically when safe; retry with --debug. If this persists after confirming no agent-device daemon process is running, run: ${r}`:`agent-device did not observe reachable daemon metadata after retrying. Stale metadata was cleaned automatically when safe; retry with --debug and check daemon diagnostics logs. If stale metadata returns after confirming no agent-device daemon process is running, run: ${r}`}(o,t.paths)})}async function tv(t,a,r){if(!tb(t.command)||!a.startedByClient&&!r.ownedStateDir||eV(a.info))return;let n={pid:a.info.pid,removedInfo:!1,removedLock:!1,removedStateDir:!1,error:void 0};try{await eK(a.info)}catch(e){n.error=e instanceof Error?e.message:String(e)}finally{let t=e.existsSync(r.paths.infoPath);eH(r.paths.infoPath),n.removedInfo=t&&!e.existsSync(r.paths.infoPath);let a=e.existsSync(r.paths.lockPath);eH(r.paths.lockPath),n.removedLock=a&&!e.existsSync(r.paths.lockPath),r.ownedStateDir&&(e.rmSync(r.paths.baseDir,{recursive:!0,force:!0}),n.removedStateDir=!e.existsSync(r.paths.baseDir))}g({level:n.error?"warn":"info",phase:"daemon_replay_cleanup",data:n})}function tb(e){return e===C.replay||e===C.test}async function tA(e,t,a){let r,n=Date.now();for(a.exited.then(e=>{r=e});Date.now()-n<e;){if(r)return{kind:"early_exit",exit:r};let e=eL(t.paths.infoPath);if(e&&await tn(e,t.transportPreference))return{kind:"ready",info:e};if(r)return{kind:"early_exit",exit:r};await R(100)}return{kind:"timeout"}}function tS(){let t=L(),a=[r.join(t,"dist","src","internal","daemon.js"),r.join(t,"dist","src","daemon.js")],n=a[0];if(void 0===n)throw new f("COMMAND_FAILED","Daemon dist path list is empty");let i=a.find(t=>e.existsSync(t))??n,o=r.join(t,"src","daemon.ts"),s=a.some(t=>e.existsSync(t)),l=e.existsSync(o);if(!s&&!l)throw new f("COMMAND_FAILED","Daemon entry not found",{distPaths:a,srcPath:o});return{root:t,distPath:i,distPaths:a,srcPath:o,useSrc:process.execArgv.includes("--experimental-strip-types")?l:!s&&l}}function t_(){let e=tS();return x(e.useSrc?e.srcPath:e.distPath,e.root)}function tM(e){return e.error?`daemon process ${e.pid} failed to start: ${e.error}`:e.signal?`daemon process ${e.pid} exited before readiness with signal ${e.signal}`:`daemon process ${e.pid} exited before readiness with code ${e.exitCode??0}`}async function tD(t){var a,n,o,s,l;let c,u,p,m,h,I,v,b=t.meta?.requestId??y(),A=!!(t.meta?.debug||t.flags?.verbose),S=(a=t,m=a.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,n=t,function(e,t){let a;if(!(!e||"localhost"===(a=new URL(e).hostname.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1"))||(d.isIPv4(a)?th.check(a,"ipv4"):!!d.isIPv6(a)&&th.check(a,"ipv6")))&&("string"!=typeof t||!(t.trim().length>0)))throw new f("INVALID_ARGS","Remote daemon base URL for non-loopback hosts requires daemon authentication",{daemonBaseUrl:e,hint:"Provide --daemon-auth-token or AGENT_DEVICE_DAEMON_AUTH_TOKEN when using a non-loopback remote daemon URL."})}(u=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new f("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new f("INVALID_ARGS","Daemon base URL must use http or https",{daemonBaseUrl:e});return t.toString().replace(/\/+$/,"")}}(c=n.flags?.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL),p=n.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN),I=function(e,t){let a=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,r=E(a);if(t&&"socket"===r)throw new f("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:t});return{preference:r,serverMode:k(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===a?"dual":void 0))}}(t,(h={rawBaseUrl:c,remoteBaseUrl:u,authToken:p}).remoteBaseUrl),o=t,s=m,l=h.rawBaseUrl,{paths:P((v=tb(o.command)&&!s&&!l)?e.mkdtempSync(r.join(i.tmpdir(),"agent-device-replay-daemon-")):m),transportPreference:I.preference,serverMode:I.serverMode,ownedStateDir:v,remoteBaseUrl:h.remoteBaseUrl,remoteAuthToken:h.authToken}),_=function(e){if(e.command!==C.test){var t;return"number"==typeof e.flags?.timeoutMs&&((t=e.command)===C.prepare||t===C.replay||t===C.snapshot)?e.flags.timeoutMs:e.command===C.prepare?24e4:9e4}}(t),M=await w("daemon_startup",async()=>await ty(S),{requestId:b,session:t.session}),D=M.info,x=await ek(t,D),N={...t,positionals:x.positionals,flags:x.flags,token:D.token,meta:{...t.meta??{},requestId:b,debug:A,cwd:t.meta?.cwd,sessionExplicit:t.meta?.sessionExplicit,tenantId:t.meta?.tenantId??t.flags?.tenant,runId:t.meta?.runId??t.flags?.runId,leaseId:t.meta?.leaseId??t.flags?.leaseId,sessionIsolation:t.meta?.sessionIsolation??t.flags?.sessionIsolation,lockPolicy:t.meta?.lockPolicy,lockPlatform:t.meta?.lockPlatform,...x.uploadedArtifactId?{uploadedArtifactId:x.uploadedArtifactId}:{},...x.clientArtifactPaths?{clientArtifactPaths:x.clientArtifactPaths}:{},...x.installSource?{installSource:x.installSource}:{}}};g({level:"info",phase:"daemon_request_prepare",data:{requestId:b,command:t.command,session:t.session}});try{return await w("daemon_request",async()=>await to(D,N,S.transportPreference,S.paths,_),{requestId:b,command:t.command})}finally{await tv(t,M,S)}}th.addSubnet("127.0.0.0",8,"ipv4"),th.addAddress("::1","ipv6"),th.addSubnet("::ffff:127.0.0.0",104,"ipv6");let tP=/^[0-9a-fA-F-]{32,36}$/;function tk(e){if(e&&tP.test(e))return e.replaceAll("-","").toUpperCase()}function tx(e,t){return`${e.uuid}:${tE(t)}`}function tE(e){return`0x${e.toString(16)}`}function tN(e){return"string"==typeof e&&e.length>0?e:void 0}function t$(...e){for(let t of e){let e=tN(t);if(e)return e}}function tT(e){return"object"==typeof e&&null!==e}function tC(e){return tT(e)?e:void 0}function tU(e){try{let t=JSON.parse(e);return tT(t)?t:null}catch{return null}}function tL(e){if("number"==typeof e&&Number.isSafeInteger(e))return e;if("string"==typeof e){let t=e.startsWith("0x")?Number.parseInt(e,16):Number(e);return Number.isSafeInteger(t)?t:void 0}}function tR(e,t,a){var r;if(!Object.hasOwn(e,t))return;let n="bigint"==typeof(r=e[t])?r:"number"==typeof r&&Number.isSafeInteger(r)?BigInt(r):"string"!=typeof r?void 0:/^(?:0x[0-9a-fA-F]+|\d+)$/.test(r)?BigInt(r):void 0;if(void 0!==n)return n;tO(a,t)}function tO(e,t){throw new f("INVALID_ARGS",`Invalid ${e} numeric field: ${t}`,{hint:"Crash artifact numeric fields must be integer numbers or integer numeric strings."})}function tF(e){return[...new Set(e)]}let tB=/^(?:arm64e?|arm64_32|x86_64|armv7[sk]?|i386)$/;async function tj(e){return e.dsym&&e.searchPath?[tz(e.cwd,e.dsym),...await tq(tz(e.cwd,e.searchPath))]:e.dsym?[tz(e.cwd,e.dsym)]:e.searchPath?await tq(tz(e.cwd,e.searchPath)):[]}async function tq(e){let t=[],a=0;async function n(i){if(!(t.length>=200)){if((a+=1)>1e4)throw new f("COMMAND_FAILED","debug symbols search-path scan exceeded bounds.",{searchPath:e,maxEntries:1e4,hint:"Pass --dsym <App.dSYM> directly or narrow --search-path to the build products directory."});if(!(await tK(i,e)).isDirectory()){i===e&&function(e){throw new f("INVALID_ARGS",`debug symbols search path is not a directory: ${e}`,{hint:"Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly."})}(e);return}if(i.endsWith(".dSYM"))return void t.push(i);for(let e of(await c.readdir(i,{withFileTypes:!0})))e.isDirectory()&&await n(r.join(i,e.name))}}return await n(e),t}async function tK(e,t){try{return await c.stat(e)}catch{throw new f("INVALID_ARGS",`debug symbols search path does not exist: ${t}`,{hint:"Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly."})}}async function tV(e,t){let a=(await Promise.all(tF(e).map(e=>tG(e,t)))).flat();if(0===a.length)throw new f("COMMAND_FAILED","No UUIDs found in dSYM bundle.",{hint:"Verify the path points to a built .dSYM bundle with DWARF contents."});return a}async function tG(e,t){var a;await tH(e);let r=await m(t,["--uuid",e],{timeoutMs:15e3,allowFailure:!0});if(0!==r.exitCode)throw new f("COMMAND_FAILED",`Failed to inspect dSYM UUIDs: ${e}`,{stderr:r.stderr,hint:"Verify the dSYM bundle is valid and readable."});return a=e,r.stdout.split("\n").flatMap(e=>{let t=e.match(/^UUID:\s+([0-9a-fA-F-]{32,36})\s+\(([^)]+)\)\s+(.+)$/),r=tk(t?.[1]);return t&&r?[{dsymPath:a,uuid:r,arch:t[2],binaryPath:t[3].trim()}]:[]})}async function tH(e){let t=await c.stat(e).catch(()=>null);if(!(t?.isDirectory()&&e.endsWith(".dSYM")))throw new f("INVALID_ARGS",`Not a .dSYM bundle: ${e}`,{hint:"Pass the .dSYM bundle path, not the DWARF executable inside it."})}function tz(e,t){return r.resolve(e,t)}function tY(e,t){let a=`${t}:`,r=e.find(e=>e.trimStart().startsWith(a));return r&&r.slice(r.indexOf(":")+1).trim()||void 0}function tW(e,t,a,r){return{index:e,image:t.name,address:tE(a),symbol:r.get(tx(t,a))?.text}}function tJ(e){var t;let a;return[(a=(t=e).topFrames.find(e=>e.symbol))?`Start with ${a.symbol} in ${a.image}; it is the first symbolicated frame captured on the crashed thread.`:t.topFrames.length>0?"No symbolicated frame was found on the crashed thread; verify matching dSYMs for the top images.":void 0,e.exceptionType?`Exception: ${e.exceptionType}`:void 0,e.terminationReason?`Termination: ${e.terminationReason}`:void 0].filter(e=>!!e).slice(0,3)}async function tX(e,t,a){let r=new Map;for(let n of(function(e,t){let a=new Map;for(let r of e){let e=t.get(r.image.uuid);if(!e)continue;let n=`${r.image.uuid}:${e.dsym.binaryPath}`,i=a.get(n)??{...e,addresses:[]};i.addresses.push(r.address),a.set(n,i)}return a})(e,t).values())for(let e of(await tQ(a,n)))r.set(tx(e.image,e.address),e);return r}async function tQ(e,t){var a,r,n,i;let o,s,l=tF(t.addresses.map(tE)),d=await m(e,(a=t,r=l,["-arch",a.image.arch??a.dsym.arch??"arm64","-o",a.dsym.binaryPath,"-l",tE(a.image.base),...r]),{timeoutMs:3e4,allowFailure:!0});return 0!==d.exitCode&&function(e){throw new f("COMMAND_FAILED","atos failed while symbolicating crash frames.",{stderr:e,hint:"Verify the crash artifact and dSYM were produced from the same build and architecture."})}(d.stderr),n=t.image,i=l,s=(""===(o=d.stdout.split(/\r?\n/)).at(-1)&&o.pop(),o),i.map((e,t)=>{let a=s[t]?.trim();return{image:n,address:BigInt(e),text:!function(e,t){if(!e)return!1;let a=e.trim().toLowerCase();return!!a&&"??"!==a&&a!==t.toLowerCase()&&!a.startsWith("0x")}(a,e)?void 0:a}})}async function tZ(){return{dwarfdump:await t0("dwarfdump"),atos:await t0("atos")}}async function t0(e){try{let t=await m("xcrun",["--find",e],{timeoutMs:5e3,allowFailure:!0}),a=t.stdout.trim();if(0===t.exitCode&&a.length>0)return a}catch{}throw new f("TOOL_MISSING",`Apple symbolication tool not found: ${e}`,{hint:"Install Xcode Command Line Tools and verify xcrun --find dwarfdump and xcrun --find atos succeed."})}async function t1(e){var t,a,n,i,o,s,l,d,u,p,m,h,y,w,g,I,v,b,A,S,_,M,D,P,k,x,E;let N,$,T,C,U,L,R,O,F;if(void 0!==e.action&&"symbols"!==e.action)throw new f("INVALID_ARGS","debug supports only the symbols workflow.",{hint:"Use debug symbols --artifact <crash.ips|crash.log> --dsym <App.dSYM> or --search-path <dir> --out <path>."});let B=e.cwd??process.cwd(),j=t5(B,e.artifact),q=t5(B,e.out??(a=j,$=(N=r.extname(a))?a.slice(0,-N.length):a,`${$}-symbolicated${N||".log"}`)),K=function(e){var t;let a,n=function(e){let t=tU(e);if(t)return{payload:t};let a=e.indexOf("\n");if(-1===a)return null;let r=e.slice(0,a),n=tU(e.slice(a+1));return n?{header:r,payload:n}:null}(e);if(!n)return null;let i=(Array.isArray(n.payload.usedImages)?n.payload.usedImages:[]).flatMap((e,t)=>(function(e,t){if(!e||"object"!=typeof e)return[];let a=tk(tN(e.uuid)),n=tR(e,"base","IPS usedImages");if(!a||void 0===n)return[];let i=tN(e.path);return[{index:t,name:tN(e.name)??(i?r.basename(i):`image-${t}`),uuid:a,arch:tN(e.arch),base:n,path:i}]})(e,t));if(0===i.length)return null;let o=(t=Array.isArray(n.payload.threads)?n.payload.threads:[],a=new Map(i.map(e=>[e.index,e])),t.flatMap((e,t)=>(function(e){if(!e||"object"!=typeof e)return[];let t=e.frames;return Array.isArray(t)?t.filter(e=>tT(e)):[]})(e).flatMap((e,r)=>(function(e,t,a,r){let n=function(e,t,a){if(!Object.hasOwn(e,t))return;let r=tL(e[t]);if(void 0!==r)return r;tO(a,t)}(e,"imageIndex","IPS frame"),i=tR(e,"imageOffset","IPS frame");if(void 0===n||void 0===i)return[];let o=t.get(n);return o?[{frame:e,frameIndex:r,threadIndex:a,image:o,address:o.base+i}]:[]})(e,a,t,r))));return{format:"ips",images:i,addresses:o.map(({frame:e,...t})=>t),document:n,frameMatches:o,write:e=>(function(e,t,a){for(let e of t){let t=a.get(tx(e.image,e.address))?.text;t&&function(e,t){let a,r=(a=t.match(/^(.*) \+ (\d+)$/))?{symbol:a[1],location:Number(a[2])}:{symbol:t};e.symbol=r.symbol,void 0!==r.location&&(e.symbolLocation=r.location)}(e.frame,t)}e.payload.agentDeviceSymbolication={tool:"agent-device debug symbols",symbolicatedFrames:[...a.values()].filter(e=>e.text).length};let r=`${JSON.stringify(e.payload,null,2)}
5
+ `;return e.header?`${e.header}
6
+ ${r}`:r})(n,o,e)}}(t=await t3(j,"crash artifact"))??function(e){let t=e.split("\n"),a=function(e){let t=[],a=e.findIndex(e=>/^Binary Images:/i.test(e.trim()));if(-1===a)return t;for(let n of e.slice(a+1)){let e=function(e){let t=e.match(/^\s*(0x[0-9a-fA-F]+)\s*-\s*(0x[0-9a-fA-F]+)\s+\+?(.+?)\s+<([0-9a-fA-F-]{32,36})>\s+(.+)$/);if(!t)return null;let a=tk(t[4]);if(!a)return null;let n=function(e,t){let a=e.split(/\s+/),n=a.at(-1);if(n&&tB.test(n))return{name:a.slice(0,-1).join(" ").trim(),arch:n};let i=r.basename(t);return{name:e.startsWith(i)?i:e}}(t[3].trim(),t[5].trim());return{name:n.name,arch:n.arch,uuid:a,base:BigInt(t[1]),end:BigInt(t[2]),path:t[5].trim()}}(n);e&&t.push(e)}return t}(t);if(0===a.length)return null;let n=function(e,t){let a,r=[];for(let[n,i]of e.entries()){let e=i.match(/^Thread\s+(\d+)\s+Crashed:/);e?a=Number(e[1]):(0===i.trim().length||/^Thread\s+\d+/.test(i))&&(a=void 0);let o=function(e,t){let a=e.match(/^\s*\d+\s+(.+?)\s+(0x[0-9a-fA-F]+)\b/);if(!a)return null;let r=a[1].trim(),n=BigInt(a[2]),i=function(e,t,a){let r=e.filter(e=>e.name===t);return r.find(e=>{var t,r;return t=e,r=a,void 0!==t.end&&t.base<=r&&r<=t.end})??(1===r.length?r[0]:void 0)}(t,r,n);return i?{image:i,address:n}:null}(i,t),s=i.match(/^\s*(\d+)/);o&&s&&r.push({...o,frameIndex:Number(s[1]),lineIndex:n,threadIndex:a})}return r}(t,a);return{format:"text",images:a,addresses:n,lines:t,frameMatches:n,write(e){let a=new Map(n.map(e=>[e.lineIndex,e]));return t.map((t,r)=>{let n=a.get(r);if(!n)return t;let i=e.get(tx(n.image,n.address))?.text;return!i||t.includes(i)?t:`${t} // ${i}`}).join("\n")}}}(t);K||function(){throw new f("UNSUPPORTED_OPERATION","debug symbols currently supports Apple crash artifacts with Binary Images or IPS usedImages.",{hint:"For Android Java/R8 crashes, use retrace with mapping.txt. For Android native crashes, use ndk-stack or addr2line with unstripped .so symbols. Capture the crash with logs, then symbolicate externally until Android support is added."})}();let V=await tj({cwd:B,dsym:e.dsym,searchPath:e.searchPath});if(0===V.length)throw new f("INVALID_ARGS","debug symbols requires --dsym or --search-path.",{hint:"Pass a matching .dSYM bundle directly, or pass --search-path <dir> so agent-device can match crash image UUIDs to local dSYMs."});let G=await tZ(),H=await tV(V,G.dwarfdump),z=function(e,t,a){let r=new Map;for(let a of e){let e=t.find(e=>e.uuid===a.uuid&&(void 0===a.arch||void 0===e.arch||e.arch===a.arch));e&&r.set(a.uuid,{image:a,dsym:e})}if(r.size>0)return r;let n=tF(e.map(e=>e.uuid)),i=tF(t.map(e=>e.uuid));throw new f("COMMAND_FAILED",a?"dSYM UUID does not match any Apple image in the crash artifact.":"No matching dSYM UUID found under search path.",{artifactUuidCount:n.length,artifactUuidSample:n.slice(0,5),dsymUuidCount:i.length,dsymUuidSample:i.slice(0,5),hint:"Use dwarfdump --uuid <App.dSYM> and compare it with the crash Binary Images or usedImages UUID, then pass the matching dSYM/search path."})}(K.images,H,!!e.dsym),Y=await tX(K.addresses,z,G.atos),W=K.write(Y);await c.mkdir(r.dirname(q),{recursive:!0}),await c.writeFile(q,W,"utf8");let J=[...z.values()].map(({image:e,dsym:t})=>({name:e.name,uuid:e.uuid,arch:e.arch??t.arch,dsymPath:t.dsymPath,binaryPath:t.binaryPath})),X=[...Y.values()].filter(e=>e.text).length,Q=K.images.length-J.length,Z=Q>0?[`${Q} Apple image${1===Q?"":"s"} had no matching dSYM and were left unchanged.`]:void 0;return{kind:"debugSymbols",platform:"apple",artifactPath:j,outPath:q,crash:"ips"===K.format?(n=K.document,i=K.frameMatches,o=Y,U=function(e){let t=tL(e.faultingThread);if(void 0!==t)return t;let a=(Array.isArray(e.threads)?e.threads:[]).findIndex(e=>tC(e)?.triggered===!0);return -1===a?void 0:a}(n.payload),{...L={format:"ips",...(T=(s=n).payload,C=(l=s.header)?tU(l):null,{appName:(d=T,u=C,t$(d.procName,u?.app_name,u?.name)),bundleId:(p=T,m=C,t$(tC(p.bundleInfo)?.CFBundleIdentifier,m?.bundleID)),version:(h=T,y=C,t$(tC(h.bundleInfo)?.CFBundleShortVersionString,y?.app_version)),incident:(w=T,g=C,t$(w.incident,g?.incident_id)),timestamp:(I=T,v=C,t$(I.captureTime,v?.timestamp)),exceptionType:(b=T.exception,tN(tC(b)?.type)),exceptionCodes:function(e){let t=tC(e);if(t)return t$(t.codes,t.rawCodes)}(T.exception),terminationReason:function(e){let t=tC(e);if(t){let e;return(e=[tN(t.namespace),tN(t.code),tN(t.reason)].filter(e=>!!e)).length>0?e.join(" "):void 0}}(T.termination)}),crashedThread:U,topFrames:(A=i,S=U,_=o,A.filter(e=>void 0===S||e.threadIndex===S).slice(0,5).map(e=>tW(e.frameIndex,e.image,e.address,_))),findings:[]},findings:tJ(L)}):(M=K.lines,D=K.frameMatches,P=Y,O=function(e){let t=tY(e,"Triggered by Thread"),a=t?Number.parseInt(t,10):NaN;if(Number.isSafeInteger(a))return a;for(let t of e){let e=t.match(/^Thread\s+(\d+)\s+Crashed:/);if(e)return Number(e[1])}}(M),{...F={format:"text",appName:(R=tY(M,"Process"),R?.replace(/\s+\[\d+\]$/,"")),bundleId:tY(M,"Identifier"),version:tY(M,"Version"),incident:tY(M,"Incident Identifier"),timestamp:tY(M,"Date/Time"),exceptionType:tY(M,"Exception Type"),exceptionCodes:tY(M,"Exception Codes"),terminationReason:tY(M,"Termination Reason"),crashedThread:O,topFrames:(k=D,x=O,E=P,void 0===x?[]:k.filter(e=>e.threadIndex===x).slice(0,5).map(e=>tW(e.frameIndex,e.image,e.address,E))),findings:[]},findings:tJ(F)}),matchedImages:J,symbolicatedFrames:X,skippedImages:Q,warnings:Z,message:`Symbolicated ${X} frame${1===X?"":"s"} -> ${q}`}}async function t3(e,t){await t2(e,t);try{return await c.readFile(e,"utf8")}catch(a){throw new f("INVALID_ARGS",`Failed to read ${t}: ${e}`,{message:a instanceof Error?a.message:String(a)})}}async function t2(e,t){try{let a=await c.stat(e);if(a.size<=0x4000000)return;throw new f("INVALID_ARGS",`${t} is too large: ${e}`,{actualBytes:a.size,maxBytes:0x4000000,hint:"Pass a bounded Apple .ips/.crash artifact. For very large logs, first narrow the log to the crash report, or use logs grep/tail for lead-up context."})}catch(a){if(a instanceof f)throw a;throw new f("INVALID_ARGS",`Failed to read ${t}: ${e}`,{message:a instanceof Error?a.message:String(a)})}}function t5(e,t){return r.resolve(e,t)}let t4={...G,...et,...ee,...er,...en,...H,...ea,...Z,...el,...Y,...J,batch:ei(function(e,t){let a=t4[e];if(!a)throw Error(`Missing daemon writer for batch command: ${e}`);return a(t)})};function t6(e={},t={}){let a=t.transport??tD,r=async(t,r=[],n={})=>{let i=t7(e,n),o=await a({session:X(i.session),command:t,positionals:r,flags:Q(i),runtime:i.runtime,meta:W(i)});return o.ok||function(e){throw new f(u(e.code),e.message,{...e.details??{},hint:e.hint,diagnosticId:e.diagnosticId,logPath:e.logPath})}(o.error),o.data??{}},n=async(e={})=>{let t=await r(T.sessionList,[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(O)},i=async(e,t={})=>{let a=t4[e](t);return await r(a.command,a.positionals,a.options)},o=(t={})=>X(t7(e,t).session);return{command:{wait:async e=>await i("wait",e),alert:async(e={})=>await i("alert",e),appState:async(e={})=>await i("appstate",e),back:async(e={})=>await i("back",e),home:async(e={})=>await i("home",e),rotate:async e=>await i("rotate",e),appSwitcher:async(e={})=>await i("app-switcher",e),keyboard:async(e={})=>await i("keyboard",e),clipboard:async e=>await i("clipboard",e),reactNative:async e=>await i("react-native",e),prepare:async e=>await i("prepare",e)},devices:{list:async(e={})=>{let t=await i("devices",e);return(Array.isArray(t.devices)?t.devices:[]).map(es)},boot:async(e={})=>await i("boot",e),shutdown:async(e={})=>await i("shutdown",e)},sessions:{list:async(e={})=>await n(e),stateDir:async(t={})=>P(t7(e,t).stateDir??process.env.AGENT_DEVICE_STATE_DIR).baseDir,close:async(e={})=>{let t=o(e),a=(await i("close",e)).shutdown;return{session:t,shutdown:"object"==typeof a&&null!==a?a:void 0,identifiers:{session:t}}}},apps:{install:async e=>V(await i("install",e),o(e)),reinstall:async e=>V(await i("reinstall",e),o(e)),installFromSource:async e=>eu(await i("install-from-source",e),o(e)),list:async(e={})=>{let t=await i("apps",e);return Array.isArray(t.apps)?t.apps.filter(e=>"string"==typeof e):[]},open:async e=>{let t=o(e),a=await i("open",e),r=z(a),n=j(a,"appBundleId");return{session:t,sessionStateDir:j(a,"sessionStateDir"),appName:j(a,"appName"),appBundleId:n,appId:n,startup:ec(a.startup),runtime:eo(a.runtime),device:r,identifiers:{session:t,deviceId:r?.id,deviceName:r?.name,udid:r?.ios?.udid,serial:r?.android?.serial,appId:n,appBundleId:n}}},close:async(e={})=>{let t=o(e),a=(await i("close",e)).shutdown;return{session:t,closedApp:e.app,shutdown:"object"==typeof a&&null!==a?a:void 0,identifiers:{session:t}}},push:async e=>await i("push",e),triggerEvent:async e=>await i("trigger-app-event",e)},materializations:{release:async e=>q(await r(T.releaseMaterializedPaths,[],{...e,materializationId:e.materializationId}))},leases:{allocate:async e=>t9(await r(T.leaseAllocate,[],{...e,leaseId:void 0,leaseTtlMs:e.ttlMs})),heartbeat:async e=>t9(await r(T.leaseHeartbeat,[],{...e,leaseTtlMs:e.ttlMs})),release:async e=>({released:!0===(await r(T.leaseRelease,[],e)).released})},metro:{prepare:async t=>await ep({projectRoot:t.projectRoot??e.cwd,kind:t.kind,publicBaseUrl:t.publicBaseUrl,proxyBaseUrl:t.proxyBaseUrl,proxyBearerToken:t.bearerToken,bridgeScope:t.bridgeScope,launchUrl:t.launchUrl,companionProfileKey:t.companionProfileKey,companionConsumerKey:t.companionConsumerKey,metroPort:t.port,listenHost:t.listenHost,statusHost:t.statusHost,startupTimeoutMs:t.startupTimeoutMs,probeTimeoutMs:t.probeTimeoutMs,reuseExisting:t.reuseExisting,installDependenciesIfNeeded:t.installDependenciesIfNeeded,runtimeFilePath:t.runtimeFilePath,logPath:t.logPath}),reload:async(t={})=>await ef({metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,runtime:e.runtime,timeoutMs:t.timeoutMs})},capture:{snapshot:async(e={})=>{var t,a,r;let n,s,l,d,c=o(e);return t=await i("snapshot",e),a=c,n=j(t,"appBundleId"),{nodes:K(t.nodes),truncated:!0===t.truncated,appName:j(t,"appName"),appBundleId:n,...(s=t8((r=t).visibility),l=t8(r.unchanged),d=b(r.snapshotDiagnostics),{...s?{visibility:s}:{},...B(r),...l?{unchanged:l}:{},...d?{snapshotDiagnostics:d}:{}}),identifiers:{session:a,appId:n,appBundleId:n}}},screenshot:async(e={})=>{let t=o(e),a=await i("screenshot",e);return{path:F(a,"path"),overlayRefs:ed(a),identifiers:{session:t}}},diff:async e=>await i("diff",e)},interactions:{click:async e=>await i("click",e),press:async e=>await i("press",e),longPress:async e=>await i("longpress",e),swipe:async e=>await i("swipe",e),pan:async e=>await i("gesture-pan",e),fling:async e=>await i("gesture-fling",e),swipeGesture:async e=>await i("gesture-swipe",e),focus:async e=>await i("focus",e),type:async e=>await i("type",e),fill:async e=>await i("fill",e),scroll:async e=>await i("scroll",e),pinch:async e=>await i("gesture-pinch",e),rotateGesture:async e=>await i("gesture-rotate",e),transformGesture:async e=>await i("gesture-transform",e),get:async e=>await i("get",e),is:async e=>await i("is",e),find:async e=>await i("find",e)},replay:{run:async e=>await i("replay",e),test:async e=>await i("test",e)},batch:{run:async e=>await i("batch",e)},observability:{perf:async(e={})=>await i("perf",e),logs:async(e={})=>await i("logs",e),network:async(e={})=>await i("network",e)},debug:{symbols:async t=>await t1({cwd:t.cwd??e.cwd,...t})},recording:{record:async e=>await i("record",e),trace:async e=>await i("trace",e)},settings:{update:async e=>await i("settings",e)}}}function t8(e){return"object"==typeof e&&null!==e?e:void 0}function t7(e,t){return{...e,...t}}function t9(e){let t=e.lease;if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Invalid lease response from daemon");return{leaseId:F(t,"leaseId"),tenantId:F(t,"tenantId"),runId:F(t,"runId"),backend:F(t,"backend"),createdAt:"number"==typeof t.createdAt?t.createdAt:void 0,heartbeatAt:"number"==typeof t.heartbeatAt?t.heartbeatAt:void 0,expiresAt:"number"==typeof t.expiresAt?t.expiresAt:void 0}}export{t6 as createAgentDeviceClient,ez as formatDurationSeconds,eY as replayTestFailureStepLines,tD as sendToDaemon};