agent-device 0.12.5 → 0.12.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.
- package/dist/src/641.js +33 -33
- package/dist/src/818.js +1 -1
- package/dist/src/backend.d.ts +326 -4
- package/dist/src/bin.js +36 -36
- package/dist/src/commands/index.d.ts +978 -6
- package/dist/src/commands/index.js +1 -1
- package/dist/src/daemon.js +15 -15
- package/dist/src/index.d.ts +977 -5
- package/dist/src/index.js +3 -3
- package/dist/src/testing/conformance.d.ts +341 -4
- package/dist/src/testing/conformance.js +1 -1
- package/package.json +1 -1
- package/skills/agent-device/references/bootstrap-install.md +5 -3
- package/skills/agent-device/references/macos-desktop.md +1 -1
- package/skills/agent-device/references/remote-tenancy.md +64 -16
package/dist/src/641.js
CHANGED
|
@@ -1,38 +1,38 @@
|
|
|
1
|
-
let e,t;import{__webpack_require__ as n}from"./1~rslib-runtime.js";import r,{existsSync as i,promises as a}from"node:fs";import o from"node:path";import{URL as s,fileURLToPath as l}from"node:url";import{AsyncLocalStorage as u}from"node:async_hooks";import d,{createHash as c}from"node:crypto";import p,{hostname as f}from"node:os";import{PNG as h}from"pngjs";import m from"node:net";import{XMLParser as w}from"fast-xml-parser";import g from"node:dns/promises";import y from"node:fs/promises";import{TextDecoder as b}from"node:util";import{whichCmd as v,resolveFileOverridePath as I,runCmdStreaming as A,asAppError as x,runCmdDetached as S,runCmdBackground as N,AppError as _,runCmd as M,runCmdSync as D,isExecutablePath as E,resolveExecutableOverridePath as C,redactDiagnosticData as O}from"./818.js";var k={};n.r(k),n.d(k,{ensureAndroidEmulatorBooted:()=>og,listAndroidDevices:()=>oc,waitForAndroidBoot:()=>oy});var L={};n.r(L),n.d(L,{TM:()=>uR,ensureBootedSimulator:()=>l_,installIosApp:()=>uP,installIosInstallablePath:()=>uF,listIosApps:()=>uj,L5:()=>uk,IJ:()=>uL,TJ:()=>uV,J7:()=>uU,reinstallIosApp:()=>u$,resolveIosApp:()=>uO,kc:()=>uw,Cm:()=>uB,ap:()=>uG});let R="<wifi|airplane|location> <on|off>",T="appearance <light|dark|toggle>",P="faceid <match|nonmatch|enroll|unenroll>",$="touchid <match|nonmatch|enroll|unenroll>",F="fingerprint <match|nonmatch>",U="permission <grant|deny|reset> <camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri> [full|limited]",G="permission <grant|reset> <accessibility|screen-recording|input-monitoring>",V=`macOS supports only settings ${T} and settings ${G}. wifi|airplane|location remain unsupported on macOS.`,B=`settings ${R} | settings ${T} | settings ${P} | settings ${$} | settings ${F} | settings ${U} | settings ${G}`,j=`settings requires ${R}, ${T}, ${P}, ${$}, ${F}, ${U}, or ${G}`;function q(e){return`Unsupported macOS setting: ${e}. ${V}`}let W=["app","frontmost-app","desktop","menubar"];function z(e){let t=e?.trim().toLowerCase();if("app"===t||"frontmost-app"===t||"desktop"===t||"menubar"===t)return t;throw new _("INVALID_ARGS",`Invalid surface: ${e}. Use ${W.join("|")}.`)}function X(e){var t;let n,r=Y(e.label),i=Y(e.value),a=Y(e.identifier),o=(t=a)&&!/^[\w.]+:id\/[\w.-]+$/i.test(t)&&!/^_?NS:\d+$/i.test(t)?a:"";return(n=H(e.type??"")).includes("textfield")||n.includes("securetextfield")||n.includes("searchfield")||n.includes("edittext")||n.includes("textview")||n.includes("textarea")?i||r||o:r||i||o}function Y(e){return"string"==typeof e?e.trim():""}function H(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 J(e,t={}){let n=[],r=[];for(let i of e){let e=i.depth??0,a=i.label?.trim()||i.value?.trim()||i.identifier?.trim()||"",o=Q(i.type??"Element");if("group"===o&&!a)continue;for(;n.length>0&&e<=n[n.length-1];)n.pop();let s=n.length;n.push(e),r.push({node:i,depth:s,type:o,text:K(i,s,!1,o,t)})}return r}function K(e,t,n,r,i={}){var a,o,s,l,u;let d,c,p=r??Q(e.type??"Element"),f=(d=X(e),{text:d,isLargeSurface:c=function(e,t){if("text-view"===t||"text-field"===t||"search"===t)return!0;let n=H(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,p),shouldSummarize:c&&!!(a=d)&&(a.length>80||/[\r\n]/.test(a))}),h=(o=e,s=p,l=i,u=f,l.summarizeTextSurfaces&&u.shouldSummarize&&function(e,t,n){let r=Y(e.label);if(r&&r!==n)return r;let i=Y(e.identifier);if(i&&!et(i)&&i!==n)return i;switch(t){case"text":case"text-view":return"Text view";case"text-field":return"Text field";case"search":return"Search field";default:return""}}(o,s,u.text)||Z(o,s)),m=" ".repeat(t),w=e.ref?`@${e.ref}`:"",g=(function(e,t,n,r){let i,a=[];if(!1===e.enabled&&a.push("disabled"),!n.summarizeTextSurfaces||(!0===e.selected&&a.push("selected"),ee(t)&&a.push("editable"),function(e,t){if("scroll-area"===t)return!0;let n=(e.type??"").toLowerCase(),r=`${e.role??""} ${e.subrole??""}`.toLowerCase();return n.includes("scroll")||r.includes("scroll")}(e,t)&&a.push("scrollable"),!r.shouldSummarize))return a;return a.push(`preview:"${((i=r.text.replace(/\s+/g," ").trim()).length<=48?i:`${i.slice(0,45)}...`).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`),a.push("truncated"),[...new Set(a)]})(e,p,i,f).map(e=>` [${e}]`).join(""),y=h?` "${h}"`:"";return n?`${m}${w} [${p}]${g}`.trimEnd():`${m}${w} [${p}]${y}${g}`.trimEnd()}function Z(e,t){var n,r;let i,a=e.label?.trim();if(a&&(n=t,r=a,("scroll-area"===n||"list"===n||"collection"===n||"table"===n)&&(i=r.trim().toLowerCase())&&/^(vertical|horizontal)\s+scroll\s+bar(?:,?\s*\d+\s+pages?)?$/.test(i)))return"";let o=e.value?.trim();if(ee(t)){if(o)return o;if(a)return a}else if(a)return a;if(o)return o;let s=e.identifier?.trim();return!s||et(s)&&("group"===t||"image"===t||"list"===t||"collection"===t)?"":s}function Q(e){let t=e.replace(/XCUIElementType/gi,"").toLowerCase(),n=e.includes(".")&&(e.startsWith("android.")||e.startsWith("androidx.")||e.startsWith("com."));switch(t.includes(".")&&(t=t.replace(/^android\.widget\./,"").replace(/^android\.view\./,"").replace(/^android\.webkit\./,"").replace(/^androidx\./,"").replace(/^com\.google\.android\./,"").replace(/^com\.android\./,""),n&&t.includes(".")&&(t=t.slice(t.lastIndexOf(".")+1))),t){case"application":return"application";case"navigationbar":return"navigation-bar";case"tabbar":return"tab-bar";case"button":case"imagebutton":return"button";case"link":return"link";case"cell":return"cell";case"statictext":case"checkedtextview":return"text";case"textfield":case"edittext":return"text-field";case"textview":return n?"text":"text-view";case"textarea":return"text-view";case"switch":return"switch";case"slider":return"slider";case"image":case"imageview":return"image";case"webview":return"webview";case"framelayout":case"linearlayout":case"relativelayout":case"constraintlayout":case"viewgroup":case"view":case"group":return"group";case"listview":case"recyclerview":return"list";case"collectionview":return"collection";case"searchfield":return"search";case"segmentedcontrol":return"segmented-control";case"window":return"window";case"checkbox":return"checkbox";case"radio":return"radio";case"menuitem":return"menu-item";case"toolbar":return"toolbar";case"scrollarea":case"scrollview":case"nestedscrollview":return"scroll-area";case"table":return"table";default:return t||"element"}}function ee(e){return"text-field"===e||"text-view"===e||"search"===e}function et(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function en(e){return new Map(e.map(e=>[e.index,e]))}function er(e){return e.label?.trim()||e.value?.trim()||e.identifier?.trim()||""}function ei(e){return e.map((e,t)=>({...e,ref:`e${t+1}`}))}function ea(e){let t=e.trim();return t.startsWith("@")?t.slice(1)||null:t.startsWith("e")?t:null}function eo(e,t){return e.find(e=>e.ref===t)??null}function es(e){return{x:Math.round(e.x+e.width/2),y:Math.round(e.y+e.height/2)}}function el(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}function eu(e){let t=null,n=-1;for(let r of e){let e=r.width*r.height;e>n&&(t=r,n=e)}return t}function ed(e,t,n,r){return Math.max(e,n)<=Math.min(t,r)}function ec(e){let t=`${e??""}`.toLowerCase();return t.includes("scroll")||t.includes("recyclerview")||t.includes("listview")||t.includes("gridview")||t.includes("collectionview")||"table"===t}function ep(e){return!!ec(e.type)||`${e.role??""} ${e.subrole??""}`.toLowerCase().includes("scroll")}function ef(e){if(0===e.length)return{nodes:e,hiddenCount:0,summaryLines:[]};let t=en(e),n=new Set,r=[];for(let i of e){if(eh(i,e,t)){!function(e,t,n){let r=e,i=new Set;for(;r&&!i.has(r.index);)i.add(r.index),t.add(r.index),r="number"==typeof r.parentIndex?n.get(r.parentIndex):void 0}(i,n,t);continue}r.push(i)}let i=function(e,t,n,r){let i=new Map,a=new Set;for(let e of t){if(!e.rect)continue;let t=eg(e,n,r);if(!t?.rect)continue;let o=ew(e.rect,t.rect);if(!o)continue;let s=i.get(t.index)??new Set;s.add(o),i.set(t.index,s),a.add(e.index)}return function(e,t,n,r){for(let i of e){let e=function(e){let t=function(e,t){if(!(e?.trim().toLowerCase()??"").includes("vertical scroll bar"))return null;let n=function(e){if(!e)return null;let t=/^(\d{1,3})%$/.exec(e.trim());if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?Math.max(0,Math.min(100,n)):null}(t);return null===n?null:n<=1?{above:!1,below:!0}:n>=99?{above:!0,below:!1}:{above:!0,below:!0}}(e.label,e.value);if(!t)return null;let n=new Set;return t.above&&n.add("above"),t.below&&n.add("below"),n.size>0?n:null}(i);if(!e||0===e.size)continue;let a=eg(i,t,n);if(!a)continue;let o=r.get(a.index)??new Set;for(let t of e)o.add(t);r.set(a.index,o)}}(e,n,r,i),{directionsByContainer:i,coveredNodeIndexes:a}}(e,r,n,t),a=0===n.size?e:e.filter(e=>n.has(e.index));return{nodes:a.map(e=>(function(e,t){let n=t.get(e.index);if(!n||0===n.size)return e;let r=!!(!0===e.hiddenContentAbove||n.has("above"))||void 0,i=!!(!0===e.hiddenContentBelow||n.has("below"))||void 0;return{...e,hiddenContentAbove:r,hiddenContentBelow:i}})(e,i.directionsByContainer)),hiddenCount:0===n.size?0:e.length-a.length,summaryLines:function(e,t,n){let r=new Map;for(let i of e){let e=function(e,t,n){if(!e.rect)return null;let r=em(e,t,n);return r?ew(e.rect,r):null}(i,t,n);if(!e)continue;let a=r.get(e)??[];a.push(i),r.set(e,a)}return["above","below"].flatMap(e=>{let t=r.get(e);if(!t||0===t.length)return[];let n=(function(e){let t=new Set,n=[];for(let r of e){let e=er(r);!e||t.has(e)||(t.add(e),n.push(e))}return n})(t).slice(0,3).map(e=>`"${e}"`),i=1===t.length?"interactive item":"interactive items",a=n.length>0?`: ${n.join(", ")}`:"";return[`[off-screen ${e}] ${t.length} ${i}${a}`]})}(r.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")||!!er(e)}(e)),e,t)}}function eh(e,t,n=en(t)){var r;if(!e.rect)return!0;let i=em(e,t,n);return!i||(r=e.rect,ed(r.x,r.x+r.width,i.x,i.x+i.width)&&ed(r.y,r.y+r.height,i.y,i.y+i.height))}function em(e,t,n=en(t)){let r=function(e,t){let n="number"==typeof e.parentIndex?t.get(e.parentIndex):void 0,r=new Set;for(;n&&!r.has(n.index);){if(r.add(n.index),n.rect&&ep(n))return n.rect;n="number"==typeof n.parentIndex?t.get(n.parentIndex):void 0}return null}(e,n);return r||function(e,t){let n=es(t),r=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)}),i=r.filter(e=>{let t=(e.type??"").toLowerCase();return t.includes("application")||t.includes("window")}),a=eu(i.map(e=>e.rect).filter(e=>el(e,n.x,n.y)));if(a)return a;let o=eu(i.map(e=>e.rect));if(o)return o;let s=eu(r.map(e=>e.rect).filter(e=>el(e,n.x,n.y)));return s||null}(t,e.rect??{x:0,y:0,width:0,height:0})}function ew(e,t){return e.y+e.height<=t.y?"above":e.y>=t.y+t.height?"below":null}function eg(e,t,n){let r="number"==typeof e.parentIndex?n.get(e.parentIndex):void 0,i=new Set;for(;r&&!i.has(r.index);){if(i.add(r.index),t.has(r.index)&&ep(r))return r;r="number"==typeof r.parentIndex?n.get(r.parentIndex):void 0}return null}function ey(){try{let e=eb();return JSON.parse(r.readFileSync(o.join(e,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}function eb(){let e=o.dirname(l(import.meta.url)),t=e;for(let e=0;e<6;e+=1){let e=o.join(t,"package.json");if(r.existsSync(e))return t;t=o.dirname(t)}return e}let ev=new u;function eI(){return d.randomBytes(8).toString("hex")}async function eA(e,t){let n={...e,diagnosticId:`${Date.now().toString(36)}-${d.randomBytes(4).toString("hex")}`,events:[]};return await ev.run(n,t)}function ex(){let e=ev.getStore();return e?{diagnosticId:e.diagnosticId,requestId:e.requestId,session:e.session,command:e.command,debug:e.debug}:{}}function eS(e){let t=ev.getStore();if(!t)return;let n={ts:new Date().toISOString(),level:e.level??"info",phase:e.phase,session:t.session,requestId:t.requestId,command:t.command,durationMs:e.durationMs,data:e.data?O(e.data):void 0};if(t.events.push(n),!t.debug)return;let i=`[agent-device][diag] ${JSON.stringify(n)}
|
|
2
|
-
`;try{t.logPath&&r.appendFile(t.logPath,
|
|
3
|
-
`),t.events=[],s}catch{return null}}let eM=[/(^|[/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])src\/daemon\.ts($|[\s"'])/];function eD(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function eE(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=D("ps",["-p",String(e),"-o","lstart="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let n=t.stdout.trim();return n.length>0?n:null}catch{return null}}function eC(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=D("ps",["-p",String(e),"-o","command="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let n=t.stdout.trim();return n.length>0?n:null}catch{return null}}function eO(e,t){let n;if(!eD(e))return!1;if(t){let n=eE(e);if(!n||n!==t)return!1}let r=eC(e);return!!r&&!!(n=r.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&eM.some(e=>e.test(n))}function ek(e,t){try{return process.kill(e,t),!0}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return!1;throw t}}async function eL(e,t){if(!eD(e))return!0;let n=Date.now();for(;Date.now()-n<t;)if(await new Promise(e=>setTimeout(e,50)),!eD(e))return!0;return!eD(e)}async function eR(e,t){!eO(e,t.expectedStartTime)||!ek(e,"SIGTERM")||await eL(e,t.termTimeoutMs)||ek(e,"SIGKILL")&&await eL(e,t.killTimeoutMs)}function eT(e){return e?.HOME?.trim()||p.homedir()}function eP(e,t={}){return"~"===e?eT(t.env):e.startsWith("~/")?o.join(eT(t.env),e.slice(2)):e}function e$(e,t={}){let n=eP(e,t);return o.isAbsolute(n)?n:o.resolve(t.cwd??process.cwd(),n)}function eF(e){let t,n=(t=(e??"").trim())?e$(t):o.join(eP("~"),".agent-device");return{baseDir:n,infoPath:o.join(n,"daemon.json"),lockPath:o.join(n,"daemon.lock"),logPath:o.join(n,"daemon.log"),sessionsDir:o.join(n,"sessions")}}function eU(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function eG(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function eV(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function eB(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}let ej=/(?:^|[^\w$.])(?:import|export)\s+(?:type\s+)?(?:[^'"`]*?\s+from\s+)?['"]([^'"]+)['"]/gm,eq=/import\(\s*['"]([^'"]+)['"]\s*\)/gm,eW=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];function ez(){let e=process.argv[1];return e?eX(e):"unknown"}function eX(e,t=eb()){try{let n=o.resolve(t),i=[o.resolve(e)],a=new Set,s=[];for(;i.length>0;){let e=i.pop();if(!e||a.has(e))continue;a.add(e);let t=r.statSync(e);if(!t.isFile())continue;let l=o.relative(n,e)||e;s.push(`${l}:${t.size}:${Math.trunc(t.mtimeMs)}`);let u=r.readFileSync(e,"utf8");for(let t of function(e){let t=new Set;return eY(e,ej,t),eY(e,eq,t),[...t]}(u)){let n=function(e,t){let n=o.resolve(o.dirname(e),t),r=eH(n);if(r)return r;for(let e of eW){let t=eH(`${n}${e}`);if(t)return t}for(let e of eW){let t=eH(o.join(n,`index${e}`));if(t)return t}return null}(e,t);n&&i.push(n)}}let l=s.sort().join("|"),u=d.createHash("sha1").update(l).digest("hex");return`graph:${s.length}:${u}`}catch{return"unknown"}}function eY(e,t,n){t.lastIndex=0;let r=null;for(;null!==(r=t.exec(e));){let e=r[1]?.trim();e?.startsWith(".")&&n.add(e)}}function eH(e){try{return r.statSync(e).isFile()?e:null}catch{return null}}let eJ=100,eK=new Set(["batch","replay"]),eZ=new Set(["command","positionals","flags","runtime"]);function eQ(e){let t;try{t=JSON.parse(e)}catch{throw new _("INVALID_ARGS","Batch steps must be valid JSON.")}if(!Array.isArray(t)||0===t.length)throw new _("INVALID_ARGS","Batch steps must be a non-empty JSON array.");return t}function e0(e,t){if(!Array.isArray(e)||0===e.length)throw new _("INVALID_ARGS","batch requires a non-empty batchSteps array.");if(e.length>t)throw new _("INVALID_ARGS",`batch has ${e.length} steps; max allowed is ${t}.`);let n=[];for(let t=0;t<e.length;t+=1){let r=e[t];if(!r||"object"!=typeof r)throw new _("INVALID_ARGS",`Invalid batch step at index ${t}.`);let i=Object.keys(r).filter(e=>!eZ.has(e));if(i.length>0){let e=i.map(e=>`"${e}"`).join(", ");throw new _("INVALID_ARGS",`Batch step ${t+1} has unknown field(s): ${e}. Allowed fields: command, positionals, flags, runtime.`)}let a="string"==typeof r.command?r.command.trim().toLowerCase():"";if(!a)throw new _("INVALID_ARGS",`Batch step ${t+1} requires command.`);if(eK.has(a))throw new _("INVALID_ARGS",`Batch step ${t+1} cannot run ${a}.`);if(void 0!==r.positionals&&!Array.isArray(r.positionals))throw new _("INVALID_ARGS",`Batch step ${t+1} positionals must be an array.`);let o=r.positionals??[];if(o.some(e=>"string"!=typeof e))throw new _("INVALID_ARGS",`Batch step ${t+1} positionals must contain only strings.`);if(void 0!==r.flags&&("object"!=typeof r.flags||Array.isArray(r.flags)||!r.flags))throw new _("INVALID_ARGS",`Batch step ${t+1} flags must be an object.`);if(void 0!==r.runtime&&("object"!=typeof r.runtime||Array.isArray(r.runtime)||!r.runtime))throw new _("INVALID_ARGS",`Batch step ${t+1} runtime must be an object.`);n.push({command:a,positionals:o,flags:r.flags??{},runtime:r.runtime})}return n}let e1=new Set(["id","role","text","label","value","appname","windowtitle"]),e2=new Set(["visible","hidden","editable","selected","enabled","hittable"]),e3=new Set([...e1,...e2]);function e4(e){let t=e.trim();if(!t)throw new _("INVALID_ARGS","Selector expression cannot be empty");let n=function(e){let t=[],n="",r=null;for(let i=0;i<e.length;i+=1){let a=e[i];if(('"'===a||"'"===a)&&!tt(e,i)){r=e7(r,a),n+=a;continue}if(!r&&"|"===a&&"|"===e[i+1]){let r=n.trim();if(!r)throw new _("INVALID_ARGS",`Invalid selector fallback expression: ${e}`);t.push(r),n="",i+=1;continue}n+=a}let i=n.trim();if(!i)throw new _("INVALID_ARGS",`Invalid selector fallback expression: ${e}`);return t.push(i),t}(t);if(0===n.length)throw new _("INVALID_ARGS","Selector expression cannot be empty");return{raw:t,selectors:n.map(e=>(function(e){let t=e.trim();if(!t)throw new _("INVALID_ARGS","Selector segment cannot be empty");let n=function(e){let t=[],n="",r=null;for(let i=0;i<e.length;i+=1){let a=e[i];if(('"'===a||"'"===a)&&!tt(e,i)){r=e7(r,a),n+=a;continue}if(!r&&/\s/.test(a)){n.trim()&&t.push(n.trim()),n="";continue}n+=a}if(r)throw new _("INVALID_ARGS",`Unclosed quote in selector: ${e}`);return n.trim()&&t.push(n.trim()),t}(t);if(0===n.length)throw new _("INVALID_ARGS",`Invalid selector segment: ${e}`);return{raw:t,terms:n.map(e9)}})(e))}}function e5(e){try{return e4(e)}catch{return null}}function e8(e,t={}){if(0===e.length)return null;let n=t.preferTrailingValue??!1,r=0,i=[];for(;r<e.length&&function(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 e3.has(e)}return e3.has(t.toLowerCase())}(e[r]);){r+=1;let t=e.slice(0,r).join(" ").trim();t&&e5(t)&&i.push(r)}if(0===i.length)return null;let a=i[i.length-1];if(n){for(let t=i.length-1;t>=0;t-=1)if(i[t]<e.length){a=i[t];break}}let o=e.slice(0,a).join(" ").trim();return o?{selectorExpression:o,rest:e.slice(a)}:null}function e6(e){let t=e[0]??"",n=e8(e.slice(1),{preferTrailingValue:"text"===t});return{predicate:t,split:n}}function e9(e){let t=e.trim();if(!t)throw new _("INVALID_ARGS","Empty selector term");let n=t.indexOf("=");if(-1===n){let n=t.toLowerCase();if(!e2.has(n))throw new _("INVALID_ARGS",`Invalid selector term "${e}", expected key=value`);return{key:n,value:!0}}let r=t.slice(0,n).trim().toLowerCase(),i=t.slice(n+1).trim();if(!e3.has(r))throw new _("INVALID_ARGS",`Unknown selector key: ${r}`);if(!i)throw new _("INVALID_ARGS",`Missing selector value for key: ${r}`);if(e2.has(r)){let e,t="true"===(e=te(i).toLowerCase())||"false"!==e&&null;if(null===t)throw new _("INVALID_ARGS",`Invalid boolean value for ${r}: ${i}`);return{key:r,value:t}}return{key:r,value:te(i)}}function e7(e,t){return e?e===t?null:e:t}function te(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1).replace(/\\(["'])/g,"$1"):t}function tt(e,t){let n=0;for(let r=t-1;r>=0&&"\\"===e[r];r-=1)n+=1;return n%2==1}function tn(e,t){let n=t.toLowerCase();return e.find(e=>{let t=(e.label??"").toLowerCase(),r=(e.value??"").toLowerCase(),i=(e.identifier??"").toLowerCase();return t.includes(n)||r.includes(n)||i.includes(n)})??null}function tr(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&&ti(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||!ti(t))continue;let i=Math.abs(e.rect.y+e.rect.height/2-n);(!r||i<r.distance)&&(r={label:t,distance:i})}return r?.label}(e,t)??(n&&ti(n)?n:void 0)}function ti(e){let t=e.trim();return!(!t||/^(true|false)$/i.test(t)||/^\d+$/.test(t))}function ta(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 i=to(r.type??""),a=[r.label,r.value,r.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0),o=!!a&&ti(a);if(("group"===i||"ioscontentgroup"===i)&&!o){t.push(e);continue}let s=Math.max(0,e-t.length);n.push({...r,depth:s})}return n}function to(e){let t=e.trim().replace(/XCUIElementType/gi,"");t.startsWith("AX")&&(t=t.slice(2));let n=Math.max((t=t.toLowerCase()).lastIndexOf("."),t.lastIndexOf("/"));return -1!==n&&(t=t.slice(n+1)),t}function ts(e,t){let n=to(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 tl(e,t){if(t.hittable)return t;let n=t,r=new Set;for(;void 0!==n.parentIndex&&!r.has(n.ref);){r.add(n.ref);let t=e[n.parentIndex];if(!t)break;if(t.hittable)return t;n=t}return null}function tu(e){return[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").filter(e=>e.length>0)[0]??""}function td(e){return!0===e.hittable||!!e.rect&&e.rect.width>0&&e.rect.height>0}function tc(e,t){return ts(e.type??"",t)&&!1!==e.enabled}function tp(e,t,n,r={}){let i=th(n);if(!i)return{matches:[],score:0};let a=0,o=[];for(let n of e){if(r.requireRect&&!n.rect)continue;let e=function(e,t,n){switch(t){case"role":return function(e,t){let n=function(e){let t=e.trim();return t?t=(t.split(".").pop()??t).replace(/XCUIElementType/gi,"").toLowerCase():""}(e??"");return n?n===t?2:+!!n.includes(t):0}(e.type,n);case"label":return tf(e.label,n);case"value":return tf(e.value,n);case"id":return tf(e.identifier,n);default:return Math.max(tf(e.label,n),tf(e.value,n),tf(e.identifier,n))}}(n,t,i);if(!(e<=0)){if(e>a){a=e,o.length=0,o.push(n);continue}e===a&&o.push(n)}}return{matches:o,score:a}}function tf(e,t){let n=th(e??"");return n?n===t?2:+!!n.includes(t):0}function th(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function tm(e){let t="any",n=0;["text","label","value","role","id"].includes(e[0])&&(t=e[0],n=1);let r=e[n]??"",i=e.slice(n+1);if(0===i.length)return{locator:t,query:r,action:"click"};let a=i[0].toLowerCase();if("get"===a){let e=i[1]?.toLowerCase();if("text"===e)return{locator:t,query:r,action:"get_text"};if("attrs"===e)return{locator:t,query:r,action:"get_attrs"};throw new _("INVALID_ARGS","find get only supports text or attrs")}if("wait"===a)return{locator:t,query:r,action:"wait",timeoutMs:function(e){if(!e)return null;let t=Number(e);return Number.isFinite(t)?t:null}(i[1])??void 0};if("exists"===a)return{locator:t,query:r,action:"exists"};if("click"===a)return{locator:t,query:r,action:"click"};if("focus"===a)return{locator:t,query:r,action:"focus"};if("fill"===a)return{locator:t,query:r,action:"fill",value:i.slice(1).join(" ")};if("type"===a)return{locator:t,query:r,action:"type",value:i.slice(1).join(" ")};throw new _("INVALID_ARGS",`Unsupported find action: ${i[0]}`)}function tw(e,t,n){return t.terms.every(t=>(function(e,t,n){switch(t.key){case"id":return tg(e.identifier,String(t.value));case"role":return tg(to(e.type??""),String(t.value));case"label":return tg(e.label,String(t.value));case"value":return tg(e.value,String(t.value));case"text":return tg(tu(e),String(t.value));case"appname":return tg(e.appName,String(t.value));case"windowtitle":return tg(e.windowTitle,String(t.value));case"visible":return td(e)===!!t.value;case"hidden":return!td(e)==!!t.value;case"editable":return tc(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 tg(e,t){return th(e??"")===th(t)}function ty(e,t,n){let r=n.requireRect??!1,i=n.requireUnique??!0,a=[];for(let o=0;o<t.selectors.length;o+=1){let s=t.selectors[o],l=function(e,t,n,r){let i=0,a=null,o=null,s=!1;for(let l of e){if(r&&!l.rect||!tw(l,t,n))continue;if(i+=1,a??=l,!o){o=l;continue}let e=function(e,t){let n=e.depth??0,r=t.depth??0;if(n!==r)return n>r?1:-1;let i=tI(e),a=tI(t);return i!==a?i<a?1:-1:0}(l,o);e>0?(o=l,s=!1):0===e&&(s=!0)}return{count:i,firstNode:a,disambiguated:s?null:o}}(e,s,n.platform,r);if(a.push({selector:s.raw,matches:l.count}),0!==l.count&&l.firstNode){if(i&&1!==l.count){if(!n.disambiguateAmbiguous||!l.disambiguated)continue;return{node:l.disambiguated,selector:s,selectorIndex:o,matches:l.count,diagnostics:a}}return{node:l.firstNode,selector:s,selectorIndex:o,matches:l.count,diagnostics:a}}}return null}function tb(e,t,n){let r=n.requireRect??!1,i=[];for(let a=0;a<t.selectors.length;a+=1){let o=t.selectors[a],s=function(e,t,n,r){let i=0;for(let a of e)(!r||a.rect)&&tw(a,t,n)&&(i+=1);return i}(e,o,n.platform,r);if(i.push({selector:o.raw,matches:s}),s>0)return{selectorIndex:a,selector:o,matches:s,diagnostics:i}}return null}function tv(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 tI(e){return e.rect?e.rect.width*e.rect.height:1/0}function tA(e,t,n={}){let r=[],i=to(e.type??""),a=tS(e.identifier),o=tS(e.label),s=tS(e.value),l=tS(tu(e)),u="fill"===n.action;a&&r.push(`id=${tx(a)}`),i&&o&&r.push(u?`role=${tx(i)} label=${tx(o)} editable=true`:`role=${tx(i)} label=${tx(o)}`),o&&r.push(u?`label=${tx(o)} editable=true`:`label=${tx(o)}`),s&&r.push(u?`value=${tx(s)} editable=true`:`value=${tx(s)}`),l&&l!==o&&l!==s&&r.push(u?`text=${tx(l)} editable=true`:`text=${tx(l)}`),i&&u&&!r.some(e=>e.includes("editable=true"))&&r.push(`role=${tx(i)} editable=true`);let d=Array.from(new Set(r));return 0===d.length&&i&&d.push(u?`role=${tx(i)} editable=true`:`role=${tx(i)}`),0===d.length&&td(e)&&d.push("visible=true"),d}function tx(e){return JSON.stringify(e)}function tS(e){if(!e)return null;let t=e.trim();return t||null}function tN(e){return e?{message:e}:{}}function t_(e,t){return t?{...e,message:t}:e}function tM(e){return"string"==typeof e?.message&&e.message.length>0?e.message:null}function tD(e){let t=e.appId??e.bundleId??e.packageName;return{session:e.session,appId:t,appBundleId:e.bundleId,package:e.packageName}}function tE(e,t,n){return{deviceId:t,deviceName:n,..."android"===e?{serial:t}:"ios"===e?{udid:t}:{}}}function tC(e,t={}){let n=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&&n?{serial:e.android?.serial??e.id}:{}}}function tO(e){return{name:e.name,...tC(e.device,{includeAndroidSerial:!1}),createdAt:e.createdAt}}function tk(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){let t=e.created?"Created":"Reused",n=e.booted?" (booted)":"";return t_({udid:e.udid,device:e.device,runtime:e.runtime,ios_simulator_device_set:e.iosSimulatorDeviceSet??null,created:e.created,booted:e.booted},`${t}: ${e.device} ${e.udid}${n}`)}function tR(e){return e.bundleId??e.package??e.app}function tT(e){return t_({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: ${tR(e)}`)}function tP(e){return e.appName??e.bundleId??e.packageName??e.launchTarget}function t$(e){return t_({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: ${tP(e)}`)}function tF(e){let t=e.appName??e.appBundleId??e.session;return t_({session:e.session,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.startup?{startup:e.startup}:{},...e.runtime?{runtime:e.runtime}:{},...e.device?tC(e.device):{}},t?`Opened: ${t}`:"Opened")}function tU(e){return{session:e.session,...e.shutdown?{shutdown:e.shutdown}:{},...tN(e.session?`Closed: ${e.session}`:"Closed")}}function tG(e){return{nodes:e.nodes,truncated:e.truncated,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.visibility?{visibility:e.visibility}:{},...e.warnings&&e.warnings.length>0?{warnings:e.warnings}:{}}}let tV=["emulator","platform-tools",o.join("cmdline-tools","latest","bin"),o.join("cmdline-tools","tools","bin")];function tB(e){let t=new Set,n=[];for(let r of e){let e=r.trim();!e||t.has(e)||(t.add(e),n.push(e))}return n}function tj(e=process.env){let t=e.ANDROID_SDK_ROOT?.trim(),n=e.ANDROID_HOME?.trim(),r=e.HOME?.trim()||p.homedir();return tB([t??"",n??"",r?o.join(r,"Android","Sdk"):""])}async function tq(e){try{return await a.access(e,a.constants.X_OK),!0}catch{return!1}}async function tW(e=process.env){let t,n=[];for(let r of tj(e)){let e=[];for(let t of tV){let n=o.join(r,t);await tq(n)&&e.push(n)}0!==e.length&&(t||(t=r),n.push(...e))}if(t&&(e.ANDROID_SDK_ROOT=e.ANDROID_SDK_ROOT?.trim()||t,e.ANDROID_HOME=e.ANDROID_HOME?.trim()||t),0===n.length)return;let r=(e.PATH??"").split(o.delimiter).map(e=>e.trim()).filter(e=>e.length>0);e.PATH=tB([...n,...r]).join(o.delimiter)}function tz(e,t){return["-s",e.id,...t]}async function tX(){if(await tW(),!await v("adb"))throw new _("TOOL_MISSING","adb not found in PATH")}function tY(e,t){let n=`${e}
|
|
4
|
-
${t}`.toLowerCase();return n.includes("no shell command implementation")||n.includes("unknown command")}async function
|
|
5
|
-
`:
|
|
1
|
+
let e,t;import{__webpack_require__ as n}from"./1~rslib-runtime.js";import r,{existsSync as a,promises as i}from"node:fs";import o from"node:path";import{URL as s,fileURLToPath as l}from"node:url";import{AsyncLocalStorage as u}from"node:async_hooks";import d,{createHash as c}from"node:crypto";import p,{hostname as f}from"node:os";import{PNG as h}from"pngjs";import m from"node:net";import{XMLParser as w}from"fast-xml-parser";import g from"node:dns/promises";import y from"node:fs/promises";import{TextDecoder as b}from"node:util";import{whichCmd as v,resolveFileOverridePath as I,runCmdStreaming as A,asAppError as x,runCmdDetached as N,runCmdBackground as S,AppError as _,runCmd as k,runCmdSync as D,isExecutablePath as M,resolveExecutableOverridePath as E,redactDiagnosticData as O}from"./818.js";var C={};n.r(C),n.d(C,{ensureAndroidEmulatorBooted:()=>s8,listAndroidDevices:()=>s0,waitForAndroidBoot:()=>s6});var R={};n.r(R),n.d(R,{TM:()=>ch,ensureBootedSimulator:()=>di,installIosApp:()=>cw,installIosInstallablePath:()=>cy,listIosApps:()=>cx,L5:()=>cp,IJ:()=>cf,TJ:()=>cI,J7:()=>cb,reinstallIosApp:()=>cg,resolveIosApp:()=>cc,kc:()=>d8,Cm:()=>cA,ap:()=>cv});let L="<wifi|airplane|location> <on|off>",P="appearance <light|dark|toggle>",T="faceid <match|nonmatch|enroll|unenroll>",$="touchid <match|nonmatch|enroll|unenroll>",F="fingerprint <match|nonmatch>",U="permission <grant|deny|reset> <camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri> [full|limited]",G="permission <grant|reset> <accessibility|screen-recording|input-monitoring>",V=`macOS supports only settings ${P} and settings ${G}. wifi|airplane|location remain unsupported on macOS.`,B=`settings ${L} | settings ${P} | settings ${T} | settings ${$} | settings ${F} | settings ${U} | settings ${G}`,j=`settings requires ${L}, ${P}, ${T}, ${$}, ${F}, ${U}, or ${G}`;function q(e){return`Unsupported macOS setting: ${e}. ${V}`}let W=["app","frontmost-app","desktop","menubar"];function z(e){let t=e?.trim().toLowerCase();if("app"===t||"frontmost-app"===t||"desktop"===t||"menubar"===t)return t;throw new _("INVALID_ARGS",`Invalid surface: ${e}. Use ${W.join("|")}.`)}function X(e){var t;let n,r=H(e.label),a=H(e.value),i=H(e.identifier),o=(t=i)&&!/^[\w.]+:id\/[\w.-]+$/i.test(t)&&!/^_?NS:\d+$/i.test(t)?i:"";return(n=Y(e.type??"")).includes("textfield")||n.includes("securetextfield")||n.includes("searchfield")||n.includes("edittext")||n.includes("textview")||n.includes("textarea")?a||r||o:r||a||o}function H(e){return"string"==typeof e?e.trim():""}function Y(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 J(e,t={}){let n=[],r=[];for(let a of e){let e=a.depth??0,i=a.label?.trim()||a.value?.trim()||a.identifier?.trim()||"",o=Q(a.type??"Element");if("group"===o&&!i)continue;for(;n.length>0&&e<=n[n.length-1];)n.pop();let s=n.length;n.push(e),r.push({node:a,depth:s,type:o,text:K(a,s,!1,o,t)})}return r}function K(e,t,n,r,a={}){var i,o,s,l,u;let d,c,p=r??Q(e.type??"Element"),f=(d=X(e),{text:d,isLargeSurface:c=function(e,t){if("text-view"===t||"text-field"===t||"search"===t)return!0;let n=Y(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,p),shouldSummarize:c&&!!(i=d)&&(i.length>80||/[\r\n]/.test(i))}),h=(o=e,s=p,l=a,u=f,l.summarizeTextSurfaces&&u.shouldSummarize&&function(e,t,n){let r=H(e.label);if(r&&r!==n)return r;let a=H(e.identifier);if(a&&!et(a)&&a!==n)return a;switch(t){case"text":case"text-view":return"Text view";case"text-field":return"Text field";case"search":return"Search field";default:return""}}(o,s,u.text)||Z(o,s)),m=" ".repeat(t),w=e.ref?`@${e.ref}`:"",g=(function(e,t,n,r){let a,i=[];if(!1===e.enabled&&i.push("disabled"),!n.summarizeTextSurfaces||(!0===e.selected&&i.push("selected"),ee(t)&&i.push("editable"),function(e,t){if("scroll-area"===t)return!0;let n=(e.type??"").toLowerCase(),r=`${e.role??""} ${e.subrole??""}`.toLowerCase();return n.includes("scroll")||r.includes("scroll")}(e,t)&&i.push("scrollable"),!r.shouldSummarize))return i;return i.push(`preview:"${((a=r.text.replace(/\s+/g," ").trim()).length<=48?a:`${a.slice(0,45)}...`).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`),i.push("truncated"),[...new Set(i)]})(e,p,a,f).map(e=>` [${e}]`).join(""),y=h?` "${h}"`:"";return n?`${m}${w} [${p}]${g}`.trimEnd():`${m}${w} [${p}]${y}${g}`.trimEnd()}function Z(e,t){var n,r;let a,i=e.label?.trim();if(i&&(n=t,r=i,("scroll-area"===n||"list"===n||"collection"===n||"table"===n)&&(a=r.trim().toLowerCase())&&/^(vertical|horizontal)\s+scroll\s+bar(?:,?\s*\d+\s+pages?)?$/.test(a)))return"";let o=e.value?.trim();if(ee(t)){if(o)return o;if(i)return i}else if(i)return i;if(o)return o;let s=e.identifier?.trim();return!s||et(s)&&("group"===t||"image"===t||"list"===t||"collection"===t)?"":s}function Q(e){let t=e.replace(/XCUIElementType/gi,"").toLowerCase(),n=e.includes(".")&&(e.startsWith("android.")||e.startsWith("androidx.")||e.startsWith("com."));switch(t.includes(".")&&(t=t.replace(/^android\.widget\./,"").replace(/^android\.view\./,"").replace(/^android\.webkit\./,"").replace(/^androidx\./,"").replace(/^com\.google\.android\./,"").replace(/^com\.android\./,""),n&&t.includes(".")&&(t=t.slice(t.lastIndexOf(".")+1))),t){case"application":return"application";case"navigationbar":return"navigation-bar";case"tabbar":return"tab-bar";case"button":case"imagebutton":return"button";case"link":return"link";case"cell":return"cell";case"statictext":case"checkedtextview":return"text";case"textfield":case"edittext":return"text-field";case"textview":return n?"text":"text-view";case"textarea":return"text-view";case"switch":return"switch";case"slider":return"slider";case"image":case"imageview":return"image";case"webview":return"webview";case"framelayout":case"linearlayout":case"relativelayout":case"constraintlayout":case"viewgroup":case"view":case"group":return"group";case"listview":case"recyclerview":return"list";case"collectionview":return"collection";case"searchfield":return"search";case"segmentedcontrol":return"segmented-control";case"window":return"window";case"checkbox":return"checkbox";case"radio":return"radio";case"menuitem":return"menu-item";case"toolbar":return"toolbar";case"scrollarea":case"scrollview":case"nestedscrollview":return"scroll-area";case"table":return"table";default:return t||"element"}}function ee(e){return"text-field"===e||"text-view"===e||"search"===e}function et(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function en(e){return new Map(e.map(e=>[e.index,e]))}function er(e){return e.label?.trim()||e.value?.trim()||e.identifier?.trim()||""}function ea(e){return e.map((e,t)=>({...e,ref:`e${t+1}`}))}function ei(e){let t=e.trim();return t.startsWith("@")?t.slice(1)||null:t.startsWith("e")?t:null}function eo(e,t){return e.find(e=>e.ref===t)??null}function es(e){return{x:Math.round(e.x+e.width/2),y:Math.round(e.y+e.height/2)}}function el(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}function eu(e){let t=null,n=-1;for(let r of e){let e=r.width*r.height;e>n&&(t=r,n=e)}return t}function ed(e,t,n,r){return Math.max(e,n)<=Math.min(t,r)}function ec(e){let t=`${e??""}`.toLowerCase();return t.includes("scroll")||t.includes("recyclerview")||t.includes("listview")||t.includes("gridview")||t.includes("collectionview")||"table"===t}function ep(e){return!!ec(e.type)||`${e.role??""} ${e.subrole??""}`.toLowerCase().includes("scroll")}function ef(e){if(0===e.length)return{nodes:e,hiddenCount:0,summaryLines:[]};let t=en(e),n=new Set,r=[];for(let a of e){if(eh(a,e,t)){!function(e,t,n){let r=e,a=new Set;for(;r&&!a.has(r.index);)a.add(r.index),t.add(r.index),r="number"==typeof r.parentIndex?n.get(r.parentIndex):void 0}(a,n,t);continue}r.push(a)}let a=function(e,t,n,r){let a=new Map,i=new Set;for(let e of t){if(!e.rect)continue;let t=eg(e,n,r);if(!t?.rect)continue;let o=ew(e.rect,t.rect);if(!o)continue;let s=a.get(t.index)??new Set;s.add(o),a.set(t.index,s),i.add(e.index)}return function(e,t,n,r){for(let a of e){let e=function(e){let t=function(e,t){if(!(e?.trim().toLowerCase()??"").includes("vertical scroll bar"))return null;let n=function(e){if(!e)return null;let t=/^(\d{1,3})%$/.exec(e.trim());if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?Math.max(0,Math.min(100,n)):null}(t);return null===n?null:n<=1?{above:!1,below:!0}:n>=99?{above:!0,below:!1}:{above:!0,below:!0}}(e.label,e.value);if(!t)return null;let n=new Set;return t.above&&n.add("above"),t.below&&n.add("below"),n.size>0?n:null}(a);if(!e||0===e.size)continue;let i=eg(a,t,n);if(!i)continue;let o=r.get(i.index)??new Set;for(let t of e)o.add(t);r.set(i.index,o)}}(e,n,r,a),{directionsByContainer:a,coveredNodeIndexes:i}}(e,r,n,t),i=0===n.size?e:e.filter(e=>n.has(e.index));return{nodes:i.map(e=>(function(e,t){let n=t.get(e.index);if(!n||0===n.size)return e;let r=!!(!0===e.hiddenContentAbove||n.has("above"))||void 0,a=!!(!0===e.hiddenContentBelow||n.has("below"))||void 0;return{...e,hiddenContentAbove:r,hiddenContentBelow:a}})(e,a.directionsByContainer)),hiddenCount:0===n.size?0:e.length-i.length,summaryLines:function(e,t,n){let r=new Map;for(let a of e){let e=function(e,t,n){if(!e.rect)return null;let r=em(e,t,n);return r?ew(e.rect,r):null}(a,t,n);if(!e)continue;let i=r.get(e)??[];i.push(a),r.set(e,i)}return["above","below"].flatMap(e=>{let t=r.get(e);if(!t||0===t.length)return[];let n=(function(e){let t=new Set,n=[];for(let r of e){let e=er(r);!e||t.has(e)||(t.add(e),n.push(e))}return n})(t).slice(0,3).map(e=>`"${e}"`),a=1===t.length?"interactive item":"interactive items",i=n.length>0?`: ${n.join(", ")}`:"";return[`[off-screen ${e}] ${t.length} ${a}${i}`]})}(r.filter(e=>!a.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")||!!er(e)}(e)),e,t)}}function eh(e,t,n=en(t)){var r;if(!e.rect)return!0;let a=em(e,t,n);return!a||(r=e.rect,ed(r.x,r.x+r.width,a.x,a.x+a.width)&&ed(r.y,r.y+r.height,a.y,a.y+a.height))}function em(e,t,n=en(t)){let r=function(e,t){let n="number"==typeof e.parentIndex?t.get(e.parentIndex):void 0,r=new Set;for(;n&&!r.has(n.index);){if(r.add(n.index),n.rect&&ep(n))return n.rect;n="number"==typeof n.parentIndex?t.get(n.parentIndex):void 0}return null}(e,n);return r||function(e,t){let n=es(t),r=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=r.filter(e=>{let t=(e.type??"").toLowerCase();return t.includes("application")||t.includes("window")}),i=eu(a.map(e=>e.rect).filter(e=>el(e,n.x,n.y)));if(i)return i;let o=eu(a.map(e=>e.rect));if(o)return o;let s=eu(r.map(e=>e.rect).filter(e=>el(e,n.x,n.y)));return s||null}(t,e.rect??{x:0,y:0,width:0,height:0})}function ew(e,t){return e.y+e.height<=t.y?"above":e.y>=t.y+t.height?"below":null}function eg(e,t,n){let r="number"==typeof e.parentIndex?n.get(e.parentIndex):void 0,a=new Set;for(;r&&!a.has(r.index);){if(a.add(r.index),t.has(r.index)&&ep(r))return r;r="number"==typeof r.parentIndex?n.get(r.parentIndex):void 0}return null}function ey(){try{let e=eb();return JSON.parse(r.readFileSync(o.join(e,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}function eb(){let e=o.dirname(l(import.meta.url)),t=e;for(let e=0;e<6;e+=1){let e=o.join(t,"package.json");if(r.existsSync(e))return t;t=o.dirname(t)}return e}let ev=new u;function eI(){return d.randomBytes(8).toString("hex")}async function eA(e,t){let n={...e,diagnosticId:`${Date.now().toString(36)}-${d.randomBytes(4).toString("hex")}`,events:[]};return await ev.run(n,t)}function ex(){let e=ev.getStore();return e?{diagnosticId:e.diagnosticId,requestId:e.requestId,session:e.session,command:e.command,debug:e.debug}:{}}function eN(e){let t=ev.getStore();if(!t)return;let n={ts:new Date().toISOString(),level:e.level??"info",phase:e.phase,session:t.session,requestId:t.requestId,command:t.command,durationMs:e.durationMs,data:e.data?O(e.data):void 0};if(t.events.push(n),!t.debug)return;let a=`[agent-device][diag] ${JSON.stringify(n)}
|
|
2
|
+
`;try{t.logPath&&r.appendFile(t.logPath,a,()=>{}),t.traceLogPath&&r.appendFile(t.traceLogPath,a,()=>{}),t.logPath||t.traceLogPath||process.stderr.write(a)}catch{}}async function eS(e,t,n){let r=Date.now();try{let a=await t();return eN({level:"info",phase:e,durationMs:Date.now()-r,data:n}),a}catch(t){throw eN({level:"error",phase:e,durationMs:Date.now()-r,data:{...n??{},error:t instanceof Error?t.message:String(t)}}),t}}function e_(e={}){let t=ev.getStore();if(!t||!e.force&&!t.debug||0===t.events.length)return null;try{let e=(t.session??"default").replace(/[^a-zA-Z0-9._-]/g,"_"),n=new Date().toISOString().slice(0,10),a=o.join(p.homedir(),".agent-device","logs",e,n);r.mkdirSync(a,{recursive:!0});let i=new Date().toISOString().replace(/[:.]/g,"-"),s=o.join(a,`${i}-${t.diagnosticId}.ndjson`),l=t.events.map(e=>JSON.stringify(O(e)));return r.writeFileSync(s,`${l.join("\n")}
|
|
3
|
+
`),t.events=[],s}catch{return null}}let ek=[/(^|[/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])src\/daemon\.ts($|[\s"'])/];function eD(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function eM(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=D("ps",["-p",String(e),"-o","lstart="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let n=t.stdout.trim();return n.length>0?n:null}catch{return null}}function eE(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=D("ps",["-p",String(e),"-o","command="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let n=t.stdout.trim();return n.length>0?n:null}catch{return null}}function eO(e,t){let n;if(!eD(e))return!1;if(t){let n=eM(e);if(!n||n!==t)return!1}let r=eE(e);return!!r&&!!(n=r.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&ek.some(e=>e.test(n))}function eC(e,t){try{return process.kill(e,t),!0}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return!1;throw t}}async function eR(e,t){if(!eD(e))return!0;let n=Date.now();for(;Date.now()-n<t;)if(await new Promise(e=>setTimeout(e,50)),!eD(e))return!0;return!eD(e)}async function eL(e,t){!eO(e,t.expectedStartTime)||!eC(e,"SIGTERM")||await eR(e,t.termTimeoutMs)||eC(e,"SIGKILL")&&await eR(e,t.killTimeoutMs)}function eP(e){return e?.HOME?.trim()||p.homedir()}function eT(e,t={}){return"~"===e?eP(t.env):e.startsWith("~/")?o.join(eP(t.env),e.slice(2)):e}function e$(e,t={}){let n=eT(e,t);return o.isAbsolute(n)?n:o.resolve(t.cwd??process.cwd(),n)}function eF(e){let t,n=(t=(e??"").trim())?e$(t):o.join(eT("~"),".agent-device");return{baseDir:n,infoPath:o.join(n,"daemon.json"),lockPath:o.join(n,"daemon.lock"),logPath:o.join(n,"daemon.log"),sessionsDir:o.join(n,"sessions")}}function eU(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function eG(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function eV(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function eB(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}let ej=/(?:^|[^\w$.])(?:import|export)\s+(?:type\s+)?(?:[^'"`]*?\s+from\s+)?['"]([^'"]+)['"]/gm,eq=/import\(\s*['"]([^'"]+)['"]\s*\)/gm,eW=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];function ez(){let e=process.argv[1];return e?eX(e):"unknown"}function eX(e,t=eb()){try{let n=o.resolve(t),a=[o.resolve(e)],i=new Set,s=[];for(;a.length>0;){let e=a.pop();if(!e||i.has(e))continue;i.add(e);let t=r.statSync(e);if(!t.isFile())continue;let l=o.relative(n,e)||e;s.push(`${l}:${t.size}:${Math.trunc(t.mtimeMs)}`);let u=r.readFileSync(e,"utf8");for(let t of function(e){let t=new Set;return eH(e,ej,t),eH(e,eq,t),[...t]}(u)){let n=function(e,t){let n=o.resolve(o.dirname(e),t),r=eY(n);if(r)return r;for(let e of eW){let t=eY(`${n}${e}`);if(t)return t}for(let e of eW){let t=eY(o.join(n,`index${e}`));if(t)return t}return null}(e,t);n&&a.push(n)}}let l=s.sort().join("|"),u=d.createHash("sha1").update(l).digest("hex");return`graph:${s.length}:${u}`}catch{return"unknown"}}function eH(e,t,n){t.lastIndex=0;let r=null;for(;null!==(r=t.exec(e));){let e=r[1]?.trim();e?.startsWith(".")&&n.add(e)}}function eY(e){try{return r.statSync(e).isFile()?e:null}catch{return null}}let eJ=100,eK=new Set(["batch","replay"]),eZ=new Set(["command","positionals","flags","runtime"]);function eQ(e){let t;try{t=JSON.parse(e)}catch{throw new _("INVALID_ARGS","Batch steps must be valid JSON.")}if(!Array.isArray(t)||0===t.length)throw new _("INVALID_ARGS","Batch steps must be a non-empty JSON array.");return t}function e0(e,t){if(!Array.isArray(e)||0===e.length)throw new _("INVALID_ARGS","batch requires a non-empty batchSteps array.");if(e.length>t)throw new _("INVALID_ARGS",`batch has ${e.length} steps; max allowed is ${t}.`);let n=[];for(let t=0;t<e.length;t+=1){let r=e[t];if(!r||"object"!=typeof r)throw new _("INVALID_ARGS",`Invalid batch step at index ${t}.`);let a=Object.keys(r).filter(e=>!eZ.has(e));if(a.length>0){let e=a.map(e=>`"${e}"`).join(", ");throw new _("INVALID_ARGS",`Batch step ${t+1} has unknown field(s): ${e}. Allowed fields: command, positionals, flags, runtime.`)}let i="string"==typeof r.command?r.command.trim().toLowerCase():"";if(!i)throw new _("INVALID_ARGS",`Batch step ${t+1} requires command.`);if(eK.has(i))throw new _("INVALID_ARGS",`Batch step ${t+1} cannot run ${i}.`);if(void 0!==r.positionals&&!Array.isArray(r.positionals))throw new _("INVALID_ARGS",`Batch step ${t+1} positionals must be an array.`);let o=r.positionals??[];if(o.some(e=>"string"!=typeof e))throw new _("INVALID_ARGS",`Batch step ${t+1} positionals must contain only strings.`);if(void 0!==r.flags&&("object"!=typeof r.flags||Array.isArray(r.flags)||!r.flags))throw new _("INVALID_ARGS",`Batch step ${t+1} flags must be an object.`);if(void 0!==r.runtime&&("object"!=typeof r.runtime||Array.isArray(r.runtime)||!r.runtime))throw new _("INVALID_ARGS",`Batch step ${t+1} runtime must be an object.`);n.push({command:i,positionals:o,flags:r.flags??{},runtime:r.runtime})}return n}let e1=new Set(["id","role","text","label","value","appname","windowtitle"]),e2=new Set(["visible","hidden","editable","selected","enabled","hittable"]),e3=new Set([...e1,...e2]);function e4(e){let t=e.trim();if(!t)throw new _("INVALID_ARGS","Selector expression cannot be empty");let n=function(e){let t=[],n="",r=null;for(let a=0;a<e.length;a+=1){let i=e[a];if(('"'===i||"'"===i)&&!tt(e,a)){r=e7(r,i),n+=i;continue}if(!r&&"|"===i&&"|"===e[a+1]){let r=n.trim();if(!r)throw new _("INVALID_ARGS",`Invalid selector fallback expression: ${e}`);t.push(r),n="",a+=1;continue}n+=i}let a=n.trim();if(!a)throw new _("INVALID_ARGS",`Invalid selector fallback expression: ${e}`);return t.push(a),t}(t);if(0===n.length)throw new _("INVALID_ARGS","Selector expression cannot be empty");return{raw:t,selectors:n.map(e=>(function(e){let t=e.trim();if(!t)throw new _("INVALID_ARGS","Selector segment cannot be empty");let n=function(e){let t=[],n="",r=null;for(let a=0;a<e.length;a+=1){let i=e[a];if(('"'===i||"'"===i)&&!tt(e,a)){r=e7(r,i),n+=i;continue}if(!r&&/\s/.test(i)){n.trim()&&t.push(n.trim()),n="";continue}n+=i}if(r)throw new _("INVALID_ARGS",`Unclosed quote in selector: ${e}`);return n.trim()&&t.push(n.trim()),t}(t);if(0===n.length)throw new _("INVALID_ARGS",`Invalid selector segment: ${e}`);return{raw:t,terms:n.map(e9)}})(e))}}function e5(e){try{return e4(e)}catch{return null}}function e8(e,t={}){if(0===e.length)return null;let n=t.preferTrailingValue??!1,r=0,a=[];for(;r<e.length&&function(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 e3.has(e)}return e3.has(t.toLowerCase())}(e[r]);){r+=1;let t=e.slice(0,r).join(" ").trim();t&&e5(t)&&a.push(r)}if(0===a.length)return null;let i=a[a.length-1];if(n){for(let t=a.length-1;t>=0;t-=1)if(a[t]<e.length){i=a[t];break}}let o=e.slice(0,i).join(" ").trim();return o?{selectorExpression:o,rest:e.slice(i)}:null}function e6(e){let t=e[0]??"",n=e8(e.slice(1),{preferTrailingValue:"text"===t});return{predicate:t,split:n}}function e9(e){let t=e.trim();if(!t)throw new _("INVALID_ARGS","Empty selector term");let n=t.indexOf("=");if(-1===n){let n=t.toLowerCase();if(!e2.has(n))throw new _("INVALID_ARGS",`Invalid selector term "${e}", expected key=value`);return{key:n,value:!0}}let r=t.slice(0,n).trim().toLowerCase(),a=t.slice(n+1).trim();if(!e3.has(r))throw new _("INVALID_ARGS",`Unknown selector key: ${r}`);if(!a)throw new _("INVALID_ARGS",`Missing selector value for key: ${r}`);if(e2.has(r)){let e,t="true"===(e=te(a).toLowerCase())||"false"!==e&&null;if(null===t)throw new _("INVALID_ARGS",`Invalid boolean value for ${r}: ${a}`);return{key:r,value:t}}return{key:r,value:te(a)}}function e7(e,t){return e?e===t?null:e:t}function te(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1).replace(/\\(["'])/g,"$1"):t}function tt(e,t){let n=0;for(let r=t-1;r>=0&&"\\"===e[r];r-=1)n+=1;return n%2==1}function tn(e,t){let n=t.toLowerCase();return e.find(e=>{let t=(e.label??"").toLowerCase(),r=(e.value??"").toLowerCase(),a=(e.identifier??"").toLowerCase();return t.includes(n)||r.includes(n)||a.includes(n)})??null}function tr(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&&ta(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||!ta(t))continue;let a=Math.abs(e.rect.y+e.rect.height/2-n);(!r||a<r.distance)&&(r={label:t,distance:a})}return r?.label}(e,t)??(n&&ta(n)?n:void 0)}function ta(e){let t=e.trim();return!(!t||/^(true|false)$/i.test(t)||/^\d+$/.test(t))}function ti(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 a=to(r.type??""),i=[r.label,r.value,r.identifier].map(e=>"string"==typeof e?e.trim():"").find(e=>e&&e.length>0),o=!!i&&ta(i);if(("group"===a||"ioscontentgroup"===a)&&!o){t.push(e);continue}let s=Math.max(0,e-t.length);n.push({...r,depth:s})}return n}function to(e){let t=e.trim().replace(/XCUIElementType/gi,"");t.startsWith("AX")&&(t=t.slice(2));let n=Math.max((t=t.toLowerCase()).lastIndexOf("."),t.lastIndexOf("/"));return -1!==n&&(t=t.slice(n+1)),t}function ts(e,t){let n=to(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 tl(e,t){if(t.hittable)return t;let n=t,r=new Set;for(;void 0!==n.parentIndex&&!r.has(n.ref);){r.add(n.ref);let t=e[n.parentIndex];if(!t)break;if(t.hittable)return t;n=t}return null}function tu(e){return[e.label,e.value,e.identifier].map(e=>"string"==typeof e?e.trim():"").filter(e=>e.length>0)[0]??""}function td(e){return!0===e.hittable||!!e.rect&&e.rect.width>0&&e.rect.height>0}function tc(e,t){return ts(e.type??"",t)&&!1!==e.enabled}function tp(e,t,n,r={}){let a=th(n);if(!a)return{matches:[],score:0};let i=0,o=[];for(let n of e){if(r.requireRect&&!n.rect)continue;let e=function(e,t,n){switch(t){case"role":return function(e,t){let n=function(e){let t=e.trim();return t?t=(t.split(".").pop()??t).replace(/XCUIElementType/gi,"").toLowerCase():""}(e??"");return n?n===t?2:+!!n.includes(t):0}(e.type,n);case"label":return tf(e.label,n);case"value":return tf(e.value,n);case"id":return tf(e.identifier,n);default:return Math.max(tf(e.label,n),tf(e.value,n),tf(e.identifier,n))}}(n,t,a);if(!(e<=0)){if(e>i){i=e,o.length=0,o.push(n);continue}e===i&&o.push(n)}}return{matches:o,score:i}}function tf(e,t){let n=th(e??"");return n?n===t?2:+!!n.includes(t):0}function th(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function tm(e){let t="any",n=0;["text","label","value","role","id"].includes(e[0])&&(t=e[0],n=1);let r=e[n]??"",a=e.slice(n+1);if(0===a.length)return{locator:t,query:r,action:"click"};let i=a[0].toLowerCase();if("get"===i){let e=a[1]?.toLowerCase();if("text"===e)return{locator:t,query:r,action:"get_text"};if("attrs"===e)return{locator:t,query:r,action:"get_attrs"};throw new _("INVALID_ARGS","find get only supports text or attrs")}if("wait"===i)return{locator:t,query:r,action:"wait",timeoutMs:function(e){if(!e)return null;let t=Number(e);return Number.isFinite(t)?t:null}(a[1])??void 0};if("exists"===i)return{locator:t,query:r,action:"exists"};if("click"===i)return{locator:t,query:r,action:"click"};if("focus"===i)return{locator:t,query:r,action:"focus"};if("fill"===i)return{locator:t,query:r,action:"fill",value:a.slice(1).join(" ")};if("type"===i)return{locator:t,query:r,action:"type",value:a.slice(1).join(" ")};throw new _("INVALID_ARGS",`Unsupported find action: ${a[0]}`)}function tw(e,t,n){return t.terms.every(t=>(function(e,t,n){switch(t.key){case"id":return tg(e.identifier,String(t.value));case"role":return tg(to(e.type??""),String(t.value));case"label":return tg(e.label,String(t.value));case"value":return tg(e.value,String(t.value));case"text":return tg(tu(e),String(t.value));case"appname":return tg(e.appName,String(t.value));case"windowtitle":return tg(e.windowTitle,String(t.value));case"visible":return td(e)===!!t.value;case"hidden":return!td(e)==!!t.value;case"editable":return tc(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 tg(e,t){return th(e??"")===th(t)}function ty(e,t,n){let r=n.requireRect??!1,a=n.requireUnique??!0,i=[];for(let o=0;o<t.selectors.length;o+=1){let s=t.selectors[o],l=function(e,t,n,r){let a=0,i=null,o=null,s=!1;for(let l of e){if(r&&!l.rect||!tw(l,t,n))continue;if(a+=1,i??=l,!o){o=l;continue}let e=function(e,t){let n=e.depth??0,r=t.depth??0;if(n!==r)return n>r?1:-1;let a=tI(e),i=tI(t);return a!==i?a<i?1:-1:0}(l,o);e>0?(o=l,s=!1):0===e&&(s=!0)}return{count:a,firstNode:i,disambiguated:s?null:o}}(e,s,n.platform,r);if(i.push({selector:s.raw,matches:l.count}),0!==l.count&&l.firstNode){if(a&&1!==l.count){if(!n.disambiguateAmbiguous||!l.disambiguated)continue;return{node:l.disambiguated,selector:s,selectorIndex:o,matches:l.count,diagnostics:i}}return{node:l.firstNode,selector:s,selectorIndex:o,matches:l.count,diagnostics:i}}}return null}function tb(e,t,n){let r=n.requireRect??!1,a=[];for(let i=0;i<t.selectors.length;i+=1){let o=t.selectors[i],s=function(e,t,n,r){let a=0;for(let i of e)(!r||i.rect)&&tw(i,t,n)&&(a+=1);return a}(e,o,n.platform,r);if(a.push({selector:o.raw,matches:s}),s>0)return{selectorIndex:i,selector:o,matches:s,diagnostics:a}}return null}function tv(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 tI(e){return e.rect?e.rect.width*e.rect.height:1/0}function tA(e,t,n={}){let r=[],a=to(e.type??""),i=tN(e.identifier),o=tN(e.label),s=tN(e.value),l=tN(tu(e)),u="fill"===n.action;i&&r.push(`id=${tx(i)}`),a&&o&&r.push(u?`role=${tx(a)} label=${tx(o)} editable=true`:`role=${tx(a)} label=${tx(o)}`),o&&r.push(u?`label=${tx(o)} editable=true`:`label=${tx(o)}`),s&&r.push(u?`value=${tx(s)} editable=true`:`value=${tx(s)}`),l&&l!==o&&l!==s&&r.push(u?`text=${tx(l)} editable=true`:`text=${tx(l)}`),a&&u&&!r.some(e=>e.includes("editable=true"))&&r.push(`role=${tx(a)} editable=true`);let d=Array.from(new Set(r));return 0===d.length&&a&&d.push(u?`role=${tx(a)} editable=true`:`role=${tx(a)}`),0===d.length&&td(e)&&d.push("visible=true"),d}function tx(e){return JSON.stringify(e)}function tN(e){if(!e)return null;let t=e.trim();return t||null}function tS(e){return e?{message:e}:{}}function t_(e,t){return t?{...e,message:t}:e}function tk(e){return"string"==typeof e?.message&&e.message.length>0?e.message:null}function tD(e){let t=e.appId??e.bundleId??e.packageName;return{session:e.session,appId:t,appBundleId:e.bundleId,package:e.packageName}}function tM(e,t,n){return{deviceId:t,deviceName:n,..."android"===e?{serial:t}:"ios"===e?{udid:t}:{}}}function tE(e,t={}){let n=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&&n?{serial:e.android?.serial??e.id}:{}}}function tO(e){return{name:e.name,...tE(e.device,{includeAndroidSerial:!1}),createdAt:e.createdAt}}function tC(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 tR(e){let t=e.created?"Created":"Reused",n=e.booted?" (booted)":"";return t_({udid:e.udid,device:e.device,runtime:e.runtime,ios_simulator_device_set:e.iosSimulatorDeviceSet??null,created:e.created,booted:e.booted},`${t}: ${e.device} ${e.udid}${n}`)}function tL(e){return e.bundleId??e.package??e.app}function tP(e){return t_({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 tT(e){return e.appName??e.bundleId??e.packageName??e.launchTarget}function t$(e){return t_({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: ${tT(e)}`)}function tF(e){let t=e.appName??e.appBundleId??e.session;return t_({session:e.session,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.startup?{startup:e.startup}:{},...e.runtime?{runtime:e.runtime}:{},...e.device?tE(e.device):{}},t?`Opened: ${t}`:"Opened")}function tU(e){return{session:e.session,...e.shutdown?{shutdown:e.shutdown}:{},...tS(e.session?`Closed: ${e.session}`:"Closed")}}function tG(e){return{nodes:e.nodes,truncated:e.truncated,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.visibility?{visibility:e.visibility}:{},...e.warnings&&e.warnings.length>0?{warnings:e.warnings}:{}}}let tV=["emulator","platform-tools",o.join("cmdline-tools","latest","bin"),o.join("cmdline-tools","tools","bin")];function tB(e){let t=new Set,n=[];for(let r of e){let e=r.trim();!e||t.has(e)||(t.add(e),n.push(e))}return n}function tj(e=process.env){let t=e.ANDROID_SDK_ROOT?.trim(),n=e.ANDROID_HOME?.trim(),r=e.HOME?.trim()||p.homedir();return tB([t??"",n??"",r?o.join(r,"Android","Sdk"):""])}async function tq(e){try{return await i.access(e,i.constants.X_OK),!0}catch{return!1}}async function tW(e=process.env){let t,n=[];for(let r of tj(e)){let e=[];for(let t of tV){let n=o.join(r,t);await tq(n)&&e.push(n)}0!==e.length&&(t||(t=r),n.push(...e))}if(t&&(e.ANDROID_SDK_ROOT=e.ANDROID_SDK_ROOT?.trim()||t,e.ANDROID_HOME=e.ANDROID_HOME?.trim()||t),0===n.length)return;let r=(e.PATH??"").split(o.delimiter).map(e=>e.trim()).filter(e=>e.length>0);e.PATH=tB([...n,...r]).join(o.delimiter)}function tz(e,t){return["-s",e.id,...t]}async function tX(){if(await tW(),!await v("adb"))throw new _("TOOL_MISSING","adb not found in PATH")}function tH(e,t){let n=`${e}
|
|
4
|
+
${t}`.toLowerCase();return n.includes("no shell command implementation")||n.includes("unknown command")}async function tY(e){await new Promise(t=>setTimeout(t,e))}let tJ=/\.(?:apk|aab)$/i,tK=/^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)+$/;function tZ(e){var t,n;let r=e.trim();return 0===r.length?"other":tJ.test(r)?r.includes("/")||r.includes("\\")||r.startsWith(".")||r.startsWith("~")||(t=r,!tK.test(t))?"binary":"package":(n=r,tK.test(n))?"package":"other"}function tQ(e){return`Android runtime hints require an installed package name, not "${e}". Install or reinstall the app first, then relaunch by package.`}let t0=["AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET","IOS_SIMULATOR_DEVICE_SET"],t1=["AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST","ANDROID_DEVICE_ALLOWLIST"];function t2(e){return e?.trim()||void 0}function t3(e,t){for(let n of e){let e=t2(t[n]);if(e)return e}}function t4(e,t=process.env){return t2(e)??t3(t0,t)}function t5(e){return new Set(e.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean))}function t8(e,t=process.env){let n=t2(e)??t3(t1,t);if(n)return t5(n)}function t6(e,t={}){let n=t4(t.simulatorSetPath);return n?["simctl","--set",n,...e]:["simctl",...e]}function t9(e,t){return"ios"!==e.platform||"simulator"!==e.kind?["simctl",...t]:t6(t,{simulatorSetPath:e.simulatorSetPath})}let t7="shared_prefs/ReactNativeDevPrefs.xml",ne="debug_http_host",nt="dev_server_https",nn="RCT_jsLocation",nr="RCT_packager_scheme",na="React Native runtime hints require adb run-as access to the app sandbox. Verify the app is debuggable and the selected package/device are correct.",ni='<?xml version="1.0" encoding="utf-8" standalone="yes" ?>\n<map>\n</map>\n';function no(e){return void 0!==ns(e)}function ns(e){if(!e)return;let t=nb(e.metroHost),n=nI(e.metroPort),r="http",a=nb(e.bundleUrl);if(a){var i;let e;try{e=new s(a)}catch(e){throw new _("INVALID_ARGS",`Invalid runtime bundle URL: ${a}`,{},e)}("http:"===e.protocol||"https:"===e.protocol)&&(t??=nb(e.hostname),n??=nI(e.port.length>0?Number(e.port):"https:"===(i=e.protocol)?443:"http:"===i?80:void 0),r="https:"===e.protocol?"https":"http")}if(t&&n)return{host:t,port:n,scheme:r}}async function nl(e){let{device:t,appId:n,runtime:r}=e;if(!n)return;let a=ns(r);if(a){if("android"===t.platform)return void await nd(t,n,a);"ios"===t.platform&&"simulator"===t.kind&&await nh(t,n,a)}}async function nu(e){let{device:t,appId:n}=e;if(n){if("android"===t.platform)return void await nc(t,n);"ios"===t.platform&&"simulator"===t.kind&&await nm(t,n)}}async function nd(e,t,n){var r,a,i,o,s,l;let u,d;nv(t);let c=(r=await np(e,t),a=ne,i=`${n.host}:${n.port}`,u=` <string name="${nA(a)}">${nA(i)}</string>`,ng(ny(r,a),u));o=c,s=nt,l="https"===n.scheme,d=` <boolean name="${nA(s)}" value="${l?"true":"false"}" />`,c=ng(ny(o,s),d),await nf(e,t,c)}async function nc(e,t){nv(t);let n=await np(e,t),r=ny(n,ne),a=ny(r,nt);a!==n&&await nf(e,t,a)}async function np(e,t){let n=await k("adb",tz(e,["shell","run-as",t,"cat",t7]),{allowFailure:!0});return 0!==n.exitCode?ni:nw(n.stdout)}async function nf(e,t,n){let r=tz(e,["shell","run-as",t,"id"]),a=await k("adb",r,{allowFailure:!0});if(0!==a.exitCode){let e=nx(a.stdout,a.stderr);throw new _("COMMAND_FAILED",e?`Failed to access Android app sandbox for ${t}`:`Failed to probe Android app sandbox for ${t}`,{package:t,cmd:"adb",args:r,stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode,hint:e?na:"adb shell run-as probe failed. Check adb connectivity and that the device is reachable. Inspect stderr/details for more information."})}try{await k("adb",tz(e,["shell","run-as",t,"mkdir","-p","shared_prefs"])),await k("adb",tz(e,["shell","run-as",t,"tee",t7]),{stdin:n.trimEnd()})}catch(r){let e=x(r);if("TOOL_MISSING"===e.code)throw e;let n=nx("string"==typeof e.details?.stdout?e.details.stdout:"","string"==typeof e.details?.stderr?e.details.stderr:"");throw new _("COMMAND_FAILED",n?`Failed to access Android app sandbox for ${t}`:`Failed to write Android runtime hints for ${t}`,{...e.details??{},package:t,cmd:"adb",phase:"write-runtime-hints",hint:n?na:"adb run-as succeeded, but writing ReactNativeDevPrefs.xml failed. Inspect stderr/details for the failing shell command."},e)}}async function nh(e,t,n){await k("xcrun",t9(e,["spawn",e.id,"defaults","write",t,nn,"-string",`${n.host}:${n.port}`])),await k("xcrun",t9(e,["spawn",e.id,"defaults","write",t,nr,"-string",n.scheme]))}async function nm(e,t){await k("xcrun",t9(e,["spawn",e.id,"defaults","delete",t,nn]),{allowFailure:!0}),await k("xcrun",t9(e,["spawn",e.id,"defaults","delete",t,nr]),{allowFailure:!0})}function nw(e){let t=e.trim();return t.includes("<map")&&t.includes("</map>")?`${t}
|
|
5
|
+
`:ni}function ng(e,t){return nw(e).replace("</map>",`${t}
|
|
6
6
|
</map>`)}function ny(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return nw(e).replace(RegExp(`^\\s*<string name="${n}">[\\s\\S]*?<\\/string>\\n?`,"m"),"").replace(RegExp(`^\\s*<boolean name="${n}" value="(?:true|false)"\\s*\\/?>\\n?`,"m"),"")}function nb(e){let t=e?.trim();return t&&t.length>0?t:void 0}function nv(e){if("binary"!==tZ(e))return;let t=tQ(e);throw new _("INVALID_ARGS",t,{package:e,hint:t})}function nI(e){if(Number.isInteger(e)&&!(e<=0)&&!(e>65535))return e}function nA(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function nx(e,t){let n=`${e}
|
|
7
|
-
${t}`.toLowerCase();return["run-as: package not debuggable","run-as: permission denied","run-as: package is unknown","run-as: unknown package","is unknown","is not an application","could not set capabilities"].some(e=>n.includes(e))}async function nS(e,t,n){if("path"===t.kind&&!e.policy.allowLocalInputPaths)throw new _("INVALID_ARGS",`Local ${n.field??"input"} paths are not allowed by command policy`);try{return await e.artifacts.resolveInput(t,n)}catch(e){throw x(e)}}async function nN(e,t,n){if(t?.kind==="path"&&!e.policy.allowLocalOutputPaths)throw new _("INVALID_ARGS","Local output paths are not allowed by command policy");try{return await e.artifacts.reserveOutput(t,{...n,visibility:n.visibility??"client-visible",requestedClientPath:t?.kind==="downloadableArtifact"?t.clientPath??n.requestedClientPath:n.requestedClientPath})}catch(e){throw x(e)}}async function n_(e,t){try{return await e.artifacts.createTempFile(t)}catch(e){throw x(e)}}function nM(e,t){try{return h.sync.read(e)}catch(e){throw new _("COMMAND_FAILED",`Failed to decode ${t} as PNG`,{label:t,reason:e instanceof Error?e.message:String(e)})}}let nD=[0,187,255,255];function nE(e,t,n,r){if(t<0||t>=e.width||n<0||n>=e.height)return;let i=(n*e.width+t)*4;e.data[i]=r[0],e.data[i+1]=r[1],e.data[i+2]=r[2],e.data[i+3]=r[3]}function nC(e,t,n){return Math.min(Math.max(e,t),n)}let nO={icon:90,toggle:90,chevron:75,separator:45,visual:35,background:10},nk={leading:20,trailing:20,separator:10,unknown:0,background:-30};function nL(e){return"background"!==e.likelyKind}function nR(e,t){return e.width>=.25*t.width||e.height>=.06*t.height}function nT(e,t){let n,r=0;for(let i of t){let t=nG(e,i.rect);t<=r||(r=t,n=i)}return n}function nP(e){let t=[];for(let n of[...e].sort((e,t)=>e.rect.y-t.rect.y)){let e=t.find(e=>{var t,r;return t=e.rect,nG(t,r=n.rect)>0||Math.abs(nV(t).y-nV(r).y)<=.5*Math.max(t.height,r.height)});if(!e){t.push({rect:n.rect,blocks:[n]});continue}e.blocks.push(n),e.blocks.sort((e,t)=>e.rect.x-t.rect.x),e.rect=function(e){let t=1/0,n=1/0,r=-1/0,i=-1/0;for(let a of e)t=Math.min(t,a.x),n=Math.min(n,a.y),r=Math.max(r,a.x+a.width),i=Math.max(i,a.y+a.height);return{x:t,y:n,width:r-t,height:i-n}}([e.rect,n.rect])}return t}function n$(e,t){let n,r=nV(e);for(let e of t){var i,a;let t=Math.sqrt((i=r,a=nV(e.rect),(i.x-a.x)**2+(i.y-a.y)**2));n&&t>=n.distance||(n={block:e,distance:t})}return n}function nF(e){let t=nU(e);return e.differentPixels>=24&&t.width>=3&&t.height>=3}function nU(e){return{x:e.minX,y:e.minY,width:e.maxX-e.minX+1,height:e.maxY-e.minY+1}}function nG(e,t){return Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))}function nV(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}function nB(e,t,n){return Math.min(Math.max(e,t),n)}async function nj(e){if(await v("tesseract"))try{let[t,n]=await Promise.all([nW(e.baselinePath),nW(e.currentPath)]);if(0!==t.exitCode||0!==n.exitCode)return;let r=nq(t.stdout,e.width,e.height),i=nq(n.stdout,e.width,e.height),a=function(e,t){let n=new Set,r=[];for(let a of e){var i;let e=nZ(a.text),o=function(e,t,n,r){let i=null,a=1/0;for(let l=0;l<n.length;l+=1){var o,s;if(r.has(l))continue;let u=n[l];if(nZ(u.text)!==t)continue;let d=(o=nH(e.normalizedRect),s=nH(u.normalizedRect),(o.x-s.x)**2+(o.y-s.y)**2);d>=a||(i=l,a=d)}return i}(a,e,t,n);if(null===o)continue;n.add(o);let s=function(e,t){let n={x:t.rect.x-e.rect.x,y:t.rect.y-e.rect.y,width:t.rect.width-e.rect.width,height:t.rect.height-e.rect.height},r=n1(t.rect.width/e.rect.width),i=n1(t.rect.height/e.rect.height),a=Math.abs(r-1)>=.08||Math.abs(i-1)>=.12;return{text:e.text,baselineRect:e.rect,currentRect:t.rect,delta:n,confidence:Math.round(100*Math.min(e.confidence,t.confidence))/100,possibleTextMetricMismatch:a}}(a,t[o]);i=s,(Math.abs(i.delta.x)>=2||Math.abs(i.delta.y)>=2||Math.abs(i.delta.width)>=2||Math.abs(i.delta.height)>=2||i.possibleTextMetricMismatch)&&r.push(s)}return r.sort((e,t)=>nz(t)-nz(e)).slice(0,12)}(r,i),o=function(e){let t=[];for(let n of[...e].sort((e,t)=>e.currentRect.y-t.currentRect.y)){let e=t.find(e=>32>=Math.abs(n.delta.x-nQ(e.map(e=>e.delta.x))));e?e.push(n):t.push([n])}return t.filter(e=>e.length>=2).map(nX).filter(e=>e.yRange.max-e.yRange.min<=60).sort((e,t)=>nY(t)-nY(e)).slice(0,4)}(a);if(0===r.length&&0===i.length)return;return{provider:"tesseract",baselineBlocks:r.length,currentBlocks:i.length,baselineBlocksRaw:r,currentBlocksRaw:i,matches:a,...o.length>0?{movementClusters:o}:{}}}catch{return}}function nq(e,t,n){let[r,...i]=e.split(/\r?\n/);if(!r)return[];let a=new Map(r.split(" ").map((e,t)=>[e,t])),o=[];for(let e of i){var s;if(!e.trim())continue;let t=e.split(" "),n=nK(t,a,"level"),r=nJ(t,a,"text").trim(),i=nK(t,a,"conf");if(5!==n||(s=r,!/[\p{L}\p{N}]/u.test(s))||i<0)continue;let l=nK(t,a,"left"),u=nK(t,a,"top"),d=nK(t,a,"width"),c=nK(t,a,"height");d<=0||c<=0||o.push({key:[nJ(t,a,"page_num"),nJ(t,a,"block_num"),nJ(t,a,"par_num"),nJ(t,a,"line_num")].join(":"),text:r,confidence:i,rect:{x:l,y:u,width:d,height:c}})}let l=new Map;for(let e of o){let t=l.get(e.key);t?t.push(e):l.set(e.key,[e])}return Array.from(l.values()).flatMap(e=>(function(e){let t=[...e].sort((e,t)=>e.rect.x-t.rect.x),n=[],r=[];for(let e of t){let t=r.at(-1);if(!t){r.push(e);continue}if(e.rect.x-(t.rect.x+t.rect.width)>Math.max(48,2.5*Math.max(t.rect.height,e.rect.height))){n.push(r),r=[e];continue}r.push(e)}return r.length>0&&n.push(r),n})(e)).map(e=>(function(e,t,n){if(0===e.length)return null;let r=[...e].sort((e,t)=>e.rect.x-t.rect.x),i=function(e){let t=1/0,n=1/0,r=-1/0,i=-1/0;for(let a of e)t=Math.min(t,a.x),n=Math.min(n,a.y),r=Math.max(r,a.x+a.width),i=Math.max(i,a.y+a.height);return{x:t,y:n,width:r-t,height:i-n}}(r.map(e=>e.rect)),a=Math.round(100*nQ(r.map(e=>e.confidence)))/100;return{text:r.map(e=>e.text).join(" "),confidence:a,rect:i,normalizedRect:{x:n0(i.x/t),y:n0(i.y/n),width:n0(i.width/t),height:n0(i.height/n)}}})(e,t,n)).filter(e=>null!==e)}function nW(e){return M("tesseract",[e,"stdout","-l","eng","tsv"],{allowFailure:!0,timeoutMs:1e4})}function nz(e){return Math.abs(e.delta.x)+Math.abs(e.delta.y)+Math.abs(e.delta.width)+Math.abs(e.delta.height)+25*!!e.possibleTextMetricMismatch}function nX(e){let t=e.map(e=>e.delta.x),n=e.map(e=>e.delta.y);return{texts:e.map(e=>e.text),xRange:{min:Math.min(...t),max:Math.max(...t)},yRange:{min:Math.min(...n),max:Math.max(...n)}}}function nY(e){return 2*Math.abs((e.xRange.min+e.xRange.max)/2)+Math.abs((e.yRange.min+e.yRange.max)/2)}function nH(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}function nJ(e,t,n){let r=t.get(n);return void 0===r?"":e[r]??""}function nK(e,t,n){let r=Number(nJ(e,t,n));return Number.isFinite(r)?r:0}function nZ(e){return e.trim().replace(/\s+/g," ").toLowerCase()}function nQ(e){return e.reduce((e,t)=>e+t,0)/e.length}function n0(e){return Math.round(100*e*100)/100}function n1(e){return Math.round(1e3*e)/1e3}function n2(e,t,n,r){return{r:Math.round(e/r),g:Math.round(t/r),b:Math.round(n/r)}}function n3(e){return .2126*e.r+.7152*e.g+.0722*e.b}function n4(e){return`#${n5(e.r)}${n5(e.g)}${n5(e.b)}`}function n5(e){return e.toString(16).padStart(2,"0")}function n8(e){return Math.round(100*e*100)/100}let n6=255*Math.sqrt(3);async function n9(e,t,n={}){let r,i,s,l;await n7(e,"Baseline image not found"),await n7(t,"Current screenshot not found");let u=n.outputPath,[d,c]=await Promise.all([a.readFile(e),a.readFile(t)]),p=nM(d,"baseline screenshot"),f=nM(c,"current screenshot");re(p.width,p.height,"baseline screenshot",n.maxPixels),re(f.width,f.height,"current screenshot",n.maxPixels);let m=n.threshold??.1;if(p.width!==f.width||p.height!==f.height){let e=p.width*p.height;return await rt(n.outputPath),{match:!1,mismatchPercentage:100,totalPixels:e,differentPixels:e,dimensionMismatch:{expected:{width:p.width,height:p.height},actual:{width:f.width,height:f.height}}}}let w=p.width*p.height,g=m*n6,y=new h({width:p.width,height:p.height}),b=new Uint8Array(w),v=0;for(let e=0,t=0;e<p.data.length;e+=4,t+=1){if(Math.sqrt((p.data[e]-f.data[e])**2+(p.data[e+1]-f.data[e+1])**2+(p.data[e+2]-f.data[e+2])**2)>g){v+=1,b[t]=1;let n=rn(f,e);y.data[e]=rr(n,220,.78),y.data[e+1]=rr(n,0,.78),y.data[e+2]=rr(n,0,.78),y.data[e+3]=255;continue}let n=rn(f,e);y.data[e]=n,y.data[e+1]=n,y.data[e+2]=n,y.data[e+3]=255}let I=v>0?(x=(r=function(e){let{diffMask:t,baseline:n,current:r}=e,{width:i,height:a}=n,o=new Uint8Array(t.length),s=new Int32Array(t.length),l=[];for(let e=0;e<t.length;e+=1){if(1!==t[e]||1===o[e])continue;let u=0,d=0;s[0]=e,d+=1,o[e]=1;let c=e%i,p=Math.floor(e/i),f={minX:c,minY:p,maxX:c,maxY:p,differentPixels:0,baselineRed:0,baselineGreen:0,baselineBlue:0,currentRed:0,currentGreen:0,currentBlue:0};for(;u<d;){let e=s[u];u+=1,function(e,t,n,r,i){let a=t%n,o=Math.floor(t/n),s=4*t;e.minX=Math.min(e.minX,a),e.minY=Math.min(e.minY,o),e.maxX=Math.max(e.maxX,a),e.maxY=Math.max(e.maxY,o),e.differentPixels+=1,e.baselineRed+=r.data[s],e.baselineGreen+=r.data[s+1],e.baselineBlue+=r.data[s+2],e.currentRed+=i.data[s],e.currentGreen+=i.data[s+1],e.currentBlue+=i.data[s+2]}(f,e,i,n,r);let l=e%i,c=Math.floor(e/i);for(let e=-1;e<=1;e+=1){let n=c+e;if(!(n<0)&&!(n>=a))for(let r=-1;r<=1;r+=1){if(0===r&&0===e)continue;let a=l+r;if(a<0||a>=i)continue;let u=n*i+a;1===t[u]&&1!==o[u]&&(o[u]=1,s[d]=u,d+=1)}}}l.push(f)}return l}(A={diffMask:b,baseline:p,current:f,totalPixels:w,differentPixels:v,maxRegions:n.maxRegions})).length<=2e3?function(e){let t=[];for(let i of e.sort((e,t)=>{let n=e.minY-t.minY;return 0!==n?n:e.minX-t.minX})){var n,r;let e=t.find(e=>{var t,n,r;return t=e,n=i,r=12,t.minX-r<=n.maxX&&n.minX-r<=t.maxX&&t.minY-r<=n.maxY&&n.minY-r<=t.maxY});if(!e){t.push({...i});continue}n=e,r=i,n.minX=Math.min(n.minX,r.minX),n.minY=Math.min(n.minY,r.minY),n.maxX=Math.max(n.maxX,r.maxX),n.maxY=Math.max(n.maxY,r.maxY),n.differentPixels+=r.differentPixels,n.baselineRed+=r.baselineRed,n.baselineGreen+=r.baselineGreen,n.baselineBlue+=r.baselineBlue,n.currentRed+=r.currentRed,n.currentGreen+=r.currentGreen,n.currentBlue+=r.currentBlue}return t}(r):r,x.flatMap(e=>{var t,n,r;let i;return(t=e,n=A.baseline.width,r=A.baseline.height,i=t.maxX-t.minX+1,t.maxY-t.minY+1>=Math.max(48,Math.round(.07*r))&&i>=.35*n)?function(e,t,n){var r;let i=function(e,t){let n=[],r=null;for(let i=0;i<e.length;i+=1){if(e[i]<=t){r??=i;continue}null!==r&&(i-r>=6&&n.push([r,i-1]),r=null)}return null!==r&&e.length-r>=6&&n.push([r,e.length-1]),n}((r=function(e,t,n){let r=[];for(let i=e.minY;i<=e.maxY;i+=1){let a=0;for(let r=e.minX;r<=e.maxX;r+=1)1===t[i*n+r]&&(a+=1);r.push(a)}return r}(e,t.diffMask,t.baseline.width)).map((e,t)=>{let n=0,i=0,a=Math.max(0,t-3),o=Math.min(r.length-1,t+3);for(let e=a;e<=o;e+=1)n+=r[e],i+=1;return Math.round(n/i)}),Math.max(1,Math.round((e.maxX-e.minX+1)*.08))),a=function(e,t,n){let r=[],i=e.minY;for(let[a,o]of t){let t=e.minY+Math.round((a+o)/2);t-i+1<n||e.maxY-t<n||(r.push([i,t]),i=t+1)}return r.push([i,e.maxY]),r}(e,i,n);if(a.length<=1)return[e];let o=a.map(([n,r])=>(function(e,t,n,r){let i=null;for(let s=t;s<=n;s+=1)for(let t=e.minX;t<=e.maxX;t+=1){var a,o;let e=s*r.baseline.width+t;1===r.diffMask[e]&&function(e,t,n,r,i,a){let o=4*t;e.minX=Math.min(e.minX,n),e.minY=Math.min(e.minY,r),e.maxX=Math.max(e.maxX,n),e.maxY=Math.max(e.maxY,r),e.differentPixels+=1,e.baselineRed+=i.data[o],e.baselineGreen+=i.data[o+1],e.baselineBlue+=i.data[o+2],e.currentRed+=a.data[o],e.currentGreen+=a.data[o+1],e.currentBlue+=a.data[o+2]}(i??={minX:a=t,minY:o=s,maxX:a,maxY:o,differentPixels:0,baselineRed:0,baselineGreen:0,baselineBlue:0,currentRed:0,currentGreen:0,currentBlue:0},e,t,s,r.baseline,r.current)}return i})(e,n,r,t)).filter(e=>null!==e);return o.length>1?o:[e]}(e,A,Math.max(24,Math.round(.03*A.baseline.height))):[e]})).sort((e,t)=>{let n=t.differentPixels-e.differentPixels;if(0!==n)return n;let r=e.minY-t.minY;return 0!==r?r:e.minX-t.minX}).slice(0,Math.max(0,A.maxRegions??8)).map((e,t)=>{var n,r,i,a,o,s,l,u,d,c,p;let f,h,m,w,g,y,b,v,I,x,S,N,_,M,D,E,C;return n=e,r=t+1,i={width:A.baseline.width,height:A.baseline.height,totalPixels:A.totalPixels,differentPixels:A.differentPixels},y={x:n.minX,y:n.minY,width:n.maxX-n.minX+1,height:n.maxY-n.minY+1},b={x:Math.round(n.minX+y.width/2),y:Math.round(n.minY+y.height/2)},v=n2(n.baselineRed,n.baselineGreen,n.baselineBlue,n.differentPixels),I=n2(n.currentRed,n.currentGreen,n.currentBlue,n.differentPixels),x=y.width*y.height,S=n8(n.differentPixels/x),N=Math.round(n3(v)),_=Math.round(n3(I)),M=(a=y,o=i.width,s=i.height,a.width>=.55*o&&a.height>=.12*s?"large-area":a.width>=2.5*a.height?"horizontal-band":a.height>=2.5*a.width?"vertical-band":"compact"),D=(f=x/i.totalPixels)>=.04?"large":f>=.01?"medium":"small",E=(l=v,u=I,h=n3(l),Math.abs(m=n3(u)-h)>=12?m>0?"brighter":"darker":Math.max(Math.abs(u.r-l.r),Math.abs(u.g-l.g),Math.abs(u.b-l.b))>=12?"color-shift":"mixed"),C=(d=b,c=i.width,p=i.height,w=d.x<c/3?"left":d.x>2*c/3?"right":"center",g=d.y<p/3?"top":d.y>2*p/3?"bottom":"middle","center"===w&&"middle"===g?"center":`${g}-${w}`),{index:r,rect:y,normalizedRect:{x:n8(y.x/i.width),y:n8(y.y/i.height),width:n8(y.width/i.width),height:n8(y.height/i.height)},differentPixels:n.differentPixels,shareOfDiffPercentage:n8(n.differentPixels/i.differentPixels),densityPercentage:S,shape:M,size:D,location:C,averageBaselineColorHex:n4(v),averageCurrentColorHex:n4(I),baselineLuminance:N,currentLuminance:_,dominantChange:E}}):[];if(v>0&&u){var A,x,S;for(let e of I)e.rect.width<4||e.rect.height<4||function(e,t){let n=nC(t.x,0,e.width-1),r=nC(t.y,0,e.height-1),i=nC(t.x+t.width-1,0,e.width-1),a=nC(t.y+t.height-1,0,e.height-1);for(let t=0;t<2;t+=1){for(let o=n;o<=i;o+=1)nE(e,o,r+t,nD),nE(e,o,a-t,nD);for(let o=r;o<=a;o+=1)nE(e,n+t,o,nD),nE(e,i-t,o,nD)}}(y,e.rect);await a.mkdir(o.dirname(u),{recursive:!0}),await a.writeFile(u,h.sync.write(y))}else await rt(n.outputPath);let N=v>0?await nj({baselinePath:e,currentPath:t,width:p.width,height:p.height}):void 0,_=N&&(N.matches.length>0||(N.movementClusters?.length??0)>0)?{provider:N.provider,baselineBlocks:N.baselineBlocks,currentBlocks:N.currentBlocks,matches:N.matches,...N.movementClusters?{movementClusters:N.movementClusters}:{}}:void 0,M=v>0&&N?(i=function(e){let t=[];for(let n of e.sort((e,t)=>e.minY-t.minY||e.minX-t.minX)){let e=t.find(e=>{var t,r,i;return t=e,r=n,i=10,t.minX-i<=r.maxX&&r.minX-i<=t.maxX&&t.minY-i<=r.maxY&&r.minY-i<=t.maxY});if(!e){t.push({...n});continue}e.minX=Math.min(e.minX,n.minX),e.minY=Math.min(e.minY,n.minY),e.maxX=Math.max(e.maxX,n.maxX),e.maxY=Math.max(e.maxY,n.maxY),e.differentPixels+=n.differentPixels}return t}(function(e,t,n){let r=new Uint8Array(e.length),i=new Int32Array(e.length),a=[];for(let o=0;o<e.length;o+=1){if(1!==e[o]||1===r[o])continue;let s=0,l=0;i[0]=o,l+=1,r[o]=1;let u=o%t,d=Math.floor(o/t),c={minX:u,minY:d,maxX:u,maxY:d,differentPixels:0};for(;s<l;){let a=i[s];s+=1;let o=a%t,u=Math.floor(a/t);c.minX=Math.min(c.minX,o),c.minY=Math.min(c.minY,u),c.maxX=Math.max(c.maxX,o),c.maxY=Math.max(c.maxY,u),c.differentPixels+=1;for(let a=-1;a<=1;a+=1){let s=u+a;if(!(s<0)&&!(s>=n))for(let n=-1;n<=1;n+=1){if(0===n&&0===a)continue;let u=o+n;if(u<0||u>=t)continue;let d=s*t+u;1===e[d]&&1!==r[d]&&(r[d]=1,i[l]=d,l+=1)}}}a.push(c)}return a}(function(e,t,n,r){let i=new Uint8Array(e);if(!r)return i;for(let e of[...r.baselineBlocksRaw,...r.currentBlocksRaw]){var a;!function(e,t,n,r){let i=nB(Math.floor(r.x),0,t-1),a=nB(Math.floor(r.y),0,n-1),o=nB(Math.ceil(r.x+r.width),0,t),s=nB(Math.ceil(r.y+r.height),0,n);for(let n=a;n<s;n+=1)for(let r=i;r<o;r+=1)e[n*t+r]=0}(i,t,n,{x:(a=e.rect).x-8,y:a.y-8,width:a.width+16,height:a.height+16})}return i}((S={diffMask:b,width:p.width,height:p.height,regions:I,ocr:N}).diffMask,S.width,S.height,S.ocr),S.width,S.height)),s=nP(S.ocr?.currentBlocksRaw??[]),l=nP(S.ocr?.baselineBlocksRaw??[]),i.filter(nF).map(e=>{var t,n,r,i,a,o,u,d,c,p,f;let h,m,w,g,y,b,v,I,A,x;return t=e,n=S,r=s,i=l,g=function(e,t){let n,r=0;for(let i of t){let t=function(e,t){let n=Math.max(e.x,t.x),r=Math.max(e.y,t.y),i=Math.min(e.x+e.width,t.x+t.width),a=Math.min(e.y+e.height,t.y+t.height);return i<=n||a<=r?0:(i-n)*(a-r)}(e,i.rect);t<=r||(r=t,n=i)}return n?.index}(w=nU(t),n.regions),y=function(e,t,n){let r=nT(e,t);if(r)return n$(e,r.blocks);let i=nT(e,n);return i?n$(e,i.blocks):void 0}(w,r,i),b=function(e,t,n){if(e.height<=3&&e.width>=.12*n)return"separator";if(!t)return e.width>=.4*n?"background":"unknown";if(e.width>=.4*n)return"background";let r=e.x+e.width/2,i=t.x+t.width/2;return r<i-t.width/2?"leading":r>i+t.width/2?"trailing":e.width>=.35*n?"background":"unknown"}(w,y?.block.rect,n.width),v=(a=w,o=b,u=t.differentPixels,d=n,h=a.width/a.height,m=u/(a.width*a.height),"separator"===o?"separator":"background"===o?"background":"trailing"===o&&h>=1.5&&h<=3.8&&m>=.35?"toggle":"trailing"===o&&a.width<=.06*d.width&&a.height<=.04*d.height?"chevron":"leading"===o&&h>=.55&&h<=1.8?"icon":nR(a,d)?"background":"visual"),I={...g?{regionIndex:g}:{},slot:b,likelyKind:v,rect:w},{...g?{regionIndex:g}:{},slot:b,likelyKind:v,rect:w,...y?{nearestText:y.block.text.trim().replace(/^[^\p{L}\p{N}]+/u,"").replace(/^\p{L}\s+/u,"")}:{},score:(c=I,p=t.differentPixels,f=n,A=nR(c.rect,f)?-35:0,x=20*!!c.regionIndex,nO[c.likelyKind]+nk[c.slot]+x+A+Math.min(20,p/200))}}).filter(e=>e.rect.y>=.08*S.height).filter(nL).sort((e,t)=>t.score-e.score).slice(0,Math.max(0,S.maxDeltas??12)).map((e,t)=>{var n;return n=e,{index:t+1,...n.regionIndex?{regionIndex:n.regionIndex}:{},slot:n.slot,likelyKind:n.likelyKind,rect:n.rect,...n.nearestText?{nearestText:n.nearestText}:{}}})):[],D=w>0?Math.round(v/w*1e4)/100:0;return{...v>0&&u?{diffPath:u}:{},...I.length>0?{regions:I}:{},..._?{ocr:_}:{},...M.length>0?{nonTextDeltas:M}:{},totalPixels:w,differentPixels:v,mismatchPercentage:D,match:0===v}}async function n7(e,t){try{await a.access(e)}catch{throw new _("INVALID_ARGS",`${t}: ${e}`)}}function re(e,t,n,r){if(null==r||r<=0)return;let i=e*t;if(!(i<=r))throw new _("INVALID_ARGS",`${n} is ${i} pixels, which exceeds the configured maxImagePixels limit of ${r}`)}async function rt(e){if(e)try{await a.unlink(e)}catch(e){var t;if(!("object"==typeof(t=e)&&null!==t&&"code"in t&&"ENOENT"===t.code))throw e}}function rn(e,t){return rr(Math.round(.299*e.data[t]+.587*e.data[t+1]+.114*e.data[t+2]),255,.72)}function rr(e,t,n){return Math.round(e*(1-n)+t*n)}function ri(e){return e.width*e.height}function ra(e){return Math.round(100*e*100)/100}async function ro(e,t){let n=await n_(e,{prefix:"agent-device-diff-current",ext:".png"});try{await rl(e,t,n.path,ru(t))}catch(e){throw await n.cleanup(),e}return n}async function rs(e,t,n,r,i){var a,o,s,l;if(!t.overlayRefs)return r;if(r.match||r.dimensionMismatch)return n&&await rc(n),r;let u=(a=t,o=n,a.currentOverlayOut?a.currentOverlayOut:a.out?.kind==="path"?{kind:"path",path:rd(o??a.out.path)}:a.out?.kind==="downloadableArtifact"?{kind:"downloadableArtifact",...a.out.clientPath?{clientPath:rd(a.out.clientPath)}:{},...a.out.fileName?{fileName:rd(a.out.fileName)}:{}}:void 0),d=await nN(e,u,{field:"currentOverlayPath",ext:".png"});try{let n=await rl(e,t,d.path,{overlayRefs:!0,...ru(t)}),a=await d.publish();return a&&i.push(a),{...r,currentOverlayPath:n.path??d.path,...n.overlayRefs?{currentOverlayRefCount:n.overlayRefs.length}:{},...r.regions&&n.overlayRefs?{regions:(s=r.regions,l=n.overlayRefs,s.map(e=>{var t,n;let r,i=(t=e,n=l,r=ri(t.rect),n.map(e=>{var n,i;let a,o,s,l,u=e.overlayRect,d=(n=t.rect,i=u,a=Math.max(n.x,i.x),o=Math.max(n.y,i.y),s=Math.min(n.x+n.width,i.x+i.width),l=Math.min(n.y+n.height,i.y+i.height),s<=a||l<=o?0:(s-a)*(l-o));return d<=0?null:{ref:e.ref,...e.label?{label:e.label}:{},rect:u,overlayCoveragePercentage:ra(d/ri(u)),regionCoveragePercentage:ra(d/r)}}).filter(e=>null!==e).sort((e,t)=>{let n=t.regionCoveragePercentage-e.regionCoveragePercentage;return 0!==n?n:t.overlayCoveragePercentage-e.overlayCoveragePercentage}).slice(0,3).map(e=>({ref:e.ref,...e.label?{label:e.label}:{},rect:e.rect,regionCoveragePercentage:e.regionCoveragePercentage})));return i.length>0?{...e,currentOverlayMatches:i}:e}))}:{}}}catch(e){throw await d.cleanup?.(),e}}async function rl(e,t,n,r={}){if(!e.backend.captureScreenshot)throw new _("UNSUPPORTED_OPERATION","screenshot is not supported by this backend");return await e.backend.captureScreenshot({session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata},n,r)??{}}function ru(e){return e.surface?{surface:e.surface}:{}}function rd(e){let t=o.extname(e),n=t?e.slice(0,-t.length):e;return`${n}.current-overlay${t||".png"}`}async function rc(e){try{await a.unlink(rd(e))}catch(e){var t;if(!("object"==typeof(t=e)&&null!==t&&"code"in t&&"ENOENT"===t.code))throw e}}function rp(e){return"live"===e.kind}function rf(e,t){let n=Q(e.type??"Element"),r=Z(e,n),i=!1===e.enabled?"disabled":"enabled",a=!0===e.selected?"selected":"unselected",o=!0===e.hittable?"hittable":"not-hittable";return[String(t??e.depth??0),n,r,i,a,o].join("|")}function rh(e,t){return t.flatten?e.map(e=>({text:K(e,0,!1),comparable:rf(e,0)})):J(e).map(e=>({text:e.text,comparable:rf(e.node,e.depth)}))}function rm(e,t){return e.get(t)??0}async function rw(e,t){var n,r,i,a,o;let s,l,u,d,c,p;if(!e.backend.captureSnapshot)throw new _("UNSUPPORTED_OPERATION","snapshot is not supported by this backend");let f=t.session??"default",h=await e.sessions.get(f),m=await e.backend.captureSnapshot({session:f,requestId:t.requestId,appId:h?.appId,appBundleId:h?.appBundleId,signal:t.signal??e.signal,metadata:t.metadata},{interactiveOnly:t.interactiveOnly,compact:t.compact,depth:t.depth,scope:t.scope,raw:t.raw}),w=(n=m,r=e,n.snapshot?n.snapshot:{nodes:n.nodes??[],truncated:n.truncated,backend:n.backend,createdAt:ry(r)}),g=ry(e);return{snapshot:w,result:m,session:h,warnings:(s=[...(i={result:m,snapshot:w,options:t,session:h,capturedAt:w.createdAt??g,runtimeNow:g}).result.warnings??[]],l=!0===i.options.interactiveOnly,u=i.result.analysis,"android"===i.snapshot.backend&&l&&0===i.snapshot.nodes.length&&u&&(u.rawNodeCount??0)>=12&&(s.push(`Interactive snapshot is empty after filtering ${u.rawNodeCount} raw Android nodes. Likely causes: depth too low, transient route change, or collector filtering.`),"number"==typeof i.options.depth&&"number"==typeof u.maxDepth&&u.maxDepth>=i.options.depth+2&&s.push(`Interactive output is empty at depth ${i.options.depth}; retry without -d.`)),c=!!(d=i.session?.snapshot)&&[i.capturedAt,i.runtimeNow].some(e=>{let t=e-d.createdAt;return t>=0&&t<=2e3}),!i.result.freshness&&d&&c&&(a=d.nodes.length,o=i.snapshot.nodes.length,!(a<12)&&o<=Math.floor(.2*a))&&s.push("Recent snapshots dropped sharply in node count, which suggests stale or mid-transition UI. Use screenshot as visual truth, wait briefly, then re-snapshot once."),p=i.result.freshness,p?.staleAfterRetries&&"android"===i.snapshot.backend&&("stuck-route"===p.reason?s.push(`Recent ${p.action} was followed by a nearly identical snapshot after ${p.retryCount} automatic retr${1===p.retryCount?"y":"ies"}. If you expected navigation or submit, the tree may still be stale. Use screenshot as visual truth, wait briefly, then re-snapshot once.`):"sharp-drop"===p.reason&&s.push("Recent snapshots dropped sharply in node count, which suggests stale or mid-transition UI. Use screenshot as visual truth, wait briefly, then re-snapshot once.")),Array.from(new Set(s)))}}function rg(e,t){let n=t.session?.name??e??"default";return{...t.session??{name:n},name:n,snapshot:t.snapshot,appName:t.result.appName??t.session?.appName,appBundleId:t.result.appBundleId??t.session?.appBundleId}}function ry(e){return e.clock?.now()??Date.now()}function rb(e){return["visible","hidden","exists","editable","selected","text"].includes(e)}function rv(e){return!!(e&&Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.width)&&Number.isFinite(e.height)&&e.width>0&&e.height>0)}function rI(e){return"text"===e||"label"===e||"any"===e}function rA(e,t){return{session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata}}function rx(e){return e.clock?.now()??Date.now()}async function rS(e,t){e.clock?await e.clock.sleep(t):await new Promise(e=>setTimeout(e,t))}async function rN(e,t){let n=t??"default",r=await e.sessions.get(n);if(!r)throw new _("SESSION_NOT_FOUND","No active session. Run open first.");if(!r.snapshot)throw new _("INVALID_ARGS","No snapshot in session. Run snapshot first.");return{sessionName:n,session:r,snapshot:r.snapshot}}async function r_(e,t,n={updateSession:!0}){if(!e.backend.captureSnapshot)throw new _("UNSUPPORTED_OPERATION","snapshot is not supported by this backend");let r=t.session??"default",i=await e.sessions.get(r),a=await e.backend.captureSnapshot(rA(e,t),{interactiveOnly:!1,compact:!1,depth:t.depth,scope:n.scope??t.scope,raw:t.raw}),o=a.snapshot??{nodes:a.nodes??[],truncated:a.truncated,backend:a.backend,createdAt:rx(e)};return n.updateSession&&i&&await e.sessions.set({...i,snapshot:o}),{sessionName:r,session:i,snapshot:o}}async function rM(e,t,n){if(e.backend.readText){let r=await e.backend.readText(rA(e,{session:t.sessionName}),n);if(r.text.trim())return r.text}return X(n)}let rD=async(e,t)=>{if("ref"===t.target.kind){let n=await rN(e,t.session),r=function(e,t,n){let r=ea(t);if(!r)throw new _("INVALID_ARGS",n.invalidRefMessage);let i=eo(e,r)??(n.fallbackLabel.length>0?tn(e,n.fallbackLabel):null);if(!i)throw new _("COMMAND_FAILED",n.notFoundMessage);return{ref:r,node:i}}(n.snapshot.nodes,t.target.ref,{fallbackLabel:t.target.fallbackLabel??"",invalidRefMessage:"get text requires a ref like @e2",notFoundMessage:`Ref ${t.target.ref} not found`}),i=tA(r.node,e.backend.platform,{action:"get"}),a={kind:"ref",ref:`@${r.ref}`};return"attrs"===t.property?{kind:"attrs",target:a,node:r.node,selectorChain:i}:{kind:"text",target:a,text:await rM(e,n,r.node),node:r.node,selectorChain:i}}let n=await rG(e,t,t.session??"default",{selector:t.target.selector,disambiguateAmbiguous:"text"===t.property}),r=tA(n.node,e.backend.platform,{action:"get"});if("attrs"===t.property)return{kind:"attrs",target:{kind:"selector",selector:n.selector},node:n.node,selectorChain:r};let i=await rM(e,n.capture,n.node);return{kind:"text",target:{kind:"selector",selector:n.selector},text:i,node:n.node,selectorChain:r}},rE=async(e,t)=>{let n=await rD(e,{...t,property:"text",target:t.target});if("text"!==n.kind)throw new _("COMMAND_FAILED","getText returned non-text result");return n},rC=async(e,t)=>{let n=await rD(e,{...t,property:"attrs",target:t.target});if("attrs"!==n.kind)throw new _("COMMAND_FAILED","getAttrs returned non-attrs result");return n},rO=async(e,t)=>{if(!rb(t.predicate))throw new _("INVALID_ARGS","is requires predicate: visible|hidden|exists|editable|selected|text");if("text"===t.predicate&&!t.expectedText)throw new _("INVALID_ARGS","is text requires expected text value");let n=await r_(e,t,{updateSession:!0}),r=e4(t.selector);if("exists"===t.predicate){let i=tb(n.snapshot.nodes,r,{platform:e.backend.platform});if(!i)throw new _("COMMAND_FAILED",tv(r,[],{unique:!1}));return{predicate:t.predicate,pass:!0,selector:i.selector.raw,matches:i.matches,selectorChain:r.selectors.map(e=>e.raw)}}let i=ty(n.snapshot.nodes,r,{platform:e.backend.platform,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:!1});if(!i)throw new _("COMMAND_FAILED",tv(r,[],{unique:!0}));let a=function(e){let{predicate:t,node:n,nodes:r,expectedText:i,platform:a}=e,o=tu(n),s=tc(n,a),l=!0===n.selected,u="text"===t?td(n):function(e,t){if(!0===e.hittable)return!0;if(rv(e.rect))return eh(e,t);if(e.rect)return!1;let n=function(e,t){let n=new Map(t.map(e=>[e.index,e])),r=e,i=new Set;for(;"number"==typeof r.parentIndex&&!i.has(r.index);){i.add(r.index);let e=n.get(r.parentIndex);if(!e)break;if(function(e){let t=to(e.type??"");return!(t.includes("application")||t.includes("window")||t.includes("scrollview")||t.includes("tableview")||t.includes("collectionview"))&&"table"!==t&&"list"!==t&&"listview"!==t&&(!0===e.hittable||rv(e.rect))}(e))return e;r=e}return null}(e,t);return!!n&&(!0===n.hittable||!!rv(n.rect)&&eh(n,t))}(n,r),d=!1;switch(t){case"visible":d=u;break;case"hidden":d=!u;break;case"editable":d=s;break;case"selected":d=l;break;case"text":d=o===(i??"")}let c="text"===t?`expected="${i??""}" actual="${o}"`:`actual=${JSON.stringify({visible:u,editable:s,selected:l})}`;return{pass:d,actualText:o,details:c}}({predicate:t.predicate,node:i.node,nodes:n.snapshot.nodes,expectedText:t.expectedText,platform:e.backend.platform});if(!a.pass)throw new _("COMMAND_FAILED",`is ${t.predicate} failed for selector ${i.selector.raw}: ${a.details}`);return{predicate:t.predicate,pass:!0,selector:i.selector.raw,..."text"===t.predicate?{text:a.actualText}:{},selectorChain:r.selectors.map(e=>e.raw)}},rk=async(e,t)=>await rO(e,{...t,predicate:"visible",selector:t.target.selector}),rL=async(e,t)=>await rO(e,{...t,predicate:"hidden",selector:t.target.selector}),rR=async(e,t)=>{if("sleep"===t.target.kind)return await rS(e,t.target.durationMs),{kind:"sleep",waitedMs:t.target.durationMs};if("ref"===t.target.kind){let n=await rN(e,t.session),r=ea(t.target.ref);if(!r)throw new _("INVALID_ARGS",`Invalid ref: ${t.target.ref}`);let i=eo(n.snapshot.nodes,r),a=i?tr(i,n.snapshot.nodes):void 0;if(!a)throw new _("COMMAND_FAILED",`Ref ${t.target.ref} not found or has no label`);return await rF(e,t,a,t.target.timeoutMs)}if("selector"===t.target.kind)return await r$(e,t,t.target.selector,t.target.timeoutMs);if(!t.target.text)throw new _("INVALID_ARGS","wait requires text");return await rF(e,t,t.target.text,t.target.timeoutMs)},rT=async(e,t)=>{let n=await rR(e,{...t,target:{kind:"text",text:t.text,timeoutMs:t.timeoutMs}});if("text"!==n.kind)throw new _("COMMAND_FAILED","waitForText returned non-text result");return n};async function rP(e,t,n){let r=t.timeoutMs??1e4,i=rx(e);for(;rx(e)-i<r;){if(tp((await r_(e,t,{updateSession:!0,scope:rI(n)?t.query:void 0})).snapshot.nodes,n,t.query,{requireRect:!1}).matches[0])return{kind:"found",found:!0,waitedMs:rx(e)-i};await rS(e,300)}throw new _("COMMAND_FAILED","find wait timed out")}async function r$(e,t,n,r){let i=r??1e4,a=rx(e),o=e4(n);for(;rx(e)-a<i;){let n=tb((await r_(e,t,{updateSession:!0})).snapshot.nodes,o,{platform:e.backend.platform});if(n)return{kind:"selector",selector:n.selector.raw,waitedMs:rx(e)-a};await rS(e,300)}throw new _("COMMAND_FAILED",`wait timed out for selector: ${n}`)}async function rF(e,t,n,r){let i=r??1e4,a=rx(e);for(;rx(e)-a<i;){if(e.backend.findText?(await e.backend.findText(rA(e,t),n)).found:await rU(e,t,n))return{kind:"text",text:n,waitedMs:rx(e)-a};await rS(e,300)}throw new _("COMMAND_FAILED",`wait timed out for text: ${n}`)}async function rU(e,t,n){return!!tn((await r_(e,t,{updateSession:!0})).snapshot.nodes,n)}async function rG(e,t,n,r){let i=await r_(e,{...t,session:n},{updateSession:!0}),a=e4(r.selector),o=ty(i.snapshot.nodes,a,{platform:e.backend.platform,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:r.disambiguateAmbiguous});if(!o)throw new _("COMMAND_FAILED",tv(a,[],{unique:!0}));return{capture:i,node:o.node,selector:o.selector.raw,ref:`@${o.node.ref}`}}function rV(e,t,n,r){if(!Number.isFinite(e)||!Number.isInteger(e)||e<n||e>r)throw new _("INVALID_ARGS",`${t} must be an integer between ${n} and ${r}`);return e}function rB(e,t){let n=function(e,t){let n=rq(t.rect);if(!n)return null;let r=t,i=new Set;for(;!i.has(r.ref);){i.add(r.ref);let t=e.filter(e=>{if(e.parentIndex!==r.index||!e.hittable)return!1;let t=rq(e.rect);return!!t&&rW(t,n)});if(1!==t.length)break;r=t[0]}return r===t?null:r}(e,t);if(n?.rect&&rj(n.rect))return n;let r=tl(e,t);return r?.rect&&rj(r.rect)?!function(e,t,n){var r,i,a,o;let s,l,u,d=rq(e.rect),c=rq(t.rect);if(!d||!c)return!1;let p=function(e,t){let n=es(t),r=e.filter(e=>{let t=(e.type??"").toLowerCase();return t.includes("application")||t.includes("window")}).map(e=>rq(e.rect)).filter(e=>null!==e);if(0===r.length)return null;let i=r.filter(e=>el(e,n.x,n.y));return eu(i.length>0?i:r)}(n,d);return!!p&&(r=c,i=p,s=(a=r,o=i,Math.max(0,Math.min(a.x+a.width,o.x+o.width)-Math.max(a.x,o.x))*Math.max(0,Math.min(a.y+a.height,o.y+o.height)-Math.max(a.y,o.y))),l=r.width*r.height,u=i.width*i.height,!(s<=0)&&!(l<=0)&&!(u<=0)&&!!(s/u>=.9)&&!!(s/l>=.8))&&!rW(d,c)}(t,r,e)?r:t:t}function rj(e){let t=rq(e);if(!t)return null;let n=es(t);return Number.isFinite(n.x)&&Number.isFinite(n.y)?n:null}function rq(e){if(!e)return null;let t=Number(e.x),n=Number(e.y),r=Number(e.width),i=Number(e.height);return Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(i)&&!(r<0)&&!(i<0)?{x:t,y:n,width:r,height:i}:null}function rW(e,t){return .5>=Math.abs(e.x-t.x)&&.5>=Math.abs(e.y-t.y)&&.5>=Math.abs(e.width-t.width)&&.5>=Math.abs(e.height-t.height)}async function rz(e,t,n){let r=await rX(e,t,{action:n,requireInteractive:!0,promoteToHittableAncestor:!0});if(!e.backend.tap)throw new _("UNSUPPORTED_OPERATION","tap is not supported by this backend");let i=await e.backend.tap(rA(e,t),r.point,{button:t.button,count:t.count,intervalMs:t.intervalMs,holdMs:t.holdMs,jitterPx:t.jitterPx,doubleTap:t.doubleTap});return{...r,...r1(i)?{backendResult:r1(i)}:{}}}async function rX(e,t,n){if(await rY(e,t,n.action),"point"===t.target.kind)return{kind:"point",point:{x:t.target.x,y:t.target.y}};if("ref"===t.target.kind){let r=await rK(e,t,t.target),i=r.resolved,a=n.promoteToHittableAncestor?rB(r.snapshot.nodes,i.node):i.node;return function(e,t,n,r){let i=e.rect?em(e,t):null;if(!(!e.rect||!i||eh(e,t)))throw new _("COMMAND_FAILED",`Ref ${n} is off-screen and not safe to ${r}`,{reason:"offscreen_ref",ref:ea(n),rect:e.rect,viewport:i,hint:`Use scroll with the direction from the off-screen summary, take a fresh snapshot, then retry ${r} with the new ref or a selector.`})}(a,r.snapshot.nodes,t.target.ref,n.action),{kind:"ref",point:rQ(a,`Ref ${t.target.ref} not found or has invalid bounds`),target:{kind:"ref",ref:`@${i.ref}`},node:a,selectorChain:tA(a,e.backend.platform,{action:"fill"===n.action?"fill":"click"}),refLabel:tr(a,r.snapshot.nodes)}}let r=await rJ(e,t,n.requireInteractive),i=e4(t.target.selector),a=ty(r.snapshot.nodes,i,{platform:e.backend.platform,requireRect:!0,requireUnique:!0,disambiguateAmbiguous:!0});if(!a||!a.node.rect)throw new _("COMMAND_FAILED",tv(i,a?.diagnostics??[],{unique:!0}));let o=n.promoteToHittableAncestor?rB(r.snapshot.nodes,a.node):a.node;return{kind:"selector",point:rQ(o,`Selector ${a.selector.raw} resolved to invalid bounds`),target:{kind:"selector",selector:a.selector.raw},node:o,selectorChain:tA(o,e.backend.platform,{action:"fill"===n.action?"fill":"click"}),refLabel:tr(o,r.snapshot.nodes)}}async function rY(e,t,n){if("macos"!==e.backend.platform)return;let r=await rH(e,t);if(("desktop"===r||"menubar"===r)&&("menubar"!==r||"click"!==n&&"press"!==n))throw new _("UNSUPPORTED_OPERATION",`${n} is not supported on macOS ${r} sessions yet. Open an app session to act, or use the ${r} surface to inspect.`)}async function rH(e,t){let n=await e.sessions.get(t.session??"default");return n?.metadata?.surface}async function rJ(e,t,n){if(!e.backend.captureSnapshot)throw new _("UNSUPPORTED_OPERATION","snapshot is not supported by this backend");let r=t.session??"default",i=await e.sessions.get(r);if(!i)throw new _("SESSION_NOT_FOUND","No active session. Run open first.");let a=await e.backend.captureSnapshot(rA(e,t),{interactiveOnly:n,compact:n}),o=a.snapshot??{nodes:a.nodes??[],truncated:a.truncated,backend:a.backend,createdAt:rx(e)};return await e.sessions.set({...i,snapshot:o}),{snapshot:o}}async function rK(e,t,n){let r=t.session??"default",i=await e.sessions.get(r);if(!i)throw new _("SESSION_NOT_FOUND","No active session. Run open first.");if(!i.snapshot)throw new _("INVALID_ARGS","No snapshot in session. Run snapshot first.");let a=n.fallbackLabel??"",o=rZ(i.snapshot.nodes,n.ref,{fallbackLabel:a,requireRect:!0});if(o)return{snapshot:i.snapshot,resolved:o};let s=await rJ(e,t,!0),l=rZ(s.snapshot.nodes,n.ref,{fallbackLabel:a,requireRect:!0});if(!l)throw new _("COMMAND_FAILED",`Ref ${n.ref} not found or has no bounds`);return{...s,resolved:l}}function rZ(e,t,n){let r=ea(t);if(!r)throw new _("INVALID_ARGS",`Invalid ref: ${t}`);let i=eo(e,r);if(r0(i,n.requireRect))return{ref:r,node:i};let a=n.fallbackLabel.length>0?tn(e,n.fallbackLabel):null;return r0(a,n.requireRect)?{ref:r,node:a}:null}function rQ(e,t){if(!e.rect)throw new _("COMMAND_FAILED",t);let n=es(e.rect);if(!Number.isFinite(n.x)||!Number.isFinite(n.y))throw new _("COMMAND_FAILED",t);return n}function r0(e,t){if(!e)return!1;if(!t)return!0;if(!e.rect)return!1;let{x:n,y:r,width:i,height:a}=e.rect;if(!Number.isFinite(Number(n))||!Number.isFinite(Number(r))||!Number.isFinite(Number(i))||!Number.isFinite(Number(a))||0>Number(i)||0>Number(a))return!1;let o=es(e.rect);return Number.isFinite(o.x)&&Number.isFinite(o.y)}function r1(e){return e&&"object"==typeof e?e:void 0}let r2=async(e,t)=>{let n;if(!e.backend.captureScreenshot)throw new _("UNSUPPORTED_OPERATION","screenshot is not supported by this backend");let r=await nN(e,t.out,{field:"path",ext:".png"});try{await e.backend.captureScreenshot({session:t.session,requestId:t.requestId,appId:t.appId,appBundleId:t.appBundleId,signal:t.signal??e.signal,metadata:t.metadata},r.path,{fullscreen:t.fullscreen,overlayRefs:t.overlayRefs,surface:t.surface}),n=await r.publish()}catch(e){throw await r.cleanup?.(),e}return{path:r.path,...n?{artifacts:[n]}:{},...tN(`Saved screenshot: ${r.path}`)}},r3=async(e,t)=>{let n,r,i;if(!t.baseline)throw new _("INVALID_ARGS","diff screenshot requires a baseline image");let a=function(e){if(null==e||""===e)return .1;let t=Number(e);if(Number.isNaN(t)||t<0||t>1)throw new _("INVALID_ARGS","--threshold must be a number between 0 and 1");return t}(t.threshold),o=t.current??{kind:"live"};if(t.overlayRefs&&!rp(o))throw new _("INVALID_ARGS","diff screenshot <current.png> cannot use --overlay-refs because saved-image comparisons have no live accessibility refs");let s=await nS(e,t.baseline,{usage:"diff screenshot baseline",field:"baseline"}),l=[];try{let u;u=rp(o)?(r=await ro(e,t)).path:(n=await nS(e,o,{usage:"diff screenshot current",field:"current"})).path,i=t.out?await nN(e,t.out,{field:"diffPath",ext:".png"}):void 0;let d=await n9(s.path,u,{threshold:a,outputPath:i?.path,maxPixels:e.policy.maxImagePixels});rp(o)&&(d=await rs(e,t,i?.path,d,l));let c=d.diffPath?await i?.publish():void 0;return c&&l.push(c),d.diffPath||await i?.cleanup?.(),{...d,...l.length>0?{artifacts:l}:{}}}catch(e){throw await i?.cleanup?.(),e}finally{await s.cleanup?.(),await n?.cleanup?.(),await r?.cleanup?.()}},r4=async(e,t)=>{var n;let r,i,a=await rw(e,t);return await e.sessions.set(rg(t.session,a)),{nodes:a.snapshot.nodes,truncated:a.snapshot.truncated??!1,visibility:function(e){var t;let{nodes:n,backend:r,snapshotRaw:i}=e;if(i||"macos-helper"===(t=r)||"linux-atspi"===t)return{partial:!1,visibleNodeCount:n.length,totalNodeCount:n.length,reasons:[]};let a=ef(n),o=new Set;return a.hiddenCount>0&&o.add("offscreen-nodes"),a.nodes.some(e=>e.hiddenContentAbove)&&o.add("scroll-hidden-above"),a.nodes.some(e=>e.hiddenContentBelow)&&o.add("scroll-hidden-below"),{partial:o.size>0,visibleNodeCount:a.nodes.length,totalNodeCount:n.length,reasons:[...o]}}({nodes:a.snapshot.nodes,backend:a.snapshot.backend,snapshotRaw:t.raw}),...a.warnings.length>0?{warnings:a.warnings}:{},...(r=(n=a).result.appName??n.session?.appName,i=n.result.appBundleId??n.session?.appBundleId,{...r||i?{appName:r??i}:{},...i?{appBundleId:i}:{}})}},r5=async(e,t)=>{let n=await rw(e,t),r=!0===t.interactiveOnly,i=n.session?.snapshot,a=rg(t.session,n);if(!i){let t=function(e,t={}){return rh(e,t).length}(n.snapshot.nodes,{flatten:r});return await e.sessions.set(a),{mode:"snapshot",baselineInitialized:!0,summary:{additions:0,removals:0,unchanged:t},lines:[],...n.warnings.length>0?{warnings:n.warnings}:{}}}let o=function(e,t,n={}){let r=function(e,t){let n=e.length,r=t.length,i=n+r,a=new Map,o=[];a.set(1,0);for(let s=0;s<=i;s+=1){o.push(new Map(a));for(let i=-s;i<=s;i+=2){let l=i===-s||i!==s&&rm(a,i-1)<rm(a,i+1)?rm(a,i+1):rm(a,i-1)+1,u=l-i;for(;l<n&&u<r&&e[l].comparable===t[u].comparable;)l+=1,u+=1;if(a.set(i,l),l>=n&&u>=r)return function(e,t,n,r,i){let a=[],o=r,s=i;for(let r=e.length-1;r>=0;r-=1){let i=e[r],l=o-s,u=l===-r||l!==r&&rm(i,l-1)<rm(i,l+1)?l+1:l-1,d=rm(i,u),c=d-u;for(;o>d&&s>c;)a.push({kind:"unchanged",text:n[s-1].text}),o-=1,s-=1;if(0===r)break;o===d?(a.push({kind:"added",text:n[c].text}),s=c):(a.push({kind:"removed",text:t[d].text}),o=d)}return a.reverse(),a}(o,e,t,n,r)}}return[]}(rh(e,n),rh(t,n)),i={additions:0,removals:0,unchanged:0};for(let e of r)"added"===e.kind&&(i.additions+=1),"removed"===e.kind&&(i.removals+=1),"unchanged"===e.kind&&(i.unchanged+=1);return{summary:i,lines:r}}(i.nodes,n.snapshot.nodes,{flatten:r});return await e.sessions.set(a),{mode:"snapshot",baselineInitialized:!1,summary:o.summary,lines:o.lines,...n.warnings.length>0?{warnings:n.warnings}:{}}},r8=async(e,t)=>{let n=t.locator??"any";if(!t.query)throw new _("INVALID_ARGS","find requires a value");if("wait"===t.action)return await rP(e,t,n);let r=await r_(e,t,{updateSession:!0,scope:rI(n)?t.query:void 0}),i=tp(r.snapshot.nodes,n,t.query,{requireRect:!1}).matches[0];if(!i)throw new _("COMMAND_FAILED","find did not match any element");if("exists"===t.action)return{kind:"found",found:!0};let a=`@${i.ref}`;return"get_attrs"===t.action?{kind:"attrs",ref:a,node:i}:{kind:"text",ref:a,text:await rM(e,r,i),node:i}},r6=rD,r9=rE,r7=rC,ie=rO,it=rk,ir=rL,ii=rR,ia=rT,io=async(e,t)=>await rz(e,t,"click"),is=async(e,t)=>await rz(e,t,"press"),il=async(e,t)=>{var n;if(!t.text)throw new _("INVALID_ARGS","fill requires text");let r=await rX(e,t,{action:"fill",requireInteractive:!0,promoteToHittableAncestor:!1});if(!e.backend.fill)throw new _("UNSUPPORTED_OPERATION","fill is not supported by this backend");let i=await e.backend.fill(rA(e,t),r.point,t.text,{delayMs:t.delayMs}),a="node"in r?r.node.type??"":"",o=a&&!ts(a,e.backend.platform)?`fill target ${n=r,n.target?.kind==="ref"?n.target.ref:n.target?.kind==="selector"?n.target.selector:"point"} resolved to "${a}", attempting fill anyway.`:void 0;return{...r,text:t.text,...o?{warning:o}:{},...r1(i)?{backendResult:r1(i)}:{}}},iu=async(e,t)=>{var n;let r=t.text;if(!r)throw new _("INVALID_ARGS","type requires text");let i=function(e){let t=e.trim().split(/\s+/,1)[0];if(!t||!t.startsWith("@")||t.length<3)return null;let n=t.slice(1);return/^[A-Za-z_-]*\d[\w-]*$/i.test(n)||/^(?:ref|node|element|el)[\w-]*$/i.test(n)?t:null}(r);if(i)throw new _("INVALID_ARGS",`type does not accept a target ref like "${i}"`,{hint:`Use fill ${i} "text" to target that field, or press ${i} then type "text" to append.`});if(!e.backend.typeText)throw new _("UNSUPPORTED_OPERATION","type is not supported by this backend");let a=rV(t.delayMs??0,"delay-ms",0,1e4),o=await e.backend.typeText(rA(e,t),r,{delayMs:a}),s=(n=r,`Typed ${Array.from(n).length} chars`);return{kind:"text",text:r,delayMs:a,...r1(o)?{backendResult:r1(o)}:{},...tN(s)}};function id(e){let t={backend:e.backend,artifacts:e.artifacts,sessions:e.sessions??function(e=[]){let t=new Map(e.map(e=>[e.name,ic(e)]));return{get:e=>ip(t.get(e)),set:e=>{t.set(e.name,ip(e))},delete:e=>{t.delete(e)},list:()=>Array.from(t.values(),ic)}}(),policy:e.policy??function(e={}){return{allowLocalInputPaths:!1,allowLocalOutputPaths:!1,maxImagePixels:2e7,allowNamedBackendCapabilities:[],...e}}(),diagnostics:e.diagnostics,clock:e.clock,signal:e.signal};return{...t,capture:{screenshot:e=>r2(t,e),diffScreenshot:e=>r3(t,e),snapshot:e=>r4(t,e),diffSnapshot:e=>r5(t,e)},selectors:{find:e=>r8(t,e),get:e=>r6(t,e),getText:(e,n={})=>r9(t,{...n,target:e}),getAttrs:(e,n={})=>r7(t,{...n,target:e}),is:e=>ie(t,e),isVisible:(e,n={})=>it(t,{...n,target:e}),isHidden:(e,n={})=>ir(t,{...n,target:e}),wait:e=>ii(t,e),waitForText:(e,n={})=>ia(t,{...n,text:e})},interactions:{click:(e,n={})=>io(t,{...n,target:e}),press:(e,n={})=>is(t,{...n,target:e}),fill:(e,n,r={})=>il(t,{...r,target:e,text:n}),typeText:(e,n={})=>iu(t,{...n,text:e})}}}function ic(e){return ip(e)}function ip(e){if(e)return{...e,...e.snapshot?{snapshot:structuredClone(e.snapshot)}:{},...e.metadata?{metadata:function(e){try{return structuredClone(e)}catch{return{...e}}}(e.metadata)}:{}}}function ih(e={}){return{allowLocalInputPaths:!0,allowLocalOutputPaths:!0,maxImagePixels:2e7,allowNamedBackendCapabilities:[],...e}}function im(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{details:n}:{}}}}function iw(e){return e}function ig(e){return"apple"===e||"ios"===e||"macos"===e}function iy(e,t){return!t||("apple"===t?ig(e):e===t)}function ib(e){let{simulatorSetPath:t,platform:n,target:r}=e;if(t&&"macos"!==n&&"desktop"!==r)return t}async function iv(e,t,n={}){let r=e,i=e=>e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim();if(t.platform&&(r=r.filter(e=>iy(e.platform,t.platform))),t.target&&(r=r.filter(e=>(e.target??"mobile")===t.target)),t.udid){let e=r.find(e=>e.id===t.udid&&ig(e.platform));if(!e)throw new _("DEVICE_NOT_FOUND",`No Apple device with UDID ${t.udid}`);return e}if(t.serial){let e=r.find(e=>e.id===t.serial&&"android"===e.platform);if(!e)throw new _("DEVICE_NOT_FOUND",`No Android device with serial ${t.serial}`);return e}if(t.deviceName){let e=i(t.deviceName),n=r.find(t=>i(t.name)===e);if(!n)throw new _("DEVICE_NOT_FOUND",`No device named ${t.deviceName}`);return n}if(1===r.length)return r[0];if(0===r.length){var a;let e=n.simulatorSetPath;if(e&&(!(a=t.platform)||"apple"===a||"ios"===a))throw new _("DEVICE_NOT_FOUND","No devices found in the scoped simulator set",{simulatorSetPath:e,hint:`The simulator set at "${e}" appears to be empty. Create a simulator first:
|
|
8
|
-
xcrun simctl --set "${e}" create "iPhone 16" com.apple.CoreSimulator.SimDeviceType.iPhone-16 com.apple.CoreSimulator.SimRuntime.iOS-18-0`,selector:t});throw new _("DEVICE_NOT_FOUND","No devices found",{selector:t})}let o=r.filter(e=>"device"!==e.kind);o.length>0&&(r=o);let s=r.filter(e=>e.booted);return 1===s.length?s[0]:s[0]??r[0]}let
|
|
9
|
-
`)}let
|
|
7
|
+
${t}`.toLowerCase();return["run-as: package not debuggable","run-as: permission denied","run-as: package is unknown","run-as: unknown package","is unknown","is not an application","could not set capabilities"].some(e=>n.includes(e))}async function nN(e,t,n){if("path"===t.kind&&!e.policy.allowLocalInputPaths)throw new _("INVALID_ARGS",`Local ${n.field??"input"} paths are not allowed by command policy`);try{return await e.artifacts.resolveInput(t,n)}catch(e){throw x(e)}}async function nS(e,t,n){if(t?.kind==="path"&&!e.policy.allowLocalOutputPaths)throw new _("INVALID_ARGS","Local output paths are not allowed by command policy");try{return await e.artifacts.reserveOutput(t,{...n,visibility:n.visibility??"client-visible",requestedClientPath:t?.kind==="downloadableArtifact"?t.clientPath??n.requestedClientPath:n.requestedClientPath})}catch(e){throw x(e)}}async function n_(e,t){try{return await e.artifacts.createTempFile(t)}catch(e){throw x(e)}}let nk=async(e,t)=>{let n;if(!e.backend.captureScreenshot)throw new _("UNSUPPORTED_OPERATION","screenshot is not supported by this backend");let r=await nS(e,t.out,{field:"path",ext:".png"});try{await e.backend.captureScreenshot({session:t.session,requestId:t.requestId,appId:t.appId,appBundleId:t.appBundleId,signal:t.signal??e.signal,metadata:t.metadata},r.path,{fullscreen:t.fullscreen,overlayRefs:t.overlayRefs,surface:t.surface}),n=await r.publish()}catch(e){throw await r.cleanup?.(),e}return{path:r.path,...n?{artifacts:[n]}:{},...tS(`Saved screenshot: ${r.path}`)}};function nD(e,t){try{return h.sync.read(e)}catch(e){throw new _("COMMAND_FAILED",`Failed to decode ${t} as PNG`,{label:t,reason:e instanceof Error?e.message:String(e)})}}let nM=[0,187,255,255];function nE(e,t,n,r){if(t<0||t>=e.width||n<0||n>=e.height)return;let a=(n*e.width+t)*4;e.data[a]=r[0],e.data[a+1]=r[1],e.data[a+2]=r[2],e.data[a+3]=r[3]}function nO(e,t,n){return Math.min(Math.max(e,t),n)}let nC={icon:90,toggle:90,chevron:75,separator:45,visual:35,background:10},nR={leading:20,trailing:20,separator:10,unknown:0,background:-30};function nL(e){return"background"!==e.likelyKind}function nP(e,t){return e.width>=.25*t.width||e.height>=.06*t.height}function nT(e,t){let n,r=0;for(let a of t){let t=nV(e,a.rect);t<=r||(r=t,n=a)}return n}function n$(e){let t=[];for(let n of[...e].sort((e,t)=>e.rect.y-t.rect.y)){let e=t.find(e=>{var t,r;return t=e.rect,nV(t,r=n.rect)>0||Math.abs(nB(t).y-nB(r).y)<=.5*Math.max(t.height,r.height)});if(!e){t.push({rect:n.rect,blocks:[n]});continue}e.blocks.push(n),e.blocks.sort((e,t)=>e.rect.x-t.rect.x),e.rect=function(e){let t=1/0,n=1/0,r=-1/0,a=-1/0;for(let i of e)t=Math.min(t,i.x),n=Math.min(n,i.y),r=Math.max(r,i.x+i.width),a=Math.max(a,i.y+i.height);return{x:t,y:n,width:r-t,height:a-n}}([e.rect,n.rect])}return t}function nF(e,t){let n,r=nB(e);for(let e of t){var a,i;let t=Math.sqrt((a=r,i=nB(e.rect),(a.x-i.x)**2+(a.y-i.y)**2));n&&t>=n.distance||(n={block:e,distance:t})}return n}function nU(e){let t=nG(e);return e.differentPixels>=24&&t.width>=3&&t.height>=3}function nG(e){return{x:e.minX,y:e.minY,width:e.maxX-e.minX+1,height:e.maxY-e.minY+1}}function nV(e,t){return Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))}function nB(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}function nj(e,t,n){return Math.min(Math.max(e,t),n)}async function nq(e){if(await v("tesseract"))try{let[t,n]=await Promise.all([nz(e.baselinePath),nz(e.currentPath)]);if(0!==t.exitCode||0!==n.exitCode)return;let r=nW(t.stdout,e.width,e.height),a=nW(n.stdout,e.width,e.height),i=function(e,t){let n=new Set,r=[];for(let i of e){var a;let e=nQ(i.text),o=function(e,t,n,r){let a=null,i=1/0;for(let l=0;l<n.length;l+=1){var o,s;if(r.has(l))continue;let u=n[l];if(nQ(u.text)!==t)continue;let d=(o=nJ(e.normalizedRect),s=nJ(u.normalizedRect),(o.x-s.x)**2+(o.y-s.y)**2);d>=i||(a=l,i=d)}return a}(i,e,t,n);if(null===o)continue;n.add(o);let s=function(e,t){let n={x:t.rect.x-e.rect.x,y:t.rect.y-e.rect.y,width:t.rect.width-e.rect.width,height:t.rect.height-e.rect.height},r=n2(t.rect.width/e.rect.width),a=n2(t.rect.height/e.rect.height),i=Math.abs(r-1)>=.08||Math.abs(a-1)>=.12;return{text:e.text,baselineRect:e.rect,currentRect:t.rect,delta:n,confidence:Math.round(100*Math.min(e.confidence,t.confidence))/100,possibleTextMetricMismatch:i}}(i,t[o]);a=s,(Math.abs(a.delta.x)>=2||Math.abs(a.delta.y)>=2||Math.abs(a.delta.width)>=2||Math.abs(a.delta.height)>=2||a.possibleTextMetricMismatch)&&r.push(s)}return r.sort((e,t)=>nX(t)-nX(e)).slice(0,12)}(r,a),o=function(e){let t=[];for(let n of[...e].sort((e,t)=>e.currentRect.y-t.currentRect.y)){let e=t.find(e=>32>=Math.abs(n.delta.x-n0(e.map(e=>e.delta.x))));e?e.push(n):t.push([n])}return t.filter(e=>e.length>=2).map(nH).filter(e=>e.yRange.max-e.yRange.min<=60).sort((e,t)=>nY(t)-nY(e)).slice(0,4)}(i);if(0===r.length&&0===a.length)return;return{provider:"tesseract",baselineBlocks:r.length,currentBlocks:a.length,baselineBlocksRaw:r,currentBlocksRaw:a,matches:i,...o.length>0?{movementClusters:o}:{}}}catch{return}}function nW(e,t,n){let[r,...a]=e.split(/\r?\n/);if(!r)return[];let i=new Map(r.split(" ").map((e,t)=>[e,t])),o=[];for(let e of a){var s;if(!e.trim())continue;let t=e.split(" "),n=nZ(t,i,"level"),r=nK(t,i,"text").trim(),a=nZ(t,i,"conf");if(5!==n||(s=r,!/[\p{L}\p{N}]/u.test(s))||a<0)continue;let l=nZ(t,i,"left"),u=nZ(t,i,"top"),d=nZ(t,i,"width"),c=nZ(t,i,"height");d<=0||c<=0||o.push({key:[nK(t,i,"page_num"),nK(t,i,"block_num"),nK(t,i,"par_num"),nK(t,i,"line_num")].join(":"),text:r,confidence:a,rect:{x:l,y:u,width:d,height:c}})}let l=new Map;for(let e of o){let t=l.get(e.key);t?t.push(e):l.set(e.key,[e])}return Array.from(l.values()).flatMap(e=>(function(e){let t=[...e].sort((e,t)=>e.rect.x-t.rect.x),n=[],r=[];for(let e of t){let t=r.at(-1);if(!t){r.push(e);continue}if(e.rect.x-(t.rect.x+t.rect.width)>Math.max(48,2.5*Math.max(t.rect.height,e.rect.height))){n.push(r),r=[e];continue}r.push(e)}return r.length>0&&n.push(r),n})(e)).map(e=>(function(e,t,n){if(0===e.length)return null;let r=[...e].sort((e,t)=>e.rect.x-t.rect.x),a=function(e){let t=1/0,n=1/0,r=-1/0,a=-1/0;for(let i of e)t=Math.min(t,i.x),n=Math.min(n,i.y),r=Math.max(r,i.x+i.width),a=Math.max(a,i.y+i.height);return{x:t,y:n,width:r-t,height:a-n}}(r.map(e=>e.rect)),i=Math.round(100*n0(r.map(e=>e.confidence)))/100;return{text:r.map(e=>e.text).join(" "),confidence:i,rect:a,normalizedRect:{x:n1(a.x/t),y:n1(a.y/n),width:n1(a.width/t),height:n1(a.height/n)}}})(e,t,n)).filter(e=>null!==e)}function nz(e){return k("tesseract",[e,"stdout","-l","eng","tsv"],{allowFailure:!0,timeoutMs:1e4})}function nX(e){return Math.abs(e.delta.x)+Math.abs(e.delta.y)+Math.abs(e.delta.width)+Math.abs(e.delta.height)+25*!!e.possibleTextMetricMismatch}function nH(e){let t=e.map(e=>e.delta.x),n=e.map(e=>e.delta.y);return{texts:e.map(e=>e.text),xRange:{min:Math.min(...t),max:Math.max(...t)},yRange:{min:Math.min(...n),max:Math.max(...n)}}}function nY(e){return 2*Math.abs((e.xRange.min+e.xRange.max)/2)+Math.abs((e.yRange.min+e.yRange.max)/2)}function nJ(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}function nK(e,t,n){let r=t.get(n);return void 0===r?"":e[r]??""}function nZ(e,t,n){let r=Number(nK(e,t,n));return Number.isFinite(r)?r:0}function nQ(e){return e.trim().replace(/\s+/g," ").toLowerCase()}function n0(e){return e.reduce((e,t)=>e+t,0)/e.length}function n1(e){return Math.round(100*e*100)/100}function n2(e){return Math.round(1e3*e)/1e3}function n3(e,t,n,r){return{r:Math.round(e/r),g:Math.round(t/r),b:Math.round(n/r)}}function n4(e){return .2126*e.r+.7152*e.g+.0722*e.b}function n5(e){return`#${n8(e.r)}${n8(e.g)}${n8(e.b)}`}function n8(e){return e.toString(16).padStart(2,"0")}function n6(e){return Math.round(100*e*100)/100}let n9=255*Math.sqrt(3);async function n7(e,t,n={}){let r,a,s,l;await re(e,"Baseline image not found"),await re(t,"Current screenshot not found");let u=n.outputPath,[d,c]=await Promise.all([i.readFile(e),i.readFile(t)]),p=nD(d,"baseline screenshot"),f=nD(c,"current screenshot");rt(p.width,p.height,"baseline screenshot",n.maxPixels),rt(f.width,f.height,"current screenshot",n.maxPixels);let m=n.threshold??.1;if(p.width!==f.width||p.height!==f.height){let e=p.width*p.height;return await rn(n.outputPath),{match:!1,mismatchPercentage:100,totalPixels:e,differentPixels:e,dimensionMismatch:{expected:{width:p.width,height:p.height},actual:{width:f.width,height:f.height}}}}let w=p.width*p.height,g=m*n9,y=new h({width:p.width,height:p.height}),b=new Uint8Array(w),v=0;for(let e=0,t=0;e<p.data.length;e+=4,t+=1){if(Math.sqrt((p.data[e]-f.data[e])**2+(p.data[e+1]-f.data[e+1])**2+(p.data[e+2]-f.data[e+2])**2)>g){v+=1,b[t]=1;let n=rr(f,e);y.data[e]=ra(n,220,.78),y.data[e+1]=ra(n,0,.78),y.data[e+2]=ra(n,0,.78),y.data[e+3]=255;continue}let n=rr(f,e);y.data[e]=n,y.data[e+1]=n,y.data[e+2]=n,y.data[e+3]=255}let I=v>0?(x=(r=function(e){let{diffMask:t,baseline:n,current:r}=e,{width:a,height:i}=n,o=new Uint8Array(t.length),s=new Int32Array(t.length),l=[];for(let e=0;e<t.length;e+=1){if(1!==t[e]||1===o[e])continue;let u=0,d=0;s[0]=e,d+=1,o[e]=1;let c=e%a,p=Math.floor(e/a),f={minX:c,minY:p,maxX:c,maxY:p,differentPixels:0,baselineRed:0,baselineGreen:0,baselineBlue:0,currentRed:0,currentGreen:0,currentBlue:0};for(;u<d;){let e=s[u];u+=1,function(e,t,n,r,a){let i=t%n,o=Math.floor(t/n),s=4*t;e.minX=Math.min(e.minX,i),e.minY=Math.min(e.minY,o),e.maxX=Math.max(e.maxX,i),e.maxY=Math.max(e.maxY,o),e.differentPixels+=1,e.baselineRed+=r.data[s],e.baselineGreen+=r.data[s+1],e.baselineBlue+=r.data[s+2],e.currentRed+=a.data[s],e.currentGreen+=a.data[s+1],e.currentBlue+=a.data[s+2]}(f,e,a,n,r);let l=e%a,c=Math.floor(e/a);for(let e=-1;e<=1;e+=1){let n=c+e;if(!(n<0)&&!(n>=i))for(let r=-1;r<=1;r+=1){if(0===r&&0===e)continue;let i=l+r;if(i<0||i>=a)continue;let u=n*a+i;1===t[u]&&1!==o[u]&&(o[u]=1,s[d]=u,d+=1)}}}l.push(f)}return l}(A={diffMask:b,baseline:p,current:f,totalPixels:w,differentPixels:v,maxRegions:n.maxRegions})).length<=2e3?function(e){let t=[];for(let a of e.sort((e,t)=>{let n=e.minY-t.minY;return 0!==n?n:e.minX-t.minX})){var n,r;let e=t.find(e=>{var t,n,r;return t=e,n=a,r=12,t.minX-r<=n.maxX&&n.minX-r<=t.maxX&&t.minY-r<=n.maxY&&n.minY-r<=t.maxY});if(!e){t.push({...a});continue}n=e,r=a,n.minX=Math.min(n.minX,r.minX),n.minY=Math.min(n.minY,r.minY),n.maxX=Math.max(n.maxX,r.maxX),n.maxY=Math.max(n.maxY,r.maxY),n.differentPixels+=r.differentPixels,n.baselineRed+=r.baselineRed,n.baselineGreen+=r.baselineGreen,n.baselineBlue+=r.baselineBlue,n.currentRed+=r.currentRed,n.currentGreen+=r.currentGreen,n.currentBlue+=r.currentBlue}return t}(r):r,x.flatMap(e=>{var t,n,r;let a;return(t=e,n=A.baseline.width,r=A.baseline.height,a=t.maxX-t.minX+1,t.maxY-t.minY+1>=Math.max(48,Math.round(.07*r))&&a>=.35*n)?function(e,t,n){var r;let a=function(e,t){let n=[],r=null;for(let a=0;a<e.length;a+=1){if(e[a]<=t){r??=a;continue}null!==r&&(a-r>=6&&n.push([r,a-1]),r=null)}return null!==r&&e.length-r>=6&&n.push([r,e.length-1]),n}((r=function(e,t,n){let r=[];for(let a=e.minY;a<=e.maxY;a+=1){let i=0;for(let r=e.minX;r<=e.maxX;r+=1)1===t[a*n+r]&&(i+=1);r.push(i)}return r}(e,t.diffMask,t.baseline.width)).map((e,t)=>{let n=0,a=0,i=Math.max(0,t-3),o=Math.min(r.length-1,t+3);for(let e=i;e<=o;e+=1)n+=r[e],a+=1;return Math.round(n/a)}),Math.max(1,Math.round((e.maxX-e.minX+1)*.08))),i=function(e,t,n){let r=[],a=e.minY;for(let[i,o]of t){let t=e.minY+Math.round((i+o)/2);t-a+1<n||e.maxY-t<n||(r.push([a,t]),a=t+1)}return r.push([a,e.maxY]),r}(e,a,n);if(i.length<=1)return[e];let o=i.map(([n,r])=>(function(e,t,n,r){let a=null;for(let s=t;s<=n;s+=1)for(let t=e.minX;t<=e.maxX;t+=1){var i,o;let e=s*r.baseline.width+t;1===r.diffMask[e]&&function(e,t,n,r,a,i){let o=4*t;e.minX=Math.min(e.minX,n),e.minY=Math.min(e.minY,r),e.maxX=Math.max(e.maxX,n),e.maxY=Math.max(e.maxY,r),e.differentPixels+=1,e.baselineRed+=a.data[o],e.baselineGreen+=a.data[o+1],e.baselineBlue+=a.data[o+2],e.currentRed+=i.data[o],e.currentGreen+=i.data[o+1],e.currentBlue+=i.data[o+2]}(a??={minX:i=t,minY:o=s,maxX:i,maxY:o,differentPixels:0,baselineRed:0,baselineGreen:0,baselineBlue:0,currentRed:0,currentGreen:0,currentBlue:0},e,t,s,r.baseline,r.current)}return a})(e,n,r,t)).filter(e=>null!==e);return o.length>1?o:[e]}(e,A,Math.max(24,Math.round(.03*A.baseline.height))):[e]})).sort((e,t)=>{let n=t.differentPixels-e.differentPixels;if(0!==n)return n;let r=e.minY-t.minY;return 0!==r?r:e.minX-t.minX}).slice(0,Math.max(0,A.maxRegions??8)).map((e,t)=>{var n,r,a,i,o,s,l,u,d,c,p;let f,h,m,w,g,y,b,v,I,x,N,S,_,k,D,M,E;return n=e,r=t+1,a={width:A.baseline.width,height:A.baseline.height,totalPixels:A.totalPixels,differentPixels:A.differentPixels},y={x:n.minX,y:n.minY,width:n.maxX-n.minX+1,height:n.maxY-n.minY+1},b={x:Math.round(n.minX+y.width/2),y:Math.round(n.minY+y.height/2)},v=n3(n.baselineRed,n.baselineGreen,n.baselineBlue,n.differentPixels),I=n3(n.currentRed,n.currentGreen,n.currentBlue,n.differentPixels),x=y.width*y.height,N=n6(n.differentPixels/x),S=Math.round(n4(v)),_=Math.round(n4(I)),k=(i=y,o=a.width,s=a.height,i.width>=.55*o&&i.height>=.12*s?"large-area":i.width>=2.5*i.height?"horizontal-band":i.height>=2.5*i.width?"vertical-band":"compact"),D=(f=x/a.totalPixels)>=.04?"large":f>=.01?"medium":"small",M=(l=v,u=I,h=n4(l),Math.abs(m=n4(u)-h)>=12?m>0?"brighter":"darker":Math.max(Math.abs(u.r-l.r),Math.abs(u.g-l.g),Math.abs(u.b-l.b))>=12?"color-shift":"mixed"),E=(d=b,c=a.width,p=a.height,w=d.x<c/3?"left":d.x>2*c/3?"right":"center",g=d.y<p/3?"top":d.y>2*p/3?"bottom":"middle","center"===w&&"middle"===g?"center":`${g}-${w}`),{index:r,rect:y,normalizedRect:{x:n6(y.x/a.width),y:n6(y.y/a.height),width:n6(y.width/a.width),height:n6(y.height/a.height)},differentPixels:n.differentPixels,shareOfDiffPercentage:n6(n.differentPixels/a.differentPixels),densityPercentage:N,shape:k,size:D,location:E,averageBaselineColorHex:n5(v),averageCurrentColorHex:n5(I),baselineLuminance:S,currentLuminance:_,dominantChange:M}}):[];if(v>0&&u){var A,x,N;for(let e of I)e.rect.width<4||e.rect.height<4||function(e,t){let n=nO(t.x,0,e.width-1),r=nO(t.y,0,e.height-1),a=nO(t.x+t.width-1,0,e.width-1),i=nO(t.y+t.height-1,0,e.height-1);for(let t=0;t<2;t+=1){for(let o=n;o<=a;o+=1)nE(e,o,r+t,nM),nE(e,o,i-t,nM);for(let o=r;o<=i;o+=1)nE(e,n+t,o,nM),nE(e,a-t,o,nM)}}(y,e.rect);await i.mkdir(o.dirname(u),{recursive:!0}),await i.writeFile(u,h.sync.write(y))}else await rn(n.outputPath);let S=v>0?await nq({baselinePath:e,currentPath:t,width:p.width,height:p.height}):void 0,_=S&&(S.matches.length>0||(S.movementClusters?.length??0)>0)?{provider:S.provider,baselineBlocks:S.baselineBlocks,currentBlocks:S.currentBlocks,matches:S.matches,...S.movementClusters?{movementClusters:S.movementClusters}:{}}:void 0,k=v>0&&S?(a=function(e){let t=[];for(let n of e.sort((e,t)=>e.minY-t.minY||e.minX-t.minX)){let e=t.find(e=>{var t,r,a;return t=e,r=n,a=10,t.minX-a<=r.maxX&&r.minX-a<=t.maxX&&t.minY-a<=r.maxY&&r.minY-a<=t.maxY});if(!e){t.push({...n});continue}e.minX=Math.min(e.minX,n.minX),e.minY=Math.min(e.minY,n.minY),e.maxX=Math.max(e.maxX,n.maxX),e.maxY=Math.max(e.maxY,n.maxY),e.differentPixels+=n.differentPixels}return t}(function(e,t,n){let r=new Uint8Array(e.length),a=new Int32Array(e.length),i=[];for(let o=0;o<e.length;o+=1){if(1!==e[o]||1===r[o])continue;let s=0,l=0;a[0]=o,l+=1,r[o]=1;let u=o%t,d=Math.floor(o/t),c={minX:u,minY:d,maxX:u,maxY:d,differentPixels:0};for(;s<l;){let i=a[s];s+=1;let o=i%t,u=Math.floor(i/t);c.minX=Math.min(c.minX,o),c.minY=Math.min(c.minY,u),c.maxX=Math.max(c.maxX,o),c.maxY=Math.max(c.maxY,u),c.differentPixels+=1;for(let i=-1;i<=1;i+=1){let s=u+i;if(!(s<0)&&!(s>=n))for(let n=-1;n<=1;n+=1){if(0===n&&0===i)continue;let u=o+n;if(u<0||u>=t)continue;let d=s*t+u;1===e[d]&&1!==r[d]&&(r[d]=1,a[l]=d,l+=1)}}}i.push(c)}return i}(function(e,t,n,r){let a=new Uint8Array(e);if(!r)return a;for(let e of[...r.baselineBlocksRaw,...r.currentBlocksRaw]){var i;!function(e,t,n,r){let a=nj(Math.floor(r.x),0,t-1),i=nj(Math.floor(r.y),0,n-1),o=nj(Math.ceil(r.x+r.width),0,t),s=nj(Math.ceil(r.y+r.height),0,n);for(let n=i;n<s;n+=1)for(let r=a;r<o;r+=1)e[n*t+r]=0}(a,t,n,{x:(i=e.rect).x-8,y:i.y-8,width:i.width+16,height:i.height+16})}return a}((N={diffMask:b,width:p.width,height:p.height,regions:I,ocr:S}).diffMask,N.width,N.height,N.ocr),N.width,N.height)),s=n$(N.ocr?.currentBlocksRaw??[]),l=n$(N.ocr?.baselineBlocksRaw??[]),a.filter(nU).map(e=>{var t,n,r,a,i,o,u,d,c,p,f;let h,m,w,g,y,b,v,I,A,x;return t=e,n=N,r=s,a=l,g=function(e,t){let n,r=0;for(let a of t){let t=function(e,t){let n=Math.max(e.x,t.x),r=Math.max(e.y,t.y),a=Math.min(e.x+e.width,t.x+t.width),i=Math.min(e.y+e.height,t.y+t.height);return a<=n||i<=r?0:(a-n)*(i-r)}(e,a.rect);t<=r||(r=t,n=a)}return n?.index}(w=nG(t),n.regions),y=function(e,t,n){let r=nT(e,t);if(r)return nF(e,r.blocks);let a=nT(e,n);return a?nF(e,a.blocks):void 0}(w,r,a),b=function(e,t,n){if(e.height<=3&&e.width>=.12*n)return"separator";if(!t)return e.width>=.4*n?"background":"unknown";if(e.width>=.4*n)return"background";let r=e.x+e.width/2,a=t.x+t.width/2;return r<a-t.width/2?"leading":r>a+t.width/2?"trailing":e.width>=.35*n?"background":"unknown"}(w,y?.block.rect,n.width),v=(i=w,o=b,u=t.differentPixels,d=n,h=i.width/i.height,m=u/(i.width*i.height),"separator"===o?"separator":"background"===o?"background":"trailing"===o&&h>=1.5&&h<=3.8&&m>=.35?"toggle":"trailing"===o&&i.width<=.06*d.width&&i.height<=.04*d.height?"chevron":"leading"===o&&h>=.55&&h<=1.8?"icon":nP(i,d)?"background":"visual"),I={...g?{regionIndex:g}:{},slot:b,likelyKind:v,rect:w},{...g?{regionIndex:g}:{},slot:b,likelyKind:v,rect:w,...y?{nearestText:y.block.text.trim().replace(/^[^\p{L}\p{N}]+/u,"").replace(/^\p{L}\s+/u,"")}:{},score:(c=I,p=t.differentPixels,f=n,A=nP(c.rect,f)?-35:0,x=20*!!c.regionIndex,nC[c.likelyKind]+nR[c.slot]+x+A+Math.min(20,p/200))}}).filter(e=>e.rect.y>=.08*N.height).filter(nL).sort((e,t)=>t.score-e.score).slice(0,Math.max(0,N.maxDeltas??12)).map((e,t)=>{var n;return n=e,{index:t+1,...n.regionIndex?{regionIndex:n.regionIndex}:{},slot:n.slot,likelyKind:n.likelyKind,rect:n.rect,...n.nearestText?{nearestText:n.nearestText}:{}}})):[],D=w>0?Math.round(v/w*1e4)/100:0;return{...v>0&&u?{diffPath:u}:{},...I.length>0?{regions:I}:{},..._?{ocr:_}:{},...k.length>0?{nonTextDeltas:k}:{},totalPixels:w,differentPixels:v,mismatchPercentage:D,match:0===v}}async function re(e,t){try{await i.access(e)}catch{throw new _("INVALID_ARGS",`${t}: ${e}`)}}function rt(e,t,n,r){if(null==r||r<=0)return;let a=e*t;if(!(a<=r))throw new _("INVALID_ARGS",`${n} is ${a} pixels, which exceeds the configured maxImagePixels limit of ${r}`)}async function rn(e){if(e)try{await i.unlink(e)}catch(e){var t;if(!("object"==typeof(t=e)&&null!==t&&"code"in t&&"ENOENT"===t.code))throw e}}function rr(e,t){return ra(Math.round(.299*e.data[t]+.587*e.data[t+1]+.114*e.data[t+2]),255,.72)}function ra(e,t,n){return Math.round(e*(1-n)+t*n)}function ri(e){return e.width*e.height}function ro(e){return Math.round(100*e*100)/100}let rs=async(e,t)=>{let n,r,a;if(!t.baseline)throw new _("INVALID_ARGS","diff screenshot requires a baseline image");let i=function(e){if(null==e||""===e)return .1;let t=Number(e);if(Number.isNaN(t)||t<0||t>1)throw new _("INVALID_ARGS","--threshold must be a number between 0 and 1");return t}(t.threshold),o=t.current??{kind:"live"};if(t.overlayRefs&&!rh(o))throw new _("INVALID_ARGS","diff screenshot <current.png> cannot use --overlay-refs because saved-image comparisons have no live accessibility refs");let s=await nN(e,t.baseline,{usage:"diff screenshot baseline",field:"baseline"}),l=[];try{let u;u=rh(o)?(r=await rl(e,t)).path:(n=await nN(e,o,{usage:"diff screenshot current",field:"current"})).path,a=t.out?await nS(e,t.out,{field:"diffPath",ext:".png"}):void 0;let d=await n7(s.path,u,{threshold:i,outputPath:a?.path,maxPixels:e.policy.maxImagePixels});rh(o)&&(d=await ru(e,t,a?.path,d,l));let c=d.diffPath?await a?.publish():void 0;return c&&l.push(c),d.diffPath||await a?.cleanup?.(),{...d,...l.length>0?{artifacts:l}:{}}}catch(e){throw await a?.cleanup?.(),e}finally{await s.cleanup?.(),await n?.cleanup?.(),await r?.cleanup?.()}};async function rl(e,t){let n=await n_(e,{prefix:"agent-device-diff-current",ext:".png"});try{await rd(e,t,n.path,rc(t))}catch(e){throw await n.cleanup(),e}return n}async function ru(e,t,n,r,a){var i,o,s,l;if(!t.overlayRefs)return r;if(r.match||r.dimensionMismatch)return n&&await rf(n),r;let u=(i=t,o=n,i.currentOverlayOut?i.currentOverlayOut:i.out?.kind==="path"?{kind:"path",path:rp(o??i.out.path)}:i.out?.kind==="downloadableArtifact"?{kind:"downloadableArtifact",...i.out.clientPath?{clientPath:rp(i.out.clientPath)}:{},...i.out.fileName?{fileName:rp(i.out.fileName)}:{}}:void 0),d=await nS(e,u,{field:"currentOverlayPath",ext:".png"});try{let n=await rd(e,t,d.path,{overlayRefs:!0,...rc(t)}),i=await d.publish();return i&&a.push(i),{...r,currentOverlayPath:n.path??d.path,...n.overlayRefs?{currentOverlayRefCount:n.overlayRefs.length}:{},...r.regions&&n.overlayRefs?{regions:(s=r.regions,l=n.overlayRefs,s.map(e=>{var t,n;let r,a=(t=e,n=l,r=ri(t.rect),n.map(e=>{var n,a;let i,o,s,l,u=e.overlayRect,d=(n=t.rect,a=u,i=Math.max(n.x,a.x),o=Math.max(n.y,a.y),s=Math.min(n.x+n.width,a.x+a.width),l=Math.min(n.y+n.height,a.y+a.height),s<=i||l<=o?0:(s-i)*(l-o));return d<=0?null:{ref:e.ref,...e.label?{label:e.label}:{},rect:u,overlayCoveragePercentage:ro(d/ri(u)),regionCoveragePercentage:ro(d/r)}}).filter(e=>null!==e).sort((e,t)=>{let n=t.regionCoveragePercentage-e.regionCoveragePercentage;return 0!==n?n:t.overlayCoveragePercentage-e.overlayCoveragePercentage}).slice(0,3).map(e=>({ref:e.ref,...e.label?{label:e.label}:{},rect:e.rect,regionCoveragePercentage:e.regionCoveragePercentage})));return a.length>0?{...e,currentOverlayMatches:a}:e}))}:{}}}catch(e){throw await d.cleanup?.(),e}}async function rd(e,t,n,r={}){if(!e.backend.captureScreenshot)throw new _("UNSUPPORTED_OPERATION","screenshot is not supported by this backend");return await e.backend.captureScreenshot({session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata},n,r)??{}}function rc(e){return e.surface?{surface:e.surface}:{}}function rp(e){let t=o.extname(e),n=t?e.slice(0,-t.length):e;return`${n}.current-overlay${t||".png"}`}async function rf(e){try{await i.unlink(rp(e))}catch(e){var t;if(!("object"==typeof(t=e)&&null!==t&&"code"in t&&"ENOENT"===t.code))throw e}}function rh(e){return"live"===e.kind}function rm(e,t){let n=Q(e.type??"Element"),r=Z(e,n),a=!1===e.enabled?"disabled":"enabled",i=!0===e.selected?"selected":"unselected",o=!0===e.hittable?"hittable":"not-hittable";return[String(t??e.depth??0),n,r,a,i,o].join("|")}function rw(e,t){return t.flatten?e.map(e=>({text:K(e,0,!1),comparable:rm(e,0)})):J(e).map(e=>({text:e.text,comparable:rm(e.node,e.depth)}))}function rg(e,t){return e.get(t)??0}function ry(e){return"text"===e||"label"===e||"any"===e}function rb(e,t){return{session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata}}function rv(e){return e.clock?.now()??Date.now()}async function rI(e,t){e.clock?await e.clock.sleep(t):await new Promise(e=>setTimeout(e,t))}let rA=async(e,t)=>{var n;let r,a,i=await rN(e,t);return await e.sessions.set(rS(t.session,i)),{nodes:i.snapshot.nodes,truncated:i.snapshot.truncated??!1,visibility:function(e){var t;let{nodes:n,backend:r,snapshotRaw:a}=e;if(a||"macos-helper"===(t=r)||"linux-atspi"===t)return{partial:!1,visibleNodeCount:n.length,totalNodeCount:n.length,reasons:[]};let i=ef(n),o=new Set;return i.hiddenCount>0&&o.add("offscreen-nodes"),i.nodes.some(e=>e.hiddenContentAbove)&&o.add("scroll-hidden-above"),i.nodes.some(e=>e.hiddenContentBelow)&&o.add("scroll-hidden-below"),{partial:o.size>0,visibleNodeCount:i.nodes.length,totalNodeCount:n.length,reasons:[...o]}}({nodes:i.snapshot.nodes,backend:i.snapshot.backend,snapshotRaw:t.raw}),...i.warnings.length>0?{warnings:i.warnings}:{},...(r=(n=i).result.appName??n.session?.appName,a=n.result.appBundleId??n.session?.appBundleId,{...r||a?{appName:r??a}:{},...a?{appBundleId:a}:{}})}},rx=async(e,t)=>{let n=await rN(e,t),r=!0===t.interactiveOnly,a=n.session?.snapshot,i=rS(t.session,n);if(!a){let t=function(e,t={}){return rw(e,t).length}(n.snapshot.nodes,{flatten:r});return await e.sessions.set(i),{mode:"snapshot",baselineInitialized:!0,summary:{additions:0,removals:0,unchanged:t},lines:[],...n.warnings.length>0?{warnings:n.warnings}:{}}}let o=function(e,t,n={}){let r=function(e,t){let n=e.length,r=t.length,a=n+r,i=new Map,o=[];i.set(1,0);for(let s=0;s<=a;s+=1){o.push(new Map(i));for(let a=-s;a<=s;a+=2){let l=a===-s||a!==s&&rg(i,a-1)<rg(i,a+1)?rg(i,a+1):rg(i,a-1)+1,u=l-a;for(;l<n&&u<r&&e[l].comparable===t[u].comparable;)l+=1,u+=1;if(i.set(a,l),l>=n&&u>=r)return function(e,t,n,r,a){let i=[],o=r,s=a;for(let r=e.length-1;r>=0;r-=1){let a=e[r],l=o-s,u=l===-r||l!==r&&rg(a,l-1)<rg(a,l+1)?l+1:l-1,d=rg(a,u),c=d-u;for(;o>d&&s>c;)i.push({kind:"unchanged",text:n[s-1].text}),o-=1,s-=1;if(0===r)break;o===d?(i.push({kind:"added",text:n[c].text}),s=c):(i.push({kind:"removed",text:t[d].text}),o=d)}return i.reverse(),i}(o,e,t,n,r)}}return[]}(rw(e,n),rw(t,n)),a={additions:0,removals:0,unchanged:0};for(let e of r)"added"===e.kind&&(a.additions+=1),"removed"===e.kind&&(a.removals+=1),"unchanged"===e.kind&&(a.unchanged+=1);return{summary:a,lines:r}}(a.nodes,n.snapshot.nodes,{flatten:r});return await e.sessions.set(i),{mode:"snapshot",baselineInitialized:!1,summary:o.summary,lines:o.lines,...n.warnings.length>0?{warnings:n.warnings}:{}}};async function rN(e,t){var n,r,a,i,o;let s,l,u,d,c,p;if(!e.backend.captureSnapshot)throw new _("UNSUPPORTED_OPERATION","snapshot is not supported by this backend");let f=t.session??"default",h=await e.sessions.get(f),m=await e.backend.captureSnapshot({session:f,requestId:t.requestId,appId:h?.appId,appBundleId:h?.appBundleId,signal:t.signal??e.signal,metadata:t.metadata},{interactiveOnly:t.interactiveOnly,compact:t.compact,depth:t.depth,scope:t.scope,raw:t.raw}),w=(n=m,r=e,n.snapshot?n.snapshot:{nodes:n.nodes??[],truncated:n.truncated,backend:n.backend,createdAt:rv(r)}),g=rv(e);return{snapshot:w,result:m,session:h,warnings:(s=[...(a={result:m,snapshot:w,options:t,session:h,capturedAt:w.createdAt??g,runtimeNow:g}).result.warnings??[]],l=!0===a.options.interactiveOnly,u=a.result.analysis,"android"===a.snapshot.backend&&l&&0===a.snapshot.nodes.length&&u&&(u.rawNodeCount??0)>=12&&(s.push(`Interactive snapshot is empty after filtering ${u.rawNodeCount} raw Android nodes. Likely causes: depth too low, transient route change, or collector filtering.`),"number"==typeof a.options.depth&&"number"==typeof u.maxDepth&&u.maxDepth>=a.options.depth+2&&s.push(`Interactive output is empty at depth ${a.options.depth}; retry without -d.`)),c=!!(d=a.session?.snapshot)&&[a.capturedAt,a.runtimeNow].some(e=>{let t=e-d.createdAt;return t>=0&&t<=2e3}),!a.result.freshness&&d&&c&&(i=d.nodes.length,o=a.snapshot.nodes.length,!(i<12)&&o<=Math.floor(.2*i))&&s.push("Recent snapshots dropped sharply in node count, which suggests stale or mid-transition UI. Use screenshot as visual truth, wait briefly, then re-snapshot once."),p=a.result.freshness,p?.staleAfterRetries&&"android"===a.snapshot.backend&&("stuck-route"===p.reason?s.push(`Recent ${p.action} was followed by a nearly identical snapshot after ${p.retryCount} automatic retr${1===p.retryCount?"y":"ies"}. If you expected navigation or submit, the tree may still be stale. Use screenshot as visual truth, wait briefly, then re-snapshot once.`):"sharp-drop"===p.reason&&s.push("Recent snapshots dropped sharply in node count, which suggests stale or mid-transition UI. Use screenshot as visual truth, wait briefly, then re-snapshot once.")),Array.from(new Set(s)))}}function rS(e,t){let n=t.session?.name??e??"default";return{...t.session??{name:n},name:n,snapshot:t.snapshot,appName:t.result.appName??t.session?.appName,appBundleId:t.result.appBundleId??t.session?.appBundleId}}function r_(e){return["visible","hidden","exists","editable","selected","text"].includes(e)}function rk(e){return!!(e&&Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.width)&&Number.isFinite(e.height)&&e.width>0&&e.height>0)}async function rD(e,t){let n=t??"default",r=await e.sessions.get(n);if(!r)throw new _("SESSION_NOT_FOUND","No active session. Run open first.");if(!r.snapshot)throw new _("INVALID_ARGS","No snapshot in session. Run snapshot first.");return{sessionName:n,session:r,snapshot:r.snapshot}}async function rM(e,t,n={updateSession:!0}){if(!e.backend.captureSnapshot)throw new _("UNSUPPORTED_OPERATION","snapshot is not supported by this backend");let r=t.session??"default",a=await e.sessions.get(r),i=await e.backend.captureSnapshot(rb(e,t),{interactiveOnly:!1,compact:!1,depth:t.depth,scope:n.scope??t.scope,raw:t.raw}),o=i.snapshot??{nodes:i.nodes??[],truncated:i.truncated,backend:i.backend,createdAt:rv(e)};return n.updateSession&&a&&await e.sessions.set({...a,snapshot:o}),{sessionName:r,session:a,snapshot:o}}async function rE(e,t,n){if(e.backend.readText){let r=await e.backend.readText(rb(e,{session:t.sessionName}),n);if(r.text.trim())return r.text}return X(n)}let rO=async(e,t)=>{let n=t.locator??"any";if(!t.query)throw new _("INVALID_ARGS","find requires a value");if("wait"===t.action)return await rG(e,t,n);let r=await rM(e,t,{updateSession:!0,scope:ry(n)?t.query:void 0}),a=tp(r.snapshot.nodes,n,t.query,{requireRect:!1}).matches[0];if(!a)throw new _("COMMAND_FAILED","find did not match any element");if("exists"===t.action)return{kind:"found",found:!0};let i=`@${a.ref}`;return"get_attrs"===t.action?{kind:"attrs",ref:i,node:a}:{kind:"text",ref:i,text:await rE(e,r,a),node:a}},rC=async(e,t)=>{if("ref"===t.target.kind){let n=await rD(e,t.session),r=function(e,t,n){let r=ei(t);if(!r)throw new _("INVALID_ARGS",n.invalidRefMessage);let a=eo(e,r)??(n.fallbackLabel.length>0?tn(e,n.fallbackLabel):null);if(!a)throw new _("COMMAND_FAILED",n.notFoundMessage);return{ref:r,node:a}}(n.snapshot.nodes,t.target.ref,{fallbackLabel:t.target.fallbackLabel??"",invalidRefMessage:"get text requires a ref like @e2",notFoundMessage:`Ref ${t.target.ref} not found`}),a=tA(r.node,e.backend.platform,{action:"get"}),i={kind:"ref",ref:`@${r.ref}`};return"attrs"===t.property?{kind:"attrs",target:i,node:r.node,selectorChain:a}:{kind:"text",target:i,text:await rE(e,n,r.node),node:r.node,selectorChain:a}}let n=await rq(e,t,t.session??"default",{selector:t.target.selector,disambiguateAmbiguous:"text"===t.property}),r=tA(n.node,e.backend.platform,{action:"get"});if("attrs"===t.property)return{kind:"attrs",target:{kind:"selector",selector:n.selector},node:n.node,selectorChain:r};let a=await rE(e,n.capture,n.node);return{kind:"text",target:{kind:"selector",selector:n.selector},text:a,node:n.node,selectorChain:r}},rR=async(e,t)=>{let n=await rC(e,{...t,property:"text",target:t.target});if("text"!==n.kind)throw new _("COMMAND_FAILED","getText returned non-text result");return n},rL=async(e,t)=>{let n=await rC(e,{...t,property:"attrs",target:t.target});if("attrs"!==n.kind)throw new _("COMMAND_FAILED","getAttrs returned non-attrs result");return n},rP=async(e,t)=>{if(!r_(t.predicate))throw new _("INVALID_ARGS","is requires predicate: visible|hidden|exists|editable|selected|text");if("text"===t.predicate&&!t.expectedText)throw new _("INVALID_ARGS","is text requires expected text value");let n=await rM(e,t,{updateSession:!0}),r=e4(t.selector);if("exists"===t.predicate){let a=tb(n.snapshot.nodes,r,{platform:e.backend.platform});if(!a)throw new _("COMMAND_FAILED",tv(r,[],{unique:!1}));return{predicate:t.predicate,pass:!0,selector:a.selector.raw,matches:a.matches,selectorChain:r.selectors.map(e=>e.raw)}}let a=ty(n.snapshot.nodes,r,{platform:e.backend.platform,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:!1});if(!a)throw new _("COMMAND_FAILED",tv(r,[],{unique:!0}));let i=function(e){let{predicate:t,node:n,nodes:r,expectedText:a,platform:i}=e,o=tu(n),s=tc(n,i),l=!0===n.selected,u="text"===t?td(n):function(e,t){if(!0===e.hittable)return!0;if(rk(e.rect))return eh(e,t);if(e.rect)return!1;let n=function(e,t){let n=new Map(t.map(e=>[e.index,e])),r=e,a=new Set;for(;"number"==typeof r.parentIndex&&!a.has(r.index);){a.add(r.index);let e=n.get(r.parentIndex);if(!e)break;if(function(e){let t=to(e.type??"");return!(t.includes("application")||t.includes("window")||t.includes("scrollview")||t.includes("tableview")||t.includes("collectionview"))&&"table"!==t&&"list"!==t&&"listview"!==t&&(!0===e.hittable||rk(e.rect))}(e))return e;r=e}return null}(e,t);return!!n&&(!0===n.hittable||!!rk(n.rect)&&eh(n,t))}(n,r),d=!1;switch(t){case"visible":d=u;break;case"hidden":d=!u;break;case"editable":d=s;break;case"selected":d=l;break;case"text":d=o===(a??"")}let c="text"===t?`expected="${a??""}" actual="${o}"`:`actual=${JSON.stringify({visible:u,editable:s,selected:l})}`;return{pass:d,actualText:o,details:c}}({predicate:t.predicate,node:a.node,nodes:n.snapshot.nodes,expectedText:t.expectedText,platform:e.backend.platform});if(!i.pass)throw new _("COMMAND_FAILED",`is ${t.predicate} failed for selector ${a.selector.raw}: ${i.details}`);return{predicate:t.predicate,pass:!0,selector:a.selector.raw,..."text"===t.predicate?{text:i.actualText}:{},selectorChain:r.selectors.map(e=>e.raw)}},rT=async(e,t)=>await rP(e,{...t,predicate:"visible",selector:t.target.selector}),r$=async(e,t)=>await rP(e,{...t,predicate:"hidden",selector:t.target.selector}),rF=async(e,t)=>{if("sleep"===t.target.kind)return await rI(e,t.target.durationMs),{kind:"sleep",waitedMs:t.target.durationMs};if("ref"===t.target.kind){let n=await rD(e,t.session),r=ei(t.target.ref);if(!r)throw new _("INVALID_ARGS",`Invalid ref: ${t.target.ref}`);let a=eo(n.snapshot.nodes,r),i=a?tr(a,n.snapshot.nodes):void 0;if(!i)throw new _("COMMAND_FAILED",`Ref ${t.target.ref} not found or has no label`);return await rB(e,t,i,t.target.timeoutMs)}if("selector"===t.target.kind)return await rV(e,t,t.target.selector,t.target.timeoutMs);if(!t.target.text)throw new _("INVALID_ARGS","wait requires text");return await rB(e,t,t.target.text,t.target.timeoutMs)},rU=async(e,t)=>{let n=await rF(e,{...t,target:{kind:"text",text:t.text,timeoutMs:t.timeoutMs}});if("text"!==n.kind)throw new _("COMMAND_FAILED","waitForText returned non-text result");return n};async function rG(e,t,n){let r=t.timeoutMs??1e4,a=rv(e);for(;rv(e)-a<r;){if(tp((await rM(e,t,{updateSession:!0,scope:ry(n)?t.query:void 0})).snapshot.nodes,n,t.query,{requireRect:!1}).matches[0])return{kind:"found",found:!0,waitedMs:rv(e)-a};await rI(e,300)}throw new _("COMMAND_FAILED","find wait timed out")}async function rV(e,t,n,r){let a=r??1e4,i=rv(e),o=e4(n);for(;rv(e)-i<a;){let n=tb((await rM(e,t,{updateSession:!0})).snapshot.nodes,o,{platform:e.backend.platform});if(n)return{kind:"selector",selector:n.selector.raw,waitedMs:rv(e)-i};await rI(e,300)}throw new _("COMMAND_FAILED",`wait timed out for selector: ${n}`)}async function rB(e,t,n,r){let a=r??1e4,i=rv(e);for(;rv(e)-i<a;){if(e.backend.findText?(await e.backend.findText(rb(e,t),n)).found:await rj(e,t,n))return{kind:"text",text:n,waitedMs:rv(e)-i};await rI(e,300)}throw new _("COMMAND_FAILED",`wait timed out for text: ${n}`)}async function rj(e,t,n){return!!tn((await rM(e,t,{updateSession:!0})).snapshot.nodes,n)}async function rq(e,t,n,r){let a=await rM(e,{...t,session:n},{updateSession:!0}),i=e4(r.selector),o=ty(a.snapshot.nodes,i,{platform:e.backend.platform,requireRect:!1,requireUnique:!0,disambiguateAmbiguous:r.disambiguateAmbiguous});if(!o)throw new _("COMMAND_FAILED",tv(i,[],{unique:!0}));return{capture:a,node:o.node,selector:o.selector.raw,ref:`@${o.node.ref}`}}function rW(e,t,n,r){if(!Number.isFinite(e)||!Number.isInteger(e)||e<n||e>r)throw new _("INVALID_ARGS",`${t} must be an integer between ${n} and ${r}`);return e}function rz(e,t){let n=function(e,t){let n=rH(t.rect);if(!n)return null;let r=t,a=new Set;for(;!a.has(r.ref);){a.add(r.ref);let t=e.filter(e=>{if(e.parentIndex!==r.index||!e.hittable)return!1;let t=rH(e.rect);return!!t&&rY(t,n)});if(1!==t.length)break;r=t[0]}return r===t?null:r}(e,t);if(n?.rect&&rX(n.rect))return n;let r=tl(e,t);return r?.rect&&rX(r.rect)?!function(e,t,n){var r,a,i,o;let s,l,u,d=rH(e.rect),c=rH(t.rect);if(!d||!c)return!1;let p=function(e,t){let n=es(t),r=e.filter(e=>{let t=(e.type??"").toLowerCase();return t.includes("application")||t.includes("window")}).map(e=>rH(e.rect)).filter(e=>null!==e);if(0===r.length)return null;let a=r.filter(e=>el(e,n.x,n.y));return eu(a.length>0?a:r)}(n,d);return!!p&&(r=c,a=p,s=(i=r,o=a,Math.max(0,Math.min(i.x+i.width,o.x+o.width)-Math.max(i.x,o.x))*Math.max(0,Math.min(i.y+i.height,o.y+o.height)-Math.max(i.y,o.y))),l=r.width*r.height,u=a.width*a.height,!(s<=0)&&!(l<=0)&&!(u<=0)&&!!(s/u>=.9)&&!!(s/l>=.8))&&!rY(d,c)}(t,r,e)?r:t:t}function rX(e){let t=rH(e);if(!t)return null;let n=es(t);return Number.isFinite(n.x)&&Number.isFinite(n.y)?n:null}function rH(e){if(!e)return null;let t=Number(e.x),n=Number(e.y),r=Number(e.width),a=Number(e.height);return Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a)&&!(r<0)&&!(a<0)?{x:t,y:n,width:r,height:a}:null}function rY(e,t){return .5>=Math.abs(e.x-t.x)&&.5>=Math.abs(e.y-t.y)&&.5>=Math.abs(e.width-t.width)&&.5>=Math.abs(e.height-t.height)}async function rJ(e,t,n){if(await rZ(e,t,n.action),"point"===t.target.kind)return{kind:"point",point:{x:t.target.x,y:t.target.y}};if("ref"===t.target.kind){let r=await r0(e,t,t.target),a=r.resolved,i=n.promoteToHittableAncestor?rz(r.snapshot.nodes,a.node):a.node;return function(e,t,n,r){let a=e.rect?em(e,t):null;if(!(!e.rect||!a||eh(e,t)))throw new _("COMMAND_FAILED",`Ref ${n} is off-screen and not safe to ${r}`,{reason:"offscreen_ref",ref:ei(n),rect:e.rect,viewport:a,hint:`Use scroll with the direction from the off-screen summary, take a fresh snapshot, then retry ${r} with the new ref or a selector.`})}(i,r.snapshot.nodes,t.target.ref,n.action),{kind:"ref",point:r2(i,`Ref ${t.target.ref} not found or has invalid bounds`),target:{kind:"ref",ref:`@${a.ref}`},node:i,selectorChain:tA(i,e.backend.platform,{action:"fill"===n.action?"fill":"click"}),refLabel:tr(i,r.snapshot.nodes)}}let r=await rK(e,t,n.requireInteractive),a=e4(t.target.selector),i=ty(r.snapshot.nodes,a,{platform:e.backend.platform,requireRect:!0,requireUnique:!0,disambiguateAmbiguous:!0});if(!i||!i.node.rect)throw new _("COMMAND_FAILED",tv(a,i?.diagnostics??[],{unique:!0}));let o=n.promoteToHittableAncestor?rz(r.snapshot.nodes,i.node):i.node;return{kind:"selector",point:r2(o,`Selector ${i.selector.raw} resolved to invalid bounds`),target:{kind:"selector",selector:i.selector.raw},node:o,selectorChain:tA(o,e.backend.platform,{action:"fill"===n.action?"fill":"click"}),refLabel:tr(o,r.snapshot.nodes)}}async function rK(e,t,n){if(!e.backend.captureSnapshot)throw new _("UNSUPPORTED_OPERATION","snapshot is not supported by this backend");let r=t.session??"default",a=await e.sessions.get(r);if(!a)throw new _("SESSION_NOT_FOUND","No active session. Run open first.");let i=await e.backend.captureSnapshot(rb(e,t),{interactiveOnly:n,compact:n}),o=i.snapshot??{nodes:i.nodes??[],truncated:i.truncated,backend:i.backend,createdAt:rv(e)};return await e.sessions.set({...a,snapshot:o}),{snapshot:o}}async function rZ(e,t,n){if("macos"!==e.backend.platform)return;let r=await rQ(e,t);if(("desktop"===r||"menubar"===r)&&("menubar"!==r||"click"!==n&&"press"!==n))throw new _("UNSUPPORTED_OPERATION",`${n} is not supported on macOS ${r} sessions yet. Open an app session to act, or use the ${r} surface to inspect.`)}async function rQ(e,t){let n=await e.sessions.get(t.session??"default");return n?.metadata?.surface}async function r0(e,t,n){let r=t.session??"default",a=await e.sessions.get(r);if(!a)throw new _("SESSION_NOT_FOUND","No active session. Run open first.");if(!a.snapshot)throw new _("INVALID_ARGS","No snapshot in session. Run snapshot first.");let i=n.fallbackLabel??"",o=r1(a.snapshot.nodes,n.ref,{fallbackLabel:i,requireRect:!0});if(o)return{snapshot:a.snapshot,resolved:o};let s=await rK(e,t,!0),l=r1(s.snapshot.nodes,n.ref,{fallbackLabel:i,requireRect:!0});if(!l)throw new _("COMMAND_FAILED",`Ref ${n.ref} not found or has no bounds`);return{...s,resolved:l}}function r1(e,t,n){let r=ei(t);if(!r)throw new _("INVALID_ARGS",`Invalid ref: ${t}`);let a=eo(e,r);if(r3(a,n.requireRect))return{ref:r,node:a};let i=n.fallbackLabel.length>0?tn(e,n.fallbackLabel):null;return r3(i,n.requireRect)?{ref:r,node:i}:null}function r2(e,t){if(!e.rect)throw new _("COMMAND_FAILED",t);let n=es(e.rect);if(!Number.isFinite(n.x)||!Number.isFinite(n.y))throw new _("COMMAND_FAILED",t);return n}function r3(e,t){if(!e)return!1;if(!t)return!0;if(!e.rect)return!1;let{x:n,y:r,width:a,height:i}=e.rect;if(!Number.isFinite(Number(n))||!Number.isFinite(Number(r))||!Number.isFinite(Number(a))||!Number.isFinite(Number(i))||0>Number(a)||0>Number(i))return!1;let o=es(e.rect);return Number.isFinite(o.x)&&Number.isFinite(o.y)}let r4=async(e,t)=>{let n=await rJ(e,t,{action:"focus",requireInteractive:!0,promoteToHittableAncestor:!1});if(!e.backend.focus)throw new _("UNSUPPORTED_OPERATION","focus is not supported by this backend");let r=ai(await e.backend.focus(rb(e,t),n.point));return{...n,...r?{backendResult:r}:{},...tS(`Focused (${n.point.x}, ${n.point.y})`)}},r5=async(e,t)=>{let n=await rJ(e,t,{action:"longPress",requireInteractive:!0,promoteToHittableAncestor:!0});if(!e.backend.longPress)throw new _("UNSUPPORTED_OPERATION","longPress is not supported by this backend");let r=void 0===t.durationMs?void 0:rW(t.durationMs,"durationMs",0,12e4),a=ai(await e.backend.longPress(rb(e,t),n.point,{durationMs:r}));return{...n,...void 0!==r?{durationMs:r}:{},...a?{backendResult:a}:{},...tS(`Long pressed (${n.point.x}, ${n.point.y})`)}},r8=async(e,t)=>{var n,r;if(!e.backend.scroll)throw new _("UNSUPPORTED_OPERATION","scroll is not supported by this backend");let a=at(t.direction,"scroll direction"),i=(n=t.amount,r="scroll amount",void 0===n?void 0:ar(n,r)),o=function(e,t){if(void 0!==e){if(!Number.isFinite(e)||!Number.isInteger(e)||e<=0)throw new _("INVALID_ARGS",`${t} must be a positive integer`);return e}}(t.pixels,"scroll pixels");if(void 0!==i&&void 0!==o)throw new _("INVALID_ARGS","scroll accepts either amount or pixels, not both");let s=await r7(e,t),l="viewport"===s.kind?{kind:"viewport"}:{kind:"point",point:s.point},u=ai(await e.backend.scroll(rb(e,t),l,{direction:a,...void 0!==i?{amount:i}:{},...void 0!==o?{pixels:o}:{}}));return{...s,direction:a,...void 0!==i?{amount:i}:{},...void 0!==o?{pixels:o}:{},...u?{backendResult:u}:{},...tS(void 0!==o?`Scrolled ${a} by ${o}px`:void 0!==i?`Scrolled ${a} by ${i}`:`Scrolled ${a}`)}},r6=async(e,t)=>{if(!e.backend.swipe)throw new _("UNSUPPORTED_OPERATION","swipe is not supported by this backend");let n=await ae(e,t),r=function(e,t){if(t.to)return{point:an(t.to,"to")};let n=at(t.direction,"swipe direction"),r=ar(t.distance??200,"swipe distance");switch(n){case"up":return{point:{x:e.x,y:e.y-r},direction:n,distance:r};case"down":return{point:{x:e.x,y:e.y+r},direction:n,distance:r};case"left":return{point:{x:e.x-r,y:e.y},direction:n,distance:r};case"right":return{point:{x:e.x+r,y:e.y},direction:n,distance:r}}}(n.point,t),a=void 0===t.durationMs?void 0:rW(t.durationMs,"durationMs",16,1e4),i=ai(await e.backend.swipe(rb(e,t),n.point,r.point,{durationMs:a}));return{kind:"swipe",from:n.point,to:r.point,...r.direction?{direction:r.direction}:{},...void 0!==r.distance?{distance:r.distance}:{},...void 0!==a?{durationMs:a}:{},...n.target?{fromTarget:n.target}:{},...i?{backendResult:i}:{},...tS("Swiped")}},r9=async(e,t)=>{if(!e.backend.pinch)throw new _("UNSUPPORTED_OPERATION","pinch is not supported by this backend");await rZ(e,t,"pinch");let n=ar(t.scale,"pinch scale"),r=t.center?await rJ(e,{...t,target:t.center},{action:"pinch",requireInteractive:!1,promoteToHittableAncestor:!1}):void 0,a=ai(await e.backend.pinch(rb(e,t),{scale:n,...r?{center:r.point}:{}}));return{kind:"pinch",scale:n,...r?{center:r.point,centerTarget:r}:{},...a?{backendResult:a}:{},...tS(`Pinched to scale ${n}`)}};async function r7(e,t){let n=t.target??{kind:"viewport"};return"viewport"===n.kind?(await rZ(e,t,"scroll"),{kind:"viewport"}):await rJ(e,{...t,target:n},{action:"scroll",requireInteractive:!1,promoteToHittableAncestor:!1})}async function ae(e,t){if(t.from){var n;if("x"in(n=t.from)&&"y"in n)return await rZ(e,t,"swipe"),{point:an(t.from,"from")};let r=await rJ(e,{...t,target:t.from},{action:"swipe",requireInteractive:!1,promoteToHittableAncestor:!1});return{point:r.point,target:r}}if(!t.direction)throw new _("INVALID_ARGS","swipe requires from+to or a direction");return await rZ(e,t,"swipe"),{point:es(function(e){let t=e.filter(t=>eh(t,e)).map(e=>e.rect).filter(aa),n=t.length>0?t:e.map(e=>e.rect).filter(aa);if(0===n.length)throw new _("COMMAND_FAILED","Cannot infer viewport for directional swipe");let r=Math.min(...n.map(e=>e.x)),a=Math.min(...n.map(e=>e.y));return{x:r,y:a,width:Math.max(...n.map(e=>e.x+e.width))-r,height:Math.max(...n.map(e=>e.y+e.height))-a}}((await rK(e,t,!1)).snapshot.nodes)),target:{kind:"viewport"}}}function at(e,t){switch(e){case"up":case"down":case"left":case"right":return e;default:throw new _("INVALID_ARGS",`${t} must be up, down, left, or right`)}}function an(e,t){let n=Number(e.x),r=Number(e.y);if(!Number.isFinite(n)||!Number.isFinite(r))throw new _("INVALID_ARGS",`${t} point requires finite x and y`);return{x:n,y:r}}function ar(e,t){if(!Number.isFinite(e)||e<=0)throw new _("INVALID_ARGS",`${t} must be a positive number`);return e}function aa(e){return!!(e&&e.width>0&&e.height>0)}function ai(e){return e&&"object"==typeof e?e:void 0}let ao=async(e,t)=>await ad(e,t,"press"),as=async(e,t)=>await ad(e,t,"click"),al=async(e,t)=>{var n;if(!t.text)throw new _("INVALID_ARGS","fill requires text");let r=await rJ(e,t,{action:"fill",requireInteractive:!0,promoteToHittableAncestor:!1});if(!e.backend.fill)throw new _("UNSUPPORTED_OPERATION","fill is not supported by this backend");let a=ac(await e.backend.fill(rb(e,t),r.point,t.text,{delayMs:t.delayMs})),i="node"in r?r.node.type??"":"",o=i&&!ts(i,e.backend.platform)?`fill target ${n=r,n.target?.kind==="ref"?n.target.ref:n.target?.kind==="selector"?n.target.selector:"point"} resolved to "${i}", attempting fill anyway.`:void 0;return{...r,text:t.text,...o?{warning:o}:{},...a?{backendResult:a}:{}}},au=async(e,t)=>{let n=t.text;if(!n)throw new _("INVALID_ARGS","type requires text");let r=function(e){let t=e.trim().split(/\s+/,1)[0];if(!t||!t.startsWith("@")||t.length<3)return null;let n=t.slice(1);return/^[A-Za-z_-]*\d[\w-]*$/i.test(n)||/^(?:ref|node|element|el)[\w-]*$/i.test(n)?t:null}(n);if(r)throw new _("INVALID_ARGS",`type does not accept a target ref like "${r}"`,{hint:`Use fill ${r} "text" to target that field, or press ${r} then type "text" to append.`});if(!e.backend.typeText)throw new _("UNSUPPORTED_OPERATION","type is not supported by this backend");let a=rW(t.delayMs??0,"delay-ms",0,1e4),i=ac(await e.backend.typeText(rb(e,t),n,{delayMs:a}));return{kind:"text",text:n,delayMs:a,...i?{backendResult:i}:{},...tS(`Typed ${Array.from(n).length} chars`)}};async function ad(e,t,n){let r=await rJ(e,t,{action:n,requireInteractive:!0,promoteToHittableAncestor:!0});if(!e.backend.tap)throw new _("UNSUPPORTED_OPERATION","tap is not supported by this backend");let a=ac(await e.backend.tap(rb(e,t),r.point,{button:t.button,count:t.count,intervalMs:t.intervalMs,holdMs:t.holdMs,jitterPx:t.jitterPx,doubleTap:t.doubleTap}));return{...r,...a?{backendResult:a}:{}}}function ac(e){return e&&"object"==typeof e?e:void 0}let ap=async(e,t={})=>{if(!e.backend.pressBack)throw new _("UNSUPPORTED_OPERATION","system.back is not supported by this backend");let n=t.mode??"in-app";if("in-app"!==n&&"system"!==n)throw new _("INVALID_ARGS","system.back mode must be in-app or system");let r=aI(await e.backend.pressBack(rb(e,t),{mode:n}));return{kind:"systemBack",mode:n,...r?{backendResult:r}:{},...tS("Back")}},af=async(e,t={})=>{if(!e.backend.pressHome)throw new _("UNSUPPORTED_OPERATION","system.home is not supported by this backend");let n=aI(await e.backend.pressHome(rb(e,t)));return{kind:"systemHome",...n?{backendResult:n}:{},...tS("Home")}},ah=async(e,t)=>{if(!e.backend.rotate)throw new _("UNSUPPORTED_OPERATION","system.rotate is not supported by this backend");let n=function(e){switch(e){case"portrait":case"portrait-upside-down":case"landscape-left":case"landscape-right":return e;default:throw new _("INVALID_ARGS","system.rotate orientation must be portrait, portrait-upside-down, landscape-left, or landscape-right")}}(t.orientation),r=aI(await e.backend.rotate(rb(e,t),n));return{kind:"systemRotated",orientation:n,...r?{backendResult:r}:{},...tS(`Rotated to ${n}`)}},am=async(e,t={})=>{if(!e.backend.setKeyboard)throw new _("UNSUPPORTED_OPERATION","system.keyboard is not supported by this backend");let n=t.action??"status";if("status"!==n&&"get"!==n&&"dismiss"!==n)throw new _("INVALID_ARGS","system.keyboard action must be status, get, or dismiss");let r=await e.backend.setKeyboard(rb(e,t),{action:n}),a=aI(r);if("dismiss"===n){let e=av(r)?r.dismissed:void 0;return{kind:"keyboardDismissed",action:n,state:av(r)?r:{},...a?{backendResult:a}:{},...tS(!1===e?"Keyboard already hidden":"Keyboard dismissed")}}return{kind:"keyboardState",action:n,state:av(r)?r:{},...a?{backendResult:a}:{}}},aw=async(e,t)=>{if("read"===t.action){if(!e.backend.getClipboard)throw new _("UNSUPPORTED_OPERATION","system.clipboard read is not supported by this backend");let n=await e.backend.getClipboard(rb(e,t));return{kind:"clipboardText",action:"read",text:"string"==typeof n?n:n.text}}if("write"!==t.action)throw new _("INVALID_ARGS","system.clipboard action must be read or write");if(!e.backend.setClipboard)throw new _("UNSUPPORTED_OPERATION","system.clipboard write is not supported by this backend");if("string"!=typeof t.text)throw new _("INVALID_ARGS","system.clipboard write requires text");let n=aI(await e.backend.setClipboard(rb(e,t),t.text));return{kind:"clipboardUpdated",action:"write",textLength:Array.from(t.text).length,...n?{backendResult:n}:{},...tS("Clipboard updated")}},ag=async(e,t={})=>{if(!e.backend.openSettings)throw new _("UNSUPPORTED_OPERATION","system.settings is not supported by this backend");let n=function(e,t){if(void 0===e)return;let n=e.trim();if(!n)throw new _("INVALID_ARGS",`${t} must be a non-empty string`);return n}(t.target,"target"),r=aI(await e.backend.openSettings(rb(e,t),n));return{kind:"settingsOpened",...n?{target:n}:{},...r?{backendResult:r}:{},...tS(n?`Opened settings: ${n}`:"Opened settings")}},ay=async(e,t={})=>{if(!e.backend.handleAlert)throw new _("UNSUPPORTED_OPERATION","system.alert is not supported by this backend");let n=t.action??"get";if("get"!==n&&"accept"!==n&&"dismiss"!==n&&"wait"!==n)throw new _("INVALID_ARGS","system.alert action must be get, accept, dismiss, or wait");let r=void 0===t.timeoutMs?void 0:rW(t.timeoutMs,"timeoutMs",0,12e4),a=await e.backend.handleAlert(rb(e,t),n,{timeoutMs:r});var i=n,o=a;if("get"===i){if("alertStatus"!==o.kind)throw new _("COMMAND_FAILED","system.alert get returned an invalid backend result");return{kind:"alertStatus",action:i,alert:o.alert}}if("wait"===i){if("alertWait"!==o.kind)throw new _("COMMAND_FAILED","system.alert wait returned an invalid backend result");return{kind:"alertWait",action:i,alert:o.alert,...void 0!==o.waitedMs?{waitedMs:o.waitedMs}:{},...void 0!==o.timedOut?{timedOut:o.timedOut}:{},...tS(o.alert?"Alert visible":"Alert wait timed out")}}if("alertHandled"!==o.kind)throw new _("COMMAND_FAILED",`system.alert ${i} returned an invalid backend result`);return{kind:"alertHandled",action:i,handled:o.handled,...o.alert?{alert:o.alert}:{},...o.button?{button:o.button}:{},...tS(o.handled?`Alert ${i}ed`:"No alert handled")}},ab=async(e,t={})=>{if(!e.backend.openAppSwitcher)throw new _("UNSUPPORTED_OPERATION","system.appSwitcher is not supported by this backend");let n=aI(await e.backend.openAppSwitcher(rb(e,t)));return{kind:"appSwitcherOpened",...n?{backendResult:n}:{},...tS("Opened app switcher")}};function av(e){return!!(e&&"object"==typeof e)}function aI(e){return e&&"object"==typeof e?e:void 0}let aA=/^[A-Za-z0-9_.:-]{1,64}$/,ax=async(e,t)=>{var n;if(!e.backend.openApp)throw new _("UNSUPPORTED_OPERATION","apps.open is not supported by this backend");let r=function(e){var t;let n=aM(e.app,"app"),r=aM(e.appId,"appId"),a=aM(e.bundleId,"bundleId"),i=aM(e.packageName,"packageName"),o=aM(e.url,"url"),s=aM(e.activity,"activity"),l={...n?{app:n}:{},...r?{appId:r}:{},...a?{bundleId:a}:{},...i?{packageName:i}:{},...o?{url:o}:{},...s?{activity:s}:{}};if(!((t=l).app??t.appId??t.bundleId??t.packageName??t.url??t.activity))throw new _("INVALID_ARGS","apps.open requires app, appId, bundleId, packageName, url, or activity");return l}(t),a=aL(await e.backend.openApp(aR(e,t),r,{relaunch:t.relaunch}));return{kind:"appOpened",target:r,relaunch:!0===t.relaunch,...a?{backendResult:a}:{},...tS(`Opened: ${(n=r).app??n.appId??n.bundleId??n.packageName??n.url??n.activity??"app"}`)}},aN=async(e,t={})=>{if(!e.backend.closeApp)throw new _("UNSUPPORTED_OPERATION","apps.close is not supported by this backend");let n=aM(t.app,"app"),r=aL(await e.backend.closeApp(aR(e,t),n));return{kind:"appClosed",...n?{app:n}:{},...r?{backendResult:r}:{},...tS(n?`Closed: ${n}`:"Closed app")}},aS=async(e,t={})=>{if(!e.backend.listApps)throw new _("UNSUPPORTED_OPERATION","apps.list is not supported by this backend");return{kind:"appsList",apps:await e.backend.listApps(aR(e,t),t.filter??"all")}},a_=async(e,t)=>{if(!e.backend.getAppState)throw new _("UNSUPPORTED_OPERATION","apps.state is not supported by this backend");let n=aE(t.app,"app"),r=await e.backend.getAppState(aR(e,t),n);return{kind:"appState",app:n,state:r}},ak=async(e,t)=>{if(!e.backend.pushFile)throw new _("UNSUPPORTED_OPERATION","apps.push is not supported by this backend");let n=aE(t.app,"app"),r=await aO(e,t.input);try{let a=await e.backend.pushFile(aR(e,t),r.backendInput,n),i=aL(a);return{kind:"appPushed",app:n,inputKind:r.inputKind,...i?{backendResult:i}:{},...tS(`Pushed to ${n}`)}}finally{await r.cleanup?.()}},aD=async(e,t)=>{var n,r;if(!e.backend.triggerAppEvent)throw new _("UNSUPPORTED_OPERATION","apps.triggerEvent is not supported by this backend");let a=function(e){let t=aE(e,"name");if(!aA.test(t))throw new _("INVALID_ARGS",`Invalid apps.triggerEvent name: ${t}`,{hint:"Use 1-64 chars: letters, numbers, underscore, dot, colon, or dash."});return t}(t.name);n=t.payload,r=`apps.triggerEvent payload for "${a}"`,void 0!==n&&aC(n,r,8192);let i=aL(await e.backend.triggerAppEvent(aR(e,t),{name:a,...t.payload?{payload:t.payload}:{}}));return{kind:"appEventTriggered",name:a,...t.payload?{payload:t.payload}:{},...i?{backendResult:i}:{},...tS(`Triggered app event: ${a}`)}};function aM(e,t){if(void 0!==e)return aE(e,t)}function aE(e,t){let n=e?.trim();if(!n)throw new _("INVALID_ARGS",`${t} must be a non-empty string`);return n}async function aO(e,t){if(!t||"object"!=typeof t)throw new _("INVALID_ARGS","apps.push requires an input");if("json"===t.kind)return aC(t.payload,"apps.push JSON payload",8192),{backendInput:{kind:"json",payload:t.payload},inputKind:"json"};let n=await nN(e,t,{usage:"apps.push",field:"input"});return{backendInput:{kind:"file",path:n.path},inputKind:"file",...n.cleanup?{cleanup:n.cleanup}:{}}}function aC(e,t,n){if(function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw new _("INVALID_ARGS",`${t} must be a JSON object`)}(e,t),Buffer.byteLength(function(e,t){try{let n=JSON.stringify(e);if("string"!=typeof n)throw new _("INVALID_ARGS",`${t} must be JSON-serializable`);return n}catch{throw new _("INVALID_ARGS",`${t} must be JSON-serializable`)}}(e,t),"utf8")>n)throw new _("INVALID_ARGS",`${t} exceeds ${n} bytes`)}function aR(e,t){return{session:t.session,requestId:t.requestId,signal:t.signal??e.signal,metadata:t.metadata}}function aL(e){return e&&"object"==typeof e?e:void 0}let aP=async(e,t={})=>{if(!e.backend.listDevices)throw new _("UNSUPPORTED_OPERATION","admin.devices is not supported by this backend");return{kind:"adminDevices",devices:await e.backend.listDevices(rb(e,t),t.filter)}},aT=async(e,t={})=>{if(!e.backend.bootDevice)throw new _("UNSUPPORTED_OPERATION","admin.boot is not supported by this backend");let n=function(e){if(!e)return;let t=aW(e.id,"target.id"),n=aW(e.name,"target.name"),r={...t?{id:t}:{},...n?{name:n}:{},...e.platform?{platform:e.platform}:{},...e.target?{target:e.target}:{},...void 0!==e.headless?{headless:e.headless}:{}};return Object.keys(r).length>0?r:void 0}(t.target),r=aH(await e.backend.bootDevice(rb(e,t),n));return{kind:"deviceBooted",...n?{target:n}:{},...r?{backendResult:r}:{},...tS("Booted device")}},a$=async(e,t)=>{if(!e.backend.ensureSimulator)throw new _("UNSUPPORTED_OPERATION","admin.ensureSimulator is not supported by this backend");let n=az(t.device,"device");return{kind:"simulatorEnsured",...await e.backend.ensureSimulator(rb(e,t),{device:n,...t.runtime?{runtime:az(t.runtime,"runtime")}:{},...void 0!==t.boot?{boot:t.boot}:{},...void 0!==t.reuseExisting?{reuseExisting:t.reuseExisting}:{}})}},aF=async(e,t)=>await aV(e,t,"install"),aU=async(e,t)=>await aV(e,t,"reinstall"),aG=async(e,t)=>await aV(e,t,"installFromSource");async function aV(e,t,n){let r="reinstall"===n?"reinstallApp":"installApp",a=e.backend[r];if(!a)throw new _("UNSUPPORTED_OPERATION",`admin.${n} is not supported by this backend`);let i="app"in t&&void 0!==t.app?az(t.app,"app"):void 0;if("installFromSource"!==n&&!i)throw new _("INVALID_ARGS",`admin.${n} requires app`);let o=rb(e,t),s=await aB(e,o,t.source);try{var l,u,d,c,p;let t,r,f,h,m,w,g,y,b=await a.call(e.backend,o,{...i?{app:i}:{},source:s.source});return l=n,u=i,d=s.source,c=b,t=aH(c),r=aX(c,"appName"),f=aX(c,"appId"),h=aX(c,"bundleId"),m=aX(c,"packageName"),w=aX(c,"launchTarget"),g=aX(c,"installablePath"),y=aX(c,"archivePath"),{kind:"reinstall"===l?"appReinstalled":"installFromSource"===l?"appInstalledFromSource":"appInstalled",...u?{app:u}:{},source:d,...f?{appId:f}:{},...r?{appName:r}:{},...h?{bundleId:h}:{},...m?{packageName:m}:{},...w?{launchTarget:w}:{},...g?{installablePath:g}:{},...y?{archivePath:y}:{},...t?{backendResult:t}:{},...tS(`${"reinstall"===l?"Reinstalled":"Installed"}: ${r??w??u??(p=d,"path"===p.kind?p.path:"uploadedArtifact"===p.kind?p.id:p.url)}`)}}finally{await s.cleanup?.()}}async function aB(e,t,n){let r=aq(n),a=await aj(e,r);try{let n=e.backend.resolveInstallSource?await e.backend.resolveInstallSource(t,a.source):a.source;return{source:aq(n),...a.cleanup?{cleanup:a.cleanup}:{}}}catch(e){if(a.cleanup)try{await a.cleanup()}catch{}throw e}}async function aj(e,t){if("url"===t.kind)return{source:t};let n=await nN(e,t,{usage:"admin.install",field:"source"});return{source:{kind:"path",path:n.path},...n.cleanup?{cleanup:n.cleanup}:{}}}function aq(e){if(!e||"object"!=typeof e)throw new _("INVALID_ARGS","install source is required");if("path"===e.kind)return{kind:"path",path:az(e.path,"source.path")};if("uploadedArtifact"===e.kind)return{kind:"uploadedArtifact",id:az(e.id,"source.id")};if("url"===e.kind){let t=az(e.url,"source.url");return function(e){let t;try{t=new URL(e)}catch{throw new _("INVALID_ARGS",`Invalid install source URL: ${e}`)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new _("INVALID_ARGS","Install source URL must use http or https")}(t),{kind:"url",url:t}}throw new _("INVALID_ARGS","install source kind must be path, uploadedArtifact, or url")}function aW(e,t){if(void 0!==e)return az(e,t)}function az(e,t){let n=e?.trim();if(!n)throw new _("INVALID_ARGS",`${t} must be a non-empty string`);return n}function aX(e,t){let n=e[t];return"string"==typeof n&&n.length>0?n:void 0}function aH(e){return e&&"object"==typeof e?e:void 0}let aY=async(e,t)=>{let n=aK(t.action,"record"),r="start"===n?e.backend.startRecording:e.backend.stopRecording;if(!r)throw new _("UNSUPPORTED_OPERATION",`record ${n} is not supported by this backend`);let a=t.out?await nS(e,t.out,{field:"path",ext:".mp4"}):void 0;try{var i,o,s,l,u;let d,c,p=(i=t,o=a?.path,d=void 0===i.fps?void 0:rW(i.fps,"fps",1,60),c=void 0===i.quality?void 0:rW(i.quality,"quality",5,10),{...o?{outPath:o}:{},...void 0!==d?{fps:d}:{},...void 0!==c?{quality:c}:{},...void 0!==i.hideTouches?{showTouches:!0!==i.hideTouches}:{}}),f=await r.call(e.backend,rb(e,t),p),h=await a?.publish();return s=n,l=f,u=h,{..."string"==typeof l.path?{path:l.path}:{},..."string"==typeof l.telemetryPath?{telemetryPath:l.telemetryPath}:{},..."string"==typeof l.warning?{warning:l.warning}:{},...aZ(s,l,u,{startKind:"recordingStarted",stopKind:"recordingStopped",startMessage:"Recording started",stopMessage:"Recording stopped"})}}catch(e){throw await a?.cleanup?.(),e}},aJ=async(e,t)=>{let n=aK(t.action,"trace"),r="start"===n?e.backend.startTrace:e.backend.stopTrace;if(!r)throw new _("UNSUPPORTED_OPERATION",`trace ${n} is not supported by this backend`);let a=t.out?await nS(e,t.out,{field:"outPath",ext:".trace"}):void 0;try{var i,o,s;let l={...a?.path?{outPath:a.path}:{}},u=await r.call(e.backend,rb(e,t),l),d=await a?.publish();return i=n,o=u,s=d,{..."string"==typeof o.outPath?{outPath:o.outPath}:{},...aZ(i,o,s,{startKind:"traceStarted",stopKind:"traceStopped",startMessage:"Trace started",stopMessage:"Trace stopped"})}}catch(e){throw await a?.cleanup?.(),e}};function aK(e,t){if("start"===e||"stop"===e)return e;throw new _("INVALID_ARGS",`${t} action must be start or stop`)}function aZ(e,t,n,r){return{kind:"start"===e?r.startKind:r.stopKind,action:e,...n?{artifact:n}:{},backendResult:t,...tS("start"===e?r.startMessage:r.stopMessage)}}let aQ=/(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)/i;function a0(e){if(!e)return{redacted:!1};let t=!1,n={};for(let[r,a]of Object.entries(e))if(aQ.test(r))n[r]="[REDACTED]",t=!0;else{let e=a4(a,2048);n[r]=e.value??"",t||=e.redacted}return{value:n,redacted:t}}function a1(e){return void 0===e?{redacted:!1}:function(e){try{let t=JSON.parse(e),n=a3(t,a5);return a8(JSON.stringify(n.value),2048,n.redacted)}catch{return}}(e)??a4(e,2048)}function a2(e){return a3(e,e=>a4(e,2048))}function a3(e,t){if(void 0===e)return{redacted:!1};if("string"==typeof e)return t(e);if(!e||"object"!=typeof e)return{value:e,redacted:!1};if(Array.isArray(e)){let n=!1;return{value:e.map(e=>{let r=a3(e,t);return n||=r.redacted,r.value}),redacted:n}}let n=!1,r={};for(let[a,i]of Object.entries(e)){if(aQ.test(a)){r[a]="[REDACTED]",n=!0;continue}let e=a3(i,t);r[a]=e.value,n||=e.redacted}return{value:r,redacted:n}}function a4(e,t){if(void 0===e)return{redacted:!1};let n=a5(e);return a8(n.value,t,n.redacted)}function a5(e){let t=!1,n=e.replaceAll(/(authorization|token|secret|password|passwd|api[-_]?key)=([^&\s]+)/gi,(e,n)=>(t=!0,`${String(n)}=[REDACTED]`));return{value:n=(n=(n=n.replaceAll(/("(?:authorization|cookie|token|secret|password|passwd|api[-_]?key)"\s*:\s*")([^"]*)(")/gi,(e,n,r,a)=>(t=!0,`${String(n)}[REDACTED]${String(a)}`))).replaceAll(/\b(Bearer\s+)([^\s",;]+)/gi,(e,n)=>(t=!0,`${String(n)}[REDACTED]`))).replaceAll(/((?:authorization|cookie|token|secret|password|passwd|api[-_]?key)\s*[:=]\s*)([^\s,;]+)/gi,(e,n)=>(t=!0,`${String(n)}[REDACTED]`)),redacted:t}}function a8(e,t,n){if(void 0===e)return{redacted:n};let r=e;return r.length>t&&(r=`${r.slice(0,t)}...[truncated]`,n=!0),{value:r,redacted:n}}let a6=async(e,t={})=>{var n,r;let a;if(!e.backend.readLogs)throw new _("UNSUPPORTED_OPERATION","diagnostics.logs is not supported by this backend");return a=!0===(n=await e.backend.readLogs(await ie(e,t),{...it(r=t,100,500,"logs limit"),...void 0!==r.levels?{levels:ia(r.levels,"levels")}:{},...void 0!==r.search?{search:ii(r.search,"search")}:{},...void 0!==r.source?{source:ii(r.source,"source")}:{}})).redacted,{kind:"diagnosticsLogs",entries:n.entries.map(e=>{let t=a4(e.message,4096),n=a2(e.metadata);return a||=t.redacted||n.redacted,{...e.timestamp?{timestamp:e.timestamp}:{},...e.level?{level:e.level}:{},message:t.value??"",...e.source?{source:e.source}:{},...n.value?{metadata:n.value}:{}}}),...n.nextCursor?{nextCursor:n.nextCursor}:{},...n.timeWindow?{timeWindow:n.timeWindow}:{},...n.backend?{backend:n.backend}:{},redacted:a,...n.notes?{notes:n.notes}:{}}},a9=async(e,t={})=>{var n,r,a;let i;if(!e.backend.dumpNetwork)throw new _("UNSUPPORTED_OPERATION","diagnostics.network is not supported by this backend");let o={...it(a=t,25,200,"network limit"),include:function(e){if(void 0===e)return"summary";if("summary"===e||"headers"===e||"body"===e||"all"===e)return e;throw new _("INVALID_ARGS","network include must be summary, headers, body, or all")}(a.include)};return n=await e.backend.dumpNetwork(await ie(e,t),o),r=o.include??"summary",i=!0===n.redacted,{kind:"diagnosticsNetwork",entries:n.entries.map(e=>{let t=e.url?function(e){try{let t=new URL(e),n=!1;for(let e of Array.from(t.searchParams.keys()))aQ.test(e)&&(t.searchParams.set(e,"[REDACTED]"),n=!0);return{value:t.toString(),redacted:n}}catch{return a4(e,2048)}}(e.url):void 0,n="headers"===r||"all"===r?a0(e.requestHeaders):void 0,a="headers"===r||"all"===r?a0(e.responseHeaders):void 0,o="body"===r||"all"===r?a1(e.requestBody):void 0,s="body"===r||"all"===r?a1(e.responseBody):void 0,l=a2(e.metadata);return i||=(t?.redacted??!1)||(n?.redacted??!1)||(a?.redacted??!1)||(o?.redacted??!1)||(s?.redacted??!1)||l.redacted,{...e.timestamp?{timestamp:e.timestamp}:{},...e.method?{method:e.method}:{},...t?{url:t.value}:{},...void 0!==e.status?{status:e.status}:{},...void 0!==e.durationMs?{durationMs:e.durationMs}:{},...n?.value?{requestHeaders:n.value}:{},...a?.value?{responseHeaders:a.value}:{},...o?.value!==void 0?{requestBody:o.value}:{},...s?.value!==void 0?{responseBody:s.value}:{},...l.value?{metadata:l.value}:{}}}),...n.nextCursor?{nextCursor:n.nextCursor}:{},...n.timeWindow?{timeWindow:n.timeWindow}:{},...n.backend?{backend:n.backend}:{},redacted:i,...n.notes?{notes:n.notes}:{}}},a7=async(e,t={})=>{var n,r;let a;if(!e.backend.measurePerf)throw new _("UNSUPPORTED_OPERATION","diagnostics.perf is not supported by this backend");return a=!0===(n=await e.backend.measurePerf(await ie(e,t),{...ir(r=t),...void 0!==r.sampleMs?{sampleMs:rW(r.sampleMs,"sampleMs",100,6e4)}:{},...void 0!==r.metrics?{metrics:ia(r.metrics,"metrics",20)}:{}})).redacted,{kind:"diagnosticsPerf",metrics:n.metrics.map(e=>{let t=a4(e.message,4096),n=a2(e.metadata);return a||=t.redacted||n.redacted,{name:e.name,...void 0!==e.value?{value:e.value}:{},...e.unit?{unit:e.unit}:{},...e.status?{status:e.status}:{},...void 0!==t.value?{message:t.value}:{},...n.value?{metadata:n.value}:{}}}),...n.startedAt?{startedAt:n.startedAt}:{},...n.endedAt?{endedAt:n.endedAt}:{},...n.backend?{backend:n.backend}:{},redacted:a,...n.notes?{notes:n.notes}:{}}};async function ie(e,t){let n=rb(e,t),r=t.session?await e.sessions.get(t.session):void 0;return{...n,...t.appId??r?.appId?{appId:t.appId??r?.appId}:{},...t.appBundleId??r?.appBundleId?{appBundleId:t.appBundleId??r?.appBundleId}:{}}}function it(e,t,n,r){return{...ir(e),...void 0!==e.cursor?{cursor:ii(e.cursor,"cursor")}:{},limit:void 0===e.limit?t:rW(e.limit,r,1,n)}}function ir(e){return{...void 0!==e.since?{since:ii(e.since,"since")}:{},...void 0!==e.until?{until:ii(e.until,"until")}:{}}}function ia(e,t,n=50){if(!Array.isArray(e))throw new _("INVALID_ARGS",`${t} must be an array of strings`);if(e.length>n)throw new _("INVALID_ARGS",`${t} must contain at most ${n} entries`);return e.map((e,n)=>ii(e,`${t}[${n}]`))}function ii(e,t){let n=e.trim();if(!n)throw new _("INVALID_ARGS",`${t} must be a non-empty string`);return n}function io(e){return async(t,n)=>await e(t,n.options)}io(nk),io(rs),io(rA),io(rx),io(rO),io(rC),io(rP),io(rF),io(as),io(ao),io(al),io(au),io(r4),io(r5),io(r6),io(r8),io(r9),io(ap),io(af),io(ah),io(am),io(aw),io(ag),io(ay),io(ab),io(ax),io(aN),io(aS),io(a_),io(ak),io(aD),io(aP),io(aT),io(a$),io(aF),io(aU),io(aG),io(aY),io(aJ),io(a6),io(a9),io(a7);let is=nk,il=rs,iu=rA,id=rx,ic=rO,ip=rC,ih=rR,im=rL,iw=rP,ig=rT,iy=r$,ib=rF,iv=rU,iI=as,iA=ao,ix=al,iN=au,iS=r4,i_=r5,ik=r6,iD=r8,iM=r9,iE=ap,iO=af,iC=ah,iR=am,iL=aw,iP=ag,iT=ay,i$=ab,iF=ax,iU=aN,iG=aS,iV=a_,iB=ak,ij=aD,iq=aP,iW=aT,iz=a$,iX=aF,iH=aU,iY=aG,iJ=aY,iK=aJ,iZ=a6,iQ=a9,i0=a7;function i1(e){let t={backend:e.backend,artifacts:e.artifacts,sessions:e.sessions??function(e=[]){let t=new Map(e.map(e=>[e.name,i2(e)]));return{get:e=>i2(t.get(e)),set:e=>{t.set(e.name,i2(e))},delete:e=>{t.delete(e)},list:()=>Array.from(t.values(),e=>i2(e))}}(),policy:e.policy??function(e={}){return{allowLocalInputPaths:!1,allowLocalOutputPaths:!1,maxImagePixels:2e7,allowNamedBackendCapabilities:[],...e}}(),diagnostics:e.diagnostics,clock:e.clock,signal:e.signal};return{...t,capture:{screenshot:e=>is(t,e),diffScreenshot:e=>il(t,e),snapshot:e=>iu(t,e),diffSnapshot:e=>id(t,e)},selectors:{find:e=>ic(t,e),get:e=>ip(t,e),getText:(e,n={})=>ih(t,{...n,target:e}),getAttrs:(e,n={})=>im(t,{...n,target:e}),is:e=>iw(t,e),isVisible:(e,n={})=>ig(t,{...n,target:e}),isHidden:(e,n={})=>iy(t,{...n,target:e}),wait:e=>ib(t,e),waitForText:(e,n={})=>iv(t,{...n,text:e})},interactions:{click:(e,n={})=>iI(t,{...n,target:e}),press:(e,n={})=>iA(t,{...n,target:e}),fill:(e,n,r={})=>ix(t,{...r,target:e,text:n}),typeText:(e,n={})=>iN(t,{...n,text:e}),focus:(e,n={})=>iS(t,{...n,target:e}),longPress:(e,n={})=>i_(t,{...n,target:e}),swipe:e=>ik(t,e),scroll:e=>iD(t,e),pinch:e=>iM(t,e)},system:{back:e=>iE(t,e),home:e=>iO(t,e),rotate:e=>iC(t,e),keyboard:e=>iR(t,e),clipboard:e=>iL(t,e),settings:e=>iP(t,e),alert:e=>iT(t,e),appSwitcher:e=>i$(t,e)},apps:{open:e=>iF(t,e),close:e=>iU(t,e),list:e=>iG(t,e),state:e=>iV(t,e),push:e=>iB(t,e),triggerEvent:e=>ij(t,e)},admin:{devices:e=>iq(t,e),boot:e=>iW(t,e),ensureSimulator:e=>iz(t,e),install:e=>iX(t,e),reinstall:e=>iH(t,e),installFromSource:e=>iY(t,e)},recording:{record:e=>iJ(t,e),trace:e=>iK(t,e)},observability:{logs:e=>iZ(t,e),network:e=>iQ(t,e),perf:e=>i0(t,e)}}}function i2(e){if(e)return{...e,...e.snapshot?{snapshot:structuredClone(e.snapshot)}:{},...e.metadata?{metadata:function(e){try{return structuredClone(e)}catch{return{...e}}}(e.metadata)}:{}}}function i3(e={}){return{allowLocalInputPaths:!0,allowLocalOutputPaths:!0,maxImagePixels:2e7,allowNamedBackendCapabilities:[],...e}}function i4(e,t,n){return{ok:!1,error:{code:e,message:t,...n?{details:n}:{}}}}function i5(e){return e}function i8(e){return"apple"===e||"ios"===e||"macos"===e}function i6(e,t){return!t||("apple"===t?i8(e):e===t)}function i9(e){let{simulatorSetPath:t,platform:n,target:r}=e;if(t&&"macos"!==n&&"desktop"!==r)return t}async function i7(e,t,n={}){let r=e,a=e=>e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim();if(t.platform&&(r=r.filter(e=>i6(e.platform,t.platform))),t.target&&(r=r.filter(e=>(e.target??"mobile")===t.target)),t.udid){let e=r.find(e=>e.id===t.udid&&i8(e.platform));if(!e)throw new _("DEVICE_NOT_FOUND",`No Apple device with UDID ${t.udid}`);return e}if(t.serial){let e=r.find(e=>e.id===t.serial&&"android"===e.platform);if(!e)throw new _("DEVICE_NOT_FOUND",`No Android device with serial ${t.serial}`);return e}if(t.deviceName){let e=a(t.deviceName),n=r.find(t=>a(t.name)===e);if(!n)throw new _("DEVICE_NOT_FOUND",`No device named ${t.deviceName}`);return n}if(1===r.length)return r[0];if(0===r.length){var i;let e=n.simulatorSetPath;if(e&&(!(i=t.platform)||"apple"===i||"ios"===i))throw new _("DEVICE_NOT_FOUND","No devices found in the scoped simulator set",{simulatorSetPath:e,hint:`The simulator set at "${e}" appears to be empty. Create a simulator first:
|
|
8
|
+
xcrun simctl --set "${e}" create "iPhone 16" com.apple.CoreSimulator.SimDeviceType.iPhone-16 com.apple.CoreSimulator.SimRuntime.iOS-18-0`,selector:t});throw new _("DEVICE_NOT_FOUND","No devices found",{selector:t})}let o=r.filter(e=>"device"!==e.kind);o.length>0&&(r=o);let s=r.filter(e=>e.booted);return 1===s.length?s[0]:s[0]??r[0]}let oe=e=>"macos"!==e.platform,ot=e=>"macos"===e.platform||"simulator"===e.kind,on={device:!0},or={},oa={alert:{apple:{simulator:!0,device:!0},android:{},linux:or,supports:ot},pinch:{apple:{simulator:!0,device:!0},android:{},linux:or,supports:ot},"app-switcher":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:or,supports:oe},apps:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:or},back:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:on},boot:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:or,supports:oe},click:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:on},clipboard:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:on,supports:e=>"android"===e.platform||"linux"===e.platform||"macos"===e.platform||"simulator"===e.kind},keyboard:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:or,supports:e=>"android"===e.platform||"ios"===e.platform&&"tv"!==e.target},close:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:on},fill:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:on},diff:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:on},find:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:on},focus:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:on},get:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:on},is:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:on},home:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:on,supports:oe},logs:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:or},network:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:or},longpress:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:on},open:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:on},perf:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:or},install:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:or,supports:oe},"install-from-source":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:or,supports:oe},reinstall:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:or,supports:oe},press:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:on},push:{apple:{simulator:!0},android:{emulator:!0,device:!0,unknown:!0},linux:or,supports:oe},record:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:or},rotate:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:or,supports:e=>"android"===e.platform||"ios"===e.platform&&"tv"!==e.target},screenshot:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:on},scroll:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:on},swipe:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:on},settings:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:or,supports:e=>"android"===e.platform||"macos"===e.platform||"simulator"===e.kind},snapshot:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:on},"trigger-app-event":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:or},type:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:on},wait:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:on}};function oi(e,t){let n=oa[e];if(!n)return!0;let r=i8(t.platform)?n.apple:"linux"===t.platform?n.linux:n.android;return!!r&&(!n.supports||!!n.supports(t))&&!0===r[t.kind??"unknown"]}let oo=os(process.env.AGENT_DEVICE_RETRY_LOGS);function os(e){return["1","true","yes","on"].includes((e??"").trim().toLowerCase())}let ol=2e4,ou=12e4,od=1e4;class oc{startedAtMs;expiresAtMs;constructor(e,t){this.startedAtMs=e,this.expiresAtMs=e+Math.max(0,t)}static fromTimeoutMs(e,t=Date.now()){return new oc(t,e)}remainingMs(e=Date.now()){return Math.max(0,this.expiresAtMs-e)}elapsedMs(e=Date.now()){return Math.max(0,e-this.startedAtMs)}isExpired(e=Date.now()){return 0>=this.remainingMs(e)}}async function op(e,t={},n={}){let r,a={maxAttempts:t.maxAttempts??3,baseDelayMs:t.baseDelayMs??200,maxDelayMs:t.maxDelayMs??2e3,jitter:t.jitter??.2,shouldRetry:t.shouldRetry};for(let t=1;t<=a.maxAttempts;t+=1){if(n.signal?.aborted)throw new _("COMMAND_FAILED","request canceled",{reason:"request_canceled"});if(n.deadline?.isExpired()&&t>1)break;try{let r=await e({attempt:t,maxAttempts:a.maxAttempts,deadline:n.deadline});return n.onEvent?.({phase:n.phase,event:"succeeded",attempt:t,maxAttempts:a.maxAttempts,elapsedMs:n.deadline?.elapsedMs(),remainingMs:n.deadline?.remainingMs()}),oh({phase:n.phase,event:"succeeded",attempt:t,maxAttempts:a.maxAttempts,elapsedMs:n.deadline?.elapsedMs(),remainingMs:n.deadline?.remainingMs()}),r}catch(u){r=u;let e=n.classifyReason?.(u),i={phase:n.phase,event:"attempt_failed",attempt:t,maxAttempts:a.maxAttempts,elapsedMs:n.deadline?.elapsedMs(),remainingMs:n.deadline?.remainingMs(),reason:e};if(n.onEvent?.(i),oh(i),t>=a.maxAttempts||a.shouldRetry&&!a.shouldRetry(u,t))break;let o=function(e,t,n,r){let a=Math.min(t,e*2**(r-1));return Math.max(0,a+a*n*(2*Math.random()-1))}(a.baseDelayMs,a.maxDelayMs,a.jitter,t),s=n.deadline?Math.min(o,n.deadline.remainingMs()):o;if(s<=0)break;let l={phase:n.phase,event:"retry_scheduled",attempt:t,maxAttempts:a.maxAttempts,delayMs:s,elapsedMs:n.deadline?.elapsedMs(),remainingMs:n.deadline?.remainingMs(),reason:e};n.onEvent?.(l),oh(l),await function(e,t){return new Promise(n=>{if(t?.aborted)return void n();let r=!1,a=()=>{r||(r=!0,t&&t.removeEventListener("abort",o),n())},i=setTimeout(a,e);function o(){clearTimeout(i),a()}t&&t.addEventListener("abort",o,{once:!0})})}(s,n.signal)}}let i={phase:n.phase,event:"exhausted",attempt:a.maxAttempts,maxAttempts:a.maxAttempts,elapsedMs:n.deadline?.elapsedMs(),remainingMs:n.deadline?.remainingMs(),reason:n.classifyReason?.(r)};if(n.onEvent?.(i),oh(i),r)throw r;throw new _("COMMAND_FAILED","retry failed")}async function of(e,t={}){return op(()=>e(),{maxAttempts:t.attempts,baseDelayMs:t.baseDelayMs,maxDelayMs:t.maxDelayMs,jitter:t.jitter,shouldRetry:t.shouldRetry})}function oh(e){eN({level:"attempt_failed"===e.event||"exhausted"===e.event?"warn":"debug",phase:"retry",data:{...e}}),oo&&process.stderr.write(`[agent-device][retry] ${JSON.stringify(e)}
|
|
9
|
+
`)}let om=new Set,ow=new Map,og="request_canceled",oy="request canceled";function ob(e,t){if("string"==typeof e&&e.length>0)return e;let n=("string"==typeof t?t:"number"==typeof t&&Number.isFinite(t)?String(t):"generated").trim().replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,32)||"generated",r=Math.random().toString(36).slice(2,10);return`req:${n}:${process.pid}:${Date.now()}:${r}`}function ov(e){if(!e)return;!function(e){if(e.size<=5e4)return;let t=0;for(let n of e.keys()){if(t>=1e4)break;e.delete(n),t++}}(ow);let t=new AbortController;ow.set(e,t),om.has(e)&&t.abort()}function oI(e){e&&(!function(e){if(e.size<=5e4)return;let t=0;for(let n of e){if(t>=1e4)break;e.delete(n),t++}}(om),om.add(e),ow.get(e)?.abort())}function oA(e){e&&(om.delete(e),ow.delete(e))}function ox(e){return!!e&&om.has(e)}function oN(e){if(e)return ow.get(e)?.signal}function oS(){return new _("COMMAND_FAILED",oy,{reason:og})}function o_(e){return e instanceof _&&"COMMAND_FAILED"===e.code&&(e.details?.reason===og||e.message===oy)}function ok(e,t,n){if(!e)return t;let r=Number(e);return Number.isFinite(r)?Math.max(n,Math.floor(r)):t}function oD(e){let t=e.error?x(e.error):null,n=e.context?.platform,r=e.context?.phase;if(t?.code==="TOOL_MISSING")return"android"===n?"ADB_TRANSPORT_UNAVAILABLE":"IOS_TOOL_MISSING";let a=t?.details??{},i="string"==typeof a.message?a.message:void 0,o="string"==typeof a.stdout?a.stdout:void 0,s="string"==typeof a.stderr?a.stderr:void 0,l=a.boot&&"object"==typeof a.boot?a.boot:null,u=a.bootstatus&&"object"==typeof a.bootstatus?a.bootstatus:null,d=[e.message,t?.message,e.stdout,e.stderr,i,o,s,"string"==typeof l?.stdout?l.stdout:void 0,"string"==typeof l?.stderr?l.stderr:void 0,"string"==typeof u?.stdout?u.stdout:void 0,"string"==typeof u?.stderr?u.stderr:void 0].filter(Boolean).join("\n").toLowerCase();return"ios"===n&&(d.includes("runner did not accept connection")||"connect"===r&&(d.includes("timed out")||d.includes("timeout")||d.includes("econnrefused")||d.includes("connection refused")||d.includes("fetch failed")||d.includes("socket hang up")))?"IOS_RUNNER_CONNECT_TIMEOUT":"ios"===n&&"boot"===r&&(d.includes("timed out")||d.includes("timeout"))?"IOS_BOOT_TIMEOUT":"android"===n&&"boot"===r&&(d.includes("timed out")||d.includes("timeout"))?"ANDROID_BOOT_TIMEOUT":d.includes("resource temporarily unavailable")||d.includes("killed: 9")||d.includes("cannot allocate memory")||d.includes("system is low on memory")?"CI_RESOURCE_STARVATION_SUSPECTED":"android"===n&&(d.includes("device not found")||d.includes("no devices")||d.includes("device offline")||d.includes("offline")||d.includes("unauthorized")||d.includes("not authorized")||d.includes("unable to locate device")||d.includes("invalid device"))?"ADB_TRANSPORT_UNAVAILABLE":t?.code==="COMMAND_FAILED"||d.length>0?"BOOT_COMMAND_FAILED":"UNKNOWN"}function oM(e){switch(e){case"IOS_BOOT_TIMEOUT":return"Retry simulator boot and inspect simctl bootstatus logs; in CI consider increasing AGENT_DEVICE_IOS_BOOT_TIMEOUT_MS.";case"IOS_RUNNER_CONNECT_TIMEOUT":return"Retry runner startup, inspect xcodebuild logs, and verify simulator responsiveness before command execution.";case"ANDROID_BOOT_TIMEOUT":return"Retry emulator startup and verify sys.boot_completed reaches 1; consider increasing startup budget in CI.";case"ADB_TRANSPORT_UNAVAILABLE":return"Check adb server/device transport (adb devices -l), restart adb, and ensure the target device is online and authorized.";case"CI_RESOURCE_STARVATION_SUSPECTED":return"CI machine may be resource constrained; reduce parallel jobs or use a larger runner.";case"IOS_TOOL_MISSING":return"Xcode command-line tools are missing or not in PATH; run xcode-select --install and verify xcrun works.";case"BOOT_COMMAND_FAILED":return"Inspect command stderr/stdout for the failing boot phase and retry after environment validation.";default:return"Retry once and inspect verbose logs for the failing phase."}}function oE(e){return!(e instanceof _)||"COMMAND_FAILED"!==e.code||!String(e.message??"").toLowerCase().includes("xcodebuild exited early")}function oO(e){let{port:t,endpoints:n,logPath:r,lastError:a}=e,i="Runner did not accept connection";return new _("COMMAND_FAILED",i,{port:t,endpoints:n,logPath:r,lastError:a?String(a):void 0,reason:oD({error:a,message:i,context:{platform:"ios",phase:"connect"}}),hint:oM("IOS_RUNNER_CONNECT_TIMEOUT")})}async function oC(e){var t,n;let r,{session:a,port:i,logPath:o}=e,s=await a.testPromise,l="Runner did not accept connection (xcodebuild exited early)",u=oD({message:l,stdout:s.stdout,stderr:s.stderr,context:{platform:"ios",phase:"connect"}});return new _("COMMAND_FAILED",l,{port:i,logPath:o,xcodebuild:{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr},reason:u,hint:(t=s.stdout,n=s.stderr,(r=`${l}
|
|
10
10
|
${t}
|
|
11
|
-
${n}`.toLowerCase()).includes("device is busy")&&r.includes("connecting")?"Target iOS device is still connecting. Keep it unlocked, wait for device trust/connection to settle, then retry.":iJ("IOS_RUNNER_CONNECT_TIMEOUT"))})}function i0(e){if(iq(e))throw iz()}let i1=iY(process.env.AGENT_DEVICE_RUNNER_STARTUP_TIMEOUT_MS,45e3,5e3),i2=iY(process.env.AGENT_DEVICE_RUNNER_COMMAND_TIMEOUT_MS,45e3,1e3),i3=iY(process.env.AGENT_DEVICE_RUNNER_CONNECT_ATTEMPT_INTERVAL_MS,250,50),i4=iY(process.env.AGENT_DEVICE_RUNNER_CONNECT_RETRY_BASE_DELAY_MS,300,10),i5=iY(process.env.AGENT_DEVICE_RUNNER_CONNECT_RETRY_MAX_DELAY_MS,2e3,10),i8=iY(process.env.AGENT_DEVICE_RUNNER_CONNECT_REQUEST_TIMEOUT_MS,2e4,250),i6=iY(process.env.AGENT_DEVICE_IOS_DEVICE_INFO_TIMEOUT_MS,1e4,500),i9=iY(process.env.AGENT_DEVICE_RUNNER_DESTINATION_TIMEOUT_SECONDS,20,5);async function i7(e,t,n,r,i=i1,a,o){let s=ik.fromTimeoutMs(i),l=await ae(e,t,s.remainingMs()),u=null,d=Math.max(1,Math.ceil(i/i3));try{return await iL(async({deadline:s})=>{if(s?.isExpired())throw new _("COMMAND_FAILED","Runner connection deadline exceeded",{port:t,timeoutMs:i});if(a&&null!==a.child.exitCode&&void 0!==a.child.exitCode)throw await iQ({session:a,port:t,logPath:r});for(let r of("device"===e.kind&&(l=await ae(e,t,s?.remainingMs())),l))try{let e=s?.remainingMs()??i;if(e<=0)throw new _("COMMAND_FAILED","Runner connection deadline exceeded",{port:t,timeoutMs:i});return await at(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},Math.min(i8,e),o)}catch(e){if(o?.aborted||iX(e))throw iz();u=e}throw new _("COMMAND_FAILED","Runner endpoint probe failed",{port:t,endpoints:l,lastError:u?String(u):void 0})},{maxAttempts:d,baseDelayMs:i4,maxDelayMs:i5,jitter:.2,shouldRetry:iK},{deadline:s,phase:"ios_runner_connect",signal:o})}catch(e){if(o?.aborted||iX(e))throw iz();u||(u=e)}if(o?.aborted)throw iz();if("simulator"===e.kind){let i=s.remainingMs();if(i<=0)throw iZ({port:t,endpoints:l,logPath:r,lastError:u});let a=await ar(e,t,n,i);return new Response(a.body,{status:a.status})}throw iZ({port:t,endpoints:l,logPath:r,lastError:u})}async function ae(e,t,n){let r=[`http://127.0.0.1:${t}/command`];if("device"!==e.kind)return r;let i=await an(e.id,n);return i&&r.unshift(`http://[${i}]:${t}/command`),r}async function at(e,t,n,r){let i,a=new AbortController,o=setTimeout(()=>a.abort(),n);r&&(r.aborted?(clearTimeout(o),a.abort()):(i=()=>a.abort(),r.addEventListener("abort",i,{once:!0})));try{return await fetch(e,{...t,signal:a.signal})}finally{clearTimeout(o),i&&r&&r.removeEventListener("abort",i)}}async function an(e,t){if("number"==typeof t&&t<=0)return null;let n="number"==typeof t?Math.max(1,Math.min(i6,t)):i6,i=o.join(p.tmpdir(),`agent-device-devicectl-info-${process.pid}-${Date.now()}.json`);try{let t=Math.max(1,Math.ceil(n/1e3)),a=await M("xcrun",["devicectl","device","info","details","--device",e,"--json-output",i,"--timeout",String(t)],{allowFailure:!0,timeoutMs:n});if(0!==a.exitCode||!r.existsSync(i))return null;let o=JSON.parse(r.readFileSync(i,"utf8"));if(o.info?.outcome&&"success"!==o.info.outcome)return null;let s=(o.result?.connectionProperties?.tunnelIPAddress??o.result?.device?.connectionProperties?.tunnelIPAddress)?.trim();return s&&s.length>0?s:null}catch{return null}finally{ao(i)}}async function ar(e,t,n,r){let i=JSON.stringify(n),a=t9(e,["spawn",e.id,"/usr/bin/curl","-s","-X","POST","-H","Content-Type: application/json","--data",i,`http://127.0.0.1:${t}/command`]),o=await M("xcrun",a,{allowFailure:!0,timeoutMs:r}),s=o.stdout;if(0!==o.exitCode){let e=iH({message:"Runner did not accept connection (simctl spawn)",stdout:o.stdout,stderr:o.stderr,context:{platform:"ios",phase:"connect"}});throw new _("COMMAND_FAILED","Runner did not accept connection (simctl spawn)",{port:t,stdout:o.stdout,stderr:o.stderr,exitCode:o.exitCode,reason:e,hint:iJ(e)})}return{status:200,body:s}}async function ai(){return await new Promise((e,t)=>{let n=m.createServer();n.listen(0,"127.0.0.1",()=>{let r=n.address();if("object"==typeof r&&r?.port){let t=r.port;n.close(()=>e(t))}else n.close(()=>t(new _("COMMAND_FAILED","Failed to allocate port")))}),n.on("error",t)})}function aa(e,t,n,i){t&&r.appendFile(t,e,()=>{}),n&&r.appendFile(n,e,()=>{}),i&&process.stderr.write(e)}function ao(e){try{r.existsSync(e)&&r.unlinkSync(e)}catch{}}let as=new u;async function al(e,t,n){let r=as.getStore()??[];if(r.some(n=>n.locks===e&&n.key===t))return await n();let i=(e.get(t)??Promise.resolve()).catch(()=>{}).then(()=>as.run([...r,{locks:e,key:t}],n));return e.set(t,i),i.finally(()=>{e.get(t)===i&&e.delete(t)})}let au=new Set(["RUNNER_PRODUCT_MISSING","RUNNER_PRODUCT_REPAIR_FAILED"]);async function ad(e,t,n){if("macos"!==e.platform)return;if(0===t.length)throw new _("COMMAND_FAILED","Missing macOS runner product",{reason:"RUNNER_PRODUCT_MISSING",xctestrunPath:n});let i=Array.from(new Set(t)).sort((e,t)=>t.length-e.length);for(let e of i)if(!r.existsSync(e))throw new _("COMMAND_FAILED","Missing macOS runner product",{reason:"RUNNER_PRODUCT_MISSING",productPath:e,xctestrunPath:n});for(let e of i)if(0!==D("codesign",["--verify","--deep","--strict",e],{allowFailure:!0}).exitCode){await M("codesign",["--remove-signature",e],{allowFailure:!0});try{await M("codesign",["--force","--sign","-",e])}catch(r){let t=r instanceof _?r:new _("COMMAND_FAILED",String(r));throw new _("COMMAND_FAILED","Failed to repair macOS runner product signature",{reason:"RUNNER_PRODUCT_REPAIR_FAILED",productPath:e,xctestrunPath:n,error:t.message,details:t.details})}}}let ac=null;function ap(e){return function e(t){if(!Array.isArray(t))return[];let n=[];for(let r of t)if(!(!r||"object"!=typeof r||Array.isArray(r)))for(let[t,i]of Object.entries(r))":@"!==t&&"#text"!==t&&n.push({name:t,attributes:function(e){if(!e||"object"!=typeof e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))"string"==typeof r&&(t[n]=r);return t}(r[":@"]),text:ah(i)??ah(r["#text"]),children:e(i)});return n}((ac??=new w({ignoreAttributes:!1,attributeNamePrefix:"",preserveOrder:!0,trimValues:!0,parseTagValue:!1})).parse(e))}function af(e,t){for(let n of e){if("dict"===n.name)for(let e=0;e<n.children.length-1;e+=1){let r=n.children[e],i=n.children[e+1];r?.name==="key"&&r.text&&i&&t(r.text,i)}af(n.children,t)}}function ah(e){if("string"==typeof e){let t=e.trim();return t.length>0?t:null}if(!Array.isArray(e))return null;let t=e.map(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return null;let t=e["#text"];return"string"==typeof t?t.trim():null}).filter(e=>null!==e&&e.length>0).join("").trim();return t.length>0?t:null}let am="XCTestDevices",aw=".agent-device-backup",ag=".agent-device-xctestdevices-backup-",ay=o.join(p.homedir(),".agent-device","ios-runner"),ab=new Set(["ProductPaths","DependentProductPaths","TestHostPath","TestBundlePath","UITargetAppPath"]),av=new Map,aI=new Set;function aA(e){return e?.trim()??""}function ax(e=process.env){return aA(e.AGENT_DEVICE_IOS_BUNDLE_ID)||aA(e.AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID)||"com.callstack.agentdevice.runner"}function aS(e=process.env){let t=aA(e.AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID);return t||`${ax(e)}.uitests`}let aN=function(e=process.env){let t=ax(e),n=aS(e);return Array.from(new Set([aA(e.AGENT_DEVICE_IOS_RUNNER_CONTAINER_BUNDLE_ID),`${n}.xctrunner`,t].filter(e=>e.length>0)))}(process.env);function a_(e=p.homedir()){return o.join(e,"Library","Developer","XCTestDevices")}async function aM(e,t={}){if("ios"!==e.platform||"simulator"!==e.kind)return null;let n=t4(e.simulatorSetPath);if(!n)return null;let i=o.resolve(n),a=o.resolve(t.xctestDeviceSetPath??a_()),s=o.resolve(t.backupPath??function(e=a_()){return`${e}${aw}`}(a)),l=o.resolve(t.lockDirPath??function(e=p.homedir()){return o.join(e,".agent-device","xctest-device-set.lock")}()),u=t.ownerStartTime??eE(process.pid),d=await aC({lockDirPath:l,owner:{pid:t.ownerPid??process.pid,startTime:u,acquiredAtMs:t.nowMs??Date.now()}});try{if(aD({xctestDeviceSetPath:a,backupPath:s}),function(e,t){if(o.resolve(e)===o.resolve(t))return!0;try{return r.realpathSync.native(e)===r.realpathSync.native(t)}catch{return!1}}(i,a))return await d(),null;r.mkdirSync(i,{recursive:!0}),r.existsSync(a)&&r.renameSync(a,s),function(e){let{requestedSetPath:t,xctestDeviceSetPath:n}=e,i=o.dirname(n),a=o.join(i,`${am}.agent-device-link-${process.pid}-${Date.now()}`);r.mkdirSync(i,{recursive:!0});try{r.symlinkSync(t,a,"dir"),r.renameSync(a,n)}catch(e){throw r.existsSync(a)&&aE(a),e}}({requestedSetPath:i,xctestDeviceSetPath:a})}catch(e){throw aD({xctestDeviceSetPath:a,backupPath:s}),await d(),new _("COMMAND_FAILED","Failed to redirect XCTest device set path",{requestedSetPath:i,xctestDeviceSetPath:a,backupPath:s,error:String(e)})}let c=!1;return{release:async()=>{if(!c){c=!0;try{aD({xctestDeviceSetPath:a,backupPath:s})}finally{await d()}}}}}function aD(e){let{xctestDeviceSetPath:t,backupPath:n}=e,i=[n,...function(e){let t=o.dirname(e),n=o.basename(e).replace(aw,""),i=n===am?ag:`${n}${ag}`;try{return r.readdirSync(t).filter(e=>e.startsWith(i)).sort().map(e=>o.join(t,e))}catch{return[]}}(n)],a=i.find(e=>r.existsSync(e)),s=r.existsSync(t)&&r.lstatSync(t).isSymbolicLink();if(a){if(s&&aE(t),r.existsSync(t))if(!s)return void eS({level:"warn",phase:"ios_runner_xctest_device_set_restore_collision",data:{xctestDeviceSetPath:t,activeBackupPath:a}});else a!==n?r.rmSync(a,{recursive:!0,force:!0}):r.rmSync(n,{recursive:!0,force:!0});else r.mkdirSync(o.dirname(t),{recursive:!0}),r.renameSync(a,t);for(let e of i)e!==a&&r.existsSync(e)&&r.rmSync(e,{recursive:!0,force:!0});return}s&&(eS({level:"warn",phase:"ios_runner_xctest_device_set_orphaned_symlink",data:{xctestDeviceSetPath:t}}),aE(t))}function aE(e){!r.existsSync(e)||r.lstatSync(e).isSymbolicLink()&&r.unlinkSync(e)}async function aC(e){let{lockDirPath:t,owner:n}=e,i=o.join(t,"owner.json"),a=Date.now()+3e4;for(r.mkdirSync(o.dirname(t),{recursive:!0});Date.now()<a;)try{r.mkdirSync(t),function(e,t){let n=`${e}.${process.pid}.${Date.now()}.tmp`;r.writeFileSync(n,JSON.stringify(t),"utf8"),r.renameSync(n,e)}(i,n);let e=!1;return async()=>{e||(e=!0,r.rmSync(t,{recursive:!0,force:!0}))}}catch(e){if("EEXIST"!==e.code)throw e;if(function(e,t){let n=null;try{n=r.statSync(e)}catch{return!0}let i=function(e){try{return JSON.parse(r.readFileSync(e,"utf8"))}catch{return null}}(t);if(i){var a;return!(Number.isInteger((a=i).pid)&&!(a.pid<=0)&&eD(a.pid)&&(!a.startTime||eE(a.pid)===a.startTime))&&(r.rmSync(e,{recursive:!0,force:!0}),!0)}return!(Date.now()-n.mtimeMs<5e3)&&(r.rmSync(e,{recursive:!0,force:!0}),!0)}(t,i))continue;await new Promise(e=>setTimeout(e,100))}throw new _("COMMAND_FAILED","Timed out waiting for XCTest device set lock",{lockDirPath:t})}async function aO(e,t){var n;let i,a=(n=e,(i=process.env.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim())?o.resolve(i):"macos"===n.platform?o.join(ay,"derived","macos"):"simulator"===n.kind?o.join(ay,"derived"):o.join(ay,"derived",n.kind)),s=function(){let e=o.dirname(l(import.meta.url)),t=e;for(let e=0;e<6;e+=1){let e=o.join(t,"package.json");if(r.existsSync(e))return t;t=o.dirname(t)}return e}();return await al(av,a,async()=>{iD(process.env.AGENT_DEVICE_IOS_CLEAN_DERIVED)&&(aj("clean","forced_clean",{derived:a}),aB(a),ak(a));let n=function(e){let t=e.findXctestrun(e.derived);if(!t)return{reason:"missing_xctestrun",xctestrunPath:null};let n=e.resolveExistingXctestrunProductPaths(t);return n?e.xctestrunReferencesProjectRoot(t,e.projectRoot)?{reason:"reuse_ready",xctestrunPath:t,productPaths:n}:{reason:"project_root_mismatch",xctestrunPath:t,productPaths:n}:{reason:"missing_products",xctestrunPath:t,productPaths:[]}}({derived:a,projectRoot:s,findXctestrun:t=>aR(t,e),xctestrunReferencesProjectRoot:aP,resolveExistingXctestrunProductPaths:aq});if("reuse_ready"!==n.reason&&aj("rebuild",n.reason,{derived:a,xctestrunPath:n.xctestrunPath}),"reuse_ready"===n.reason)try{return await ad(e,n.productPaths,n.xctestrunPath),aj("reuse","reuse_ready",{derived:a,xctestrunPath:n.xctestrunPath}),n.xctestrunPath}catch(e){if(!function(e){if(!(e instanceof _))return!1;let t=e.details&&"object"==typeof e.details?e.details.reason:void 0;return"string"==typeof t&&au.has(t)}(e))throw e;aj("rebuild","repair_failed",{derived:a,xctestrunPath:n.xctestrunPath})}n.xctestrunPath&&(aB(a),ak(a));let i=o.join(s,"ios-runner","AgentDeviceRunner","AgentDeviceRunner.xcodeproj");if(!r.existsSync(i))throw new _("COMMAND_FAILED","iOS runner project not found",{projectPath:i});await aF(e,i,a,t);let l=aR(a,e);if(!l)throw new _("COMMAND_FAILED","Failed to locate .xctestrun after build");let u=aq(l);if(!u)throw new _("COMMAND_FAILED","Runner build is missing expected products",{xctestrunPath:l});return await ad(e,u,l),aj("build","built_new",{derived:a,xctestrunPath:l}),l})}function ak(e){try{if(!r.existsSync(e))return;if("derived"!==o.basename(e))return void r.rmSync(e,{recursive:!0,force:!0});for(let n of r.readdirSync(e,{withFileTypes:!0})){var t;t=n.name,aL.has(t)&&r.rmSync(o.join(e,n.name),{recursive:!0,force:!0})}}catch{}}let aL=new Set(["Build","BuildCache.noindex","Index.noindex","Logs","ModuleCache.noindex","SDKStatCaches.noindex","SourcePackages","TextBasedInstallAPI","info.plist"]);function aR(e,t){if(!r.existsSync(e))return null;let n=[],i=[e];for(;i.length>0;){let e=i.pop();for(let t of r.readdirSync(e,{withFileTypes:!0})){let a=o.join(e,t.name);if(t.isDirectory()){i.push(a);continue}if(t.isFile()&&t.name.endsWith(".xctestrun"))try{let e=r.statSync(a);n.push({path:a,mtimeMs:e.mtimeMs})}catch{}}}return 0===n.length?null:(n.sort((e,n)=>{if(t){let r=aT(n.path,t)-aT(e.path,t);if(0!==r)return r}return n.mtimeMs-e.mtimeMs||e.path.localeCompare(n.path)}),n[0]?.path??null)}function aT(e,t){var n;let r=0,i=e.toLowerCase();o.basename(i).startsWith("agentdevicerunner.env.")&&(r-=1e3),i.includes(`${o.sep}macos${o.sep}`)&&(r-=5e3);let a="macos"===(n=t).platform?{preferred:["macos"],disallowed:["iphoneos","iphonesimulator","appletvos","appletvsimulator"]}:"tv"===n.target?"simulator"===n.kind?{preferred:["appletvsimulator"],disallowed:["appletvos","iphoneos","iphonesimulator","macos"]}:{preferred:["appletvos"],disallowed:["appletvsimulator","iphoneos","iphonesimulator","macos"]}:"simulator"===n.kind?{preferred:["iphonesimulator"],disallowed:["iphoneos","appletvos","appletvsimulator","macos"]}:{preferred:["iphoneos"],disallowed:["iphonesimulator","appletvos","appletvsimulator","macos"]};return a.preferred.length>0&&(a.preferred.some(e=>i.includes(e))?r+=2e3:r-=500),a.disallowed.some(e=>i.includes(e))&&(r-=2500),r}function aP(e,t){try{let n=r.readFileSync(e,"utf8"),i=new Set([t]);try{i.add(r.realpathSync(t))}catch{}for(let e of i)if(n.includes(e))return!0;return!1}catch{return!1}}async function a$(e,t,n){let i,a=o.dirname(e),s=n.replace(/[^a-zA-Z0-9._-]/g,"_"),l=o.join(a,`AgentDeviceRunner.env.${s}.json`),u=o.join(a,`AgentDeviceRunner.env.${s}.xctestrun`),d=await M("plutil",["-convert","json","-o","-",e],{allowFailure:!0});if(0!==d.exitCode||!d.stdout.trim())throw new _("COMMAND_FAILED","Failed to read xctestrun plist",{xctestrunPath:e,stderr:d.stderr});try{i=JSON.parse(d.stdout)}catch(t){throw new _("COMMAND_FAILED","Failed to parse xctestrun JSON",{xctestrunPath:e,error:String(t)})}let c=e=>{e.EnvironmentVariables={...e.EnvironmentVariables??{},...t},e.UITestEnvironmentVariables={...e.UITestEnvironmentVariables??{},...t},e.UITargetAppEnvironmentVariables={...e.UITargetAppEnvironmentVariables??{},...t},e.TestingEnvironmentVariables={...e.TestingEnvironmentVariables??{},...t}},p=i.TestConfigurations;if(Array.isArray(p))for(let e of p){if(!e||"object"!=typeof e)continue;let t=e.TestTargets;if(Array.isArray(t))for(let e of t)e&&"object"==typeof e&&c(e)}for(let[e,t]of Object.entries(i))t&&"object"==typeof t&&t.TestBundlePath&&(c(t),i[e]=t);r.writeFileSync(l,JSON.stringify(i,null,2));let f=await M("plutil",["-convert","xml1","-o",u,l],{allowFailure:!0});if(0!==f.exitCode)throw new _("COMMAND_FAILED","Failed to write xctestrun plist",{tmpXctestrunPath:u,stderr:f.stderr});return{xctestrunPath:u,jsonPath:l}}async function aF(e,t,n,r){let i=function(e=process.env){let t=ax(e),n=aS(e);return[`AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID=${t}`,`AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID=${n}`]}(process.env),a=function(e=process.env,t=!1,n="ios"){if("macos"===n)return["CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO","CODE_SIGN_IDENTITY=","DEVELOPMENT_TEAM="];if(!t)return[];let r=e.AGENT_DEVICE_IOS_TEAM_ID?.trim()||"",i=e.AGENT_DEVICE_IOS_SIGNING_IDENTITY?.trim()||"",a=e.AGENT_DEVICE_IOS_PROVISIONING_PROFILE?.trim()||"",o=["CODE_SIGN_STYLE=Automatic"];return r&&o.push(`DEVELOPMENT_TEAM=${r}`),i&&o.push(`CODE_SIGN_IDENTITY=${i}`),a&&o.push(`PROVISIONING_PROFILE_SPECIFIER=${a}`),o}(process.env,"device"===e.kind,e.platform),o="device"===e.kind?["-allowProvisioningUpdates"]:[],s=await aM(e);try{var l;let s;await A("xcodebuild",["build-for-testing","-project",t,"-scheme","AgentDeviceRunner","-parallel-testing-enabled","NO",aV(e),"1","-destination",(l=e,s=aU(l),"macOS"===s?`platform=macOS,arch=${aG()}`:"simulator"===l.kind?`platform=${s} Simulator,id=${l.id}`:`generic/platform=${s}`),"-derivedDataPath",n,"COMPILER_INDEX_STORE_ENABLE=NO","ENABLE_CODE_COVERAGE=NO",...i,...o,...a],{detached:!0,onSpawn:e=>{aI.add(e),e.on("close",()=>{aI.delete(e)})},onStdoutChunk:e=>{aa(e,r.logPath,r.traceLogPath,r.verbose)},onStderrChunk:e=>{aa(e,r.logPath,r.traceLogPath,r.verbose)}})}catch(a){let e,t,n=a instanceof _?a:new _("COMMAND_FAILED",String(a)),i=(e=n.details?JSON.stringify(n.details):"",(t=`${n.message}
|
|
12
|
-
${e}`.toLowerCase()).includes("failed registering bundle identifier")||t.includes("app identifier")&&t.includes("not available")?"Set AGENT_DEVICE_IOS_BUNDLE_ID to a unique reverse-DNS value (for example, com.yourname.agentdevice.runner), then retry.":t.includes("requires a development team")?"Configure signing in Xcode or set AGENT_DEVICE_IOS_TEAM_ID for physical-device runs.":t.includes("no profiles for")||t.includes("provisioning profile")?"Install/select a valid iOS provisioning profile, or set AGENT_DEVICE_IOS_PROVISIONING_PROFILE.":t.includes("code signing")?"Enable Automatic Signing in Xcode or provide AGENT_DEVICE_IOS_TEAM_ID and optional AGENT_DEVICE_IOS_SIGNING_IDENTITY.":void 0);throw new _("COMMAND_FAILED","xcodebuild build-for-testing failed",{error:n.message,details:n.details,logPath:r.logPath,hint:
|
|
13
|
-
${n.stderr}`.toLowerCase();if(!e.includes("not installed")&&!e.includes("found nothing")&&!e.includes("no such file")&&!e.includes("invalid device")&&!e.includes("could not find"))continue}}}function
|
|
14
|
-
${e.stderr}`}function ot(e,t){return["-s",e,...t]}function on(e){return e.startsWith("emulator-")}function or(e){return e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim()}async function oi(e,t=iO){return M("adb",ot(e,["shell","getprop","sys.boot_completed"]),{allowFailure:!0,timeoutMs:t})}async function oa(e,t){let n=t.replace(/_/g," ").trim();if(!on(e))return n||e;let r=await os(e);return r?r.replace(/_/g," "):n||e}async function oo(e,t,n){try{return await n("adb",ot(e,t),{allowFailure:!0,timeoutMs:1e4})}catch(e){var r;if("COMMAND_FAILED"===(r=x(e)).code&&"number"==typeof r.details?.timeoutMs)return;throw e}}async function os(e,t=M){for(let n of["ro.boot.qemu.avd_name","persist.sys.avd_name"]){let r=await oo(e,["shell","getprop",n],t);if(!r)continue;let i=r.stdout.trim();if(0===r.exitCode&&i.length>0)return i}let n=await oo(e,["emu","avd","name"],t);if(!n)return;let r=function(e){let t=e.split("\n").map(e=>e.trim()).filter(e=>e.length>0);if(0!==t.length)return"OK"===t.at(-1)&&t.pop(),t.join("\n").trim()||void 0}(n.stdout);if(0===n.exitCode&&r)return r}async function ol(e,t){let n=oe(await M("adb",ot(e,["shell","cmd","package","has-feature",t]),{allowFailure:!0,timeoutMs:iO})).toLowerCase();return!!n.includes("true")||!n.includes("false")&&null}async function ou(e){return(await Promise.all(a7.map(async t=>await ol(e,t)))).some(e=>!0===e)}async function od(e){var t;let n;return"tv"===((n=oe(await M("adb",ot(e,["shell","getprop","ro.build.characteristics"]),{allowFailure:!0,timeoutMs:iO})).toLowerCase()).includes("tv")||n.includes("leanback")?"tv":null)||await ou(e)?"tv":(t=oe(await M("adb",ot(e,["shell","pm","list","features"]),{allowFailure:!0,timeoutMs:iO})),/feature:android\.(software\.leanback(_only)?|hardware\.type\.television)\b/i.test(t))?"tv":"mobile"}async function oc(e={}){if(await tW(),!await v("adb"))throw new _("TOOL_MISSING","adb not found in PATH");let t=e.serialAllowlist??t8(void 0),n=(await op()).filter(e=>!t||t.has(e.serial));return await Promise.all(n.map(async({serial:e,rawModel:t})=>{let[n,r,i]=await Promise.all([oa(e,t),ow(e),od(e)]);return{platform:"android",id:e,name:n,kind:on(e)?"emulator":"device",target:i,booted:r}}))}async function op(){return(await M("adb",["devices","-l"],{timeoutMs:iO})).stdout.split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith("List of devices")).map(e=>e.split(/\s+/)).filter(e=>"device"===e[1]).map(e=>({serial:e[0],rawModel:(e.find(e=>e.startsWith("model:"))??"").replace("model:","")}))}async function of(){let e=await M("emulator",["-list-avds"],{allowFailure:!0,timeoutMs:iO});if(0!==e.exitCode)throw new _("COMMAND_FAILED","Failed to list Android emulator AVDs",{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,hint:"Verify Android emulator tooling is installed and available in PATH."});return e.stdout.split("\n").map(e=>e.trim()).filter(e=>e.length>0)}async function oh(e){let t=Date.now();for(;Date.now()-t<e.timeoutMs;){try{let t=await om(e.avdName,e.serial);if(t)return{platform:"android",id:t,name:e.avdName,kind:"emulator",target:"mobile",booted:!1}}catch{}await new Promise(e=>setTimeout(e,1e3))}throw new _("COMMAND_FAILED","Android emulator did not appear in time",{avdName:e.avdName,serial:e.serial,timeoutMs:e.timeoutMs,hint:"Check emulator logs and verify the AVD can start from command line."})}async function om(e,t){let n=or(e);for(let e of(await op()).filter(e=>(!t||e.serial===t)&&on(e.serial)))if(or(e.rawModel)===n||or(await oa(e.serial,e.rawModel))===n)return e.serial}async function ow(e){try{let t=await oi(e);return"1"===t.stdout.trim()}catch{return!1}}async function og(e){var t,n;let r;await tW();let i=e.avdName.trim();if(!i)throw new _("INVALID_ARGS","Android emulator boot requires a non-empty AVD name.");let a=e.timeoutMs??12e4;if(!await v("adb"))throw new _("TOOL_MISSING","adb not found in PATH");if(!await v("emulator"))throw new _("TOOL_MISSING","emulator not found in PATH");let o=await of(),s=function(e,t){let n=e.find(e=>e===t);if(n)return n;let r=or(t);return e.find(e=>or(e)===r)}(o,i);if(!s)throw new _("DEVICE_NOT_FOUND",`No Android emulator AVD named ${e.avdName}`,{requestedAvdName:i,availableAvds:o,hint:"Run `emulator -list-avds` and pass an existing AVD name to --device."});let l=Date.now(),u=(t=await oc(),n=e.serial,r=or(s),t.find(e=>"android"===e.platform&&"emulator"===e.kind&&(!n||e.id===n)&&or(e.name)===r));if(!u){let t=["-avd",s];e.headless&&t.push("-no-window","-no-audio"),S("emulator",t)}let d=u??await oh({avdName:s,serial:e.serial,timeoutMs:a}),c=Math.max(1e3,a-(Date.now()-l));await oy(d.id,c);let p=(await oc()).find(e=>e.id===d.id);return p?{...p,name:s,booted:!0}:{...d,name:s,booted:!0}}async function oy(e,t=6e4){let n,r=ik.fromTimeoutMs(t),i=Math.max(1,Math.ceil(t/1e3)),a=!1;try{await iL(async({deadline:i})=>{if(i?.isExpired())throw a=!0,new _("COMMAND_FAILED","Android boot deadline exceeded",{serial:e,timeoutMs:t,elapsedMs:r.elapsedMs(),message:"timeout"});let o=Math.max(1e3,i?.remainingMs()??t),s=await oi(e,Math.min(o,iO));if(n=s,"1"!==s.stdout.trim())throw new _("COMMAND_FAILED","Android device is still booting",{serial:e,stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode})},{maxAttempts:i,baseDelayMs:1e3,maxDelayMs:1e3,jitter:0,shouldRetry:e=>{let t=iH({error:e,stdout:n?.stdout,stderr:n?.stderr,context:{platform:"android",phase:"boot"}});return"ADB_TRANSPORT_UNAVAILABLE"!==t&&"ANDROID_BOOT_TIMEOUT"!==t}},{deadline:r,phase:"boot",classifyReason:e=>iH({error:e,stdout:n?.stdout,stderr:n?.stderr,context:{platform:"android",phase:"boot"}})})}catch(c){let i=x(c),o=n?.stdout,s=n?.stderr,l=n?.exitCode,u=iH({error:c,stdout:o,stderr:s,context:{platform:"android",phase:"boot"}});"BOOT_COMMAND_FAILED"===u&&"Android device is still booting"===i.message&&(u="ANDROID_BOOT_TIMEOUT");let d={serial:e,timeoutMs:t,elapsedMs:r.elapsedMs(),reason:u,hint:iJ(u),stdout:o,stderr:s,exitCode:l};if(a||"ANDROID_BOOT_TIMEOUT"===u)throw new _("COMMAND_FAILED","Android device did not finish booting in time",d);if("TOOL_MISSING"===i.code)throw new _("TOOL_MISSING",i.message,{...d,...i.details??{}});if("ADB_TRANSPORT_UNAVAILABLE"===u)throw new _("COMMAND_FAILED",i.message,{...d,...i.details??{}});throw new _(i.code,i.message,{...d,...i.details??{}},i.cause)}}let ob=[".zip",".tar",".tar.gz",".tgz"];Object.freeze([...ob]);let ov=iY(process.env.AGENT_DEVICE_SOURCE_DOWNLOAD_TIMEOUT_MS,12e4,1e3),oI=["1","true","yes","on"];async function oA(e){let t=[];try{let n=await ox(e.source,{signal:e.signal,downloadTimeoutMs:e.downloadTimeoutMs});t.push(n.cleanup);let r=await oD(n.localPath,{archivePath:void 0,isInstallablePath:e.isInstallablePath,installableLabel:e.installableLabel,allowArchiveExtraction:!1!==e.allowArchiveExtraction,registerCleanup:e=>{t.push(e)}});return{archivePath:r.archivePath,installablePath:r.installablePath,cleanup:async()=>{await oL(t)}}}catch(e){throw await oL(t),e}}async function ox(e,t){if("path"===e.kind)return{localPath:eP(e.path),cleanup:async()=>{}};let n=await a.mkdtemp(o.join(p.tmpdir(),"agent-device-source-"));try{return{localPath:await oS(n,e.url,e.headers,t),cleanup:async()=>{await a.rm(n,{recursive:!0,force:!0})}}}catch(e){throw await a.rm(n,{recursive:!0,force:!0}),e}}async function oS(e,t,n,r){let i;try{i=new URL(t)}catch{throw new _("INVALID_ARGS",`Invalid source URL: ${t}`)}await oN(i);let s=r?.signal;if(s?.aborted)throw new _("COMMAND_FAILED","request canceled",{reason:"request_canceled"});let l=new AbortController,u=()=>{l.abort(s?.reason)};s?.addEventListener("abort",u,{once:!0});let d=r?.downloadTimeoutMs??ov,c=setTimeout(()=>{l.abort(Error("download timeout"))},d);try{let t=await fetch(i,{headers:n,redirect:"follow",signal:l.signal});if(!t.ok)throw new _("COMMAND_FAILED",`Failed to download app source: ${t.status} ${t.statusText}`,{status:t.status,statusText:t.statusText,url:i.toString()});let r=function(e,t){let n=e.headers.get("content-disposition"),r=n?.match(/filename\*?=(?:UTF-8'')?"?([^";]+)"?/i),i=r?.[1]?.trim();if(i)return o.basename(i);let a=o.basename(t.pathname);return a||"downloaded-artifact.bin"}(t,i),s=o.join(e,r),u=t.body;if(!u)throw new _("COMMAND_FAILED","Download response body was empty",{url:i.toString()});let d=await a.open(s,"w");try{for await(let e of u)await d.write(e)}finally{await d.close()}return s}catch(e){if(s?.aborted)throw new _("COMMAND_FAILED","request canceled",{reason:"request_canceled"},e);if(l.signal.aborted)throw new _("COMMAND_FAILED",`App source download timed out after ${d}ms`,{timeoutMs:d,url:i.toString()},e);throw e}finally{s?.removeEventListener("abort",u),clearTimeout(c)}}async function oN(e){if("http:"!==e.protocol&&"https:"!==e.protocol)throw new _("INVALID_ARGS",`Unsupported source URL protocol: ${e.protocol}`);if(!oI.includes((process.env.AGENT_DEVICE_ALLOW_PRIVATE_SOURCE_URLS??"").toLowerCase())){var t;if(!(t=e.hostname.toLowerCase())||"localhost"===t||t.endsWith(".localhost")||oM(t))throw new _("INVALID_ARGS",`Source URL host is not allowed: ${e.hostname}`,{hint:"Use a public artifact URL, or set AGENT_DEVICE_ALLOW_PRIVATE_SOURCE_URLS=1 for trusted private-network daemons."});if((await g.lookup(e.hostname,{all:!0,verbatim:!0}).catch(()=>[])).some(e=>oM(e.address)))throw new _("INVALID_ARGS",`Source URL host resolved to a private or loopback address: ${e.hostname}`,{hint:"Use a public artifact URL, or set AGENT_DEVICE_ALLOW_PRIVATE_SOURCE_URLS=1 for trusted private-network daemons."})}}function o_(e){var t,n,r,i;let a=e instanceof URL?e:new URL(e),o=a.hostname.toLowerCase();if(!o)return!1;let s=a.pathname;return t=o,n=s,("api.github.com"===t?/^\/repos\/[^/]+\/[^/]+\/actions\/artifacts\/\d+\/zip$/i.test(n):"github.com"===t&&/^\/[^/]+\/[^/]+\/(?:actions\/runs\/\d+\/artifacts\/\d+|suites\/\d+\/artifacts\/\d+)$/i.test(n))||(r=o,i=s,("expo.dev"===r||!!r.endsWith(".expo.dev"))&&/^\/(?:artifacts\/eas\/|accounts\/[^/]+\/projects\/[^/]+\/builds\/)/i.test(i))}function oM(e){let t,n=m.isIP(e);return 4===n?function(e){let t=e.split(".").map(e=>Number.parseInt(e,10));if(4!==t.length||t.some(e=>Number.isNaN(e)||e<0||e>255))return!1;let[n,r]=t;return 10===n||127===n||169===n&&254===r||172===n&&!!(r>=16)&&!!(r<=31)||192===n&&168===r}(e):6===n&&!!("::1"===(t=e.toLowerCase())||t.startsWith("fc")||t.startsWith("fd")||t.startsWith("fe80:"))}async function oD(e,t){let n=await a.stat(e).catch(()=>null);if(!n)throw new _("INVALID_ARGS",`App source not found: ${e}`);if(t.isInstallablePath(e,n))return{archivePath:t.archivePath,installablePath:e};if(n.isFile()&&ok(e)){if(!t.allowArchiveExtraction)throw new _("INVALID_ARGS",`URL sources must point directly to a ${t.installableLabel}; archive extraction is not allowed`,{path:e});let n=await oC(e);return t.registerCleanup(n.cleanup),await oD(n.outputPath,{...t,archivePath:t.archivePath??e})}if(n.isDirectory()){let n=await oE(e,t.isInstallablePath);if(1===n.length)return{archivePath:t.archivePath,installablePath:n[0]};if(n.length>1)throw new _("INVALID_ARGS",`Found multiple ${t.installableLabel} candidates under ${e}`,{matches:n});let r=await oE(e,(e,t)=>t.isFile()&&ok(e));if(1===r.length){if(!t.allowArchiveExtraction)throw new _("INVALID_ARGS",`URL sources must point directly to a ${t.installableLabel}; nested archives are not allowed`,{path:r[0]});let e=await oC(r[0]);return t.registerCleanup(e.cleanup),await oD(e.outputPath,{...t,archivePath:t.archivePath??r[0]})}if(r.length>1)throw new _("INVALID_ARGS",`Found multiple nested archives under ${e}; expected one ${t.installableLabel} source`,{matches:r})}throw new _("INVALID_ARGS",`Expected ${t.installableLabel} source, but got ${e}`)}async function oE(e,t){let n=[],r=[{path:e,depth:0}];for(;r.length>0;){let e=r.shift();if(!e)continue;let i=await a.readdir(e.path,{withFileTypes:!0});for(let a of(i.sort((e,t)=>e.name.localeCompare(t.name)),i)){let i=o.join(e.path,a.name);if(t(i,a)){n.push(i);continue}a.isDirectory()&&e.depth<5&&r.push({path:i,depth:e.depth+1})}}return n}async function oC(e){let t=await a.mkdtemp(o.join(p.tmpdir(),"agent-device-archive-"));try{return e.toLowerCase().endsWith(".zip")?await oO(e,t):e.toLowerCase().endsWith(".tar.gz")||e.toLowerCase().endsWith(".tgz")?await M("tar",["-xzf",e,"-C",t]):await M("tar",["-xf",e,"-C",t]),{outputPath:t,cleanup:async()=>{await a.rm(t,{recursive:!0,force:!0})}}}catch(e){throw await a.rm(t,{recursive:!0,force:!0}),e}}async function oO(e,t){await M("unzip",["-q",e,"-d",t])}function ok(e){let t=e.toLowerCase();return ob.some(e=>t.endsWith(e))}async function oL(e){for(let t=e.length-1;t>=0;t-=1)await e[t]()}let oR=new b("utf-16le");async function oT(e){for(let n of["AndroidManifest.xml","base/manifest/AndroidManifest.xml"]){var t;let r=await oP(e,n);if(!r)continue;let i=(t=r).subarray(0,Math.min(t.length,128)).toString("utf8").trimStart().startsWith("<")?function(e){let t=e.match(/<manifest\b[^>]*\bpackage\s*=\s*["']([^"']+)["']/i);return t?.[1]}(t.toString("utf8")):function(e){let t;if(!(e.length<8)&&3===e.readUInt16LE(0))for(let n=e.readUInt16LE(2);n+8<=e.length;){let r=e.readUInt16LE(n),i=e.readUInt16LE(n+2),a=e.readUInt32LE(n+4);if(a<=0||n+a>e.length)break;if(1===r)t=function(e){if(e.length<28)return[];let t=e.readUInt32LE(8),n=e.readUInt32LE(16),r=e.readUInt32LE(20),i=(256&n)!=0,a=[];for(let n=0;n<t;n+=1){let t=28+4*n;if(t+4>e.length)break;let o=r+e.readUInt32LE(t);a.push(i?function(e,t){let[,n]=o$(e,t),[r,i]=o$(e,t+n),a=t+n+i;return e.subarray(a,a+r).toString("utf8")}(e,o):function(e,t){let[n,r]=function(e,t){let n=e.readUInt16LE(t);return(32768&n)==0?[n,2]:[(32767&n)<<16|e.readUInt16LE(t+2),4]}(e,t),i=t+r;return oR.decode(e.subarray(i,i+2*n))}(e,o))}return a}(e.subarray(n,n+a));else if(258===r&&t){let r=function(e,t,n,r){if(n<36||t+n>e.length||"manifest"!==r[e.readUInt32LE(t+20)])return;let i=e.readUInt16LE(t+24),a=e.readUInt16LE(t+26),o=e.readUInt16LE(t+28),s=t+i;for(let t=0;t<o;t+=1){let n=s+t*a;if(n+20>e.length)break;if("package"!==r[e.readUInt32LE(n+4)])continue;let i=e.readUInt32LE(n+8);if(0xffffffff!==i)return r[i];let o=e.readUInt8(n+15),l=e.readUInt32LE(n+16);if(3===o)return r[l];break}}(e,n,i,t);if(r)return r}n+=a}}(t);if(i)return i}return await oF(e)}async function oP(e,t){try{let n=await M("unzip",["-p",e,t],{allowFailure:!0,binaryStdout:!0});if(0!==n.exitCode||!n.stdoutBuffer||0===n.stdoutBuffer.length)return;return n.stdoutBuffer}catch{return}}function o$(e,t){let n=e.readUInt8(t);return(128&n)==0?[n,1]:[(127&n)<<8|e.readUInt8(t+1),2]}async function oF(e){let t=await oU();if(!t)return;let n=await M(t,["dump","badging",e],{allowFailure:!0});if(0!==n.exitCode)return;let r=n.stdout.match(/package:\s+name='([^']+)'/);return r?.[1]}async function oU(){if(void 0!==e)return e??void 0;try{for(let t of tj()){let n=o.join(t,"build-tools");try{for(let t of(await y.readdir(n)).sort((e,t)=>t.localeCompare(e,void 0,{numeric:!0}))){let r=o.join(n,t,"aapt");if(o.isAbsolute(r)&&await E(r))return e=r,r}}catch{}}}catch{}e=null}async function oG(e,t){let n="url"===e.kind&&o_(e.url),r=await oA({source:e,isInstallablePath:(e,t)=>{var n;let r;return t.isFile()&&(n=e,".apk"===(r=o.extname(n).toLowerCase())||".aab"===r)},installableLabel:"Android installable (.apk or .aab)",allowArchiveExtraction:"url"!==e.kind||n,signal:t?.signal}),i=t?.resolveIdentity===!1?{}:await oV(r.installablePath);return{archivePath:r.archivePath,installablePath:r.installablePath,packageName:i.packageName,cleanup:r.cleanup}}async function oV(e){let t=o.extname(e).toLowerCase();return".apk"!==t&&".aab"!==t?{}:{packageName:await oT(e)}}function oB(e,t){let n=0;for(;n<e.length&&function(e,t){if(!e)return!1;let n=e.charCodeAt(0);return n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||"_"===e||"."===e||t&&"$"===e}(e[n],t);)n+=1;return e.slice(0,n)}let oj={settings:{type:"intent",value:"android.settings.SETTINGS"}},oq="android.intent.category.LAUNCHER",oW="android.intent.category.LEANBACK_LAUNCHER",oz="android.intent.category.DEFAULT",oX="Run agent-device apps --platform android to discover the installed package name, then retry open with that exact package.";async function oY(e,t){let n=t.trim();if("package"===tZ(n))return{type:"package",value:n};let r=oj[n.toLowerCase()];if(r)return r;let i=(await M("adb",tz(e,["shell","pm","list","packages"]))).stdout.split("\n").map(e=>e.replace("package:","").trim()).filter(Boolean).filter(e=>e.toLowerCase().includes(n.toLowerCase()));if(1===i.length)return{type:"package",value:i[0]};if(i.length>1)throw new _("INVALID_ARGS",`Multiple packages matched "${t}"`,{matches:i,hint:"Run agent-device apps --platform android to see the exact installed package names before retrying open."});throw new _("APP_NOT_INSTALLED",`No package found matching "${t}"`,{hint:oX})}async function oH(e,t="all"){let n=await oJ(e);return("user-installed"===t?(await oZ(e)).filter(e=>n.has(e)):Array.from(n)).sort((e,t)=>e.localeCompare(t)).map(e=>({package:e,name:oQ(e)}))}async function oJ(e){let t=new Set;for(let n of oK(e,{includeFallbackWhenUnknown:!0})){let r=await M("adb",tz(e,["shell","cmd","package","query-activities","--brief","-a","android.intent.action.MAIN","-c",n]),{allowFailure:!0});if(0===r.exitCode&&0!==r.stdout.trim().length)for(let e of function(e){let t=new Set;for(let n of e.split("\n")){let e=n.trim();if(!e)continue;let r=e.split(/\s+/)[0],i=r.includes("/")?r.split("/")[0]:r;i&&t.add(i)}return Array.from(t)}(r.stdout))t.add(e)}return t}function oK(e,t={}){return"tv"===e.target?[oW]:"mobile"===e.target?[oq]:t.includeFallbackWhenUnknown?[oq,oW]:[oq]}async function oZ(e){return(await M("adb",tz(e,["shell","pm","list","packages","-3"]))).stdout.split("\n").map(e=>{let t=e.trim();return t.startsWith("package:")?t.slice(8):t}).filter(Boolean)}function oQ(e){let t=new Set(["com","android","google","app","apps","service","services","mobile","client"]),n=e.split(".").flatMap(e=>e.split(/[_-]+/)).map(e=>e.trim().toLowerCase()).filter(e=>e.length>0),r=n[n.length-1]??e;for(let e=n.length-1;e>=0;e-=1){let i=n[e];if(!t.has(i)){r=i;break}}return r.split(/[^a-z0-9]+/i).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}async function o0(e){let t=await o1(e,[["shell","dumpsys","window","windows"],["shell","dumpsys","window"]]);if(t)return t;let n=await o1(e,[["shell","dumpsys","activity","activities"],["shell","dumpsys","activity"]]);return n||{}}async function o1(e,t){for(let n of t){let t=function(e){let t=e.split("\n");for(let e of["mCurrentFocus=Window{","mFocusedApp=AppWindowToken{","mResumedActivity:","ResumedActivity:"])for(let n of t){let t=n.indexOf(e);if(-1===t)continue;let r=function(e){for(let t of e.trim().split(/\s+/)){let e=t.indexOf("/");if(e<=0)continue;let n=oB(t.slice(0,e),!1),r=oB(t.slice(e+1),!0);if(n&&r&&n.length===e)return{package:n,activity:r}}return null}(n.slice(t+e.length));if(r)return r}return null}((await M("adb",tz(e,n),{allowFailure:!0})).stdout??"");if(t)return t}return null}async function o2(e,t,n){var r,i;let a;e.booted||await oy(e.id);let o=t.trim();if(a6(o)){if(n)throw new _("INVALID_ARGS","Activity override is not supported when opening a deep link URL");await M("adb",tz(e,["shell","am","start","-W","-a","android.intent.action.VIEW","-d",o]));return}let s=await oY(e,t),l=oK(e)[0]??oq;if("intent"===s.type){if(n)throw new _("INVALID_ARGS","Activity override requires a package name, not an intent");await M("adb",tz(e,["shell","am","start","-W","-a",s.value]));return}if(n){let t=n.includes("/")?n:`${s.value}/${n.startsWith(".")?n:`.${n}`}`;try{await M("adb",tz(e,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",oz,"-c",l,"-n",t]))}catch(t){throw await o5(e,s.value,t),t}return}let u=await M("adb",tz(e,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",oz,"-c",l,"-p",s.value]),{allowFailure:!0});if(0===u.exitCode&&(r=u.stdout,i=u.stderr,a=`${r}
|
|
15
|
-
${
|
|
16
|
-
${n.stderr}`;return!!(0===n.exitCode&&/\bpackage:/i.test(r))||(
|
|
17
|
-
${String(n.details?.stderr??"")}`:"")||!await
|
|
18
|
-
${r.stderr}`.toLowerCase();if(!e.includes("unknown package")&&!e.includes("not installed"))throw new _("COMMAND_FAILED",`adb uninstall failed for ${n.value}`,{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode})}return{package:n.value}}let st=null;async function sn(){let e=`${process.env.PATH??""}::${process.env.AGENT_DEVICE_BUNDLETOOL_JAR??""}`;if(st?.key===e)return st.invocation;if(await v("bundletool")){let t={cmd:"bundletool",prefixArgs:[]};return st={key:e,invocation:t},t}let t=await I(process.env.AGENT_DEVICE_BUNDLETOOL_JAR,"AGENT_DEVICE_BUNDLETOOL_JAR");if(!t)throw new _("TOOL_MISSING","bundletool not found in PATH. Install bundletool or set AGENT_DEVICE_BUNDLETOOL_JAR to a bundletool-all.jar path.");let n={cmd:"java",prefixArgs:["-jar",t]};return st={key:e,invocation:n},n}async function sr(e){let t=await sn();await M(t.cmd,[...t.prefixArgs,...e])}async function si(e,t){let n,r=await a.mkdtemp(o.join(p.tmpdir(),"agent-device-aab-")),i=o.join(r,"bundle.apks"),s=(n=process.env.AGENT_DEVICE_ANDROID_BUNDLETOOL_MODE?.trim())&&n.length>0?n:"universal";try{await sr(["build-apks","--bundle",t,"--output",i,"--mode",s]),await sr(["install-apks","--apks",i,"--device-id",e.id])}finally{await a.rm(r,{recursive:!0,force:!0})}}async function sa(e,t){".aab"===o.extname(t).toLowerCase()?await si(e,t):await M("adb",tz(e,["install","-r",t]))}async function so(e){return new Set((await M("adb",tz(e,["shell","pm","list","packages"]))).stdout.split("\n").map(e=>e.replace("package:","").trim()).filter(Boolean))}async function ss(e,t){let n=Array.from(await so(e)).filter(e=>!t.has(e));if(1===n.length)return n[0]}async function sl(e,t){e.booted||await oy(e.id),await sa(e,t)}async function su(e,t,n){let r=n?void 0:await so(e);return await sl(e,t),n??(r?await ss(e,r):void 0)}async function sd(e,t){e.booted||await oy(e.id);let n=await oG({kind:"path",path:t});try{let t=await su(e,n.installablePath,n.packageName),r=t?oQ(t):void 0;return{archivePath:n.archivePath,installablePath:n.installablePath,packageName:t,appName:r,launchTarget:t}}finally{await n.cleanup()}}async function sc(e,t,n){e.booted||await oy(e.id);let{package:r}=await se(e,t),i=await oG({kind:"path",path:n},{resolveIdentity:!1});try{return await sl(e,i.installablePath),{package:r}}finally{await i.cleanup()}}function sp(e){let t=e.direction,n="up"===t||"down"===t?e.referenceHeight:e.referenceWidth,r=function(e){if(void 0===e)return .6;if(!Number.isFinite(e)||e<=0)throw new _("INVALID_ARGS","scroll amount must be a positive number");return e}(e.amount),i=void 0!==e.pixels?function(e){if(!Number.isFinite(e)||e<=0)throw new _("INVALID_ARGS","scroll pixels must be a positive integer");return Math.max(1,Math.round(e))}(e.pixels):Math.round(n*r),a=Math.max(1,Math.round(.05*n)),o=Math.max(1,Math.min(i,Math.max(1,n-2*a))),s=Math.round(o/2),l=Math.round(e.referenceWidth/2),u=Math.round(e.referenceHeight/2),d=(n,r,i,a)=>({direction:t,x1:n,y1:r,x2:i,y2:a,referenceWidth:e.referenceWidth,referenceHeight:e.referenceHeight,amount:e.amount,pixels:o});switch(t){case"up":return d(l,u-s,l,u+s);case"down":return d(l,u+s,l,u-s);case"left":return d(l-s,u,l+s,u);case"right":return d(l+s,u,l-s,u)}}function sf(e,t,n){let r=function(e){let t=0,n=0,r=[...e.children];for(;r.length>0;){let e=r.pop();t+=1,n=Math.max(n,e.depth),r.push(...e.children)}return{rawNodeCount:t,maxDepth:n}}(e),i=[],a=[],o=!1,s=n.depth??1/0,l=n.scope?function(e,t){let n=t.toLowerCase(),r=[...e.children],i=0;for(;i<r.length;){let e=r[i++],t=e.label?.toLowerCase()??"",a=e.value?.toLowerCase()??"",o=e.identifier?.toLowerCase()??"";if(t.includes(n)||a.includes(n)||o.includes(n))return e;r.push(...e.children)}return null}(e,n.scope):null,u=l?[l]:e.children,d=new Map,c=e=>{let t=d.get(e);if(void 0!==t)return t;for(let t of e.children)if(t.hittable||c(t))return d.set(e,!0),!0;return d.set(e,!1),!1},p=(e,r,l,u=!1,d=!1)=>{if(i.length>=t){o=!0;return}if(r>s)return;let f=!!n.raw||function(e,t,n,r,i){var a;let o,s=sy(e.type),l=!!(e.label&&e.label.trim().length>0),u=!!(e.identifier&&e.identifier.trim().length>0),d=l&&!sb(e.label??""),c=u&&!sb(e.identifier??""),p=(o=(a=s).split(".").pop()??a).includes("layout")||"viewgroup"===o||"view"===o,f="imageview"===s||"imagebutton"===s;if(t.interactiveOnly)return!!(e.hittable||ec(s)&&r)||!!(d||c)&&!f&&(!p||!!i)&&(n||r||i);return t.compact?d||c||!!e.hittable:!p&&!f||!!e.hittable||!!d||!!c&&!!r||r}(e,n,u,c(e),d),h=l;f&&(h=i.length,a.push(e),i.push({index:h,type:e.type??void 0,label:e.label??void 0,value:e.value??void 0,identifier:e.identifier??void 0,rect:e.rect,enabled:e.enabled,hittable:e.hittable,depth:r,parentIndex:l,...e.hiddenContentAbove?{hiddenContentAbove:!0}:{},...e.hiddenContentBelow?{hiddenContentBelow:!0}:{}}));let m=u||!!e.hittable,w=d||function(e){if(!e)return!1;let t=sy(e);return t.includes("recyclerview")||t.includes("listview")||t.includes("gridview")}(e.type);for(let t of e.children)if(p(t,r+1,h,m,w),o)return};for(let e of u)if(p(e,0,void 0,!1,!1),o)break;return o?{nodes:i,sourceNodes:a,truncated:o,analysis:r}:{nodes:i,sourceNodes:a,analysis:r}}function sh(e){let t=function(e){let t=new Map,n=e.indexOf(" "),r=e.lastIndexOf(">");if(n<0||r<=n)return t;let i=/([^\s=/>]+)\s*=\s*(["'])([\s\S]*?)\2/y,a=n;for(;a<r;){for(;a<r;){let t=e[a];if(" "!==t&&"\n"!==t&&"\r"!==t&&" "!==t)break;a+=1}if(a>=r)break;let n=e[a];if("/"===n||">"===n)break;i.lastIndex=a;let o=i.exec(e);if(!o)break;t.set(o[1],o[3]),a=i.lastIndex}return t}(e),n=e=>{let n=sm(t,e);if(null!==n)return"true"===n};return{text:sm(t,"text"),desc:sm(t,"content-desc"),resourceId:sm(t,"resource-id"),className:sm(t,"class"),bounds:sm(t,"bounds"),clickable:n("clickable"),enabled:n("enabled"),focusable:n("focusable"),focused:n("focused")}}function sm(e,t){return e.get(t)??null}function sw(e){if(!e)return;let t=/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/.exec(e);if(!t)return;let n=Number(t[1]),r=Number(t[2]);return{x:n,y:r,width:Math.max(0,Number(t[3])-n),height:Math.max(0,Number(t[4])-r)}}function sg(e){let t={type:null,label:null,value:null,identifier:null,depth:-1,children:[]},n=[t],r=/<node\b[^>]*>|<\/node>/g,i=r.exec(e);for(;i;){let t=i[0];if(t.startsWith("</node")){n.length>1&&n.pop(),i=r.exec(e);continue}let a=sh(t),o=sw(a.bounds),s=n[n.length-1],l={type:a.className,label:a.text||a.desc,value:a.text,identifier:a.resourceId,rect:o,enabled:a.enabled,hittable:a.clickable??a.focusable,depth:s.depth+1,parentIndex:void 0,children:[]};s.children.push(l),t.endsWith("/>")||n.push(l),i=r.exec(e)}return t}function sy(e){return e?e.toLowerCase():""}function sb(e){let t=e.trim();return!!t&&/^[\w.]+:id\/[\w.-]+$/i.test(t)}function sv(e){if(0===e.length)return null;let t=[...e].sort((e,t)=>e-t);return t[Math.floor(t.length/2)]??null}function sI(e,t){let n=Math.max(24,Math.round(.2*Math.min(e.size,t.size))),r=Math.max(48,Math.round(.15*Math.min(e.crossSize,t.crossSize)));return Math.abs(e.size-t.size)<=n&&Math.abs(e.crossSize-t.crossSize)<=r}function sA(e,t){return{start:e.y-t.y,size:e.height,crossSize:e.width}}async function sx(e,t={}){let n=await sN(e);if(!t.interactiveOnly){let r=function(e,t){let{sourceNodes:n,...r}=sf(sg(e),800,t);return r}(n,t);return await sS(e,r.nodes),r}let r=sg(n),i=sf(r,800,{...t,interactiveOnly:!1});await sS(e,i.nodes),function(e){if(0===e.length||e.some(e=>e.hiddenContentAbove||e.hiddenContentBelow))return;let t=new Map(ef(ei(e)).nodes.filter(e=>e.hiddenContentAbove||e.hiddenContentBelow).map(e=>[e.index,e]));for(let n of e){let e=t.get(n.index);e&&(e.hiddenContentAbove&&(n.hiddenContentAbove=!0),e.hiddenContentBelow&&(n.hiddenContentBelow=!0))}}(i.nodes),function(e){for(let[t,n]of e.sourceNodes.entries()){let r=e.nodes[t];r&&(r.hiddenContentAbove&&(n.hiddenContentAbove=!0),r.hiddenContentBelow&&(n.hiddenContentBelow=!0))}}(i);let{sourceNodes:a,...o}=sf(r,800,t);return o}async function sS(e,t){if(!t.some(e=>ec(e.type)))return;let n=await sE(e);n&&function(e,t){let n=function(e){let t={className:"root",rect:{x:0,y:0,width:0,height:0},children:[]},n=[{indent:-1,node:t}],r=/^(\s*)([\w.$]+)\{[^}]* (-?\d+),(-?\d+)-(-?\d+),(-?\d+) #/;for(let t of e.split("\n")){let e=r.exec(t);if(!e)continue;let i=e[1].length,a=Number(e[3]),o=Number(e[4]),s=Number(e[5]),l=Number(e[6]),u={className:e[2],rect:{x:a,y:o,width:Math.max(0,s-a),height:Math.max(0,l-o)},children:[]};for(;n.length>1&&i<=n[n.length-1].indent;)n.pop();n[n.length-1].node.children.push(u),n.push({indent:i,node:u})}return t.children.length>0?t:null}(t);if(!n)return;let r=function(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();if(ec(e.className)){let n=function(e){let t=e.children[0];if(!t)return null;let n=Math.max(t.rect.height,...t.children.map(e=>e.rect.y+e.rect.height)),r=t.children.filter(e=>e.rect.height>0).map(t=>sA(t.rect,e.rect)).sort((e,t)=>e.start-t.start);return 0===r.length?null:{rect:e.rect,contentExtent:n,contentBlocks:r}}(e);n&&t.push(n)}n.push(...e.children)}return t}(n);if(0!==r.length)for(let t of e){if(!t.rect||!ec(t.type))continue;let n=function(e,t){let n=null,r=1/0;for(let i of t){let t=Math.abs(i.rect.width-e.width)+Math.abs(i.rect.height-e.height);if(t>32)continue;let a=4*t+(Math.abs(i.rect.x-e.x)+Math.abs(i.rect.y-e.y));a<r&&(n=i,r=a)}return n}(t.rect,r);if(!n)continue;let i=function(e,t){let n=function(e,t){let n=t,r=new Set;for(;!r.has(n.index);){var i,a;r.add(n.index);let o=e.filter(e=>e.parentIndex===n.index&&e.rect);if(1!==o.length)return n;let s=o[0];if(i=s.rect,a=t.rect,i.x!==a.x||i.y!==a.y||i.width!==a.width||i.height!==a.height)return n;n=s}return t}(e,t);return e.filter(e=>e.parentIndex===n.index&&e.rect).map(e=>e.rect).filter(e=>e.height>0).sort((e,t)=>e.y-t.y).map(e=>sA(e,t.rect))}(e,t),a=function(e){let{viewportRect:t,visibleBlocks:n,nativeScrollView:r}=e;if(0===n.length||0===r.contentBlocks.length)return null;let i=function(e){if(0===e.contentBlocks.length)return null;let t=e.contentBlocks[0],n=e.contentBlocks[e.contentBlocks.length-1];if(!t||!n)return null;let r=sv(e.contentBlocks.map(e=>e.size))??e.rect.height,i=Math.max(48,Math.round(.5*r)),a=Math.max(24,Math.round(.25*r)),o=t.start>=i,s=e.contentExtent-(n.start+n.size)>=a;return o||s?{above:o,below:s}:null}(r),a=function(e,t){let n=new Map;for(let r of e)for(let e of t){if(!sI(r,e))continue;let t=r.start-e.start,i=8*Math.round(t/8),a=n.get(i)??[];a.push(t),n.set(i,a)}let r=null;for(let e of n.values())(!r||e.length>r.length)&&(r=e);if(!r||r.length<2)return null;let i=[...r].sort((e,t)=>e-t);return i[Math.floor(i.length/2)]??null}(r.contentBlocks,n)??function(e){let{nativeBlocks:t,visibleBlocks:n,viewportExtent:r,contentExtent:i}=e,a=[],o=[];for(let e of t)for(let t of n){if(!sI(e,t))continue;let n=e.start-t.start;16>=Math.abs(n)&&a.push(n),16>=Math.abs(n+r-i)&&o.push(n)}return o.length>0?sv(o):a.length>0?sv(a):null}({nativeBlocks:r.contentBlocks,visibleBlocks:n,viewportExtent:t.height,contentExtent:r.contentExtent});if(null===a)return i;let o=t.height;return{above:(i?.above??!1)||a>16,below:(i?.below??!1)||a+o<r.contentExtent-16}}({viewportRect:t.rect,visibleBlocks:i,nativeScrollView:n});a&&(a.above&&(t.hiddenContentAbove=!0),a.below&&(t.hiddenContentBelow=!0))}}(t,n)}async function sN(e){return iR(()=>s_(e),{shouldRetry:sD})}async function s_(e){var t,n,r;let i,a,o=await M("adb",tz(e,["exec-out","uiautomator","dump","/dev/tty"]),{allowFailure:!0}),s=sM(o.stdout,o.stderr);if(s)return s;let l="/sdcard/window_dump.xml",u=await M("adb",tz(e,["shell","uiautomator","dump",l]),{allowFailure:!0}),d=(t=l,n=u.stdout,r=u.stderr,i=`${n}
|
|
19
|
-
${r}`,
|
|
20
|
-
${t}`,r=n.indexOf("<?xml"),
|
|
21
|
-
${t.stderr}`.trim();return n.length>0?n:null}catch{return null}}async function sC(e,t,n){await M("adb",tz(e,["shell","input","tap",String(t),String(n)]))}async function sO(e,t,n,r,i,a=250){await M("adb",tz(e,["shell","input","swipe",String(t),String(n),String(r),String(i),String(a)]))}async function sk(e){await M("adb",tz(e,["shell","input","keyevent","4"]))}async function sL(e){await M("adb",tz(e,["shell","input","keyevent","3"]))}async function sR(e,t){let n=function(e){switch(e){case"portrait":return"0";case"landscape-left":return"1";case"portrait-upside-down":return"2";case"landscape-right":return"3";default:throw new _("INVALID_ARGS",`Unsupported Android rotation: ${e}`)}}(t);await M("adb",tz(e,["shell","settings","put","system","accelerometer_rotation","0"])),await M("adb",tz(e,["shell","settings","put","system","user_rotation",n]))}async function sT(e){await M("adb",tz(e,["shell","input","keyevent","187"]))}async function sP(e,t,n,r=800){await M("adb",tz(e,["shell","input","swipe",String(t),String(n),String(t),String(n),String(r)]))}async function s$(e,t,n=0){n>0&&Array.from(t).length>1?await sW(e,t,1,n):await sF(e,t)}async function sF(e,t){let n=sz(t);if(!n||"ok"!==await sX(e,t))try{let n=t.replace(/ /g,"%s");await M("adb",tz(e,["shell","input","text",n]))}catch(e){if(n&&function(e){if(!(e instanceof _)||"COMMAND_FAILED"!==e.code)return!1;let t=String(e.details?.stderr??"").toLowerCase();return!!(t.includes("exception occurred while executing 'text'")||t.includes("nullpointerexception")&&t.includes("inputshellcommand.sendtext"))}(e))throw new _("COMMAND_FAILED","Non-ASCII text input is not supported on this Android shell. Install an ADB keyboard IME or use ASCII input.",{textPreview:t.slice(0,32)},e instanceof Error?e:void 0);throw e}}async function sU(e,t,n){await sC(e,t,n)}async function sG(e,t,n,r,i=0){let a=Array.from(r).length,o=sz(r),s=[{strategy:"input_text",clearPadding:12,minClear:8,maxClear:48}];!o&&i<=0&&s.push({strategy:"clipboard_paste",clearPadding:12,minClear:8,maxClear:48}),(!o||i>0)&&s.push({strategy:"chunked_input",clearPadding:24,minClear:16,maxClear:96});let l=null;for(let o of s){var u,d;await sU(e,t,n);let s=(u=a+o.clearPadding,d=o.minClear,Math.max(d,Math.min(o.maxClear,u)));if(await sY(e,s),"input_text"===o.strategy)await s$(e,r,i);else if("clipboard_paste"===o.strategy){if("ok"!==await sX(e,r))continue}else await sW(e,r,1,i>0?i:15);let c=await sV(e,t,n,r);if(l=c.actual,c.ok)return}throw new _("COMMAND_FAILED","Android fill verification failed",{expected:r,actual:l??null})}async function sV(e,t,n,r){let i=null;for(let a of[0,150,350])if(a>0&&await tH(a),function(e,t){if(e===t)return!0;let n=sB(e),r=sB(t);return!!n&&!!r&&(!!(n===r||n.includes(r))||r.includes(n)&&n.length>=Math.max(4,Math.floor(.8*r.length)))}(i=await sH(e,t,n),r))return{ok:!0,actual:i};return{ok:!1,actual:i}}function sB(e){return(e??"").replace(/\s+/g," ").trim()}async function sj(e,t,n){let r=await sq(e),i=sp({direction:t,amount:n?.amount,pixels:n?.pixels,referenceWidth:r.width,referenceHeight:r.height});return await M("adb",tz(e,["shell","input","swipe",String(i.x1),String(i.y1),String(i.x2),String(i.y2),"300"])),i}async function sq(e){let t=(await M("adb",tz(e,["shell","wm","size"]))).stdout.match(/Physical size:\s*(\d+)x(\d+)/);if(!t)throw new _("COMMAND_FAILED","Unable to read screen size");return{width:Number(t[1]),height:Number(t[2])}}async function sW(e,t,n,r){let i=Math.max(1,Math.floor(n)),a=Array.from(t);for(let t=0;t<a.length;t+=i){let n=a.slice(t,t+i).join("");await sF(e,n),r>0&&t+i<a.length&&await tH(r)}}function sz(e){for(let t of e){let e=t.codePointAt(0);if(void 0!==e&&(e<32||e>126))return!0}return!1}async function sX(e,t){let n=await M("adb",tz(e,["shell","cmd","clipboard","set","text",t]),{allowFailure:!0});return 0!==n.exitCode?"failed":tY(n.stdout,n.stderr)?"unsupported":0===(await M("adb",tz(e,["shell","input","keyevent","KEYCODE_PASTE"]),{allowFailure:!0})).exitCode||0===(await M("adb",tz(e,["shell","input","keyevent","279"]),{allowFailure:!0})).exitCode?"ok":"failed"}async function sY(e,t){let n=Math.max(0,t);await M("adb",tz(e,["shell","input","keyevent","KEYCODE_MOVE_END"]),{allowFailure:!0});for(let t=0;t<n;t+=24){let r=Math.min(24,n-t);await M("adb",tz(e,["shell","input","keyevent",...Array(r).fill("KEYCODE_DEL")]),{allowFailure:!0})}}async function sH(e,t,n){let r,i=await sN(e),a=/<node\b[^>]*>/g,o=null,s=null,l=null;for(;null!==(r=a.exec(i));){let e=sh(r[0]),i=sw(e.bounds);if(!i)continue;let a=e.className??"",u=(e.text??"").replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&"),d=e.focused??!1;if(!u)continue;let c=Math.max(1,i.width*i.height),p=t>=i.x&&t<=i.x+i.width&&n>=i.y&&n<=i.y+i.height;if(d&&sJ(a)){(!o||c<=o.area)&&(o={text:u,area:c});continue}if(p&&sJ(a)){(!s||c<=s.area)&&(s={text:u,area:c});continue}p&&(!l||c<=l.area)&&(l={text:u,area:c})}return o?.text??s?.text??l?.text??null}function sJ(e){let t=e.toLowerCase();return t.includes("edittext")||t.includes("textfield")}async function sK(e){let t=await M("adb",tz(e,["shell","dumpsys","input_method"]),{allowFailure:!0});if(0!==t.exitCode)throw new _("COMMAND_FAILED","Failed to query Android keyboard state",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});return function(e){let t=function(e){let t=new Map;for(let n of e.matchAll(/\b(mInputShown|mIsInputViewShown|isInputViewShown)=([a-zA-Z]+)\b/g)){let e=n[1],r=n[2]?.toLowerCase();e&&("true"===r||"false"===r)&&t.set(e,"true"===r)}if(0===t.size)return null;for(let e of t.values())if(e)return!0;return!1}(e),n=t??!1;if(null===t){let t=e.match(/\bmImeWindowVis=0x([0-9a-fA-F]+)\b/);if(t?.[1]){let e=Number.parseInt(t[1],16);Number.isNaN(e)||(n=(1&e)!=0)}}let r=Array.from(e.matchAll(/\binputType=0x([0-9a-fA-F]+)\b/gi)),i=r.length>0?r[r.length-1]?.[1]:void 0,a=i?`0x${i.toLowerCase()}`:void 0;return{visible:n,inputType:a,type:a?function(e){let t=Number.parseInt(e.replace(/^0x/i,""),16);if(Number.isNaN(t))return"unknown";let n=15&t;if(2===n)return"number";if(3===n)return"phone";if(4===n)return"datetime";if(1!==n)return"unknown";let r=4080&t;return 32===r||208===r?"email":128===r||224===r||144===r?"password":"text"}(a):void 0}}(t.stdout)}async function sZ(e){let t=await sK(e),n=t,r=0;for(;n.visible&&r<2;)await M("adb",tz(e,["shell","input","keyevent","111"])),r+=1,await tH(120),n=await sK(e);if(t.visible&&n.visible)throw new _("UNSUPPORTED_OPERATION","Android keyboard dismiss is unavailable for the current IME without back navigation.",{attempts:r,inputType:n.inputType,type:n.type});return{attempts:r,wasVisible:t.visible,dismissed:t.visible&&!n.visible,visible:n.visible,inputType:n.inputType,type:n.type}}async function sQ(e){let t,n;return(n=(t=(await s1(e,["shell","cmd","clipboard","get","text"],"read")).replace(/\r\n/g,"\n").replace(/\n$/,"")).match(/^clipboard text:\s*(.*)$/i))?n[1]??"":"null"===t.trim().toLowerCase()?"":t}async function s0(e,t){await s1(e,["shell","cmd","clipboard","set","text",t],"write")}async function s1(e,t,n){let r=await M("adb",tz(e,t),{allowFailure:!0});if(tY(r.stdout,r.stderr))throw new _("UNSUPPORTED_OPERATION",`Android shell clipboard ${n} is not supported on this device.`);if(0!==r.exitCode)throw new _("COMMAND_FAILED",`Failed to ${n} Android clipboard text`,{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode});return r.stdout}let s2=["camera","microphone","photos","contacts","contacts-limited","notifications","calendar","location","location-always","media-library","motion","reminders","siri"];function s3(e){let t=e.trim().toLowerCase();if("grant"===t)return"grant";if("deny"===t)return"deny";if("reset"===t)return"reset";throw new _("INVALID_ARGS",`Invalid permission action: ${e}. Use grant|deny|reset.`)}function s4(e){let t=e?.trim().toLowerCase();if("camera"===t||"microphone"===t||"photos"===t||"contacts"===t||"contacts-limited"===t||"notifications"===t||"calendar"===t||"location"===t||"location-always"===t||"media-library"===t||"motion"===t||"reminders"===t||"siri"===t)return t;throw new _("INVALID_ARGS",`permission setting requires a target: ${s2.join("|")}`)}function s5(e){let t=e.trim().toLowerCase();if("light"===t)return"light";if("dark"===t)return"dark";if("toggle"===t)return"toggle";throw new _("INVALID_ARGS",`Invalid appearance state: ${e}. Use light|dark|toggle.`)}async function s8(e,t,n,r,i){switch(t.toLowerCase()){case"wifi":{let t=s9(n);await M("adb",tz(e,["shell","svc","wifi",t?"enable":"disable"]));return}case"airplane":{let t=s9(n);await M("adb",tz(e,["shell","settings","put","global","airplane_mode_on",t?"1":"0"])),await M("adb",tz(e,["shell","am","broadcast","-a","android.intent.action.AIRPLANE_MODE","--ez","state",t?"true":"false"]));return}case"location":{let t=s9(n);await M("adb",tz(e,["shell","settings","put","secure","location_mode",t?"3":"0"]));return}case"appearance":{let t=await s7(e,n);await M("adb",tz(e,["shell","cmd","uimode","night","dark"===t?"yes":"no"]));return}case"fingerprint":{let t=function(e){let t=e.trim().toLowerCase();if("match"===t)return"match";if("nonmatch"===t)return"nonmatch";throw new _("INVALID_ARGS",`Invalid fingerprint state: ${e}. Use match|nonmatch.`)}(n);await s6(e,t);return}case"permission":{if(!r)throw new _("INVALID_ARGS","permission setting requires an active app in session");let t=s3(n),a=function(e,t){let n=s4(e);if(t?.trim())throw new _("INVALID_ARGS",`Permission mode is only supported for photos. Received: ${t}.`);if("camera"===n)return{kind:"pm",value:"android.permission.CAMERA",type:"camera"};if("microphone"===n)return{kind:"pm",value:"android.permission.RECORD_AUDIO",type:"microphone"};if("photos"===n)return{kind:"pm",value:"android.permission.READ_MEDIA_IMAGES",type:"photos"};if("contacts"===n)return{kind:"pm",value:"android.permission.READ_CONTACTS",type:"contacts"};if("notifications"===n)return{kind:"notifications",appOps:"POST_NOTIFICATION",permission:"android.permission.POST_NOTIFICATIONS"};throw new _("INVALID_ARGS",`Unsupported permission target on Android: ${e}. Use camera|microphone|photos|contacts|notifications.`)}(i?.permissionTarget,i?.permissionMode);if("notifications"===a.kind)return void await lt(e,r,t,a);let o="grant"===t?"grant":"revoke";if("photos"===a.type)return void await le(e,r,o);await M("adb",tz(e,["shell","pm",o,r,a.value]));return}default:throw new _("INVALID_ARGS",`Unsupported setting: ${t}`)}}async function s6(e,t){var n;let r,i,a=(n=e,i=[["shell","cmd","fingerprint","touch",r="match"===t?"1":"9999"],["shell","cmd","fingerprint","finger",r]],"emulator"===n.kind&&i.push(["emu","finger","touch",r]),i),o=[];for(let t of a){let n=await M("adb",tz(e,t),{allowFailure:!0});if(0===n.exitCode)return;o.push({args:t,stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode})}let s=o.map(e=>({args:e.args.join(" "),exitCode:e.exitCode,stderr:e.stderr.slice(0,400)}));if(o.length>0&&o.every(e=>{var t,n;let r;return t=e.stdout,n=e.stderr,(r=`${t}
|
|
22
|
-
${n}`.toLowerCase()).includes("unknown command")||r.includes("can't find service: fingerprint")||r.includes("service fingerprint was not found")||r.includes("fingerprint cmd unavailable")||r.includes("emu command is not supported")||r.includes("emulator console is not running")||r.includes("fingerprint")&&r.includes("not found")}))throw new _("UNSUPPORTED_OPERATION","Android fingerprint simulation is not supported on this target/runtime.",{deviceId:e.id,action:t,hint:"Use an Android emulator with biometric support, or a device/runtime that exposes cmd fingerprint.",attempts:s});throw new _("COMMAND_FAILED","Failed to simulate Android fingerprint.",{deviceId:e.id,action:t,attempts:s})}function
|
|
23
|
-
${t}`);if(!n)return null;let r=n[1].toLowerCase();return"yes"===r?"dark":"no"===r?"light":"auto"===r?"auto":null}(r.stdout,r.stderr);if(!
|
|
24
|
-
${t}`.toLowerCase();return n.includes("device is busy")&&n.includes("connecting")?"iOS device is still connecting. Keep it unlocked and connected by cable until it is fully available in Xcode Devices, then retry.":n.includes("coredeviceservice")&&n.includes("timed out")?"CoreDevice service timed out. Reconnect the device and retry; if it persists restart Xcode and the iOS device.":null}function
|
|
25
|
-
${t.stderr}`.toLowerCase(),s=o.includes("already booted")||o.includes("current state: booted");if(0!==t.exitCode&&!s)throw new _("COMMAND_FAILED","simctl boot failed",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});let l=await
|
|
26
|
-
`,"utf8"),r}async function
|
|
11
|
+
${n}`.toLowerCase()).includes("device is busy")&&r.includes("connecting")?"Target iOS device is still connecting. Keep it unlocked, wait for device trust/connection to settle, then retry.":oM("IOS_RUNNER_CONNECT_TIMEOUT"))})}function oR(e){if(ox(e))throw oS()}let oL=ok(process.env.AGENT_DEVICE_RUNNER_STARTUP_TIMEOUT_MS,45e3,5e3),oP=ok(process.env.AGENT_DEVICE_RUNNER_COMMAND_TIMEOUT_MS,45e3,1e3),oT=ok(process.env.AGENT_DEVICE_RUNNER_CONNECT_ATTEMPT_INTERVAL_MS,250,50),o$=ok(process.env.AGENT_DEVICE_RUNNER_CONNECT_RETRY_BASE_DELAY_MS,300,10),oF=ok(process.env.AGENT_DEVICE_RUNNER_CONNECT_RETRY_MAX_DELAY_MS,2e3,10),oU=ok(process.env.AGENT_DEVICE_RUNNER_CONNECT_REQUEST_TIMEOUT_MS,2e4,250),oG=ok(process.env.AGENT_DEVICE_IOS_DEVICE_INFO_TIMEOUT_MS,1e4,500),oV=ok(process.env.AGENT_DEVICE_RUNNER_DESTINATION_TIMEOUT_SECONDS,20,5);async function oB(e,t,n,r,a=oL,i,o){let s=oc.fromTimeoutMs(a),l=await oj(e,t,s.remainingMs()),u=null,d=Math.max(1,Math.ceil(a/oT));try{return await op(async({deadline:s})=>{if(s?.isExpired())throw new _("COMMAND_FAILED","Runner connection deadline exceeded",{port:t,timeoutMs:a});if(i&&null!==i.child.exitCode&&void 0!==i.child.exitCode)throw await oC({session:i,port:t,logPath:r});for(let r of("device"===e.kind&&(l=await oj(e,t,s?.remainingMs())),l))try{let e=s?.remainingMs()??a;if(e<=0)throw new _("COMMAND_FAILED","Runner connection deadline exceeded",{port:t,timeoutMs:a});return await oq(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},Math.min(oU,e),o)}catch(e){if(o?.aborted||o_(e))throw oS();u=e}throw new _("COMMAND_FAILED","Runner endpoint probe failed",{port:t,endpoints:l,lastError:u?String(u):void 0})},{maxAttempts:d,baseDelayMs:o$,maxDelayMs:oF,jitter:.2,shouldRetry:oE},{deadline:s,phase:"ios_runner_connect",signal:o})}catch(e){if(o?.aborted||o_(e))throw oS();u||(u=e)}if(o?.aborted)throw oS();if("simulator"===e.kind){let a=s.remainingMs();if(a<=0)throw oO({port:t,endpoints:l,logPath:r,lastError:u});let i=await oz(e,t,n,a);return new Response(i.body,{status:i.status})}throw oO({port:t,endpoints:l,logPath:r,lastError:u})}async function oj(e,t,n){let r=[`http://127.0.0.1:${t}/command`];if("device"!==e.kind)return r;let a=await oW(e.id,n);return a&&r.unshift(`http://[${a}]:${t}/command`),r}async function oq(e,t,n,r){let a,i=new AbortController,o=setTimeout(()=>i.abort(),n);r&&(r.aborted?(clearTimeout(o),i.abort()):(a=()=>i.abort(),r.addEventListener("abort",a,{once:!0})));try{return await fetch(e,{...t,signal:i.signal})}finally{clearTimeout(o),a&&r&&r.removeEventListener("abort",a)}}async function oW(e,t){if("number"==typeof t&&t<=0)return null;let n="number"==typeof t?Math.max(1,Math.min(oG,t)):oG,a=o.join(p.tmpdir(),`agent-device-devicectl-info-${process.pid}-${Date.now()}.json`);try{let t=Math.max(1,Math.ceil(n/1e3)),i=await k("xcrun",["devicectl","device","info","details","--device",e,"--json-output",a,"--timeout",String(t)],{allowFailure:!0,timeoutMs:n});if(0!==i.exitCode||!r.existsSync(a))return null;let o=JSON.parse(r.readFileSync(a,"utf8"));if(o.info?.outcome&&"success"!==o.info.outcome)return null;let s=(o.result?.connectionProperties?.tunnelIPAddress??o.result?.device?.connectionProperties?.tunnelIPAddress)?.trim();return s&&s.length>0?s:null}catch{return null}finally{oY(a)}}async function oz(e,t,n,r){let a=JSON.stringify(n),i=t9(e,["spawn",e.id,"/usr/bin/curl","-s","-X","POST","-H","Content-Type: application/json","--data",a,`http://127.0.0.1:${t}/command`]),o=await k("xcrun",i,{allowFailure:!0,timeoutMs:r}),s=o.stdout;if(0!==o.exitCode){let e=oD({message:"Runner did not accept connection (simctl spawn)",stdout:o.stdout,stderr:o.stderr,context:{platform:"ios",phase:"connect"}});throw new _("COMMAND_FAILED","Runner did not accept connection (simctl spawn)",{port:t,stdout:o.stdout,stderr:o.stderr,exitCode:o.exitCode,reason:e,hint:oM(e)})}return{status:200,body:s}}async function oX(){return await new Promise((e,t)=>{let n=m.createServer();n.listen(0,"127.0.0.1",()=>{let r=n.address();if("object"==typeof r&&r?.port){let t=r.port;n.close(()=>e(t))}else n.close(()=>t(new _("COMMAND_FAILED","Failed to allocate port")))}),n.on("error",t)})}function oH(e,t,n,a){t&&r.appendFile(t,e,()=>{}),n&&r.appendFile(n,e,()=>{}),a&&process.stderr.write(e)}function oY(e){try{r.existsSync(e)&&r.unlinkSync(e)}catch{}}let oJ=new u;async function oK(e,t,n){let r=oJ.getStore()??[];if(r.some(n=>n.locks===e&&n.key===t))return await n();let a=(e.get(t)??Promise.resolve()).catch(()=>{}).then(()=>oJ.run([...r,{locks:e,key:t}],n));return e.set(t,a),a.finally(()=>{e.get(t)===a&&e.delete(t)})}let oZ=new Set(["RUNNER_PRODUCT_MISSING","RUNNER_PRODUCT_REPAIR_FAILED"]);async function oQ(e,t,n){if("macos"!==e.platform)return;if(0===t.length)throw new _("COMMAND_FAILED","Missing macOS runner product",{reason:"RUNNER_PRODUCT_MISSING",xctestrunPath:n});let a=Array.from(new Set(t)).sort((e,t)=>t.length-e.length);for(let e of a)if(!r.existsSync(e))throw new _("COMMAND_FAILED","Missing macOS runner product",{reason:"RUNNER_PRODUCT_MISSING",productPath:e,xctestrunPath:n});for(let e of a)if(0!==D("codesign",["--verify","--deep","--strict",e],{allowFailure:!0}).exitCode){await k("codesign",["--remove-signature",e],{allowFailure:!0});try{await k("codesign",["--force","--sign","-",e])}catch(r){let t=r instanceof _?r:new _("COMMAND_FAILED",String(r));throw new _("COMMAND_FAILED","Failed to repair macOS runner product signature",{reason:"RUNNER_PRODUCT_REPAIR_FAILED",productPath:e,xctestrunPath:n,error:t.message,details:t.details})}}}let o0=null;function o1(e){return function e(t){if(!Array.isArray(t))return[];let n=[];for(let r of t)if(!(!r||"object"!=typeof r||Array.isArray(r)))for(let[t,a]of Object.entries(r))":@"!==t&&"#text"!==t&&n.push({name:t,attributes:function(e){if(!e||"object"!=typeof e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))"string"==typeof r&&(t[n]=r);return t}(r[":@"]),text:o3(a)??o3(r["#text"]),children:e(a)});return n}((o0??=new w({ignoreAttributes:!1,attributeNamePrefix:"",preserveOrder:!0,trimValues:!0,parseTagValue:!1})).parse(e))}function o2(e,t){for(let n of e){if("dict"===n.name)for(let e=0;e<n.children.length-1;e+=1){let r=n.children[e],a=n.children[e+1];r?.name==="key"&&r.text&&a&&t(r.text,a)}o2(n.children,t)}}function o3(e){if("string"==typeof e){let t=e.trim();return t.length>0?t:null}if(!Array.isArray(e))return null;let t=e.map(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return null;let t=e["#text"];return"string"==typeof t?t.trim():null}).filter(e=>null!==e&&e.length>0).join("").trim();return t.length>0?t:null}let o4="XCTestDevices",o5=".agent-device-backup",o8=".agent-device-xctestdevices-backup-",o6=o.join(p.homedir(),".agent-device","ios-runner"),o9=new Set(["ProductPaths","DependentProductPaths","TestHostPath","TestBundlePath","UITargetAppPath"]),o7=new Map,se=new Set;function st(e){return e?.trim()??""}function sn(e=process.env){return st(e.AGENT_DEVICE_IOS_BUNDLE_ID)||st(e.AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID)||"com.callstack.agentdevice.runner"}function sr(e=process.env){let t=st(e.AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID);return t||`${sn(e)}.uitests`}let sa=function(e=process.env){let t=sn(e),n=sr(e);return Array.from(new Set([st(e.AGENT_DEVICE_IOS_RUNNER_CONTAINER_BUNDLE_ID),`${n}.xctrunner`,t].filter(e=>e.length>0)))}(process.env);function si(e=p.homedir()){return o.join(e,"Library","Developer","XCTestDevices")}async function so(e,t={}){if("ios"!==e.platform||"simulator"!==e.kind)return null;let n=t4(e.simulatorSetPath);if(!n)return null;let a=o.resolve(n),i=o.resolve(t.xctestDeviceSetPath??si()),s=o.resolve(t.backupPath??function(e=si()){return`${e}${o5}`}(i)),l=o.resolve(t.lockDirPath??function(e=p.homedir()){return o.join(e,".agent-device","xctest-device-set.lock")}()),u=t.ownerStartTime??eM(process.pid),d=await su({lockDirPath:l,owner:{pid:t.ownerPid??process.pid,startTime:u,acquiredAtMs:t.nowMs??Date.now()}});try{if(ss({xctestDeviceSetPath:i,backupPath:s}),function(e,t){if(o.resolve(e)===o.resolve(t))return!0;try{return r.realpathSync.native(e)===r.realpathSync.native(t)}catch{return!1}}(a,i))return await d(),null;r.mkdirSync(a,{recursive:!0}),r.existsSync(i)&&r.renameSync(i,s),function(e){let{requestedSetPath:t,xctestDeviceSetPath:n}=e,a=o.dirname(n),i=o.join(a,`${o4}.agent-device-link-${process.pid}-${Date.now()}`);r.mkdirSync(a,{recursive:!0});try{r.symlinkSync(t,i,"dir"),r.renameSync(i,n)}catch(e){throw r.existsSync(i)&&sl(i),e}}({requestedSetPath:a,xctestDeviceSetPath:i})}catch(e){throw ss({xctestDeviceSetPath:i,backupPath:s}),await d(),new _("COMMAND_FAILED","Failed to redirect XCTest device set path",{requestedSetPath:a,xctestDeviceSetPath:i,backupPath:s,error:String(e)})}let c=!1;return{release:async()=>{if(!c){c=!0;try{ss({xctestDeviceSetPath:i,backupPath:s})}finally{await d()}}}}}function ss(e){let{xctestDeviceSetPath:t,backupPath:n}=e,a=[n,...function(e){let t=o.dirname(e),n=o.basename(e).replace(o5,""),a=n===o4?o8:`${n}${o8}`;try{return r.readdirSync(t).filter(e=>e.startsWith(a)).sort().map(e=>o.join(t,e))}catch{return[]}}(n)],i=a.find(e=>r.existsSync(e)),s=r.existsSync(t)&&r.lstatSync(t).isSymbolicLink();if(i){if(s&&sl(t),r.existsSync(t))if(!s)return void eN({level:"warn",phase:"ios_runner_xctest_device_set_restore_collision",data:{xctestDeviceSetPath:t,activeBackupPath:i}});else i!==n?r.rmSync(i,{recursive:!0,force:!0}):r.rmSync(n,{recursive:!0,force:!0});else r.mkdirSync(o.dirname(t),{recursive:!0}),r.renameSync(i,t);for(let e of a)e!==i&&r.existsSync(e)&&r.rmSync(e,{recursive:!0,force:!0});return}s&&(eN({level:"warn",phase:"ios_runner_xctest_device_set_orphaned_symlink",data:{xctestDeviceSetPath:t}}),sl(t))}function sl(e){!r.existsSync(e)||r.lstatSync(e).isSymbolicLink()&&r.unlinkSync(e)}async function su(e){let{lockDirPath:t,owner:n}=e,a=o.join(t,"owner.json"),i=Date.now()+3e4;for(r.mkdirSync(o.dirname(t),{recursive:!0});Date.now()<i;)try{r.mkdirSync(t),function(e,t){let n=`${e}.${process.pid}.${Date.now()}.tmp`;r.writeFileSync(n,JSON.stringify(t),"utf8"),r.renameSync(n,e)}(a,n);let e=!1;return async()=>{e||(e=!0,r.rmSync(t,{recursive:!0,force:!0}))}}catch(e){if("EEXIST"!==e.code)throw e;if(function(e,t){let n=null;try{n=r.statSync(e)}catch{return!0}let a=function(e){try{return JSON.parse(r.readFileSync(e,"utf8"))}catch{return null}}(t);if(a){var i;return!(Number.isInteger((i=a).pid)&&!(i.pid<=0)&&eD(i.pid)&&(!i.startTime||eM(i.pid)===i.startTime))&&(r.rmSync(e,{recursive:!0,force:!0}),!0)}return!(Date.now()-n.mtimeMs<5e3)&&(r.rmSync(e,{recursive:!0,force:!0}),!0)}(t,a))continue;await new Promise(e=>setTimeout(e,100))}throw new _("COMMAND_FAILED","Timed out waiting for XCTest device set lock",{lockDirPath:t})}async function sd(e,t){var n;let a,i=(n=e,(a=process.env.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim())?o.resolve(a):"macos"===n.platform?o.join(o6,"derived","macos"):"simulator"===n.kind?o.join(o6,"derived"):o.join(o6,"derived",n.kind)),s=function(){let e=o.dirname(l(import.meta.url)),t=e;for(let e=0;e<6;e+=1){let e=o.join(t,"package.json");if(r.existsSync(e))return t;t=o.dirname(t)}return e}();return await oK(o7,i,async()=>{os(process.env.AGENT_DEVICE_IOS_CLEAN_DERIVED)&&(sA("clean","forced_clean",{derived:i}),sI(i),sc(i));let n=function(e){let t=e.findXctestrun(e.derived);if(!t)return{reason:"missing_xctestrun",xctestrunPath:null};let n=e.resolveExistingXctestrunProductPaths(t);return n?e.xctestrunReferencesProjectRoot(t,e.projectRoot)?{reason:"reuse_ready",xctestrunPath:t,productPaths:n}:{reason:"project_root_mismatch",xctestrunPath:t,productPaths:n}:{reason:"missing_products",xctestrunPath:t,productPaths:[]}}({derived:i,projectRoot:s,findXctestrun:t=>sf(t,e),xctestrunReferencesProjectRoot:sm,resolveExistingXctestrunProductPaths:sx});if("reuse_ready"!==n.reason&&sA("rebuild",n.reason,{derived:i,xctestrunPath:n.xctestrunPath}),"reuse_ready"===n.reason)try{return await oQ(e,n.productPaths,n.xctestrunPath),sA("reuse","reuse_ready",{derived:i,xctestrunPath:n.xctestrunPath}),n.xctestrunPath}catch(e){if(!function(e){if(!(e instanceof _))return!1;let t=e.details&&"object"==typeof e.details?e.details.reason:void 0;return"string"==typeof t&&oZ.has(t)}(e))throw e;sA("rebuild","repair_failed",{derived:i,xctestrunPath:n.xctestrunPath})}n.xctestrunPath&&(sI(i),sc(i));let a=o.join(s,"ios-runner","AgentDeviceRunner","AgentDeviceRunner.xcodeproj");if(!r.existsSync(a))throw new _("COMMAND_FAILED","iOS runner project not found",{projectPath:a});await sg(e,a,i,t);let l=sf(i,e);if(!l)throw new _("COMMAND_FAILED","Failed to locate .xctestrun after build");let u=sx(l);if(!u)throw new _("COMMAND_FAILED","Runner build is missing expected products",{xctestrunPath:l});return await oQ(e,u,l),sA("build","built_new",{derived:i,xctestrunPath:l}),l})}function sc(e){try{if(!r.existsSync(e))return;if("derived"!==o.basename(e))return void r.rmSync(e,{recursive:!0,force:!0});for(let n of r.readdirSync(e,{withFileTypes:!0})){var t;t=n.name,sp.has(t)&&r.rmSync(o.join(e,n.name),{recursive:!0,force:!0})}}catch{}}let sp=new Set(["Build","BuildCache.noindex","Index.noindex","Logs","ModuleCache.noindex","SDKStatCaches.noindex","SourcePackages","TextBasedInstallAPI","info.plist"]);function sf(e,t){if(!r.existsSync(e))return null;let n=[],a=[e];for(;a.length>0;){let e=a.pop();for(let t of r.readdirSync(e,{withFileTypes:!0})){let i=o.join(e,t.name);if(t.isDirectory()){a.push(i);continue}if(t.isFile()&&t.name.endsWith(".xctestrun"))try{let e=r.statSync(i);n.push({path:i,mtimeMs:e.mtimeMs})}catch{}}}return 0===n.length?null:(n.sort((e,n)=>{if(t){let r=sh(n.path,t)-sh(e.path,t);if(0!==r)return r}return n.mtimeMs-e.mtimeMs||e.path.localeCompare(n.path)}),n[0]?.path??null)}function sh(e,t){var n;let r=0,a=e.toLowerCase();o.basename(a).startsWith("agentdevicerunner.env.")&&(r-=1e3),a.includes(`${o.sep}macos${o.sep}`)&&(r-=5e3);let i="macos"===(n=t).platform?{preferred:["macos"],disallowed:["iphoneos","iphonesimulator","appletvos","appletvsimulator"]}:"tv"===n.target?"simulator"===n.kind?{preferred:["appletvsimulator"],disallowed:["appletvos","iphoneos","iphonesimulator","macos"]}:{preferred:["appletvos"],disallowed:["appletvsimulator","iphoneos","iphonesimulator","macos"]}:"simulator"===n.kind?{preferred:["iphonesimulator"],disallowed:["iphoneos","appletvos","appletvsimulator","macos"]}:{preferred:["iphoneos"],disallowed:["iphonesimulator","appletvos","appletvsimulator","macos"]};return i.preferred.length>0&&(i.preferred.some(e=>a.includes(e))?r+=2e3:r-=500),i.disallowed.some(e=>a.includes(e))&&(r-=2500),r}function sm(e,t){try{let n=r.readFileSync(e,"utf8"),a=new Set([t]);try{a.add(r.realpathSync(t))}catch{}for(let e of a)if(n.includes(e))return!0;return!1}catch{return!1}}async function sw(e,t,n){let a,i=o.dirname(e),s=n.replace(/[^a-zA-Z0-9._-]/g,"_"),l=o.join(i,`AgentDeviceRunner.env.${s}.json`),u=o.join(i,`AgentDeviceRunner.env.${s}.xctestrun`),d=await k("plutil",["-convert","json","-o","-",e],{allowFailure:!0});if(0!==d.exitCode||!d.stdout.trim())throw new _("COMMAND_FAILED","Failed to read xctestrun plist",{xctestrunPath:e,stderr:d.stderr});try{a=JSON.parse(d.stdout)}catch(t){throw new _("COMMAND_FAILED","Failed to parse xctestrun JSON",{xctestrunPath:e,error:String(t)})}let c=e=>{e.EnvironmentVariables={...e.EnvironmentVariables??{},...t},e.UITestEnvironmentVariables={...e.UITestEnvironmentVariables??{},...t},e.UITargetAppEnvironmentVariables={...e.UITargetAppEnvironmentVariables??{},...t},e.TestingEnvironmentVariables={...e.TestingEnvironmentVariables??{},...t}},p=a.TestConfigurations;if(Array.isArray(p))for(let e of p){if(!e||"object"!=typeof e)continue;let t=e.TestTargets;if(Array.isArray(t))for(let e of t)e&&"object"==typeof e&&c(e)}for(let[e,t]of Object.entries(a))t&&"object"==typeof t&&t.TestBundlePath&&(c(t),a[e]=t);r.writeFileSync(l,JSON.stringify(a,null,2));let f=await k("plutil",["-convert","xml1","-o",u,l],{allowFailure:!0});if(0!==f.exitCode)throw new _("COMMAND_FAILED","Failed to write xctestrun plist",{tmpXctestrunPath:u,stderr:f.stderr});return{xctestrunPath:u,jsonPath:l}}async function sg(e,t,n,r){let a=function(e=process.env){let t=sn(e),n=sr(e);return[`AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID=${t}`,`AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID=${n}`]}(process.env),i=function(e=process.env,t=!1,n="ios"){if("macos"===n)return["CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO","CODE_SIGN_IDENTITY=","DEVELOPMENT_TEAM="];if(!t)return[];let r=e.AGENT_DEVICE_IOS_TEAM_ID?.trim()||"",a=e.AGENT_DEVICE_IOS_SIGNING_IDENTITY?.trim()||"",i=e.AGENT_DEVICE_IOS_PROVISIONING_PROFILE?.trim()||"",o=["CODE_SIGN_STYLE=Automatic"];return r&&o.push(`DEVELOPMENT_TEAM=${r}`),a&&o.push(`CODE_SIGN_IDENTITY=${a}`),i&&o.push(`PROVISIONING_PROFILE_SPECIFIER=${i}`),o}(process.env,"device"===e.kind,e.platform),o="device"===e.kind?["-allowProvisioningUpdates"]:[],s=await so(e);try{var l;let s;await A("xcodebuild",["build-for-testing","-project",t,"-scheme","AgentDeviceRunner","-parallel-testing-enabled","NO",sv(e),"1","-destination",(l=e,s=sy(l),"macOS"===s?`platform=macOS,arch=${sb()}`:"simulator"===l.kind?`platform=${s} Simulator,id=${l.id}`:`generic/platform=${s}`),"-derivedDataPath",n,"COMPILER_INDEX_STORE_ENABLE=NO","ENABLE_CODE_COVERAGE=NO",...a,...o,...i],{detached:!0,onSpawn:e=>{se.add(e),e.on("close",()=>{se.delete(e)})},onStdoutChunk:e=>{oH(e,r.logPath,r.traceLogPath,r.verbose)},onStderrChunk:e=>{oH(e,r.logPath,r.traceLogPath,r.verbose)}})}catch(i){let e,t,n=i instanceof _?i:new _("COMMAND_FAILED",String(i)),a=(e=n.details?JSON.stringify(n.details):"",(t=`${n.message}
|
|
12
|
+
${e}`.toLowerCase()).includes("failed registering bundle identifier")||t.includes("app identifier")&&t.includes("not available")?"Set AGENT_DEVICE_IOS_BUNDLE_ID to a unique reverse-DNS value (for example, com.yourname.agentdevice.runner), then retry.":t.includes("requires a development team")?"Configure signing in Xcode or set AGENT_DEVICE_IOS_TEAM_ID for physical-device runs.":t.includes("no profiles for")||t.includes("provisioning profile")?"Install/select a valid iOS provisioning profile, or set AGENT_DEVICE_IOS_PROVISIONING_PROFILE.":t.includes("code signing")?"Enable Automatic Signing in Xcode or provide AGENT_DEVICE_IOS_TEAM_ID and optional AGENT_DEVICE_IOS_SIGNING_IDENTITY.":void 0);throw new _("COMMAND_FAILED","xcodebuild build-for-testing failed",{error:n.message,details:n.details,logPath:r.logPath,hint:a})}finally{await s?.release()}}function sy(e){var t;if("ios"!==e.platform&&"macos"!==e.platform)throw new _("UNSUPPORTED_PLATFORM",`Unsupported platform for iOS runner: ${e.platform}`);return"macos"===e.platform?"macOS":"macos"===(t=e.target)||"desktop"===t?"macOS":"tv"===t?"tvOS":"iOS"}function sb(){return"arm64"===process.arch?"arm64":"x86_64"}function sv(e){return"macos"===e.platform||"device"===e.kind?"-maximum-concurrent-test-device-destinations":"-maximum-concurrent-test-simulator-destinations"}function sI(e,t=process.env){if(t.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim()&&!function(e=process.env){return os(e.AGENT_DEVICE_IOS_ALLOW_OVERRIDE_DERIVED_CLEAN)}(t))throw new _("COMMAND_FAILED","Refusing to clean AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH automatically",{derivedPath:e,hint:"Unset AGENT_DEVICE_IOS_CLEAN_DERIVED, or set AGENT_DEVICE_IOS_ALLOW_OVERRIDE_DERIVED_CLEAN=1 if you trust this path."})}function sA(e,t,n){eN({level:"rebuild"===e?"warn":"info",phase:"runner_xctestrun_cache",data:{action:e,reason:t,...n}})}function sx(e){let t=function(e){let t=function(e){try{let t=D("plutil",["-convert","json","-o","-",e],{allowFailure:!0});if(0!==t.exitCode||!t.stdout.trim())return null;return JSON.parse(t.stdout)}catch{return null}}(e);if(t){var n,a,i=t;let e=new Set,r=t=>{if(t&&"object"==typeof t)for(let n of function(e){let t=new Set(["ProductPaths","DependentProductPaths","TestHostPath","TestBundlePath","UITargetAppPath"]),n=new Set;for(let[r,a]of Object.entries(e))if(t.has(r)){if("string"==typeof a){n.add(a);continue}if(Array.isArray(a))for(let e of a)"string"==typeof e&&n.add(e)}return Array.from(n)}(t))e.add(n)};r(i);let o=i.TestConfigurations;if(Array.isArray(o))for(let e of o){if(!e||"object"!=typeof e)continue;let t=e.TestTargets;if(Array.isArray(t))for(let e of t)r(e)}for(let e of Object.values(i))e&&"object"==typeof e&&"TestBundlePath"in e&&r(e);return Array.from(e)}if("darwin"===process.platform)return null;try{let t;return n=r.readFileSync(e,"utf8"),a=o1(n),t=new Set,o2(a,(e,n)=>{if(o9.has(e)){if("string"===n.name&&n.text)return void t.add(n.text);if("array"===n.name)for(let e of n.children)"string"===e.name&&e.text&&t.add(e.text)}}),Array.from(t)}catch{return null}}(e);if(!t||0===t.length)return null;let n=o.dirname(e),a=new Set,i=new Set,s=[];for(let e of t){if(e.startsWith("__TESTROOT__/")){let t=e.slice(13),s=o.join(n,t);if(!r.existsSync(s))return null;a.add(s);let l=function(e){let t=/\.app(?:\/|$)/.exec(e);return t&&void 0!==t.index?e.slice(0,t.index+4):null}(t);l&&i.add(o.join(n,l));continue}e.startsWith("__TESTHOST__/")&&s.push(e.slice(13))}for(let e of s){let t=Array.from(i).find(t=>r.existsSync(o.join(t,e)));if(!t)return null;a.add(o.join(t,e))}return Array.from(a)}let sN=new Map,sS=new Map;async function s_(e,t){return await oK(sS,e.id,async()=>{var n;let r,a,i=sN.get(e.id);if(i){if(function(e){return!!e&&eD(e)}(i.child.pid))return i;await sE(e.id,i)}await ("simulator"!==(n=e).kind?Promise.resolve():sP(n)),await sk(e);let o=await sd(e,t),s=await oX(),{xctestrunPath:l,jsonPath:u}=await sw(o,{AGENT_DEVICE_RUNNER_PORT:String(s)},`session-${e.id}-${s}`),d=await so(e);try{let t;({child:r,wait:a}=S("xcodebuild",["test-without-building","-only-testing","AgentDeviceRunnerUITests/RunnerTests/testCommand","-parallel-testing-enabled","NO","-test-timeouts-enabled","NO","-collect-test-diagnostics","never",sv(e),"1","-destination-timeout",String(oV),"-xctestrun",l,"-destination",(t=sy(e),"macOS"===t?`platform=macOS,arch=${sb()}`:"simulator"===e.kind?`platform=${t} Simulator,id=${e.id}`:`platform=${t},id=${e.id}`)],{allowFailure:!0,env:{...process.env,AGENT_DEVICE_RUNNER_PORT:String(s)},detached:!0}))}catch(e){throw await d?.release(),e}r.stdout?.on("data",e=>{oH(e,t.logPath,t.traceLogPath,t.verbose)}),r.stderr?.on("data",e=>{oH(e,t.logPath,t.traceLogPath,t.verbose)});let c={sessionId:`${e.id}:${s}:${Date.now()}`,device:e,deviceId:e.id,port:s,xctestrunPath:l,jsonPath:u,testPromise:a,child:r,ready:!1,simulatorSetRedirect:d??void 0};return sN.set(e.id,c),c})}async function sk(e){if("simulator"===e.kind)for(let t of sa){let n=await k("xcrun",t9(e,["uninstall",e.id,t]),{allowFailure:!0});if(0!==n.exitCode){let e=`${n.stdout}
|
|
13
|
+
${n.stderr}`.toLowerCase();if(!e.includes("not installed")&&!e.includes("found nothing")&&!e.includes("no such file")&&!e.includes("invalid device")&&!e.includes("could not find"))continue}}}function sD(e){let t=sN.get(e);return t?{sessionId:t.sessionId,alive:function(e){return!!e&&eD(e)}(t.child.pid)}:null}async function sM(e){await oK(sS,e.deviceId,async()=>{await sE(e.deviceId,e)})}async function sE(e,t){let n=t??sN.get(e);if(n){try{await oB(n.device,n.port,{command:"shutdown"},void 0,15e3)}catch{await sL(n.child.pid,"SIGTERM")}try{await Promise.race([n.testPromise,new Promise(e=>setTimeout(e,1e4))])}catch{}await sL(n.child.pid,"SIGKILL"),oY(n.xctestrunPath),oY(n.jsonPath),await n.simulatorSetRedirect?.release(),sN.get(e)===n&&sN.delete(e)}}async function sO(e){await oK(sS,e,async()=>{await sE(e)})}async function sC(){let e=Array.from(sN.values()),t=Array.from(se);await Promise.allSettled(e.map(async e=>{await sL(e.child.pid,"SIGINT")})),await Promise.allSettled(t.map(async e=>{await sL(e.pid,"SIGINT")})),await Promise.allSettled(e.map(async e=>{await sL(e.child.pid,"SIGTERM")})),await Promise.allSettled(t.map(async e=>{await sL(e.pid,"SIGTERM")})),await Promise.allSettled(e.map(async e=>{await sL(e.child.pid,"SIGKILL")})),await Promise.allSettled(t.map(async e=>{await sL(e.pid,"SIGKILL"),se.delete(e)})),await Promise.allSettled(e.map(async e=>{await e.simulatorSetRedirect?.release()}))}async function sR(){await sC();let e=Array.from(sN.keys());await Promise.allSettled(e.map(async e=>{await sO(e)}));let t=Array.from(se);await Promise.allSettled(t.map(async e=>{try{await sL(e.pid,"SIGTERM"),await sL(e.pid,"SIGKILL")}finally{se.delete(e)}}))}async function sL(e,t){if(!e||e<=0)return;try{process.kill(-e,t)}catch{}try{process.kill(e,t)}catch{}let n="SIGINT"===t?"INT":"SIGTERM"===t?"TERM":"KILL";try{await k("pkill",[`-${n}`,"-P",String(e)],{allowFailure:!0})}catch{}}async function sP(e){await k("xcrun",t9(e,["bootstatus",e.id,"-b"]),{timeoutMs:oL})}async function sT(e,t,n,r,a,i){let o=await oB(e,t.port,n,r,a,t,i);return await s$(o,t,r)}async function s$(e,t,n){let r=await e.text(),a={};try{a=JSON.parse(r)}catch{throw new _("COMMAND_FAILED","Invalid runner response",{text:r})}if(!a.ok)throw new _("string"==typeof a.error?.code&&a.error.code.trim().length>0?a.error.code:"COMMAND_FAILED",a.error?.message??"Runner error",{runner:a,xcodebuild:{exitCode:1,stdout:"",stderr:""},logPath:n});return t.ready=!0,a.data??{}}async function sF(e,t,n={}){var r;if("ios"!==e.platform&&"macos"!==e.platform)throw new _("UNSUPPORTED_PLATFORM",`Unsupported platform for iOS runner: ${e.platform}`);if("simulator"!==e.kind&&"device"!==e.kind)throw new _("UNSUPPORTED_OPERATION",`Unsupported iOS device kind for runner: ${e.kind}`);return(oR(n.requestId),"interactionFrame"===(r=t.command)||"snapshot"===r||"screenshot"===r||"findText"===r||"readText"===r||"alert"===r||"uptime"===r)?of(()=>(oR(n.requestId),sU(e,t,n)),{shouldRetry:e=>{oR(n.requestId);if(!(e instanceof _)||"COMMAND_FAILED"!==e.code)return!1;let t=`${e.message??""}`.toLowerCase();return!(t.includes("xcodebuild exited early")||t.includes("device is busy")&&t.includes("connecting"))&&!!(t.includes("runner did not accept connection")||t.includes("fetch failed")||t.includes("econnrefused")||t.includes("socket hang up"))}}):sU(e,t,n)}async function sU(e,t,n={}){let r;oR(n.requestId);let a=oN(n.requestId);try{let i=(r=await s_(e,n)).ready?oP:oL;return await sT(e,r,t,n.logPath,i,a)}catch(o){let i=o instanceof _?o:new _("COMMAND_FAILED",String(o));if("COMMAND_FAILED"===i.code&&"string"==typeof i.message&&i.message.includes("Runner did not accept connection")&&oE(i)&&r?.ready){oR(n.requestId),r?await sM(r):await sO(e.id),r=await s_(e,n);let i=await oB(r.device,r.port,t,n.logPath,oL,void 0,a);return await s$(i,r,n.logPath)}throw o}}function sG(e){let t=e.trim();if(!t||/\s/.test(t))return!1;let n=/^([A-Za-z][A-Za-z0-9+.-]*):(.+)$/.exec(t);if(!n)return!1;let r=n[1]?.toLowerCase(),a=n[2]??"";return"http"!==r&&"https"!==r&&"ws"!==r&&"wss"!==r&&"ftp"!==r&&"ftps"!==r||a.startsWith("//")}function sV(e,t){let n,r=e?.trim();return r?r:"http"===(n=t.trim().split(":")[0]?.toLowerCase())||"https"===n?"com.apple.mobilesafari":void 0}let sB=["android.software.leanback","android.software.leanback_only","android.hardware.type.television"];function sj(e){return`${e.stdout}
|
|
14
|
+
${e.stderr}`}function sq(e,t){return["-s",e,...t]}function sW(e){return e.startsWith("emulator-")}function sz(e){return e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim()}async function sX(e,t=od){return k("adb",sq(e,["shell","getprop","sys.boot_completed"]),{allowFailure:!0,timeoutMs:t})}async function sH(e,t){let n=t.replace(/_/g," ").trim();if(!sW(e))return n||e;let r=await sJ(e);return r?r.replace(/_/g," "):n||e}async function sY(e,t,n){try{return await n("adb",sq(e,t),{allowFailure:!0,timeoutMs:1e4})}catch(e){var r;if("COMMAND_FAILED"===(r=x(e)).code&&"number"==typeof r.details?.timeoutMs)return;throw e}}async function sJ(e,t=k){for(let n of["ro.boot.qemu.avd_name","persist.sys.avd_name"]){let r=await sY(e,["shell","getprop",n],t);if(!r)continue;let a=r.stdout.trim();if(0===r.exitCode&&a.length>0)return a}let n=await sY(e,["emu","avd","name"],t);if(!n)return;let r=function(e){let t=e.split("\n").map(e=>e.trim()).filter(e=>e.length>0);if(0!==t.length)return"OK"===t.at(-1)&&t.pop(),t.join("\n").trim()||void 0}(n.stdout);if(0===n.exitCode&&r)return r}async function sK(e,t){let n=sj(await k("adb",sq(e,["shell","cmd","package","has-feature",t]),{allowFailure:!0,timeoutMs:od})).toLowerCase();return!!n.includes("true")||!n.includes("false")&&null}async function sZ(e){return(await Promise.all(sB.map(async t=>await sK(e,t)))).some(e=>!0===e)}async function sQ(e){var t;let n;return"tv"===((n=sj(await k("adb",sq(e,["shell","getprop","ro.build.characteristics"]),{allowFailure:!0,timeoutMs:od})).toLowerCase()).includes("tv")||n.includes("leanback")?"tv":null)||await sZ(e)?"tv":(t=sj(await k("adb",sq(e,["shell","pm","list","features"]),{allowFailure:!0,timeoutMs:od})),/feature:android\.(software\.leanback(_only)?|hardware\.type\.television)\b/i.test(t))?"tv":"mobile"}async function s0(e={}){if(await tW(),!await v("adb"))throw new _("TOOL_MISSING","adb not found in PATH");let t=e.serialAllowlist??t8(void 0),n=(await s1()).filter(e=>!t||t.has(e.serial));return await Promise.all(n.map(async({serial:e,rawModel:t})=>{let[n,r,a]=await Promise.all([sH(e,t),s5(e),sQ(e)]);return{platform:"android",id:e,name:n,kind:sW(e)?"emulator":"device",target:a,booted:r}}))}async function s1(){return(await k("adb",["devices","-l"],{timeoutMs:od})).stdout.split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith("List of devices")).map(e=>e.split(/\s+/)).filter(e=>"device"===e[1]).map(e=>({serial:e[0],rawModel:(e.find(e=>e.startsWith("model:"))??"").replace("model:","")}))}async function s2(){let e=await k("emulator",["-list-avds"],{allowFailure:!0,timeoutMs:od});if(0!==e.exitCode)throw new _("COMMAND_FAILED","Failed to list Android emulator AVDs",{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode,hint:"Verify Android emulator tooling is installed and available in PATH."});return e.stdout.split("\n").map(e=>e.trim()).filter(e=>e.length>0)}async function s3(e){let t=Date.now();for(;Date.now()-t<e.timeoutMs;){try{let t=await s4(e.avdName,e.serial);if(t)return{platform:"android",id:t,name:e.avdName,kind:"emulator",target:"mobile",booted:!1}}catch{}await new Promise(e=>setTimeout(e,1e3))}throw new _("COMMAND_FAILED","Android emulator did not appear in time",{avdName:e.avdName,serial:e.serial,timeoutMs:e.timeoutMs,hint:"Check emulator logs and verify the AVD can start from command line."})}async function s4(e,t){let n=sz(e);for(let e of(await s1()).filter(e=>(!t||e.serial===t)&&sW(e.serial)))if(sz(e.rawModel)===n||sz(await sH(e.serial,e.rawModel))===n)return e.serial}async function s5(e){try{let t=await sX(e);return"1"===t.stdout.trim()}catch{return!1}}async function s8(e){var t,n;let r;await tW();let a=e.avdName.trim();if(!a)throw new _("INVALID_ARGS","Android emulator boot requires a non-empty AVD name.");let i=e.timeoutMs??12e4;if(!await v("adb"))throw new _("TOOL_MISSING","adb not found in PATH");if(!await v("emulator"))throw new _("TOOL_MISSING","emulator not found in PATH");let o=await s2(),s=function(e,t){let n=e.find(e=>e===t);if(n)return n;let r=sz(t);return e.find(e=>sz(e)===r)}(o,a);if(!s)throw new _("DEVICE_NOT_FOUND",`No Android emulator AVD named ${e.avdName}`,{requestedAvdName:a,availableAvds:o,hint:"Run `emulator -list-avds` and pass an existing AVD name to --device."});let l=Date.now(),u=(t=await s0(),n=e.serial,r=sz(s),t.find(e=>"android"===e.platform&&"emulator"===e.kind&&(!n||e.id===n)&&sz(e.name)===r));if(!u){let t=["-avd",s];e.headless&&t.push("-no-window","-no-audio"),N("emulator",t)}let d=u??await s3({avdName:s,serial:e.serial,timeoutMs:i}),c=Math.max(1e3,i-(Date.now()-l));await s6(d.id,c);let p=(await s0()).find(e=>e.id===d.id);return p?{...p,name:s,booted:!0}:{...d,name:s,booted:!0}}async function s6(e,t=6e4){let n,r=oc.fromTimeoutMs(t),a=Math.max(1,Math.ceil(t/1e3)),i=!1;try{await op(async({deadline:a})=>{if(a?.isExpired())throw i=!0,new _("COMMAND_FAILED","Android boot deadline exceeded",{serial:e,timeoutMs:t,elapsedMs:r.elapsedMs(),message:"timeout"});let o=Math.max(1e3,a?.remainingMs()??t),s=await sX(e,Math.min(o,od));if(n=s,"1"!==s.stdout.trim())throw new _("COMMAND_FAILED","Android device is still booting",{serial:e,stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode})},{maxAttempts:a,baseDelayMs:1e3,maxDelayMs:1e3,jitter:0,shouldRetry:e=>{let t=oD({error:e,stdout:n?.stdout,stderr:n?.stderr,context:{platform:"android",phase:"boot"}});return"ADB_TRANSPORT_UNAVAILABLE"!==t&&"ANDROID_BOOT_TIMEOUT"!==t}},{deadline:r,phase:"boot",classifyReason:e=>oD({error:e,stdout:n?.stdout,stderr:n?.stderr,context:{platform:"android",phase:"boot"}})})}catch(c){let a=x(c),o=n?.stdout,s=n?.stderr,l=n?.exitCode,u=oD({error:c,stdout:o,stderr:s,context:{platform:"android",phase:"boot"}});"BOOT_COMMAND_FAILED"===u&&"Android device is still booting"===a.message&&(u="ANDROID_BOOT_TIMEOUT");let d={serial:e,timeoutMs:t,elapsedMs:r.elapsedMs(),reason:u,hint:oM(u),stdout:o,stderr:s,exitCode:l};if(i||"ANDROID_BOOT_TIMEOUT"===u)throw new _("COMMAND_FAILED","Android device did not finish booting in time",d);if("TOOL_MISSING"===a.code)throw new _("TOOL_MISSING",a.message,{...d,...a.details??{}});if("ADB_TRANSPORT_UNAVAILABLE"===u)throw new _("COMMAND_FAILED",a.message,{...d,...a.details??{}});throw new _(a.code,a.message,{...d,...a.details??{}},a.cause)}}let s9=[".zip",".tar",".tar.gz",".tgz"];Object.freeze([...s9]);let s7=ok(process.env.AGENT_DEVICE_SOURCE_DOWNLOAD_TIMEOUT_MS,12e4,1e3),le=["1","true","yes","on"];async function lt(e){let t=[];try{let n=await ln(e.source,{signal:e.signal,downloadTimeoutMs:e.downloadTimeoutMs});t.push(n.cleanup);let r=await ls(n.localPath,{archivePath:void 0,isInstallablePath:e.isInstallablePath,installableLabel:e.installableLabel,allowArchiveExtraction:!1!==e.allowArchiveExtraction,registerCleanup:e=>{t.push(e)}});return{archivePath:r.archivePath,installablePath:r.installablePath,cleanup:async()=>{await lp(t)}}}catch(e){throw await lp(t),e}}async function ln(e,t){if("path"===e.kind)return{localPath:eT(e.path),cleanup:async()=>{}};let n=await i.mkdtemp(o.join(p.tmpdir(),"agent-device-source-"));try{return{localPath:await lr(n,e.url,e.headers,t),cleanup:async()=>{await i.rm(n,{recursive:!0,force:!0})}}}catch(e){throw await i.rm(n,{recursive:!0,force:!0}),e}}async function lr(e,t,n,r){let a;try{a=new URL(t)}catch{throw new _("INVALID_ARGS",`Invalid source URL: ${t}`)}await la(a);let s=r?.signal;if(s?.aborted)throw new _("COMMAND_FAILED","request canceled",{reason:"request_canceled"});let l=new AbortController,u=()=>{l.abort(s?.reason)};s?.addEventListener("abort",u,{once:!0});let d=r?.downloadTimeoutMs??s7,c=setTimeout(()=>{l.abort(Error("download timeout"))},d);try{let t=await fetch(a,{headers:n,redirect:"follow",signal:l.signal});if(!t.ok)throw new _("COMMAND_FAILED",`Failed to download app source: ${t.status} ${t.statusText}`,{status:t.status,statusText:t.statusText,url:a.toString()});let r=function(e,t){let n=e.headers.get("content-disposition"),r=n?.match(/filename\*?=(?:UTF-8'')?"?([^";]+)"?/i),a=r?.[1]?.trim();if(a)return o.basename(a);let i=o.basename(t.pathname);return i||"downloaded-artifact.bin"}(t,a),s=o.join(e,r),u=t.body;if(!u)throw new _("COMMAND_FAILED","Download response body was empty",{url:a.toString()});let d=await i.open(s,"w");try{for await(let e of u)await d.write(e)}finally{await d.close()}return s}catch(e){if(s?.aborted)throw new _("COMMAND_FAILED","request canceled",{reason:"request_canceled"},e);if(l.signal.aborted)throw new _("COMMAND_FAILED",`App source download timed out after ${d}ms`,{timeoutMs:d,url:a.toString()},e);throw e}finally{s?.removeEventListener("abort",u),clearTimeout(c)}}async function la(e){if("http:"!==e.protocol&&"https:"!==e.protocol)throw new _("INVALID_ARGS",`Unsupported source URL protocol: ${e.protocol}`);if(!le.includes((process.env.AGENT_DEVICE_ALLOW_PRIVATE_SOURCE_URLS??"").toLowerCase())){var t;if(!(t=e.hostname.toLowerCase())||"localhost"===t||t.endsWith(".localhost")||lo(t))throw new _("INVALID_ARGS",`Source URL host is not allowed: ${e.hostname}`,{hint:"Use a public artifact URL, or set AGENT_DEVICE_ALLOW_PRIVATE_SOURCE_URLS=1 for trusted private-network daemons."});if((await g.lookup(e.hostname,{all:!0,verbatim:!0}).catch(()=>[])).some(e=>lo(e.address)))throw new _("INVALID_ARGS",`Source URL host resolved to a private or loopback address: ${e.hostname}`,{hint:"Use a public artifact URL, or set AGENT_DEVICE_ALLOW_PRIVATE_SOURCE_URLS=1 for trusted private-network daemons."})}}function li(e){var t,n,r,a;let i=e instanceof URL?e:new URL(e),o=i.hostname.toLowerCase();if(!o)return!1;let s=i.pathname;return t=o,n=s,("api.github.com"===t?/^\/repos\/[^/]+\/[^/]+\/actions\/artifacts\/\d+\/zip$/i.test(n):"github.com"===t&&/^\/[^/]+\/[^/]+\/(?:actions\/runs\/\d+\/artifacts\/\d+|suites\/\d+\/artifacts\/\d+)$/i.test(n))||(r=o,a=s,("expo.dev"===r||!!r.endsWith(".expo.dev"))&&/^\/(?:artifacts\/eas\/|accounts\/[^/]+\/projects\/[^/]+\/builds\/)/i.test(a))}function lo(e){let t,n=m.isIP(e);return 4===n?function(e){let t=e.split(".").map(e=>Number.parseInt(e,10));if(4!==t.length||t.some(e=>Number.isNaN(e)||e<0||e>255))return!1;let[n,r]=t;return 10===n||127===n||169===n&&254===r||172===n&&!!(r>=16)&&!!(r<=31)||192===n&&168===r}(e):6===n&&!!("::1"===(t=e.toLowerCase())||t.startsWith("fc")||t.startsWith("fd")||t.startsWith("fe80:"))}async function ls(e,t){let n=await i.stat(e).catch(()=>null);if(!n)throw new _("INVALID_ARGS",`App source not found: ${e}`);if(t.isInstallablePath(e,n))return{archivePath:t.archivePath,installablePath:e};if(n.isFile()&&lc(e)){if(!t.allowArchiveExtraction)throw new _("INVALID_ARGS",`URL sources must point directly to a ${t.installableLabel}; archive extraction is not allowed`,{path:e});let n=await lu(e);return t.registerCleanup(n.cleanup),await ls(n.outputPath,{...t,archivePath:t.archivePath??e})}if(n.isDirectory()){let n=await ll(e,t.isInstallablePath);if(1===n.length)return{archivePath:t.archivePath,installablePath:n[0]};if(n.length>1)throw new _("INVALID_ARGS",`Found multiple ${t.installableLabel} candidates under ${e}`,{matches:n});let r=await ll(e,(e,t)=>t.isFile()&&lc(e));if(1===r.length){if(!t.allowArchiveExtraction)throw new _("INVALID_ARGS",`URL sources must point directly to a ${t.installableLabel}; nested archives are not allowed`,{path:r[0]});let e=await lu(r[0]);return t.registerCleanup(e.cleanup),await ls(e.outputPath,{...t,archivePath:t.archivePath??r[0]})}if(r.length>1)throw new _("INVALID_ARGS",`Found multiple nested archives under ${e}; expected one ${t.installableLabel} source`,{matches:r})}throw new _("INVALID_ARGS",`Expected ${t.installableLabel} source, but got ${e}`)}async function ll(e,t){let n=[],r=[{path:e,depth:0}];for(;r.length>0;){let e=r.shift();if(!e)continue;let a=await i.readdir(e.path,{withFileTypes:!0});for(let i of(a.sort((e,t)=>e.name.localeCompare(t.name)),a)){let a=o.join(e.path,i.name);if(t(a,i)){n.push(a);continue}i.isDirectory()&&e.depth<5&&r.push({path:a,depth:e.depth+1})}}return n}async function lu(e){let t=await i.mkdtemp(o.join(p.tmpdir(),"agent-device-archive-"));try{return e.toLowerCase().endsWith(".zip")?await ld(e,t):e.toLowerCase().endsWith(".tar.gz")||e.toLowerCase().endsWith(".tgz")?await k("tar",["-xzf",e,"-C",t]):await k("tar",["-xf",e,"-C",t]),{outputPath:t,cleanup:async()=>{await i.rm(t,{recursive:!0,force:!0})}}}catch(e){throw await i.rm(t,{recursive:!0,force:!0}),e}}async function ld(e,t){await k("unzip",["-q",e,"-d",t])}function lc(e){let t=e.toLowerCase();return s9.some(e=>t.endsWith(e))}async function lp(e){for(let t=e.length-1;t>=0;t-=1)await e[t]()}let lf=new b("utf-16le");async function lh(e){for(let n of["AndroidManifest.xml","base/manifest/AndroidManifest.xml"]){var t;let r=await lm(e,n);if(!r)continue;let a=(t=r).subarray(0,Math.min(t.length,128)).toString("utf8").trimStart().startsWith("<")?function(e){let t=e.match(/<manifest\b[^>]*\bpackage\s*=\s*["']([^"']+)["']/i);return t?.[1]}(t.toString("utf8")):function(e){let t;if(!(e.length<8)&&3===e.readUInt16LE(0))for(let n=e.readUInt16LE(2);n+8<=e.length;){let r=e.readUInt16LE(n),a=e.readUInt16LE(n+2),i=e.readUInt32LE(n+4);if(i<=0||n+i>e.length)break;if(1===r)t=function(e){if(e.length<28)return[];let t=e.readUInt32LE(8),n=e.readUInt32LE(16),r=e.readUInt32LE(20),a=(256&n)!=0,i=[];for(let n=0;n<t;n+=1){let t=28+4*n;if(t+4>e.length)break;let o=r+e.readUInt32LE(t);i.push(a?function(e,t){let[,n]=lw(e,t),[r,a]=lw(e,t+n),i=t+n+a;return e.subarray(i,i+r).toString("utf8")}(e,o):function(e,t){let[n,r]=function(e,t){let n=e.readUInt16LE(t);return(32768&n)==0?[n,2]:[(32767&n)<<16|e.readUInt16LE(t+2),4]}(e,t),a=t+r;return lf.decode(e.subarray(a,a+2*n))}(e,o))}return i}(e.subarray(n,n+i));else if(258===r&&t){let r=function(e,t,n,r){if(n<36||t+n>e.length||"manifest"!==r[e.readUInt32LE(t+20)])return;let a=e.readUInt16LE(t+24),i=e.readUInt16LE(t+26),o=e.readUInt16LE(t+28),s=t+a;for(let t=0;t<o;t+=1){let n=s+t*i;if(n+20>e.length)break;if("package"!==r[e.readUInt32LE(n+4)])continue;let a=e.readUInt32LE(n+8);if(0xffffffff!==a)return r[a];let o=e.readUInt8(n+15),l=e.readUInt32LE(n+16);if(3===o)return r[l];break}}(e,n,a,t);if(r)return r}n+=i}}(t);if(a)return a}return await lg(e)}async function lm(e,t){try{let n=await k("unzip",["-p",e,t],{allowFailure:!0,binaryStdout:!0});if(0!==n.exitCode||!n.stdoutBuffer||0===n.stdoutBuffer.length)return;return n.stdoutBuffer}catch{return}}function lw(e,t){let n=e.readUInt8(t);return(128&n)==0?[n,1]:[(127&n)<<8|e.readUInt8(t+1),2]}async function lg(e){let t=await ly();if(!t)return;let n=await k(t,["dump","badging",e],{allowFailure:!0});if(0!==n.exitCode)return;let r=n.stdout.match(/package:\s+name='([^']+)'/);return r?.[1]}async function ly(){if(void 0!==e)return e??void 0;try{for(let t of tj()){let n=o.join(t,"build-tools");try{for(let t of(await y.readdir(n)).sort((e,t)=>t.localeCompare(e,void 0,{numeric:!0}))){let r=o.join(n,t,"aapt");if(o.isAbsolute(r)&&await M(r))return e=r,r}}catch{}}}catch{}e=null}async function lb(e,t){let n="url"===e.kind&&li(e.url),r=await lt({source:e,isInstallablePath:(e,t)=>{var n;let r;return t.isFile()&&(n=e,".apk"===(r=o.extname(n).toLowerCase())||".aab"===r)},installableLabel:"Android installable (.apk or .aab)",allowArchiveExtraction:"url"!==e.kind||n,signal:t?.signal}),a=t?.resolveIdentity===!1?{}:await lv(r.installablePath);return{archivePath:r.archivePath,installablePath:r.installablePath,packageName:a.packageName,cleanup:r.cleanup}}async function lv(e){let t=o.extname(e).toLowerCase();return".apk"!==t&&".aab"!==t?{}:{packageName:await lh(e)}}function lI(e,t){let n=0;for(;n<e.length&&function(e,t){if(!e)return!1;let n=e.charCodeAt(0);return n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||"_"===e||"."===e||t&&"$"===e}(e[n],t);)n+=1;return e.slice(0,n)}let lA={settings:{type:"intent",value:"android.settings.SETTINGS"}},lx="android.intent.category.LAUNCHER",lN="android.intent.category.LEANBACK_LAUNCHER",lS="android.intent.category.DEFAULT",l_="Run agent-device apps --platform android to discover the installed package name, then retry open with that exact package.";async function lk(e,t){let n=t.trim();if("package"===tZ(n))return{type:"package",value:n};let r=lA[n.toLowerCase()];if(r)return r;let a=(await k("adb",tz(e,["shell","pm","list","packages"]))).stdout.split("\n").map(e=>e.replace("package:","").trim()).filter(Boolean).filter(e=>e.toLowerCase().includes(n.toLowerCase()));if(1===a.length)return{type:"package",value:a[0]};if(a.length>1)throw new _("INVALID_ARGS",`Multiple packages matched "${t}"`,{matches:a,hint:"Run agent-device apps --platform android to see the exact installed package names before retrying open."});throw new _("APP_NOT_INSTALLED",`No package found matching "${t}"`,{hint:l_})}async function lD(e,t="all"){let n=await lM(e);return("user-installed"===t?(await lO(e)).filter(e=>n.has(e)):Array.from(n)).sort((e,t)=>e.localeCompare(t)).map(e=>({package:e,name:lC(e)}))}async function lM(e){let t=new Set;for(let n of lE(e,{includeFallbackWhenUnknown:!0})){let r=await k("adb",tz(e,["shell","cmd","package","query-activities","--brief","-a","android.intent.action.MAIN","-c",n]),{allowFailure:!0});if(0===r.exitCode&&0!==r.stdout.trim().length)for(let e of function(e){let t=new Set;for(let n of e.split("\n")){let e=n.trim();if(!e)continue;let r=e.split(/\s+/)[0],a=r.includes("/")?r.split("/")[0]:r;a&&t.add(a)}return Array.from(t)}(r.stdout))t.add(e)}return t}function lE(e,t={}){return"tv"===e.target?[lN]:"mobile"===e.target?[lx]:t.includeFallbackWhenUnknown?[lx,lN]:[lx]}async function lO(e){return(await k("adb",tz(e,["shell","pm","list","packages","-3"]))).stdout.split("\n").map(e=>{let t=e.trim();return t.startsWith("package:")?t.slice(8):t}).filter(Boolean)}function lC(e){let t=new Set(["com","android","google","app","apps","service","services","mobile","client"]),n=e.split(".").flatMap(e=>e.split(/[_-]+/)).map(e=>e.trim().toLowerCase()).filter(e=>e.length>0),r=n[n.length-1]??e;for(let e=n.length-1;e>=0;e-=1){let a=n[e];if(!t.has(a)){r=a;break}}return r.split(/[^a-z0-9]+/i).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}async function lR(e){let t=await lL(e,[["shell","dumpsys","window","windows"],["shell","dumpsys","window"]]);if(t)return t;let n=await lL(e,[["shell","dumpsys","activity","activities"],["shell","dumpsys","activity"]]);return n||{}}async function lL(e,t){for(let n of t){let t=function(e){let t=e.split("\n");for(let e of["mCurrentFocus=Window{","mFocusedApp=AppWindowToken{","mResumedActivity:","ResumedActivity:"])for(let n of t){let t=n.indexOf(e);if(-1===t)continue;let r=function(e){for(let t of e.trim().split(/\s+/)){let e=t.indexOf("/");if(e<=0)continue;let n=lI(t.slice(0,e),!1),r=lI(t.slice(e+1),!0);if(n&&r&&n.length===e)return{package:n,activity:r}}return null}(n.slice(t+e.length));if(r)return r}return null}((await k("adb",tz(e,n),{allowFailure:!0})).stdout??"");if(t)return t}return null}async function lP(e,t,n){var r,a;let i;e.booted||await s6(e.id);let o=t.trim();if(sG(o)){if(n)throw new _("INVALID_ARGS","Activity override is not supported when opening a deep link URL");await k("adb",tz(e,["shell","am","start","-W","-a","android.intent.action.VIEW","-d",o]));return}let s=await lk(e,t),l=lE(e)[0]??lx;if("intent"===s.type){if(n)throw new _("INVALID_ARGS","Activity override requires a package name, not an intent");await k("adb",tz(e,["shell","am","start","-W","-a",s.value]));return}if(n){let t=n.includes("/")?n:`${s.value}/${n.startsWith(".")?n:`.${n}`}`;try{await k("adb",tz(e,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",lS,"-c",l,"-n",t]))}catch(t){throw await lF(e,s.value,t),t}return}let u=await k("adb",tz(e,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",lS,"-c",l,"-p",s.value]),{allowFailure:!0});if(0===u.exitCode&&(r=u.stdout,a=u.stderr,i=`${r}
|
|
15
|
+
${a}`,!/Error:.*(?:Activity not started|unable to resolve Intent)/i.test(i)))return;let d=await lG(e,s.value);if(!d){if(!await l$(e,s.value))throw lT(s.value);throw new _("COMMAND_FAILED",`Failed to launch ${s.value}`,{stdout:u.stdout,stderr:u.stderr})}await k("adb",tz(e,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",lS,"-c",l,"-n",d]))}function lT(e){return new _("APP_NOT_INSTALLED",`No package found matching "${e}"`,{package:e,hint:l_})}async function l$(e,t){let n=await k("adb",tz(e,["shell","pm","path",t]),{allowFailure:!0}),r=`${n.stdout}
|
|
16
|
+
${n.stderr}`;return!!(0===n.exitCode&&/\bpackage:/i.test(r))||(lU(r),!1)}async function lF(e,t,n){if(lU(n instanceof _?`${String(n.details?.stdout??"")}
|
|
17
|
+
${String(n.details?.stderr??"")}`:"")||!await l$(e,t))throw lT(t)}function lU(e){return/\bunknown package\b/i.test(e)||/\bpackage .* (?:was|is) not found\b/i.test(e)||/\bpackage .* does not exist\b/i.test(e)||/\bcould not find package\b/i.test(e)}async function lG(e,t){for(let n of Array.from(new Set(lE(e,{includeFallbackWhenUnknown:!0})))){let r=await k("adb",tz(e,["shell","cmd","package","resolve-activity","--brief","-a","android.intent.action.MAIN","-c",n,t]),{allowFailure:!0});if(0!==r.exitCode)continue;let a=function(e){let t=e.split("\n").map(e=>e.trim()).filter(Boolean);for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n.includes("/"))return n.split(/\s+/)[0]}return null}(r.stdout);if(a)return a}return null}async function lV(e){e.booted||await s6(e.id)}async function lB(e,t){if("settings"===t.trim().toLowerCase())return void await k("adb",tz(e,["shell","am","force-stop","com.android.settings"]));let n=await lk(e,t);if("intent"===n.type)throw new _("INVALID_ARGS","Close requires a package name, not an intent");await k("adb",tz(e,["shell","am","force-stop",n.value]))}async function lj(e,t){let n=await lk(e,t);if("intent"===n.type)throw new _("INVALID_ARGS","App uninstall requires a package name, not an intent");let r=await k("adb",tz(e,["uninstall",n.value]),{allowFailure:!0});if(0!==r.exitCode){let e=`${r.stdout}
|
|
18
|
+
${r.stderr}`.toLowerCase();if(!e.includes("unknown package")&&!e.includes("not installed"))throw new _("COMMAND_FAILED",`adb uninstall failed for ${n.value}`,{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode})}return{package:n.value}}let lq=null;async function lW(){let e=`${process.env.PATH??""}::${process.env.AGENT_DEVICE_BUNDLETOOL_JAR??""}`;if(lq?.key===e)return lq.invocation;if(await v("bundletool")){let t={cmd:"bundletool",prefixArgs:[]};return lq={key:e,invocation:t},t}let t=await I(process.env.AGENT_DEVICE_BUNDLETOOL_JAR,"AGENT_DEVICE_BUNDLETOOL_JAR");if(!t)throw new _("TOOL_MISSING","bundletool not found in PATH. Install bundletool or set AGENT_DEVICE_BUNDLETOOL_JAR to a bundletool-all.jar path.");let n={cmd:"java",prefixArgs:["-jar",t]};return lq={key:e,invocation:n},n}async function lz(e){let t=await lW();await k(t.cmd,[...t.prefixArgs,...e])}async function lX(e,t){let n,r=await i.mkdtemp(o.join(p.tmpdir(),"agent-device-aab-")),a=o.join(r,"bundle.apks"),s=(n=process.env.AGENT_DEVICE_ANDROID_BUNDLETOOL_MODE?.trim())&&n.length>0?n:"universal";try{await lz(["build-apks","--bundle",t,"--output",a,"--mode",s]),await lz(["install-apks","--apks",a,"--device-id",e.id])}finally{await i.rm(r,{recursive:!0,force:!0})}}async function lH(e,t){".aab"===o.extname(t).toLowerCase()?await lX(e,t):await k("adb",tz(e,["install","-r",t]))}async function lY(e){return new Set((await k("adb",tz(e,["shell","pm","list","packages"]))).stdout.split("\n").map(e=>e.replace("package:","").trim()).filter(Boolean))}async function lJ(e,t){let n=Array.from(await lY(e)).filter(e=>!t.has(e));if(1===n.length)return n[0]}async function lK(e,t){e.booted||await s6(e.id),await lH(e,t)}async function lZ(e,t,n){let r=n?void 0:await lY(e);return await lK(e,t),n??(r?await lJ(e,r):void 0)}async function lQ(e,t){e.booted||await s6(e.id);let n=await lb({kind:"path",path:t});try{let t=await lZ(e,n.installablePath,n.packageName),r=t?lC(t):void 0;return{archivePath:n.archivePath,installablePath:n.installablePath,packageName:t,appName:r,launchTarget:t}}finally{await n.cleanup()}}async function l0(e,t,n){e.booted||await s6(e.id);let{package:r}=await lj(e,t),a=await lb({kind:"path",path:n},{resolveIdentity:!1});try{return await lK(e,a.installablePath),{package:r}}finally{await a.cleanup()}}function l1(e){let t=e.direction,n="up"===t||"down"===t?e.referenceHeight:e.referenceWidth,r=function(e){if(void 0===e)return .6;if(!Number.isFinite(e)||e<=0)throw new _("INVALID_ARGS","scroll amount must be a positive number");return e}(e.amount),a=void 0!==e.pixels?function(e){if(!Number.isFinite(e)||e<=0)throw new _("INVALID_ARGS","scroll pixels must be a positive integer");return Math.max(1,Math.round(e))}(e.pixels):Math.round(n*r),i=Math.max(1,Math.round(.05*n)),o=Math.max(1,Math.min(a,Math.max(1,n-2*i))),s=Math.round(o/2),l=Math.round(e.referenceWidth/2),u=Math.round(e.referenceHeight/2),d=(n,r,a,i)=>({direction:t,x1:n,y1:r,x2:a,y2:i,referenceWidth:e.referenceWidth,referenceHeight:e.referenceHeight,amount:e.amount,pixels:o});switch(t){case"up":return d(l,u-s,l,u+s);case"down":return d(l,u+s,l,u-s);case"left":return d(l-s,u,l+s,u);case"right":return d(l+s,u,l-s,u)}}function l2(e,t,n){let r=function(e){let t=0,n=0,r=[...e.children];for(;r.length>0;){let e=r.pop();t+=1,n=Math.max(n,e.depth),r.push(...e.children)}return{rawNodeCount:t,maxDepth:n}}(e),a=[],i=[],o=!1,s=n.depth??1/0,l=n.scope?function(e,t){let n=t.toLowerCase(),r=[...e.children],a=0;for(;a<r.length;){let e=r[a++],t=e.label?.toLowerCase()??"",i=e.value?.toLowerCase()??"",o=e.identifier?.toLowerCase()??"";if(t.includes(n)||i.includes(n)||o.includes(n))return e;r.push(...e.children)}return null}(e,n.scope):null,u=l?[l]:e.children,d=new Map,c=e=>{let t=d.get(e);if(void 0!==t)return t;for(let t of e.children)if(t.hittable||c(t))return d.set(e,!0),!0;return d.set(e,!1),!1},p=(e,r,l,u=!1,d=!1)=>{if(a.length>=t){o=!0;return}if(r>s)return;let f=!!n.raw||function(e,t,n,r,a){var i;let o,s=l6(e.type),l=!!(e.label&&e.label.trim().length>0),u=!!(e.identifier&&e.identifier.trim().length>0),d=l&&!l9(e.label??""),c=u&&!l9(e.identifier??""),p=(o=(i=s).split(".").pop()??i).includes("layout")||"viewgroup"===o||"view"===o,f="imageview"===s||"imagebutton"===s;if(t.interactiveOnly)return!!(e.hittable||ec(s)&&r)||!!(d||c)&&!f&&(!p||!!a)&&(n||r||a);return t.compact?d||c||!!e.hittable:!p&&!f||!!e.hittable||!!d||!!c&&!!r||r}(e,n,u,c(e),d),h=l;f&&(h=a.length,i.push(e),a.push({index:h,type:e.type??void 0,label:e.label??void 0,value:e.value??void 0,identifier:e.identifier??void 0,rect:e.rect,enabled:e.enabled,hittable:e.hittable,depth:r,parentIndex:l,...e.hiddenContentAbove?{hiddenContentAbove:!0}:{},...e.hiddenContentBelow?{hiddenContentBelow:!0}:{}}));let m=u||!!e.hittable,w=d||function(e){if(!e)return!1;let t=l6(e);return t.includes("recyclerview")||t.includes("listview")||t.includes("gridview")}(e.type);for(let t of e.children)if(p(t,r+1,h,m,w),o)return};for(let e of u)if(p(e,0,void 0,!1,!1),o)break;return o?{nodes:a,sourceNodes:i,truncated:o,analysis:r}:{nodes:a,sourceNodes:i,analysis:r}}function l3(e){let t=function(e){let t=new Map,n=e.indexOf(" "),r=e.lastIndexOf(">");if(n<0||r<=n)return t;let a=/([^\s=/>]+)\s*=\s*(["'])([\s\S]*?)\2/y,i=n;for(;i<r;){for(;i<r;){let t=e[i];if(" "!==t&&"\n"!==t&&"\r"!==t&&" "!==t)break;i+=1}if(i>=r)break;let n=e[i];if("/"===n||">"===n)break;a.lastIndex=i;let o=a.exec(e);if(!o)break;t.set(o[1],o[3]),i=a.lastIndex}return t}(e),n=e=>{let n=l4(t,e);if(null!==n)return"true"===n};return{text:l4(t,"text"),desc:l4(t,"content-desc"),resourceId:l4(t,"resource-id"),className:l4(t,"class"),bounds:l4(t,"bounds"),clickable:n("clickable"),enabled:n("enabled"),focusable:n("focusable"),focused:n("focused")}}function l4(e,t){return e.get(t)??null}function l5(e){if(!e)return;let t=/\[(\d+),(\d+)\]\[(\d+),(\d+)\]/.exec(e);if(!t)return;let n=Number(t[1]),r=Number(t[2]);return{x:n,y:r,width:Math.max(0,Number(t[3])-n),height:Math.max(0,Number(t[4])-r)}}function l8(e){let t={type:null,label:null,value:null,identifier:null,depth:-1,children:[]},n=[t],r=/<node\b[^>]*>|<\/node>/g,a=r.exec(e);for(;a;){let t=a[0];if(t.startsWith("</node")){n.length>1&&n.pop(),a=r.exec(e);continue}let i=l3(t),o=l5(i.bounds),s=n[n.length-1],l={type:i.className,label:i.text||i.desc,value:i.text,identifier:i.resourceId,rect:o,enabled:i.enabled,hittable:i.clickable??i.focusable,depth:s.depth+1,parentIndex:void 0,children:[]};s.children.push(l),t.endsWith("/>")||n.push(l),a=r.exec(e)}return t}function l6(e){return e?e.toLowerCase():""}function l9(e){let t=e.trim();return!!t&&/^[\w.]+:id\/[\w.-]+$/i.test(t)}function l7(e){if(0===e.length)return null;let t=[...e].sort((e,t)=>e-t);return t[Math.floor(t.length/2)]??null}function ue(e,t){let n=Math.max(24,Math.round(.2*Math.min(e.size,t.size))),r=Math.max(48,Math.round(.15*Math.min(e.crossSize,t.crossSize)));return Math.abs(e.size-t.size)<=n&&Math.abs(e.crossSize-t.crossSize)<=r}function ut(e,t){return{start:e.y-t.y,size:e.height,crossSize:e.width}}async function un(e,t={}){let n=await ua(e);if(!t.interactiveOnly){let r=function(e,t){let{sourceNodes:n,...r}=l2(l8(e),800,t);return r}(n,t);return await ur(e,r.nodes),r}let r=l8(n),a=l2(r,800,{...t,interactiveOnly:!1});await ur(e,a.nodes),function(e){if(0===e.length||e.some(e=>e.hiddenContentAbove||e.hiddenContentBelow))return;let t=new Map(ef(ea(e)).nodes.filter(e=>e.hiddenContentAbove||e.hiddenContentBelow).map(e=>[e.index,e]));for(let n of e){let e=t.get(n.index);e&&(e.hiddenContentAbove&&(n.hiddenContentAbove=!0),e.hiddenContentBelow&&(n.hiddenContentBelow=!0))}}(a.nodes),function(e){for(let[t,n]of e.sourceNodes.entries()){let r=e.nodes[t];r&&(r.hiddenContentAbove&&(n.hiddenContentAbove=!0),r.hiddenContentBelow&&(n.hiddenContentBelow=!0))}}(a);let{sourceNodes:i,...o}=l2(r,800,t);return o}async function ur(e,t){if(!t.some(e=>ec(e.type)))return;let n=await ul(e);n&&function(e,t){let n=function(e){let t={className:"root",rect:{x:0,y:0,width:0,height:0},children:[]},n=[{indent:-1,node:t}],r=/^(\s*)([\w.$]+)\{[^}]* (-?\d+),(-?\d+)-(-?\d+),(-?\d+) #/;for(let t of e.split("\n")){let e=r.exec(t);if(!e)continue;let a=e[1].length,i=Number(e[3]),o=Number(e[4]),s=Number(e[5]),l=Number(e[6]),u={className:e[2],rect:{x:i,y:o,width:Math.max(0,s-i),height:Math.max(0,l-o)},children:[]};for(;n.length>1&&a<=n[n.length-1].indent;)n.pop();n[n.length-1].node.children.push(u),n.push({indent:a,node:u})}return t.children.length>0?t:null}(t);if(!n)return;let r=function(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();if(ec(e.className)){let n=function(e){let t=e.children[0];if(!t)return null;let n=Math.max(t.rect.height,...t.children.map(e=>e.rect.y+e.rect.height)),r=t.children.filter(e=>e.rect.height>0).map(t=>ut(t.rect,e.rect)).sort((e,t)=>e.start-t.start);return 0===r.length?null:{rect:e.rect,contentExtent:n,contentBlocks:r}}(e);n&&t.push(n)}n.push(...e.children)}return t}(n);if(0!==r.length)for(let t of e){if(!t.rect||!ec(t.type))continue;let n=function(e,t){let n=null,r=1/0;for(let a of t){let t=Math.abs(a.rect.width-e.width)+Math.abs(a.rect.height-e.height);if(t>32)continue;let i=4*t+(Math.abs(a.rect.x-e.x)+Math.abs(a.rect.y-e.y));i<r&&(n=a,r=i)}return n}(t.rect,r);if(!n)continue;let a=function(e,t){let n=function(e,t){let n=t,r=new Set;for(;!r.has(n.index);){var a,i;r.add(n.index);let o=e.filter(e=>e.parentIndex===n.index&&e.rect);if(1!==o.length)return n;let s=o[0];if(a=s.rect,i=t.rect,a.x!==i.x||a.y!==i.y||a.width!==i.width||a.height!==i.height)return n;n=s}return t}(e,t);return e.filter(e=>e.parentIndex===n.index&&e.rect).map(e=>e.rect).filter(e=>e.height>0).sort((e,t)=>e.y-t.y).map(e=>ut(e,t.rect))}(e,t),i=function(e){let{viewportRect:t,visibleBlocks:n,nativeScrollView:r}=e;if(0===n.length||0===r.contentBlocks.length)return null;let a=function(e){if(0===e.contentBlocks.length)return null;let t=e.contentBlocks[0],n=e.contentBlocks[e.contentBlocks.length-1];if(!t||!n)return null;let r=l7(e.contentBlocks.map(e=>e.size))??e.rect.height,a=Math.max(48,Math.round(.5*r)),i=Math.max(24,Math.round(.25*r)),o=t.start>=a,s=e.contentExtent-(n.start+n.size)>=i;return o||s?{above:o,below:s}:null}(r),i=function(e,t){let n=new Map;for(let r of e)for(let e of t){if(!ue(r,e))continue;let t=r.start-e.start,a=8*Math.round(t/8),i=n.get(a)??[];i.push(t),n.set(a,i)}let r=null;for(let e of n.values())(!r||e.length>r.length)&&(r=e);if(!r||r.length<2)return null;let a=[...r].sort((e,t)=>e-t);return a[Math.floor(a.length/2)]??null}(r.contentBlocks,n)??function(e){let{nativeBlocks:t,visibleBlocks:n,viewportExtent:r,contentExtent:a}=e,i=[],o=[];for(let e of t)for(let t of n){if(!ue(e,t))continue;let n=e.start-t.start;16>=Math.abs(n)&&i.push(n),16>=Math.abs(n+r-a)&&o.push(n)}return o.length>0?l7(o):i.length>0?l7(i):null}({nativeBlocks:r.contentBlocks,visibleBlocks:n,viewportExtent:t.height,contentExtent:r.contentExtent});if(null===i)return a;let o=t.height;return{above:(a?.above??!1)||i>16,below:(a?.below??!1)||i+o<r.contentExtent-16}}({viewportRect:t.rect,visibleBlocks:a,nativeScrollView:n});i&&(i.above&&(t.hiddenContentAbove=!0),i.below&&(t.hiddenContentBelow=!0))}}(t,n)}async function ua(e){return of(()=>ui(e),{shouldRetry:us})}async function ui(e){var t,n,r;let a,i,o=await k("adb",tz(e,["exec-out","uiautomator","dump","/dev/tty"]),{allowFailure:!0}),s=uo(o.stdout,o.stderr);if(s)return s;let l="/sdcard/window_dump.xml",u=await k("adb",tz(e,["shell","uiautomator","dump",l]),{allowFailure:!0}),d=(t=l,n=u.stdout,r=u.stderr,a=`${n}
|
|
19
|
+
${r}`,i=/dumped to:\s*(\S+)/i.exec(a),i?.[1]??t),c=await k("adb",tz(e,["shell","cat",d])),p=uo(c.stdout,c.stderr);if(!p)throw new _("COMMAND_FAILED","uiautomator dump did not return XML",{stdout:c.stdout,stderr:c.stderr});return p}function uo(e,t){let n=`${e}
|
|
20
|
+
${t}`,r=n.indexOf("<?xml"),a=r>=0?r:n.indexOf("<hierarchy");if(a<0)return null;let i=n.lastIndexOf("</hierarchy>");if(i<0||i<a)return null;let o=n.slice(a,i+12).trim();return o.length>0?o:null}function us(e){if(!(e instanceof _)||"COMMAND_FAILED"!==e.code)return!1;let t=`${e.details?.stderr??""}`.toLowerCase();return!!(t.includes("device offline")||t.includes("device not found")||t.includes("transport error")||t.includes("connection reset")||t.includes("broken pipe")||t.includes("timed out")||t.includes("no such file or directory"))}async function ul(e){try{let t=await k("adb",tz(e,["shell","dumpsys","activity","top"]),{allowFailure:!0,timeoutMs:8e3}),n=`${t.stdout}
|
|
21
|
+
${t.stderr}`.trim();return n.length>0?n:null}catch{return null}}async function uu(e,t,n){await k("adb",tz(e,["shell","input","tap",String(t),String(n)]))}async function ud(e,t,n,r,a,i=250){await k("adb",tz(e,["shell","input","swipe",String(t),String(n),String(r),String(a),String(i)]))}async function uc(e){await k("adb",tz(e,["shell","input","keyevent","4"]))}async function up(e){await k("adb",tz(e,["shell","input","keyevent","3"]))}async function uf(e,t){let n=function(e){switch(e){case"portrait":return"0";case"landscape-left":return"1";case"portrait-upside-down":return"2";case"landscape-right":return"3";default:throw new _("INVALID_ARGS",`Unsupported Android rotation: ${e}`)}}(t);await k("adb",tz(e,["shell","settings","put","system","accelerometer_rotation","0"])),await k("adb",tz(e,["shell","settings","put","system","user_rotation",n]))}async function uh(e){await k("adb",tz(e,["shell","input","keyevent","187"]))}async function um(e,t,n,r=800){await k("adb",tz(e,["shell","input","swipe",String(t),String(n),String(t),String(n),String(r)]))}async function uw(e,t,n=0){n>0&&Array.from(t).length>1?await uN(e,t,1,n):await ug(e,t)}async function ug(e,t){let n=uS(t);if(!n||"ok"!==await u_(e,t))try{let n=t.replace(/ /g,"%s");await k("adb",tz(e,["shell","input","text",n]))}catch(e){if(n&&function(e){if(!(e instanceof _)||"COMMAND_FAILED"!==e.code)return!1;let t=String(e.details?.stderr??"").toLowerCase();return!!(t.includes("exception occurred while executing 'text'")||t.includes("nullpointerexception")&&t.includes("inputshellcommand.sendtext"))}(e))throw new _("COMMAND_FAILED","Non-ASCII text input is not supported on this Android shell. Install an ADB keyboard IME or use ASCII input.",{textPreview:t.slice(0,32)},e instanceof Error?e:void 0);throw e}}async function uy(e,t,n){await uu(e,t,n)}async function ub(e,t,n,r,a=0){let i=Array.from(r).length,o=uS(r),s=[{strategy:"input_text",clearPadding:12,minClear:8,maxClear:48}];!o&&a<=0&&s.push({strategy:"clipboard_paste",clearPadding:12,minClear:8,maxClear:48}),(!o||a>0)&&s.push({strategy:"chunked_input",clearPadding:24,minClear:16,maxClear:96});let l=null;for(let o of s){var u,d;await uy(e,t,n);let s=(u=i+o.clearPadding,d=o.minClear,Math.max(d,Math.min(o.maxClear,u)));if(await uk(e,s),"input_text"===o.strategy)await uw(e,r,a);else if("clipboard_paste"===o.strategy){if("ok"!==await u_(e,r))continue}else await uN(e,r,1,a>0?a:15);let c=await uv(e,t,n,r);if(l=c.actual,c.ok)return}throw new _("COMMAND_FAILED","Android fill verification failed",{expected:r,actual:l??null})}async function uv(e,t,n,r){let a=null;for(let i of[0,150,350])if(i>0&&await tY(i),function(e,t){if(e===t)return!0;let n=uI(e),r=uI(t);return!!n&&!!r&&(!!(n===r||n.includes(r))||r.includes(n)&&n.length>=Math.max(4,Math.floor(.8*r.length)))}(a=await uD(e,t,n),r))return{ok:!0,actual:a};return{ok:!1,actual:a}}function uI(e){return(e??"").replace(/\s+/g," ").trim()}async function uA(e,t,n){let r=await ux(e),a=l1({direction:t,amount:n?.amount,pixels:n?.pixels,referenceWidth:r.width,referenceHeight:r.height});return await k("adb",tz(e,["shell","input","swipe",String(a.x1),String(a.y1),String(a.x2),String(a.y2),"300"])),a}async function ux(e){let t=(await k("adb",tz(e,["shell","wm","size"]))).stdout.match(/Physical size:\s*(\d+)x(\d+)/);if(!t)throw new _("COMMAND_FAILED","Unable to read screen size");return{width:Number(t[1]),height:Number(t[2])}}async function uN(e,t,n,r){let a=Math.max(1,Math.floor(n)),i=Array.from(t);for(let t=0;t<i.length;t+=a){let n=i.slice(t,t+a).join("");await ug(e,n),r>0&&t+a<i.length&&await tY(r)}}function uS(e){for(let t of e){let e=t.codePointAt(0);if(void 0!==e&&(e<32||e>126))return!0}return!1}async function u_(e,t){let n=await k("adb",tz(e,["shell","cmd","clipboard","set","text",t]),{allowFailure:!0});return 0!==n.exitCode?"failed":tH(n.stdout,n.stderr)?"unsupported":0===(await k("adb",tz(e,["shell","input","keyevent","KEYCODE_PASTE"]),{allowFailure:!0})).exitCode||0===(await k("adb",tz(e,["shell","input","keyevent","279"]),{allowFailure:!0})).exitCode?"ok":"failed"}async function uk(e,t){let n=Math.max(0,t);await k("adb",tz(e,["shell","input","keyevent","KEYCODE_MOVE_END"]),{allowFailure:!0});for(let t=0;t<n;t+=24){let r=Math.min(24,n-t);await k("adb",tz(e,["shell","input","keyevent",...Array(r).fill("KEYCODE_DEL")]),{allowFailure:!0})}}async function uD(e,t,n){let r,a=await ua(e),i=/<node\b[^>]*>/g,o=null,s=null,l=null;for(;null!==(r=i.exec(a));){let e=l3(r[0]),a=l5(e.bounds);if(!a)continue;let i=e.className??"",u=(e.text??"").replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&"),d=e.focused??!1;if(!u)continue;let c=Math.max(1,a.width*a.height),p=t>=a.x&&t<=a.x+a.width&&n>=a.y&&n<=a.y+a.height;if(d&&uM(i)){(!o||c<=o.area)&&(o={text:u,area:c});continue}if(p&&uM(i)){(!s||c<=s.area)&&(s={text:u,area:c});continue}p&&(!l||c<=l.area)&&(l={text:u,area:c})}return o?.text??s?.text??l?.text??null}function uM(e){let t=e.toLowerCase();return t.includes("edittext")||t.includes("textfield")}async function uE(e){let t=await k("adb",tz(e,["shell","dumpsys","input_method"]),{allowFailure:!0});if(0!==t.exitCode)throw new _("COMMAND_FAILED","Failed to query Android keyboard state",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});return function(e){let t=function(e){let t=new Map;for(let n of e.matchAll(/\b(mInputShown|mIsInputViewShown|isInputViewShown)=([a-zA-Z]+)\b/g)){let e=n[1],r=n[2]?.toLowerCase();e&&("true"===r||"false"===r)&&t.set(e,"true"===r)}if(0===t.size)return null;for(let e of t.values())if(e)return!0;return!1}(e),n=t??!1;if(null===t){let t=e.match(/\bmImeWindowVis=0x([0-9a-fA-F]+)\b/);if(t?.[1]){let e=Number.parseInt(t[1],16);Number.isNaN(e)||(n=(1&e)!=0)}}let r=Array.from(e.matchAll(/\binputType=0x([0-9a-fA-F]+)\b/gi)),a=r.length>0?r[r.length-1]?.[1]:void 0,i=a?`0x${a.toLowerCase()}`:void 0;return{visible:n,inputType:i,type:i?function(e){let t=Number.parseInt(e.replace(/^0x/i,""),16);if(Number.isNaN(t))return"unknown";let n=15&t;if(2===n)return"number";if(3===n)return"phone";if(4===n)return"datetime";if(1!==n)return"unknown";let r=4080&t;return 32===r||208===r?"email":128===r||224===r||144===r?"password":"text"}(i):void 0}}(t.stdout)}async function uO(e){let t=await uE(e),n=t,r=0;for(;n.visible&&r<2;)await k("adb",tz(e,["shell","input","keyevent","111"])),r+=1,await tY(120),n=await uE(e);if(t.visible&&n.visible)throw new _("UNSUPPORTED_OPERATION","Android keyboard dismiss is unavailable for the current IME without back navigation.",{attempts:r,inputType:n.inputType,type:n.type});return{attempts:r,wasVisible:t.visible,dismissed:t.visible&&!n.visible,visible:n.visible,inputType:n.inputType,type:n.type}}async function uC(e){let t,n;return(n=(t=(await uL(e,["shell","cmd","clipboard","get","text"],"read")).replace(/\r\n/g,"\n").replace(/\n$/,"")).match(/^clipboard text:\s*(.*)$/i))?n[1]??"":"null"===t.trim().toLowerCase()?"":t}async function uR(e,t){await uL(e,["shell","cmd","clipboard","set","text",t],"write")}async function uL(e,t,n){let r=await k("adb",tz(e,t),{allowFailure:!0});if(tH(r.stdout,r.stderr))throw new _("UNSUPPORTED_OPERATION",`Android shell clipboard ${n} is not supported on this device.`);if(0!==r.exitCode)throw new _("COMMAND_FAILED",`Failed to ${n} Android clipboard text`,{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode});return r.stdout}let uP=["camera","microphone","photos","contacts","contacts-limited","notifications","calendar","location","location-always","media-library","motion","reminders","siri"];function uT(e){let t=e.trim().toLowerCase();if("grant"===t)return"grant";if("deny"===t)return"deny";if("reset"===t)return"reset";throw new _("INVALID_ARGS",`Invalid permission action: ${e}. Use grant|deny|reset.`)}function u$(e){let t=e?.trim().toLowerCase();if("camera"===t||"microphone"===t||"photos"===t||"contacts"===t||"contacts-limited"===t||"notifications"===t||"calendar"===t||"location"===t||"location-always"===t||"media-library"===t||"motion"===t||"reminders"===t||"siri"===t)return t;throw new _("INVALID_ARGS",`permission setting requires a target: ${uP.join("|")}`)}function uF(e){let t=e.trim().toLowerCase();if("light"===t)return"light";if("dark"===t)return"dark";if("toggle"===t)return"toggle";throw new _("INVALID_ARGS",`Invalid appearance state: ${e}. Use light|dark|toggle.`)}async function uU(e,t,n,r,a){switch(t.toLowerCase()){case"wifi":{let t=uV(n);await k("adb",tz(e,["shell","svc","wifi",t?"enable":"disable"]));return}case"airplane":{let t=uV(n);await k("adb",tz(e,["shell","settings","put","global","airplane_mode_on",t?"1":"0"])),await k("adb",tz(e,["shell","am","broadcast","-a","android.intent.action.AIRPLANE_MODE","--ez","state",t?"true":"false"]));return}case"location":{let t=uV(n);await k("adb",tz(e,["shell","settings","put","secure","location_mode",t?"3":"0"]));return}case"appearance":{let t=await uB(e,n);await k("adb",tz(e,["shell","cmd","uimode","night","dark"===t?"yes":"no"]));return}case"fingerprint":{let t=function(e){let t=e.trim().toLowerCase();if("match"===t)return"match";if("nonmatch"===t)return"nonmatch";throw new _("INVALID_ARGS",`Invalid fingerprint state: ${e}. Use match|nonmatch.`)}(n);await uG(e,t);return}case"permission":{if(!r)throw new _("INVALID_ARGS","permission setting requires an active app in session");let t=uT(n),i=function(e,t){let n=u$(e);if(t?.trim())throw new _("INVALID_ARGS",`Permission mode is only supported for photos. Received: ${t}.`);if("camera"===n)return{kind:"pm",value:"android.permission.CAMERA",type:"camera"};if("microphone"===n)return{kind:"pm",value:"android.permission.RECORD_AUDIO",type:"microphone"};if("photos"===n)return{kind:"pm",value:"android.permission.READ_MEDIA_IMAGES",type:"photos"};if("contacts"===n)return{kind:"pm",value:"android.permission.READ_CONTACTS",type:"contacts"};if("notifications"===n)return{kind:"notifications",appOps:"POST_NOTIFICATION",permission:"android.permission.POST_NOTIFICATIONS"};throw new _("INVALID_ARGS",`Unsupported permission target on Android: ${e}. Use camera|microphone|photos|contacts|notifications.`)}(a?.permissionTarget,a?.permissionMode);if("notifications"===i.kind)return void await uq(e,r,t,i);let o="grant"===t?"grant":"revoke";if("photos"===i.type)return void await uj(e,r,o);await k("adb",tz(e,["shell","pm",o,r,i.value]));return}default:throw new _("INVALID_ARGS",`Unsupported setting: ${t}`)}}async function uG(e,t){var n;let r,a,i=(n=e,a=[["shell","cmd","fingerprint","touch",r="match"===t?"1":"9999"],["shell","cmd","fingerprint","finger",r]],"emulator"===n.kind&&a.push(["emu","finger","touch",r]),a),o=[];for(let t of i){let n=await k("adb",tz(e,t),{allowFailure:!0});if(0===n.exitCode)return;o.push({args:t,stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode})}let s=o.map(e=>({args:e.args.join(" "),exitCode:e.exitCode,stderr:e.stderr.slice(0,400)}));if(o.length>0&&o.every(e=>{var t,n;let r;return t=e.stdout,n=e.stderr,(r=`${t}
|
|
22
|
+
${n}`.toLowerCase()).includes("unknown command")||r.includes("can't find service: fingerprint")||r.includes("service fingerprint was not found")||r.includes("fingerprint cmd unavailable")||r.includes("emu command is not supported")||r.includes("emulator console is not running")||r.includes("fingerprint")&&r.includes("not found")}))throw new _("UNSUPPORTED_OPERATION","Android fingerprint simulation is not supported on this target/runtime.",{deviceId:e.id,action:t,hint:"Use an Android emulator with biometric support, or a device/runtime that exposes cmd fingerprint.",attempts:s});throw new _("COMMAND_FAILED","Failed to simulate Android fingerprint.",{deviceId:e.id,action:t,attempts:s})}function uV(e){let t=e.toLowerCase();if("on"===t||"true"===t||"1"===t)return!0;if("off"===t||"false"===t||"0"===t)return!1;throw new _("INVALID_ARGS",`Invalid setting state: ${e}`)}async function uB(e,t){let n=uF(t);if("toggle"!==n)return n;let r=await k("adb",tz(e,["shell","cmd","uimode","night"]),{allowFailure:!0});if(0!==r.exitCode)throw new _("COMMAND_FAILED","Failed to read current Android appearance",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode});let a=function(e,t){let n=/night mode:\s*(yes|no|auto)\b/i.exec(`${e}
|
|
23
|
+
${t}`);if(!n)return null;let r=n[1].toLowerCase();return"yes"===r?"dark":"no"===r?"light":"auto"===r?"auto":null}(r.stdout,r.stderr);if(!a)throw new _("COMMAND_FAILED","Unable to determine current Android appearance for toggle",{stdout:r.stdout,stderr:r.stderr});return"auto"===a?"dark":"dark"===a?"light":"dark"}async function uj(e,t,n){let r=await uW(e),a=[];for(let i of null!==r&&r>=33?["android.permission.READ_MEDIA_IMAGES","android.permission.READ_EXTERNAL_STORAGE"]:["android.permission.READ_EXTERNAL_STORAGE","android.permission.READ_MEDIA_IMAGES"]){let r=await k("adb",tz(e,["shell","pm",n,t,i]),{allowFailure:!0});if(0===r.exitCode)return;a.push({permission:i,stderr:r.stderr,exitCode:r.exitCode})}throw new _("COMMAND_FAILED",`Failed to ${n} Android photos permission`,{appPackage:t,sdkInt:r,attempts:a})}async function uq(e,t,n,r){"grant"===n?await k("adb",tz(e,["shell","pm","grant",t,r.permission]),{allowFailure:!0}):(await k("adb",tz(e,["shell","pm","revoke",t,r.permission]),{allowFailure:!0}),"reset"===n&&(await k("adb",tz(e,["shell","pm","clear-permission-flags",t,r.permission,"user-set"]),{allowFailure:!0}),await k("adb",tz(e,["shell","pm","clear-permission-flags",t,r.permission,"user-fixed"]),{allowFailure:!0}))),await k("adb",tz(e,["shell","appops","set",t,r.appOps,"grant"===n?"allow":"deny"===n?"deny":"default"]))}async function uW(e){let t=await k("adb",tz(e,["shell","getprop","ro.build.version.sdk"]),{allowFailure:!0});if(0!==t.exitCode)return null;let n=Number.parseInt(t.stdout.trim(),10);return!Number.isFinite(n)||n<=0?null:n}async function uz(e,t,n){let r="string"==typeof n.action&&n.action.trim()?n.action.trim():`${t}.TEST_PUSH`,a=["shell","am","broadcast","-a",r,"-p",t],i="string"==typeof n.receiver?n.receiver.trim():"";i&&a.push("-n",i);let o=n.extras;if(void 0!==o&&("object"!=typeof o||null===o||Array.isArray(o)))throw new _("INVALID_ARGS","Android push payload extras must be an object");let s=0;for(let[e,t]of Object.entries(o??{}))e&&(function(e,t,n){if("string"==typeof n)return e.push("--es",t,n);if("boolean"==typeof n)return e.push("--ez",t,n?"true":"false");if("number"==typeof n&&Number.isFinite(n))return Number.isInteger(n)?e.push("--ei",t,String(n)):e.push("--ef",t,String(n));throw new _("INVALID_ARGS",`Unsupported Android broadcast extra type for "${t}". Use string, boolean, or number.`)}(a,e,t),s+=1);return await k("adb",tz(e,a)),{action:r,extrasCount:s}}let uX=Buffer.from([137,80,78,71,13,10,26,10]);async function uH(e,t){await uY(e);try{await tY(1e3),await uK(e,t)}finally{await uJ(e).catch(()=>{})}}async function uY(e){let t=t=>k("adb",tz(e,["shell",t]),{allowFailure:!0});await t("settings put global sysui_demo_allowed 1");let n=e=>t(`am broadcast -a com.android.systemui.demo -e command ${e}`);await n("clock -e hhmm 0941"),await n("notifications -e visible false")}async function uJ(e){await k("adb",tz(e,["shell","am broadcast -a com.android.systemui.demo -e command exit"]),{allowFailure:!0})}async function uK(e,t){let n=await k("adb",tz(e,["exec-out","screencap","-p"]),{binaryStdout:!0});if(!n.stdoutBuffer)throw new _("COMMAND_FAILED","Failed to capture screenshot");let r=n.stdoutBuffer.indexOf(uX);if(r<0)throw new _("COMMAND_FAILED","Screenshot data does not contain a valid PNG header");let a=function(e,t){let n=t+uX.length;for(;n+8<=e.length;){let t=e.readUInt32BE(n),r=n+4,a=e.toString("ascii",r,r+4),i=n+12+t;if(i>e.length)break;if("IEND"===a)return i;n=i}return null}(n.stdoutBuffer,r);if(!a)throw new _("COMMAND_FAILED","Screenshot data does not contain a complete PNG payload");await i.writeFile(t,n.stdoutBuffer.subarray(r,a))}let uZ=ok(process.env.AGENT_DEVICE_IOS_BOOT_TIMEOUT_MS,ou,5e3),uQ=ok(process.env.AGENT_DEVICE_IOS_SIMCTL_LIST_TIMEOUT_MS,ol,1e3),u0=ok(process.env.AGENT_DEVICE_IOS_APP_LAUNCH_TIMEOUT_MS,3e4,5e3),u1=ok(process.env.AGENT_DEVICE_IOS_DEVICECTL_TIMEOUT_MS,2e4,1e3),u2=ok(process.env.AGENT_DEVICE_IOS_SIMULATOR_FOCUS_TIMEOUT_MS,1e4,1e3),u3=ok(process.env.AGENT_DEVICE_IOS_SIMULATOR_SCREENSHOT_TIMEOUT_MS,2e4,1e3),u4=ok(process.env.AGENT_DEVICE_IOS_RUNNER_SCREENSHOT_COPY_TIMEOUT_MS,2e4,1e3),u5=os(process.env.AGENT_DEVICE_IOS_SIMULATOR_SCREENSHOT_RUNNER_FALLBACK);async function u8(e,t){let n=["devicectl",...e],r=await k("xcrun",n,{allowFailure:!0,timeoutMs:u1});if(0===r.exitCode)return;let a=String(r.stdout??""),i=String(r.stderr??"");throw new _("COMMAND_FAILED",`Failed to ${t.action}`,{cmd:"xcrun",args:n,exitCode:r.exitCode,stdout:a,stderr:i,deviceId:t.deviceId,hint:de(a,i)??u7})}async function u6(e,t){let n=o.join(p.tmpdir(),`agent-device-ios-apps-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`),r=["devicectl","device","info","apps","--device",e.id,"--include-all-apps","--json-output",n],a=await k("xcrun",r,{allowFailure:!0,timeoutMs:u1});try{var s,l;if(0!==a.exitCode){let t=String(a.stdout??""),n=String(a.stderr??"");throw new _("COMMAND_FAILED","Failed to list iOS apps",{cmd:"xcrun",args:r,exitCode:a.exitCode,stdout:t,stderr:n,deviceId:e.id,hint:de(t,n)??u7})}let o=await i.readFile(n,"utf8");return s=function(e){let t=e?.result?.apps;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!e||"object"!=typeof e)continue;let t="string"==typeof e.bundleIdentifier?e.bundleIdentifier.trim():"";if(!t)continue;let r="string"==typeof e.name&&e.name.trim().length>0?e.name.trim():t,a="string"==typeof e.url&&e.url.trim().length>0?e.url.trim():void 0;n.push({bundleId:t,name:r,url:a})}return n}(JSON.parse(o)),l=t,"user-installed"===l?s.filter(e=>!e.bundleId.startsWith("com.apple.")):s}catch(t){if(t instanceof _)throw t;throw new _("COMMAND_FAILED","Failed to parse iOS apps list",{deviceId:e.id,cause:String(t)})}finally{await i.unlink(n).catch(()=>{})}}async function u9(e){let t=o.join(p.tmpdir(),`agent-device-ios-processes-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`),n=["devicectl","device","info","processes","--device",e.id,"--json-output",t],r=await k("xcrun",n,{allowFailure:!0,timeoutMs:u1});try{if(0!==r.exitCode){let t=String(r.stdout??""),a=String(r.stderr??"");throw new _("COMMAND_FAILED","Failed to list iOS processes",{cmd:"xcrun",args:n,exitCode:r.exitCode,stdout:t,stderr:a,deviceId:e.id,hint:de(t,a)??u7})}let a=await i.readFile(t,"utf8");return function(e){let t=e?.result?.runningProcesses;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!e||"object"!=typeof e)continue;let t="string"==typeof e.executable?e.executable.trim():"",r="number"==typeof e.processIdentifier&&Number.isFinite(e.processIdentifier)?e.processIdentifier:NaN;t&&Number.isFinite(r)&&n.push({executable:t,pid:r})}return n}(JSON.parse(a))}catch(t){if(t instanceof _)throw t;throw new _("COMMAND_FAILED","Failed to parse iOS process list",{deviceId:e.id,cause:String(t)})}finally{await i.unlink(t).catch(()=>{})}}let u7="Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.";function de(e,t){let n=`${e}
|
|
24
|
+
${t}`.toLowerCase();return n.includes("device is busy")&&n.includes("connecting")?"iOS device is still connecting. Keep it unlocked and connected by cable until it is fully available in Xcode Devices, then retry.":n.includes("coredeviceservice")&&n.includes("timed out")?"CoreDevice service timed out. Reconnect the device and retry; if it persists restart Xcode and the iOS device.":null}function dt(e){if(!(e instanceof _)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{};if(4!==t.exitCode)return!1;let n=String(t.stderr??"").toLowerCase();return n.includes("fbsopenapplicationserviceerrordomain")&&n.includes("the request to open")}async function dn(e,t){let n=await k("xcrun",t9(e,["get_app_container",e.id,t]),{allowFailure:!0});if(0!==n.exitCode)return{installed:!1};let r=n.stdout.trim();if(!r)return{installed:!1};let a=await k("plutil",["-extract","CFBundleExecutable","raw","-o","-",`${r}/Info.plist`],{allowFailure:!0});if(0!==a.exitCode||!a.stdout.trim())return{installed:!0};let i=a.stdout.trim(),o=`${r}/${i}`,s=await k("otool",["-l",o],{allowFailure:!0});if(0!==s.exitCode)return{installed:!0};let l=s.stdout.toLowerCase();return{installed:!0,simulatorCompatible:l.includes("iossimulator")||l.includes("platform 7")}}function dr(e,t){if("simulator"!==e.kind)throw new _("UNSUPPORTED_OPERATION",`${t} is only supported on iOS simulators`)}async function da(){await k("open",["-a","Simulator"],{allowFailure:!0,timeoutMs:u2})}async function di(e){let t,n;if("simulator"!==e.kind||"Booted"===await dl(e))return;let r=oc.fromTimeoutMs(uZ);try{await op(async({deadline:r})=>{if(r?.isExpired())throw new _("COMMAND_FAILED","iOS simulator boot deadline exceeded",{timeoutMs:uZ});let a=Math.max(1e3,r?.remainingMs()??uZ),i=await k("xcrun",t9(e,["boot",e.id]),{allowFailure:!0,timeoutMs:a});t={stdout:String(i.stdout??""),stderr:String(i.stderr??""),exitCode:i.exitCode};let o=`${t.stdout}
|
|
25
|
+
${t.stderr}`.toLowerCase(),s=o.includes("already booted")||o.includes("current state: booted");if(0!==t.exitCode&&!s)throw new _("COMMAND_FAILED","simctl boot failed",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});let l=await k("xcrun",t9(e,["bootstatus",e.id,"-b"]),{allowFailure:!0,timeoutMs:a});if(n={stdout:String(l.stdout??""),stderr:String(l.stderr??""),exitCode:l.exitCode},0!==n.exitCode)throw new _("COMMAND_FAILED","simctl bootstatus failed",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode});let u=await dl(e);if("Booted"!==u)throw new _("COMMAND_FAILED","Simulator is still booting",{state:u})},{maxAttempts:3,baseDelayMs:500,maxDelayMs:2e3,jitter:.2,shouldRetry:e=>{let r=oD({error:e,stdout:n?.stdout??t?.stdout,stderr:n?.stderr??t?.stderr,context:{platform:"ios",phase:"boot"}});return"IOS_BOOT_TIMEOUT"!==r&&"CI_RESOURCE_STARVATION_SUSPECTED"!==r}},{deadline:r,phase:"boot",classifyReason:e=>oD({error:e,stdout:n?.stdout??t?.stdout,stderr:n?.stderr??t?.stderr,context:{platform:"ios",phase:"boot"}})})}catch(i){let a=oD({error:i,stdout:n?.stdout??t?.stdout,stderr:n?.stderr??t?.stderr,context:{platform:"ios",phase:"boot"}});throw new _("COMMAND_FAILED","iOS simulator failed to boot",{platform:"ios",deviceId:e.id,timeoutMs:uZ,elapsedMs:r.elapsedMs(),reason:a,hint:oM(a),boot:t,bootstatus:n})}await da()}async function ds(e){let t=t9(e,["shutdown",e.id]),n=await k("xcrun",t,{allowFailure:!0,timeoutMs:15e3});return{success:0===n.exitCode,exitCode:n.exitCode,stdout:String(n.stdout??""),stderr:String(n.stderr??"")}}async function dl(e){let t="string"==typeof e?e:e.id,n="string"==typeof e?t6(["list","devices","-j"]):t9(e,["list","devices","-j"]),r=await k("xcrun",n,{allowFailure:!0,timeoutMs:uQ});if(0!==r.exitCode)return null;try{let e=JSON.parse(String(r.stdout??""));for(let n of Object.values(e.devices??{})){let e=n.find(e=>e.udid===t);if(e)return e.state}return null}catch{return null}}async function du(e,t){try{let n=await k("plutil",["-extract",t,"raw","-o","-",e],{allowFailure:!0});if(0===n.exitCode){let e=String(n.stdout??"").trim();if(e.length>0)return e}}catch{}try{var n,r;let a;return n=await i.readFile(e,"utf8"),r=t,o2(o1(n),(e,t)=>{void 0===a&&e===r&&"string"===t.name&&(a=t.text??void 0)}),a}catch{return}}async function dd(e,t){if("url"===e.kind&&!li(e.url))throw new _("INVALID_ARGS","iOS install_from_source URL sources are only supported for trusted artifact services such as GitHub Actions and EAS. Use a path source for other hosts.");let n=await lt({source:e,isInstallablePath:(e,t)=>t.isDirectory()&&e.toLowerCase().endsWith(".app")||t.isFile()&&e.toLowerCase().endsWith(".ipa"),installableLabel:"iOS installable (.app or .ipa)",allowArchiveExtraction:"url"!==e.kind||li(e.url),signal:t?.signal}),r=await dp(n.installablePath,t),a=await dc(r.installPath);return{archivePath:n.archivePath??(n.installablePath.toLowerCase().endsWith(".ipa")?n.installablePath:void 0),installablePath:r.installPath,bundleId:a.bundleId,appName:a.appName,cleanup:async()=>{await r.cleanup(),await n.cleanup()}}}async function dc(e){let t=o.join(e,"Info.plist"),[n,r,a]=await Promise.all([du(t,"CFBundleIdentifier"),du(t,"CFBundleDisplayName"),du(t,"CFBundleName")]);return{bundleId:n,appName:r??a}}async function dp(e,t){if(!e.toLowerCase().endsWith(".ipa"))return{installPath:e,cleanup:async()=>{}};let n=await i.mkdtemp(o.join(p.tmpdir(),"agent-device-ios-ipa-")),r=async()=>{await i.rm(n,{recursive:!0,force:!0})};try{await k("unzip",["-q",e,"-d",n]);let a=o.join(n,"Payload"),s=(await i.readdir(a,{withFileTypes:!0}).catch(()=>{throw new _("INVALID_ARGS","Invalid IPA: missing Payload directory")})).filter(e=>e.isDirectory()&&e.name.toLowerCase().endsWith(".app")).map(e=>({installPath:o.join(a,e.name),bundleName:e.name.replace(/\.app$/i,"")}));if(1===s.length)return{installPath:s[0].installPath,cleanup:r};if(0===s.length)throw new _("INVALID_ARGS","Invalid IPA: expected at least one .app under Payload, found 0");await df(s);let l=t?.appIdentifierHint?.trim();if(l){let e=function(e,t){let n=t.toLowerCase(),r=e.filter(e=>e.bundleName.toLowerCase()===n);if(1===r.length)return r[0];if(r.length>1)throw new _("INVALID_ARGS",`Invalid IPA: multiple app bundles matched "${t}" by name. Use a bundle id hint instead.`);if(t.includes(".")){let t=e.filter(e=>e.bundleId?.toLowerCase()===n);if(1===t.length)return t[0]}}(s,l);if(e)return{installPath:e.installPath,cleanup:r};throw new _("INVALID_ARGS",`Invalid IPA: found ${s.length} .app bundles under Payload and none matched "${l}". Available bundles: ${s.map(dh).join(", ")}`)}throw new _("INVALID_ARGS",`Invalid IPA: found ${s.length} .app bundles under Payload. Pass an app identifier or bundle name matching one of: ${s.map(dh).join(", ")}`)}catch(e){throw await r(),e}}async function df(e){await Promise.all(e.map(async e=>{if(e.bundleId&&e.appName)return;let t=await dc(e.installPath);e.bundleId=e.bundleId??t.bundleId,e.appName=e.appName??t.appName}))}function dh(e){let t=e.bundleId??e.appName;return t?`${e.bundleName}.app (${t})`:`${e.bundleName}.app`}function dm(e,t){return"user-installed"===t?e.filter(e=>!e.bundleId.startsWith("com.apple.")):e}let dw="agent-device-macos-helper",dg="AGENT_DEVICE_MACOS_HELPER_BIN",dy=o.join(p.homedir(),".agent-device","macos-helper","current"),db=o.join(dy,"manifest.json"),dv=/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+$/;function dI(e){let t=e.trim();if(!dv.test(t))throw new _("INVALID_ARGS","macOS bundle id must use reverse-DNS form like com.example.App",{bundleId:e});return t}function dA(){return function(e){let t=o.dirname(e);for(;;){let e=o.join(t,"macos-helper");if(a(o.join(e,"Package.swift")))return e;let n=o.dirname(t);if(n===t)break;t=n}throw new _("COMMAND_FAILED","Unable to locate macOS helper package root",{modulePath:e})}(l(import.meta.url))}async function dx(e){let t=await i.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(async t=>{let n=o.join(e,t.name);return t.isDirectory()?".build"===t.name?[]:await dx(n):t.isFile()&&(t.name.endsWith(".swift")||"Package.swift"===t.name)?[n]:[]}))).flat().sort()}async function dN(e){let t=await dx(e),n=c("sha256");for(let r of t)n.update(o.relative(e,r)),n.update("\0"),n.update(await i.readFile(r)),n.update("\0");let r=await k("swift",["--version"],{allowFailure:!0,cwd:e,timeoutMs:1e4});return n.update("swift-version"),n.update("\0"),n.update(r.stdout||r.stderr||`exit:${r.exitCode}`),n.update("\0"),n.digest("hex")}async function dS(){try{let e=JSON.parse(await i.readFile(db,"utf8"));return"string"==typeof e.fingerprint?e.fingerprint:null}catch{return null}}async function d_(){let e=await E(process.env[dg],dg);if(e)return e;let t=dA(),n=await dN(t),r=o.join(dy,dw);try{if(await dS()===n)return await i.access(r),r}catch{}let a=o.join(dA(),".build","release",dw);process.stderr.write("agent-device: building macOS helper (first run or helper update)\n"),await k("swift",["build","-c","release","--package-path",t],{cwd:t,timeoutMs:12e4}),await i.mkdir(dy,{recursive:!0});let s=`${r}.tmp`;return await i.copyFile(a,s),await i.rename(s,r),await i.chmod(r,493),await i.writeFile(db,`${JSON.stringify({fingerprint:n},null,2)}
|
|
26
|
+
`,"utf8"),r}async function dk(e){let t=process.env[dg]?.trim();if("darwin"!==process.platform&&!t)throw new _("UNSUPPORTED_PLATFORM","macOS helper is only available on macOS");let n=await d_(),r=await k(n,e,{allowFailure:!0,timeoutMs:3e4}),a=r.stdout.trim(),i=null;if(a)try{i=JSON.parse(a)}catch{i=null}if(0===r.exitCode&&i?.ok)return i.data;throw new _("COMMAND_FAILED",i&&!i.ok?i.error?.message??`macOS helper exited with code ${r.exitCode}`:a||r.stderr.trim()||`macOS helper exited with code ${r.exitCode}`,{helperPath:n,args:e,stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode,...i&&!i.ok?i.error?.details:{}})}async function dD(){return await dk(["app","frontmost"])}async function dM(e){return await dk(["app","quit","--bundle-id",dI(e)])}async function dE(e,t){return await dk(["permission",e,t])}async function dO(e,t={}){let n=["alert",e];return t.bundleId&&n.push("--bundle-id",dI(t.bundleId)),t.surface&&n.push("--surface",t.surface),await dk(n)}async function dC(e,t={}){let n=["snapshot","--surface",e];return t.bundleId&&n.push("--bundle-id",dI(t.bundleId)),await dk(n)}async function dR(e,t,n={}){let r=["read","--x",String(e),"--y",String(t)];return n.bundleId&&r.push("--bundle-id",dI(n.bundleId)),n.surface&&r.push("--surface",n.surface),await dk(r)}async function dL(e,t,n={}){let r=["press","--x",String(e),"--y",String(t)];return n.bundleId&&r.push("--bundle-id",dI(n.bundleId)),n.surface&&r.push("--surface",n.surface),await dk(r)}async function dP(e,t={}){let n=["screenshot","--out",e];return t.surface&&n.push("--surface",t.surface),t.fullscreen&&n.push("--fullscreen"),await dk(n)}let dT={settings:"com.apple.systempreferences"},d$=/^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/;function dF(e,t){let n=["-b",e];return t&&n.push(t),n}async function dU(e){for(let t of[o.join(e,"Contents","Info.plist"),o.join(e,"Info.plist")]){let[e,n,r]=await Promise.all([du(t,"CFBundleIdentifier"),du(t,"CFBundleDisplayName"),du(t,"CFBundleName")]);if(e||n||r)return{bundleId:e,appName:n??r}}return{}}async function dG(e){let t=e.trim(),n=dT[t.toLowerCase()];if(n)return n;if(d$.test(t))return t;let r=(await dX("all")).filter(e=>e.name.toLowerCase()===t.toLowerCase());if(1===r.length)return r[0].bundleId;if(r.length>1)throw new _("INVALID_ARGS",`Multiple apps matched "${e}"`,{matches:r});throw new _("APP_NOT_INSTALLED",`No app found matching "${e}"`)}async function dV(e,t,n){let r=n?.url?.trim();if(r){if(!sG(r))throw new _("INVALID_ARGS","open <app> <url> requires a valid URL target");let e=n?.appBundleId??await dG(t);await k("open",dF(e,r));return}let a=t.trim();if(sG(a))return void await k("open",[a]);let i=n?.appBundleId??await dG(a);await k("open",dF(i))}async function dB(e,t){let n=await dG(t),r=await dM(n);if(r.running&&!r.terminated&&!r.forceTerminated)throw new _("COMMAND_FAILED",`Failed to close macOS app ${t}`,{bundleId:n,running:r.running,terminated:r.terminated,forceTerminated:r.forceTerminated})}async function dj(){let e=await k("pbpaste",[],{allowFailure:!0});if(0!==e.exitCode)throw new _("COMMAND_FAILED","Failed to read macOS clipboard",{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode});return e.stdout.replace(/\r\n/g,"\n").replace(/\n$/,"")}async function dq(e){let t=await k("pbcopy",[],{allowFailure:!0,stdin:e});if(0!==t.exitCode)throw new _("COMMAND_FAILED","Failed to write macOS clipboard",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode})}async function dW(){let e=await k("osascript",["-e",'tell application "System Events" to tell appearance preferences to get dark mode'],{allowFailure:!0});if(0!==e.exitCode)throw new _("COMMAND_FAILED","Failed to read macOS appearance",{stdout:e.stdout,stderr:e.stderr,exitCode:e.exitCode});let t=e.stdout.trim().toLowerCase();if("true"===t)return!0;if("false"===t)return!1;throw new _("COMMAND_FAILED",`Unable to determine current macOS appearance from osascript output: ${e.stdout.trim()}`)}async function dz(e){let t=uF(e),n="toggle"===t?!await dW():"dark"===t,r=`tell application "System Events" to tell appearance preferences to set dark mode to ${n?"true":"false"}`,a=await k("osascript",["-e",r],{allowFailure:!0});if(0!==a.exitCode)throw new _("COMMAND_FAILED","Failed to set macOS appearance",{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode})}async function dX(e="all"){let t=["/Applications","/System/Applications",o.join(p.homedir(),"Applications")],n=new Set;for(let e of t){let t=await i.stat(e).catch(()=>null);if(!t?.isDirectory())continue;let r=await k("find",[e,"-maxdepth","4","-type","d","-name","*.app"],{allowFailure:!0});if(0===r.exitCode)for(let e of r.stdout.split("\n")){let t=e.trim();t&&n.add(t)}}return dm((await Promise.all(Array.from(n).map(async e=>{let t=await dU(e).catch(()=>({})),n=t.bundleId;return n?{bundleId:n,name:t.appName??o.basename(e,".app")}:null}))).filter(e=>null!==e).sort((e,t)=>e.name.localeCompare(t.name)),e)}let dH=["--time","9:41","--dataNetwork","wifi","--wifiMode","active","--wifiBars","3","--batteryState","charged","--batteryLevel","100"],dY={0:"hide",1:"wifi",6:"3g",7:"4g",8:"lte",9:"lte-a",10:"lte+",11:"5g",12:"5g+",13:"5g-uwb",14:"5g-uc"},dJ={1:"searching",2:"failed",3:"active"},dK={0:"notSupported",1:"searching",2:"failed",3:"active"};function dZ(e,t,n){return k("xcrun",t9(e,t),n)}async function dQ(e,t){var n,r;let a;await d1(e),t&&await d2(e,(a=[],(n=t).dataNetwork&&a.push("--dataNetwork",n.dataNetwork),n.wifiMode&&a.push("--wifiMode",n.wifiMode),void 0!==n.wifiBars&&("wifi"===n.dataNetwork||n.wifiMode)&&a.push("--wifiBars",n.wifiBars),n.cellularMode&&a.push("--cellularMode",n.cellularMode),void 0!==n.cellularBars&&(n.cellularMode||(r=n.dataNetwork)&&"hide"!==r&&"wifi"!==r||void 0!==n.operatorName)&&a.push("--cellularBars",n.cellularBars),void 0!==n.operatorName&&a.push("--operatorName",n.operatorName),a))}async function d0(e){let t=await dZ(e,["status_bar",e.id,"list"],{allowFailure:!0});if(0!==t.exitCode)throw new _("COMMAND_FAILED","Failed to read simulator status bar overrides",{exitCode:t.exitCode,stdout:t.stdout,stderr:t.stderr});return function(e){let t={};for(let n of e.split("\n").map(e=>e.trim()).filter(e=>e.length>0&&"Current Status Bar Overrides:"!==e&&!/^=+$/.test(e))){let e=/^DataNetworkType:\s+(\d+)$/.exec(n);if(e){let n=Number(e[1]),r=dY[n];if(!r)throw new _("COMMAND_FAILED",`Unsupported simulator data network type: ${n}`);t.dataNetwork=r;continue}let r=/^WiFi Mode:\s+(\d+),\s+WiFi Bars:\s+(\d+)$/.exec(n);if(r){let e=dJ[Number(r[1])];e&&(t.wifiMode=e),t.wifiBars=r[2];continue}let a=/^Cell Mode:\s+(\d+),\s+Cell Bars:\s+(\d+)$/.exec(n);if(a){let e=Number(a[1]),n=dK[e];if(!n)throw new _("COMMAND_FAILED",`Unsupported simulator cellular mode: ${e}`);t.cellularMode=n,t.cellularBars=a[2];continue}let i=/^Operator Name:\s*(.*)$/.exec(n);if(i){t.operatorName=i[1]??"";continue}}return 0===Object.keys(t).length?null:t}(t.stdout)}async function d1(e){await dZ(e,["status_bar",e.id,"clear"])}async function d2(e,t){0!==t.length&&await dZ(e,["status_bar",e.id,"override",...t])}function d3(e,t,n){eN({level:"warn",phase:`ios_screenshot_status_bar_${t}`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,...function(e){if(!(e instanceof _))return{reason:e instanceof Error?e.message:String(e)};let t=e.details??{},n=Array.isArray(t.args)?t.args.filter(e=>"string"==typeof e).join(" "):void 0;return{errorCode:e.code,reason:e.message,timeoutMs:"number"==typeof t.timeoutMs?t.timeoutMs:void 0,exitCode:"number"==typeof t.exitCode?t.exitCode:void 0,stderr:"string"==typeof t.stderr&&t.stderr.trim()?t.stderr:void 0,stdout:"string"==typeof t.stdout&&t.stdout.trim()?t.stdout:void 0,commandArgs:n}}(n)}})}function d4(e,t,n){return k("xcrun",t9(e,t),n)}let d5={ensureBooted:di,prepareStatusBarForScreenshot:async function e(e){let t=null,n=!1;try{t=await d0(e),n=!0}catch(t){d3(e,"snapshot_failed",t)}try{await d1(e),await d2(e,dH)}catch(t){d3(e,"prepare_failed",t)}return async()=>{await dQ(e,n?t:null)}},captureWithRetry:d9,runnerFallbackEnabled:u5,captureWithRunner:d7,shouldFallbackToRunner:co};async function d8(e,t,n,r){if("macos"===e.platform)return void await d7(e,t,n,r);if("simulator"===e.kind)return void await d6(e,t,n,r);try{await u8(["device","screenshot","--device",e.id,t],{action:"capture iOS screenshot",deviceId:e.id});return}catch(t){if(!function(e){if(!(e instanceof _)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{},n="string"==typeof t.stdout?t.stdout:"",r="string"==typeof t.stderr?t.stderr:"",a=`${e.message}
|
|
27
27
|
${n}
|
|
28
|
-
${r}`.toLowerCase();return
|
|
28
|
+
${r}`.toLowerCase();return a.includes("unknown option '--device'")||a.includes("unknown subcommand")&&a.includes("screenshot")||a.includes("unrecognized subcommand")&&a.includes("screenshot")}(t))throw t;cr(e,"devicectl_screenshot",t)}await d7(e,t,n,r)}async function d6(e,t,n,r,a=d5){if("simulator"!==e.kind)throw new _("UNSUPPORTED_OPERATION","Simulator screenshot fallback flow supports only iOS simulators");let i="object"==typeof r&&null!==r?r:a;await i.ensureBooted(e);let o=async()=>{};try{o=await i.prepareStatusBarForScreenshot(e)}catch(t){ca(e,"prepare_failed",t)}try{try{await i.captureWithRetry(e,t);return}catch(t){if(!i.shouldFallbackToRunner(t))throw t;if(!i.runnerFallbackEnabled){var s,l,u;let n,r;throw s=e,l=t,n=ci(l),eN({level:"warn",phase:"ios_screenshot_fallback_skipped",data:{platform:s.platform,deviceKind:s.kind,deviceId:s.id,from:"simctl_screenshot",to:"runner",reason:"Simulator runner fallback is disabled to avoid XCTest automation instability during screenshot capture.",...n}}),r=(u=t)instanceof _?u:new _("COMMAND_FAILED","Failed to capture iOS screenshot: simulator screenshot retries exhausted",void 0,u),new _(r.code,r.message,{...r.details??{},hint:"Restart the simulator and retry. If simctl screenshots keep timing out and you accept the stability tradeoff, set AGENT_DEVICE_IOS_SIMULATOR_SCREENSHOT_RUNNER_FALLBACK=1 to allow XCTest runner fallback."},r)}cr(e,"simctl_screenshot",t)}await i.captureWithRunner(e,t,n,"boolean"==typeof r?r:void 0)}finally{await o().catch(t=>ca(e,"restore_failed",t))}}async function d9(e,t){let n=oc.fromTimeoutMs(u3);await op(async({deadline:n})=>{await d4(e,["io",e.id,"screenshot",t],{timeoutMs:Math.max(1e3,n?.remainingMs()??u3)})},{maxAttempts:5,baseDelayMs:1e3,maxDelayMs:5e3,jitter:.2,shouldRetry:e=>co(e)},{deadline:n,phase:"ios_simulator_screenshot"})}async function d7(e,t,n,r){let a=(await sF(e,{command:"screenshot",appBundleId:n,fullscreen:r})).message;if(!a)throw new _("COMMAND_FAILED","Failed to capture iOS screenshot: runner returned no file path");"macos"===e.platform?await i.copyFile(a,t):"simulator"===e.kind?await ct(e,a,t):await ce(e,a,t)}async function ce(e,t,n){let r=oc.fromTimeoutMs(u4),a={exitCode:1,stdout:"",stderr:""};for(let i of sa)if(0===(a=await k("xcrun",["devicectl","device","copy","from","--device",e.id,"--source",t,"--destination",n,"--domain-type","appDataContainer","--domain-identifier",i],{allowFailure:!0,timeoutMs:cn(r,u4,"runner screenshot copy")})).exitCode)return;let i=a.stderr.trim()||a.stdout.trim()||`devicectl exited with code ${a.exitCode}`;throw new _("COMMAND_FAILED",`Failed to capture iOS screenshot: ${i}`)}async function ct(e,t,n){let r=oc.fromTimeoutMs(u4),a="Unable to locate runner container for simulator screenshot";for(let s of sa){let l=await d4(e,["get_app_container",e.id,s,"data"],{allowFailure:!0,timeoutMs:cn(r,u4,"runner screenshot container lookup")});if(0!==l.exitCode){let e=l.stderr.trim();e&&(a=e);continue}let u=l.stdout.trim();if(!u){a="simctl get_app_container returned empty output";continue}for(let e of function(e,t){let n=o.resolve(e),r=t.trim();if(!r)return[];let a=[],i=new Set,s=e=>{let t=o.normalize(e);i.has(t)||(i.add(t),a.push(t))},l=r.replace(/^\/+/,""),u=l.replace(/\\/g,"/");if(l&&s(o.join(n,l)),o.isAbsolute(r)&&s(o.normalize(r)),u.startsWith("tmp/"))s(o.join(n,u));else{let e=u.lastIndexOf("/tmp/");if(e>=0){let t=u.slice(e+1);s(o.join(n,t))}}let d=o.basename(r);return d&&s(o.join(n,"tmp",d)),a}(u,t))try{await i.copyFile(e,n);return}catch(e){a=e instanceof Error?e.message:String(e)}}throw new _("COMMAND_FAILED",`Failed to capture iOS screenshot: ${a}`)}function cn(e,t,n){let r=e.remainingMs();if(r>0)return r;throw new _("COMMAND_FAILED",`iOS ${n} timed out after ${t}ms`,{timeoutMs:t,step:n})}function cr(e,t,n){let r=ci(n);eN({level:"warn",phase:"ios_screenshot_fallback",data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,from:t,to:"runner",...r}})}function ca(e,t,n){eN({level:"warn",phase:`ios_screenshot_status_bar_${t}`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,...ci(n)}})}function ci(e){if(!(e instanceof _))return{reason:e instanceof Error?e.message:String(e)};let t=e.details??{},n=Array.isArray(t.args)?t.args.filter(e=>"string"==typeof e).join(" "):void 0;return{errorCode:e.code,reason:e.message,timeoutMs:"number"==typeof t.timeoutMs?t.timeoutMs:void 0,exitCode:"number"==typeof t.exitCode?t.exitCode:void 0,stderr:"string"==typeof t.stderr&&t.stderr.trim()?t.stderr:void 0,stdout:"string"==typeof t.stdout&&t.stdout.trim()?t.stdout:void 0,commandArgs:n}}function co(e){if(!(e instanceof _)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{},n="string"==typeof t.stdout?t.stdout:"",r="string"==typeof t.stderr?t.stderr:"",a=Array.isArray(t.args)?t.args.filter(e=>"string"==typeof e).join(" "):"",i=`${e.message}
|
|
29
29
|
${n}
|
|
30
30
|
${r}
|
|
31
|
-
${
|
|
32
|
-
${
|
|
33
|
-
${r.stderr}`.toLowerCase()))throw new _("COMMAND_FAILED",`simctl uninstall failed for ${n}`,{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode});return{bundleId:n}}async function
|
|
34
|
-
`,"utf8"),await
|
|
35
|
-
${t}`);if(!n)return null;let r=n[1].toLowerCase();return"dark"===r?"dark":"light"===r?"light":null}(r.stdout,r.stderr);if(!
|
|
36
|
-
${
|
|
37
|
-
${n}`.toLowerCase()).includes("unrecognized subcommand")||r.includes("unknown subcommand")||r.includes("not supported")||r.includes("unavailable")||r.includes("biometric")&&r.includes("invalid")}))throw new _("UNSUPPORTED_OPERATION",`${n.label} simulation is not supported on this simulator runtime.`,{deviceId:e.id,action:t,setting:n.settingName,attempts:a});throw new _("COMMAND_FAILED",`Failed to simulate ${n.settingName}.`,{deviceId:e.id,action:t,setting:n.settingName,attempts:a})}async function uZ(e,t){await l_(e);let n=0,r=ik.fromTimeoutMs(lc);try{await iL(async({deadline:n})=>{var r;if(n?.isExpired())throw new _("COMMAND_FAILED","App launch deadline exceeded",{timeoutMs:lc});let i=(r=["launch",e.id,t],t9(e,r)),a=await M("xcrun",i,{allowFailure:!0});if(0!==a.exitCode)throw new _("COMMAND_FAILED",`xcrun exited with code ${a.exitCode}`,{cmd:"xcrun",args:i,stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode})},{maxAttempts:10,baseDelayMs:1e3,maxDelayMs:5e3,jitter:.2,shouldRetry:e=>!!lA(e)&&(n+=1)<3},{deadline:r})}catch(n){if(lA(n)){var i;let r=(i=await lx(e,t)).installed?!1===i.simulatorCompatible?"ARCH_MISMATCH":"PERSISTENT_LAUNCH_FAIL":"APP_NOT_INSTALLED";n.details={...n.details,hint:function(e){switch(e){case"ARCH_MISMATCH":return"The app binary was not built for the simulator platform. Rebuild with a simulator destination or use a physical device.";case"APP_NOT_INSTALLED":return"The app bundle is not installed on this simulator. Run install before open.";case"PERSISTENT_LAUNCH_FAIL":return"The simulator repeatedly refused to launch the app. Inspect crash logs in Console.app or ~/Library/Logs/DiagnosticReports/ and consider reinstalling the app.";default:return"The simulator failed to launch the app. Retry with --debug and inspect diagnostics log for details."}}(r)}}throw n}}async function uQ(e,t,n){let r=["device","process","launch","--device",e.id,t];n?.payloadUrl&&r.push("--payload-url",n.payloadUrl),await lg(r,{action:"launch iOS app",deviceId:e.id})}async function u0(e,t,n,r,i,a,o){if("tv"===t.target)return u3(await e(t,{command:"swipe",direction:function(e){switch(e){case"up":return"down";case"down":return"up";case"left":return"right";case"right":return"left";default:return e}}(i),appBundleId:n.appBundleId},r),a);let s=o??await u1(e,t,n,r),l=sp({direction:i,amount:a?.amount,pixels:a?.pixels,referenceWidth:s.referenceWidth,referenceHeight:s.referenceHeight});return u3(await e(t,{command:"drag",x:s.originX+l.x1,y:s.originY+l.y1,x2:s.originX+l.x2,y2:s.originY+l.y2,appBundleId:n.appBundleId},r),{amount:l.amount,pixels:l.pixels,preferProvidedPixels:!0})}async function u1(e,t,n,r){let i=await e(t,{command:"interactionFrame",appBundleId:n.appBundleId},r),a=u2(i.x),o=u2(i.y),s=u2(i.referenceWidth),l=u2(i.referenceHeight);if(void 0===a||void 0===o||void 0===s||void 0===l)throw new _("COMMAND_FAILED","interactionFrame did not return a usable frame");return{originX:a,originY:o,referenceWidth:s,referenceHeight:l}}function u2(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function u3(e,t){var n;let{x1:r,y1:i,x2:a,y2:o}={x1:u2((n=e).x),y1:u2(n.y),x2:u2(n.x2),y2:u2(n.y2)},s=u2(e.referenceWidth),l=u2(e.referenceHeight),u=void 0!==r&&void 0!==a?Math.round(Math.abs(a-r)):void 0,d=void 0!==i&&void 0!==o?Math.round(Math.abs(o-i)):void 0,c=t?.preferProvidedPixels&&void 0!==t.pixels?t.pixels:u&&u>0?u:d&&d>0?d:void 0;return{...void 0!==r?{x1:r}:{},...void 0!==i?{y1:i}:{},...void 0!==a?{x2:a}:{},...void 0!==o?{y2:o}:{},...void 0!==s?{referenceWidth:s}:{},...void 0!==l?{referenceHeight:l}:{},...t?.amount!==void 0?{amount:t.amount}:{},...void 0!==c?{pixels:c}:{}}}function u4(){return process.env.WAYLAND_DISPLAY||"wayland"===process.env.XDG_SESSION_TYPE?"wayland":"x11"}let u5=null;async function u8(){if(u5)return u5;let e=u4();if("wayland"===e){if(await v("ydotool"))return u5={tool:"ydotool",display:e};throw new _("TOOL_MISSING","ydotool is required for input synthesis on Wayland (xdotool does not work on Wayland). Install it via your package manager.")}if(await v("xdotool"))return u5={tool:"xdotool",display:e};throw new _("TOOL_MISSING","xdotool is required for input synthesis on X11. Install it via your package manager.")}async function u6(...e){await M("xdotool",e,{allowFailure:!1,timeoutMs:1e4})}async function u9(...e){await M("ydotool",e,{allowFailure:!1,timeoutMs:1e4})}async function u7(e,t){let{tool:n}=await u8();"xdotool"===n?await u6("mousemove","--sync",String(e),String(t)):await u9("mousemove","--absolute","-x",String(e),"-y",String(t))}async function de(e,t){let{tool:n}=await u8();"xdotool"===n?await u6("key","--clearmodifiers",e):await u9("key",...t)}async function dt(e,t,n,r){await u7(e,t);let{tool:i}=await u8();"xdotool"===i?await u6("click",n):await u9("click",r)}async function dn(e,t){await dt(e,t,"1","0xC0")}async function dr(e,t){await dt(e,t,"3","0xC1")}async function di(e,t){await dt(e,t,"2","0xC2")}async function da(e,t){let{tool:n}=await u8();await u7(e,t),"xdotool"===n?await u6("click","--repeat","2","1"):(await u9("click","0xC0"),await u9("click","0xC0"))}async function ds(e,t,n=800){let{tool:r}=await u8();await u7(e,t),"xdotool"===r?(await u6("mousedown","1"),await df(n),await u6("mouseup","1")):(await u9("click","--down","0xC0"),await df(n),await u9("click","--up","0xC0"))}async function dl(e,t){await dn(e,t)}async function du(e,t,n,r,i=300){let{tool:a}=await u8();await u7(e,t),"xdotool"===a?(await u6("mousedown","1"),await u6("mousemove","--sync",String(n),String(r)),await df(i),await u6("mouseup","1")):(await u9("click","--down","0xC0"),await u9("mousemove","--absolute","-x",String(n),"-y",String(r)),await df(i),await u9("click","--up","0xC0"))}async function dd(e,t){let{tool:n}=await u8(),r=5;if(t?.pixels!=null?r="xdotool"===n?Math.max(1,Math.round(t.pixels/15)):Math.max(1,Math.round(t.pixels/40)):t?.amount!=null&&(r=Math.max(1,Math.round(5*(t.amount/.6)))),"xdotool"===n)await u6("click","--repeat",String(r),"up"===e?"4":"down"===e?"5":"left"===e?"6":"7");else if("up"===e||"down"===e){let t="up"===e?String(-r):String(r);await u9("mousemove","--wheel","-y",t)}else{let t="left"===e?String(-r):String(r);await u9("mousemove","--wheel","-x",t)}}async function dc(e,t=0){let{tool:n}=await u8();if("xdotool"===n){let n=["type"];t>0&&n.push("--delay",String(t)),n.push("--clearmodifiers","--",e),await u6(...n)}else await u9("type","--",e)}async function dp(e,t,n,r=0){await dn(e,t),await df(100),await de("ctrl+a",["29:1","30:1","30:0","29:0"]),await df(50),await dc(n,r)}function df(e){return new Promise(t=>setTimeout(t,e))}function dh(e){let t=null;return{resolve:async function(){if(t)return t;let n="wayland"===u4()?"wayland":"x11";for(let r of"wayland"===n?e.wayland:e.x11)if(await v(r.command))return t={tool:r.tool,display:n};throw new _("TOOL_MISSING","wayland"===n?e.waylandError:e.x11Error)},resetCache:()=>{t=null}}}let dm=dh({wayland:[{tool:"grim",command:"grim"},{tool:"gnome-screenshot",command:"gnome-screenshot"}],x11:[{tool:"scrot",command:"scrot"},{tool:"import",command:"import"},{tool:"gnome-screenshot",command:"gnome-screenshot"}],waylandError:"grim or gnome-screenshot is required for screenshots on Wayland. Install via your package manager.",x11Error:"scrot, import (ImageMagick), or gnome-screenshot is required for screenshots on X11. Install via your package manager."});async function dw(e){let{tool:t}=await dm.resolve();switch(t){case"grim":await M("grim",[e]);break;case"scrot":await M("scrot",[e]);break;case"import":await M("import",["-window","root",e]);break;case"gnome-screenshot":await M("gnome-screenshot",["-f",e])}}async function dg(e){if(e.includes("://")||e.startsWith("/"))return void await M("xdg-open",[e]);if(await v(e)){M(e,[],{allowFailure:!0}).catch(t=>{eS({level:"warn",phase:"linux_app_launch",data:{app:e,error:String(t)}})}),await new Promise(e=>setTimeout(e,500));return}await M("xdg-open",[e],{allowFailure:!0})}async function dy(e){await v("wmctrl")?await M("wmctrl",["-c",e],{allowFailure:!0}):await M("pkill",["-x",e],{allowFailure:!0})}async function db(){await de("alt+Left",["56:1","105:1","105:0","56:0"])}async function dv(){await de("super+d",["125:1","32:1","32:0","125:0"])}let dI=dh({wayland:[{tool:"wl-clipboard",command:"wl-paste"}],x11:[{tool:"xclip",command:"xclip"},{tool:"xsel",command:"xsel"}],waylandError:"wl-paste (wl-clipboard) is required for clipboard access on Wayland. Install via your package manager.",x11Error:"xclip or xsel is required for clipboard access on X11. Install via your package manager."});async function dA(){let{tool:e}=await dI.resolve();switch(e){case"wl-clipboard":return(await M("wl-paste",["--no-newline"],{allowFailure:!0,timeoutMs:5e3})).stdout;case"xclip":return(await M("xclip",["-selection","clipboard","-o"],{allowFailure:!0,timeoutMs:5e3})).stdout;case"xsel":return(await M("xsel",["--clipboard","--output"],{allowFailure:!0,timeoutMs:5e3})).stdout}}async function dx(e){let{tool:t}=await dI.resolve();switch(t){case"wl-clipboard":await M("wl-copy",["--",e],{allowFailure:!1,timeoutMs:5e3});break;case"xclip":await M("xclip",["-selection","clipboard"],{allowFailure:!1,timeoutMs:5e3,stdin:e});break;case"xsel":await M("xsel",["--clipboard","--input"],{allowFailure:!1,timeoutMs:5e3,stdin:e})}}async function dS(){return"linux"!==process.platform?[]:[{platform:"linux",id:"local",name:f(),kind:"device",target:"desktop",booted:!0}]}dI.resetCache;let dN={"push button":"Button","toggle button":"Button","push button menu":"Button",label:"StaticText",static:"StaticText",caption:"StaticText",text:"TextField",entry:"TextField","password text":"TextField","spin button":"TextField",terminal:"TextArea","document text":"TextArea",paragraph:"TextArea",frame:"Window",window:"Window",dialog:"Dialog",alert:"Alert","file chooser":"Dialog","color chooser":"Dialog","font chooser":"Dialog",panel:"Group",filler:"Group",section:"Group",form:"Group",grouping:"Group","layered pane":"Group","glass pane":"Group","root pane":"Group","option pane":"Group","internal frame":"Group","desktop frame":"Group","block quote":"Group",article:"Group",comment:"Group",landmark:"Group",log:"Group",marquee:"Group",math:"Group",notification:"Group","content deletion":"Group","content insertion":"Group",mark:"Group",suggestion:"Group","scroll pane":"ScrollArea","scroll bar":"ScrollBar","menu bar":"MenuBar",menu:"Menu","popup menu":"Menu","menu item":"MenuItem","check menu item":"MenuItem","radio menu item":"MenuItem","tearoff menu item":"MenuItem","check box":"CheckBox","radio button":"RadioButton",switch:"Switch","combo box":"ComboBox","page tab":"Tab","page tab list":"TabList",table:"Table","tree table":"Table","table cell":"Cell","table row":"Row","table column header":"Cell","table row header":"Cell","column header":"Cell","row header":"Cell",list:"List","list item":"ListItem","list box":"List",tree:"Tree","tree item":"TreeItem","description list":"List","description term":"ListItem","description value":"ListItem","tool bar":"Toolbar","status bar":"StatusBar","info bar":"StatusBar",slider:"Slider","progress bar":"ProgressBar","level bar":"ProgressBar",image:"Image",icon:"Image",animation:"Image",canvas:"Image","drawing area":"Image",video:"Video",audio:"Audio",link:"Link",hyperlink:"Link",separator:"Separator",application:"Application","tool tip":"Tooltip",timer:"Timer",heading:"Heading",footnote:"Footnote","title bar":"TitleBar","date editor":"DateEditor",rating:"Slider"},d_="atspi-dump.py",dM=null;async function dD(e,t={}){let n;if("linux"!==process.platform)throw new _("UNSUPPORTED_PLATFORM","AT-SPI2 bridge is only available on Linux");if(!await v("python3"))throw new _("TOOL_MISSING","python3 is required for AT-SPI2 accessibility snapshots on Linux.");let i=t.maxNodes??1500,a=t.maxDepth??12,s=t.maxApps??24,u=[function(){if(dM)return dM;let e=o.dirname(l(import.meta.url));for(let t=0;t<5;t++){let n=o.join(e,"src","platforms","linux",d_);if(r.existsSync(n))return dM=n,n;if(0===t){let t=o.join(e,d_);if(r.existsSync(t))return dM=t,t}e=o.dirname(e)}throw new _("TOOL_MISSING",`Cannot find ${d_}. Ensure the agent-device package is installed correctly.`)}(),"--surface",e,"--max-nodes",String(i),"--max-depth",String(a),"--max-apps",String(s)],d=await M("python3",u,{allowFailure:!0,timeoutMs:3e4});if(0!==d.exitCode){let e=d.stderr.trim();if(e.includes("No module named")||e.includes("gi.require_version"))throw new _("TOOL_MISSING","AT-SPI2 Python bindings not found. Install python3-gi and gir1.2-atspi-2.0.",{cause:e});throw new _("COMMAND_FAILED",`AT-SPI2 snapshot failed (exit ${d.exitCode}): ${e||d.stdout}`)}try{n=JSON.parse(d.stdout)}catch{throw new _("COMMAND_FAILED",`AT-SPI2 snapshot returned invalid JSON: ${d.stdout.slice(0,200)}`)}if(n.error)throw new _("COMMAND_FAILED",`AT-SPI2: ${n.error}`);return{nodes:(n.nodes??[]).map(e=>{let t,n;return{index:e.index,type:(n=dN[t=e.role.toLowerCase().trim()])||t.split(/[\s_-]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),role:e.role,label:e.label??void 0,value:e.value??void 0,rect:e.rect??void 0,enabled:e.enabled??void 0,selected:e.selected??void 0,hittable:e.hittable??void 0,depth:e.depth,parentIndex:e.parentIndex??void 0,pid:e.pid??void 0,appName:e.appName??void 0,windowTitle:e.windowTitle??void 0}}),truncated:n.truncated,surface:e}}async function dE(e){let t="desktop"===e?"desktop":"frontmost-app"===e||"app"===e?"frontmost-app":("menubar"===e&&eS({level:"warn",phase:"linux_snapshot",data:{message:"menubar surface is not supported on Linux, falling back to desktop"}}),"desktop"),n=await dD(t);return{nodes:n.nodes,truncated:n.truncated}}function dC(e){return e?.clickButton??"primary"}function dO(e){return"primary"===e.button?null:"click"!==e.commandLabel?new _("INVALID_ARGS","--button is supported only for click"):"macos"!==e.platform&&"linux"!==e.platform?new _("UNSUPPORTED_OPERATION",`click --button ${e.button} is supported only on macOS and Linux`):"macos"===e.platform&&"middle"===e.button?new _("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 _("INVALID_ARGS",`click --button ${e.button} does not support repeat or gesture modifier flags`):null}function dk(e){return"primary"===e?{}:{button:e}}let dL=/^[A-Za-z0-9_.:-]{1,64}$/,dR=[[0,0],[1,0],[0,1],[-1,0],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]];async function dT(e,t,n){for(let r=0;r<e;r+=1)await n(r),r<e-1&&t>0&&await dP(t)}async function dP(e){await new Promise(t=>setTimeout(t,e))}function d$(e,t){let n,i=t?.subject??"Payload",a=e.trim();if(!a)throw new _("INVALID_ARGS",`${i} cannot be empty`);let o=t?.expandPath?t.expandPath(a,t.cwd):a;try{if(!r.statSync(o).isFile())throw new _("INVALID_ARGS",`${i} path is not a file: ${o}`);return{kind:"file",path:o}}catch(t){if(t instanceof _)throw t;let e=t.code;if("EACCES"===e||"EPERM"===e)throw new _("INVALID_ARGS",`${i} file is not readable: ${o}`);if(e&&"ENOENT"!==e)throw new _("COMMAND_FAILED",`Unable to read ${i} file: ${o}`,{cause:String(t)})}if((n=a.trim()).startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]"))return{kind:"inline",text:a};throw new _("INVALID_ARGS",`${i} file not found: ${o}`)}async function dF(e){let t=d$(e,{subject:"Push payload"}),n="inline"===t.kind?t.text:await dU(t.path);try{let e=JSON.parse(n);if(!e||"object"!=typeof e||Array.isArray(e))throw new _("INVALID_ARGS","push payload must be a JSON object");return e}catch(t){if(t instanceof _)throw t;throw new _("INVALID_ARGS",`Invalid push payload JSON: ${e}`)}}async function dU(e){try{return await a.readFile(e,"utf8")}catch(n){let t=n.code;if("ENOENT"===t)throw new _("INVALID_ARGS",`Push payload file not found: ${e}`);if("EISDIR"===t)throw new _("INVALID_ARGS",`Push payload path is not a file: ${e}`);if("EACCES"===t||"EPERM"===t)throw new _("INVALID_ARGS",`Push payload file is not readable: ${e}`);throw new _("COMMAND_FAILED",`Unable to read push payload file: ${e}`,{cause:String(n)})}}function dG(e){if(void 0===e)throw new _("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 _("INVALID_ARGS",`Invalid rotation: ${e}. Use portrait|portrait-upside-down|landscape-left|landscape-right.`)}}let dV=iY(process.env.AGENT_DEVICE_IOS_DEVICECTL_LIST_TIMEOUT_MS,8e3,500),dB=/^(iphone|ipad|ipod|appletv)/i,dj=/\b(iphone|ipad|ipod)\b/i,dq=/^appletv/i,dW=["apple tv","appletv","tvos"],dz=/^==\s*(.+?)\s*==$/,dX=/^(?<name>.+?)\s+\[(?<id>[^[\]]+)\]\s*$/;function dY(e){return(e??"").trim().toLowerCase()}function dH(e){return dY(e.hardwareProperties?.platform)}function dJ(e){return e.includes("tvos")}function dK(e){let t=dY(e);return dW.some(e=>t.includes(e))}function dZ(e){return[e.name??"",e.deviceProperties?.name??"",e.deviceProperties?.deviceType??""]}function dQ(e){return e.hardwareProperties?.productType??e.deviceProperties?.productType??""}async function d0(e={}){let t,n,r=t4(e.simulatorSetPath),i=e.target;try{t=await M("xcrun",t6(["list","devices","-j"],{simulatorSetPath:r}))}catch{return null}try{n=JSON.parse(t.stdout)}catch{return null}let a=d1(n,r),o=null,s=null,l=null;for(let e of a)i&&e.target!==i||(e.booted&&(o=o??e),"mobile"===e.target&&(s=s??e),l=l??e);return o??s??l}function d1(e,t){let n=[];for(let[r,i]of Object.entries(e.devices))if(function(e){let t=dY(e);return t.includes("ios")||t.includes("tvos")}(r))for(let e of i)e.isAvailable&&n.push({platform:"ios",id:e.udid,name:e.name,kind:"simulator",target:dJ(dY(r))?"tv":"mobile",booted:"Booted"===e.state,...t?{simulatorSetPath:t}:{}});return n}function d2(e,t){let n=new Set(e.map(e=>e.id)),r=[...e];for(let e of t)n.has(e.id)||(n.add(e.id),r.push(e));return r}async function d3(){let e=null;try{e=o.join(p.tmpdir(),`agent-device-devicectl-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);let t=await M("xcrun",["devicectl","list","devices","--json-output",e],{allowFailure:!0,timeoutMs:dV});if(0!==t.exitCode)return[];let n=await a.readFile(e,"utf8");return function(e){let t=[];for(let n of e.result?.devices??[]){if(!function(e){var t;let n=dH(e);return!!(n.includes("ios")||n.includes("tvos"))||(t=dQ(e),!!dB.test(t.trim())||dZ(e).some(dK))}(n))continue;let e=n.hardwareProperties?.udid??n.identifier??"",r=n.name??n.deviceProperties?.name??e;e&&t.push({platform:"ios",id:e,name:r,kind:"device",target:function(e){var t;return dJ(dH(e))?"tv":(t=dQ(e),dq.test(t.trim())||dZ(e).some(dK))?"tv":"mobile"}(n),booted:!0})}return t}(JSON.parse(n))}catch{return[]}finally{e&&await a.rm(e,{force:!0}).catch(()=>{})}}async function d4(){try{let e=await M("xcrun",["xctrace","list","devices"],{allowFailure:!0});if(0!==e.exitCode)return[];return function(e){let t=[],n=null;for(let r of e.split(/\r?\n/)){let e=r.trim();if(!e)continue;let i=dz.exec(e);if(i){n=i[1]?.trim()??null;continue}if("Devices"!==n)continue;let a=dX.exec(e),o=a?.groups?.id?.trim()??"",s=a?.groups?.name?.trim()??"";if(!o||!s)continue;let l=function(e){return dK(e)?"tv":dj.test(e.trim())?"mobile":null}(s);l&&t.push({platform:"ios",id:o,name:s,kind:"device",target:l,booted:!0})}return t}(e.stdout)}catch{return[]}}async function d5(e={}){if("darwin"!==process.platform)throw new _("UNSUPPORTED_PLATFORM","Apple tools are only available on macOS");if(!await v("xcrun"))throw new _("TOOL_MISSING","xcrun not found in PATH");let t=t4(e.simulatorSetPath),n=await M("xcrun",t6(["list","devices","-j"],{simulatorSetPath:t})),r=[];try{let e=JSON.parse(n.stdout);r=d1(e,t)}catch(e){throw new _("COMMAND_FAILED","Failed to parse simctl devices JSON",void 0,e)}if(r.push({platform:"macos",id:"host-macos-local",name:p.hostname(),kind:"device",target:"desktop",booted:!0}),t)return r;let[i,a]=await Promise.all([d3(),d4()]);return r=d2(r,i),d2(r,a)}async function d8(e,t,n){let r,i=!!(t.udid||t.serial||t.deviceName);try{r=await iv(e,t,n)}catch(e){if(i||!(e instanceof _)||"DEVICE_NOT_FOUND"!==e.code)throw e}if(!i&&(!t.platform||"apple"===t.platform||"ios"===t.platform)&&"desktop"!==t.target&&(!r||"device"===r.kind)){let e=await d0({simulatorSetPath:n.simulatorSetPath,target:t.target});if(e)return e}if(r)return r;throw new _("DEVICE_NOT_FOUND","No devices found",{selector:t})}async function d6(e){let t=iw(e.platform),n=ib({simulatorSetPath:t4(e.iosSimulatorDeviceSet),platform:t,target:e.target}),r=t8(e.androidDeviceAllowlist);return await eN("resolve_target_device",async()=>{let i={platform:t,target:e.target,deviceName:e.device,udid:e.udid,serial:e.serial};if(i.target&&!i.platform)throw new _("INVALID_ARGS","Device target selector requires --platform. Use --platform ios|macos|android|linux|apple with --target mobile|tv|desktop.");if("linux"===i.platform){let e=await dS();return await iv(e,i)}if("android"===i.platform){await tX();let e=await oc({serialAllowlist:r});return await iv(e,i)}if(i.platform){let e=await d5({simulatorSetPath:n});return await d8(e,i,{simulatorSetPath:n})}let a=[];try{a.push(...await oc({serialAllowlist:r}))}catch{}try{a.push(...await d5({simulatorSetPath:n}))}catch{}try{a.push(...await dS())}catch{}return await iv(a,i,{simulatorSetPath:n})},{platform:t,target:e.target})}async function d9(e,t,n,r,i){let s={requestId:i?.requestId,appBundleId:i?.appBundleId,verbose:i?.verbose,logPath:i?.logPath,traceLogPath:i?.traceLogPath},l=function(e,t){switch(e.platform){case"android":return{open:(t,n)=>o2(e,t,n?.activity),openDevice:()=>o9(e),close:t=>o7(e,t),tap:(t,n)=>sC(e,t,n),doubleTap:async(t,n)=>{await sC(e,t,n),await sC(e,t,n)},swipe:(t,n,r,i,a)=>sO(e,t,n,r,i,a),longPress:(t,n,r)=>sP(e,t,n,r),focus:(t,n)=>sU(e,t,n),type:(t,n)=>s$(e,t,n),fill:(t,n,r,i)=>sG(e,t,n,r,i),scroll:(t,n)=>sj(e,t,n),screenshot:t=>la(e,t),back:t=>sk(e),home:()=>sL(e),rotate:t=>sR(e,t),appSwitcher:()=>sT(e),readClipboard:()=>sQ(e),writeClipboard:t=>s0(e,t),setSetting:(t,n,r,i)=>s8(e,t,n,r,i)};case"linux":return{open:e=>dg(e),openDevice:()=>Promise.resolve(),close:e=>dy(e),tap:(e,t)=>dn(e,t),doubleTap:(e,t)=>da(e,t),swipe:(e,t,n,r,i)=>du(e,t,n,r,i),longPress:(e,t,n)=>ds(e,t,n),focus:(e,t)=>dl(e,t),type:(e,t)=>dc(e,t),fill:(e,t,n,r)=>dp(e,t,n,r),scroll:(e,t)=>dd(e,t),screenshot:e=>dw(e),back:()=>db(),home:()=>dv(),rotate:()=>{throw new _("UNSUPPORTED_OPERATION","rotate not supported on Linux")},appSwitcher:()=>{throw new _("UNSUPPORTED_OPERATION","appSwitcher not yet supported on Linux")},readClipboard:()=>dA(),writeClipboard:e=>dx(e),setSetting:()=>{throw new _("UNSUPPORTED_OPERATION","setSetting not supported on Linux")}};case"ios":case"macos":{let n,{overrides:r,runnerOpts:i}={runnerOpts:n={verbose:t.verbose,logPath:t.logPath,traceLogPath:t.traceLogPath,requestId:t.requestId},overrides:{tap:async(r,i)=>await a5(e,{command:"tap",x:r,y:i,appBundleId:t.appBundleId},n),doubleTap:async(r,i)=>await a5(e,{command:"tapSeries",x:r,y:i,count:1,intervalMs:0,doubleTap:!0,appBundleId:t.appBundleId},n),swipe:async(r,i,a,o,s)=>await a5(e,{command:"drag",x:r,y:i,x2:a,y2:o,durationMs:s,appBundleId:t.appBundleId},n),longPress:async(r,i,a)=>await a5(e,{command:"longPress",x:r,y:i,durationMs:a,appBundleId:t.appBundleId},n),focus:async(r,i)=>await a5(e,{command:"tap",x:r,y:i,appBundleId:t.appBundleId},n),type:async(r,i)=>{await a5(e,{command:"type",text:r,delayMs:i,appBundleId:t.appBundleId},n)},fill:async(r,i,a,o)=>{let s=await a5(e,{command:"tap",x:r,y:i,appBundleId:t.appBundleId},n);return await a5(e,{command:"type",text:a,clearFirst:!0,delayMs:o,appBundleId:t.appBundleId},n),s},scroll:async(r,i)=>await u0(a5,e,t,n,r,i)}};return{open:(t,n)=>uk(e,t,{appBundleId:n?.appBundleId,url:n?.url}),openDevice:()=>uL(e),close:t=>uR(e,t),screenshot:async(t,n)=>{"macos"===e.platform&&n?.surface&&"app"!==n.surface?await l1(t,{surface:n.surface,fullscreen:n.fullscreen}):await uw(e,t,n?.appBundleId,n?.fullscreen)},back:async n=>{await a5(e,{command:"system"===n?"backSystem":"backInApp",appBundleId:t.appBundleId},i)},home:async()=>{await a5(e,{command:"home",appBundleId:t.appBundleId},i)},rotate:async n=>{await a5(e,{command:"rotate",orientation:n,appBundleId:t.appBundleId},i)},appSwitcher:async()=>{await a5(e,{command:"appSwitcher",appBundleId:t.appBundleId},i)},readClipboard:()=>uU(e),writeClipboard:t=>uG(e,t),setSetting:(t,n,r,i)=>uB(e,t,n,r,i),...r}}default:throw new _("UNSUPPORTED_PLATFORM",`Unsupported platform: ${e.platform}`)}}(e,s);return eS({level:"debug",phase:"platform_command_prepare",data:{command:t,platform:e.platform,kind:e.kind}}),await eN("platform_command",async()=>{switch(t){case"open":return d7(e,l,n,i);case"close":{let e=n[0];if(!e)return{closed:"session",...tN("Closed session")};return await l.close(e),{app:e,...tN(`Closed: ${e}`)}}case"press":return ce(e,l,n,i,s);case"swipe":return ct(e,l,n,i,s);case"longpress":{let e=Number(n[0]),t=Number(n[1]),r=n[2]?Number(n[2]):void 0;if(Number.isNaN(e)||Number.isNaN(t))throw new _("INVALID_ARGS","longpress requires x y [durationMs]");return await l.longPress(e,t,r),{x:e,y:t,durationMs:r,...tN(`Long pressed (${e}, ${t})`)}}case"focus":{let[e,t]=n.map(Number);if(Number.isNaN(e)||Number.isNaN(t))throw new _("INVALID_ARGS","focus requires x y");return await l.focus(e,t),{x:e,y:t,...tN(`Focused (${e}, ${t})`)}}case"type":{let e=function(e){let t=e[0]?.trim();if(!t||!t.startsWith("@")||t.length<3)return null;let n=t.slice(1);return/^[A-Za-z_-]*\d[\w-]*$/i.test(n)||/^(?:ref|node|element|el)[\w-]*$/i.test(n)?t:null}(n);if(e)throw new _("INVALID_ARGS",`type does not accept a target ref like "${e}"`,{hint:`Use fill ${e} "text" to target that field, or press ${e} then type "text" to append.`});let t=n.join(" ");if(!t)throw new _("INVALID_ARGS","type requires text");let r=rV(i?.delayMs??0,"delay-ms",0,1e4);return await l.type(t,r),{text:t,delayMs:r,...tN(cp("Typed",t))}}case"fill":{let e=Number(n[0]),t=Number(n[1]),r=n.slice(2).join(" ");if(Number.isNaN(e)||Number.isNaN(t)||!r)throw new _("INVALID_ARGS","fill requires x y text");let a=rV(i?.delayMs??0,"delay-ms",0,1e4);return await l.fill(e,t,r,a),{x:e,y:t,text:r,delayMs:a,...tN(cp("Filled",r))}}case"scroll":return cn(l,n,i);case"pinch":return cr(e,n,i,s);case"trigger-app-event":{let{eventName:t,payload:r}=function(e){let t=e[0]?.trim(),n=e[1]?.trim();if(!t)throw new _("INVALID_ARGS","trigger-app-event requires <event> [payloadJson]");if(!dL.test(t))throw new _("INVALID_ARGS",`Invalid trigger-app-event event name: ${t}`,{hint:"Use 1-64 chars: letters, numbers, underscore, dot, colon, or dash."});if(e.length>2)throw new _("INVALID_ARGS","trigger-app-event accepts at most two arguments: <event> [payloadJson]");let r=function(e,t){if(e)try{let n=JSON.parse(e);if(!n||"object"!=typeof n||Array.isArray(n))throw new _("INVALID_ARGS",`trigger-app-event payload for "${t}" must be a JSON object`);let r=JSON.stringify(n);if(Buffer.byteLength(r,"utf8")>8192)throw new _("INVALID_ARGS",`trigger-app-event payload for "${t}" exceeds 8192 bytes`);return n}catch(t){if(t instanceof _)throw t;throw new _("INVALID_ARGS",`Invalid trigger-app-event payload JSON: ${e}`)}}(n,t);return{eventName:t,payload:r}}(n),a=function(e,t,n){var r;let i,a=(i=("ios"===(r=e)?process.env.AGENT_DEVICE_IOS_APP_EVENT_URL_TEMPLATE:"macos"===r?process.env.AGENT_DEVICE_MACOS_APP_EVENT_URL_TEMPLATE:process.env.AGENT_DEVICE_ANDROID_APP_EVENT_URL_TEMPLATE)??process.env.AGENT_DEVICE_APP_EVENT_URL_TEMPLATE,i?.trim()||void 0);if(!a)throw new _("UNSUPPORTED_OPERATION",`No app event URL template configured for ${e}.`,{hint:`Set AGENT_DEVICE_${e.toUpperCase()}_APP_EVENT_URL_TEMPLATE or AGENT_DEVICE_APP_EVENT_URL_TEMPLATE, for example "myapp://agent-device/event?name={event}&payload={payload}".`});let o=n?JSON.stringify(n):"",s=a.replaceAll("{event}",encodeURIComponent(t)).replaceAll("{payload}",encodeURIComponent(o)).replaceAll("{platform}",encodeURIComponent(e));if(s.length>4096)throw new _("INVALID_ARGS","trigger-app-event URL exceeds maximum supported length",{hint:"Reduce payload size or shorten AGENT_DEVICE_*_APP_EVENT_URL_TEMPLATE.",length:s.length,maxLength:4096});return s}(e.platform,t,r);return await l.open(a,{appBundleId:i?.appBundleId}),{event:t,eventUrl:a,transport:"deep-link",...tN(`Triggered app event: ${t}`)}}case"screenshot":{let e=n[0]??r??`./screenshot-${Date.now()}.png`;return await a.mkdir(o.dirname(e),{recursive:!0}),await l.screenshot(e,{appBundleId:i?.appBundleId,fullscreen:i?.screenshotFullscreen,surface:i?.surface}),{path:e,...tN(`Saved screenshot: ${e}`)}}case"back":return await l.back(i?.backMode),{action:"back",mode:i?.backMode??"in-app",...tN("Back")};case"home":return await l.home(),{action:"home",...tN("Home")};case"rotate":{let e=dG(n[0]);return await l.rotate(e),{action:"rotate",orientation:e,...tN(`Rotated to ${e}`)}}case"app-switcher":return await l.appSwitcher(),{action:"app-switcher",...tN("Opened app switcher")};case"clipboard":return ci(l,n);case"keyboard":return ca(e,l,n,i,s);case"settings":return co(e,l,n,i);case"push":return cs(e,n,i);case"snapshot":return cl(e,n,i,s);case"read":return cu(e,n,i,s);default:throw new _("INVALID_ARGS",`Unknown command: ${t}`)}},{command:t,platform:e.platform})}async function d7(e,t,n,r){let i=n[0],a=n[1];if(n.length>2)throw new _("INVALID_ARGS","open accepts at most two arguments: <app|url> [url]");if(!i)return await t.openDevice(),{app:null,...tN("Opened device")};if(void 0!==a){if("android"===e.platform)throw new _("INVALID_ARGS","open <app> <url> is supported only on Apple platforms");if(a6(i))throw new _("INVALID_ARGS","open <app> <url> requires an app target as the first argument");if(!a6(a))throw new _("INVALID_ARGS","open <app> <url> requires a valid URL target");return await t.open(i,{activity:r?.activity,appBundleId:r?.appBundleId,url:a}),{app:i,url:a,...tN(`Opened: ${i}`)}}return await t.open(i,{activity:r?.activity,appBundleId:r?.appBundleId}),{app:i,...tN(`Opened: ${i}`)}}async function ce(e,t,n,r,i){let a,[o,s]=n.map(Number);if(Number.isNaN(o)||Number.isNaN(s))throw new _("INVALID_ARGS","press requires x y");if("macos"===e.platform&&r?.surface&&"app"!==r.surface){let e=dC(r);if("primary"!==e)throw new _("UNSUPPORTED_OPERATION",`${e} click is not supported on macOS ${r.surface} sessions.`);return await l0(o,s,{bundleId:r.appBundleId,surface:r.surface}),{x:o,y:s,...tN(cd({x:o,y:s}))}}let l=dC(r);if("primary"!==l){let t=dO({commandLabel:"click",platform:e.platform,button:l,count:r?.count,intervalMs:r?.intervalMs,holdMs:r?.holdMs,jitterPx:r?.jitterPx,doubleTap:r?.doubleTap});if(t)throw t;return"linux"===e.platform?"secondary"===l?await dr(o,s):await di(o,s):await a5(e,{command:"mouseClick",x:o,y:s,button:l,appBundleId:r?.appBundleId},{verbose:r?.verbose,logPath:r?.logPath,traceLogPath:r?.traceLogPath,requestId:r?.requestId}),{x:o,y:s,button:l,...tN(cd({x:o,y:s,button:l}))}}let u=rV(r?.count??1,"count",1,200),d=rV(r?.intervalMs??0,"interval-ms",0,1e4),c=rV(r?.holdMs??0,"hold-ms",0,1e4),p=rV(r?.jitterPx??0,"jitter-px",0,100),f=r?.doubleTap===!0;if(f&&c>0)throw new _("INVALID_ARGS","double-tap cannot be combined with hold-ms");if(f&&p>0)throw new _("INVALID_ARGS","double-tap cannot be combined with jitter-px");if(("ios"===e.platform||"macos"===e.platform)&&u>1&&0===c&&0===p){let t=await a5(e,{command:"tapSeries",x:o,y:s,count:u,intervalMs:d,doubleTap:f,appBundleId:r?.appBundleId},{verbose:r?.verbose,logPath:r?.logPath,traceLogPath:r?.traceLogPath,requestId:r?.requestId});return{x:o,y:s,count:u,intervalMs:d,holdMs:c,jitterPx:p,doubleTap:f,timingMode:"runner-series",...t,...tN(cd({x:o,y:s}))}}return await dT(u,d,async e=>{let[n,r]=function(e,t){if(t<=0)return[0,0];let[n,r]=dR[e%dR.length];return[n*t,r*t]}(e,p),i=o+n,l=s+r;if(f){a??=await t.doubleTap(i,l)??void 0;return}c>0?a??=await t.longPress(i,l,c)??void 0:a??=await t.tap(i,l)??void 0}),t_({x:o,y:s,count:u,intervalMs:d,holdMs:c,jitterPx:p,doubleTap:f,...a},cd({x:o,y:s}))}async function ct(e,t,n,r,i){let a=Number(n[0]),o=Number(n[1]),s=Number(n[2]),l=Number(n[3]);if([a,o,s,l].some(Number.isNaN))throw new _("INVALID_ARGS","swipe requires x1 y1 x2 y2 [durationMs]");let u=rV(n[4]?Number(n[4]):250,"durationMs",16,1e4),d="ios"===e.platform?Math.min(60,Math.max(16,Math.round(u))):u,c=rV(r?.count??1,"count",1,200),p=rV(r?.pauseMs??0,"pause-ms",0,1e4),f=r?.pattern??"one-way";if("one-way"!==f&&"ping-pong"!==f)throw new _("INVALID_ARGS",`Invalid pattern: ${f}`);if(("ios"===e.platform||"macos"===e.platform)&&c>1){let t=await a5(e,{command:"dragSeries",x:a,y:o,x2:s,y2:l,durationMs:d,count:c,pauseMs:p,pattern:f,appBundleId:r?.appBundleId},{verbose:r?.verbose,logPath:r?.logPath,traceLogPath:r?.traceLogPath,requestId:r?.requestId});return{x1:a,y1:o,x2:s,y2:l,durationMs:u,effectiveDurationMs:d,timingMode:"runner-series",count:c,pauseMs:p,pattern:f,...t,...tN(cc(c,f))}}return await dT(c,p,async e=>{"ping-pong"===f&&e%2==1?await t.swipe(s,l,a,o,d):await t.swipe(a,o,s,l,d)}),t_({x1:a,y1:o,x2:s,y2:l,durationMs:u,effectiveDurationMs:d,timingMode:"ios"===e.platform?"safe-normalized":"direct",count:c,pauseMs:p,pattern:f},cc(c,f))}async function cn(e,t,n){let r=t[0],i=t[1]?Number(t[1]):void 0,a=n?.pixels;if(!r)throw new _("INVALID_ARGS","scroll requires direction");if(void 0!==i&&!Number.isFinite(i))throw new _("INVALID_ARGS","scroll amount must be a number");if(void 0!==i&&void 0!==a)throw new _("INVALID_ARGS","scroll accepts either a relative amount or --pixels, not both");let o=function(e){switch(e){case"up":case"down":case"left":case"right":return e;default:throw new _("INVALID_ARGS",`Unknown direction: ${e}`)}}(r),s=await e.scroll(o,{amount:i,pixels:a});return t_({direction:o,...void 0!==i?{amount:i}:{},...void 0!==a?{pixels:a}:{},...s},void 0!==a?`Scrolled ${o} by ${a}px`:void 0!==i?`Scrolled ${o} by ${i}`:`Scrolled ${o}`)}async function cr(e,t,n,r){if("android"===e.platform)throw new _("UNSUPPORTED_OPERATION","Android pinch is not supported in current adb backend; requires instrumentation-based backend.");if("macos"===e.platform&&n?.surface&&"app"!==n.surface)throw new _("UNSUPPORTED_OPERATION","pinch is only supported in macOS app sessions. Re-open the target app without --surface desktop|menubar|frontmost-app first.");let i=Number(t[0]),a=t[1]?Number(t[1]):void 0,o=t[2]?Number(t[2]):void 0;if(Number.isNaN(i)||i<=0)throw new _("INVALID_ARGS","pinch requires scale > 0");return await a5(e,{command:"pinch",scale:i,x:a,y:o,appBundleId:n?.appBundleId},{verbose:n?.verbose,logPath:n?.logPath,traceLogPath:n?.traceLogPath,requestId:n?.requestId}),{scale:i,x:a,y:o,...tN(`Pinched to scale ${i}`)}}async function ci(e,t){let n=(t[0]??"").toLowerCase();if("read"!==n&&"write"!==n)throw new _("INVALID_ARGS","clipboard requires a subcommand: read or write");if("read"===n){if(1!==t.length)throw new _("INVALID_ARGS","clipboard read does not accept additional arguments");return{action:n,text:await e.readClipboard()}}if(t.length<2)throw new _("INVALID_ARGS",'clipboard write requires text (use "" to clear clipboard)');let r=t.slice(1).join(" ");return await e.writeClipboard(r),{action:n,textLength:Array.from(r).length,...tN("Clipboard updated")}}async function ca(e,t,n,r,i){let a=(n[0]??"status").toLowerCase();if("status"!==a&&"get"!==a&&"dismiss"!==a)throw new _("INVALID_ARGS","keyboard requires a subcommand: status, get, or dismiss");if(n.length>1)throw new _("INVALID_ARGS","keyboard accepts at most one subcommand argument");if("android"===e.platform){if("dismiss"===a){let t=await sZ(e);return{platform:"android",action:"dismiss",attempts:t.attempts,wasVisible:t.wasVisible,dismissed:t.dismissed,visible:t.visible,inputType:t.inputType,type:t.type}}let t=await sK(e);return{platform:"android",action:"status",visible:t.visible,inputType:t.inputType,type:t.type}}if("ios"===e.platform){if("dismiss"!==a)throw new _("UNSUPPORTED_OPERATION","keyboard status/get is currently supported only on Android; use keyboard dismiss on iOS");let t=await a5(e,{command:"keyboardDismiss",appBundleId:r?.appBundleId},i);return{platform:"ios",action:"dismiss",wasVisible:t.wasVisible,dismissed:t.dismissed,visible:t.visible,...tN(t.dismissed?"Keyboard dismissed":"Keyboard already hidden")}}throw new _("UNSUPPORTED_OPERATION","keyboard is supported only on Android and iOS")}async function co(e,t,n,r){var i;let[a,o,s,l,u]=n,d="permission"===a?{permissionTarget:s,permissionMode:l}:void 0;eS({level:"debug",phase:"settings_apply",data:{setting:a,state:o,target:s,mode:l,platform:e.platform}});let c=await t.setSetting(a,o,u??r?.appBundleId,d);return c&&"object"==typeof c?t_({setting:a,state:o,...c},("string"==typeof(i=c).message&&i.message.length>0?i.message:void 0)??`Updated setting: ${a}`):{setting:a,state:o,...tN(`Updated setting: ${a}`)}}async function cs(e,t,n){let r=t[0]?.trim(),i=t[1]?.trim();if(!r||!i)throw new _("INVALID_ARGS","push requires <bundle|package> <payload.json|inline-json>");let a=await dF(i);if("ios"===e.platform)return await uV(e,r,a),{platform:"ios",bundleId:r,...tN(`Pushed notification to ${r}`)};let o=await lr(e,r,a);return{platform:"android",package:r,action:o.action,extrasCount:o.extrasCount,...tN(`Pushed notification to ${r}`)}}async function cl(e,t,n,r){if("linux"===e.platform){let e=await eN("snapshot_capture",async()=>await dE(n?.surface),{backend:"linux-atspi"});return{nodes:e.nodes??[],truncated:e.truncated??!1,backend:"linux-atspi"}}if("android"!==e.platform){let t=await eN("snapshot_capture",async()=>await a5(e,{command:"snapshot",appBundleId:n?.appBundleId,interactiveOnly:n?.snapshotInteractiveOnly,compact:n?.snapshotCompact,depth:n?.snapshotDepth,scope:n?.snapshotScope,raw:n?.snapshotRaw},{verbose:n?.verbose,logPath:n?.logPath,traceLogPath:n?.traceLogPath,requestId:n?.requestId}),{backend:"xctest"}),r=t.nodes??[];if(0===r.length&&"simulator"===e.kind)throw new _("COMMAND_FAILED","XCTest snapshot returned 0 nodes on iOS simulator.");return{nodes:r,truncated:t.truncated??!1,backend:"xctest"}}let i=await eN("snapshot_capture",async()=>await sx(e,{interactiveOnly:n?.snapshotInteractiveOnly,compact:n?.snapshotCompact,depth:n?.snapshotDepth,scope:n?.snapshotScope,raw:n?.snapshotRaw}),{backend:"android"});return{nodes:i.nodes??[],truncated:i.truncated??!1,backend:"android",analysis:i.analysis}}async function cu(e,t,n,r){let[i,a]=t.map(Number);if(Number.isNaN(i)||Number.isNaN(a))throw new _("INVALID_ARGS","read requires x y");if("android"===e.platform)return{action:"read",text:await sH(e,i,a)??""};if("macos"===e.platform&&n?.surface&&"app"!==n.surface)return{action:"read",text:(await lQ(i,a,{bundleId:n.appBundleId,surface:n.surface})).text};let o=await a5(e,{command:"readText",x:i,y:a,appBundleId:n?.appBundleId},{verbose:n?.verbose,logPath:n?.logPath,traceLogPath:n?.traceLogPath,requestId:n?.requestId});return{action:"read",text:"string"==typeof o.text?o.text:"string"==typeof o.message?o.message:""}}function cd(e){return e.button&&"primary"!==e.button?`Clicked ${e.button} (${e.x}, ${e.y})`:`Tapped (${e.x}, ${e.y})`}function cc(e,t){return e<=1?"Swiped":"ping-pong"===t?`Swiped ${e} times (ping-pong)`:`Swiped ${e} times`}function cp(e,t){return`${e} ${Array.from(t).length} chars`}let cf=[250,400];function ch(e,t,n=e.snapshot){if("android"!==e.device.platform)return;let r=n?.comparisonSafe===!0;e.androidSnapshotFreshness={action:t,markedAt:Date.now(),baselineCount:n?.nodes.length??0,baselineSignatures:r?cy(n?.nodes??[]):void 0,routeComparable:r}}function cm(e){if(!e||"android"!==e.device.platform)return;let t=e.androidSnapshotFreshness;if(t)return Date.now()-t.markedAt>2500?void delete e.androidSnapshotFreshness:t}function cw(e){e&&"android"===e.device.platform&&delete e.androidSnapshotFreshness}function cg(e){return"press"===e||"click"===e||"back"===e||"open"===e}function cy(e){return e.map(e=>[e.depth??0,e.type??"",e.role??"",e.label??"",e.value??"",e.identifier??"",!1===e.enabled?"disabled":"enabled",!0===e.selected?"selected":"unselected",!0===e.hittable?"hittable":"not-hittable"].join("|"))}function cb(e,t,n,r,i){return{requestId:i??ex().requestId,appBundleId:n,activity:t?.activity,verbose:t?.verbose,logPath:e,traceLogPath:r,snapshotInteractiveOnly:t?.snapshotInteractiveOnly,snapshotCompact:t?.snapshotCompact,snapshotDepth:t?.snapshotDepth,snapshotScope:t?.snapshotScope,snapshotRaw:t?.snapshotRaw,screenshotFullscreen:t?.screenshotFullscreen,count:t?.count,intervalMs:t?.intervalMs,delayMs:t?.delayMs,holdMs:t?.holdMs,jitterPx:t?.jitterPx,pixels:t?.pixels,doubleTap:t?.doubleTap,clickButton:dC(t),backMode:t?.backMode,pauseMs:t?.pauseMs,pattern:t?.pattern}}async function cv(e){let t=cm(e.session);if(t&&"android"===e.device.platform)return await cA(e,t);let n=await cI(e);return cw(e.session),{snapshot:cN(n,e.flags),analysis:n.analysis}}async function cI(e){let{device:t,session:n,flags:r,outPath:i,logPath:a,snapshotScope:o}=e;if("linux"===t.platform){let e=await dE(n?.surface);return c_({nodes:e.nodes,truncated:e.truncated,backend:"linux-atspi"},{snapshotDepth:r?.snapshotDepth,snapshotInteractiveOnly:r?.snapshotInteractiveOnly,snapshotScope:o})}return"macos"===t.platform&&n?.surface&&"app"!==n.surface?c_(await lZ(n.surface,{bundleId:"menubar"===n.surface?n.appBundleId:void 0}),{snapshotDepth:r?.snapshotDepth,snapshotInteractiveOnly:r?.snapshotInteractiveOnly,snapshotScope:o}):await d9(t,"snapshot",[],i,{...cb(a,{...r,snapshotScope:o},n?.appBundleId,n?.trace?.outPath)})}async function cA(e,t){let n=await cx(e),r=cS(n,t,e.flags),i=0;for(let a of cf){if(!r)break;await new Promise(e=>setTimeout(e,a)),n=await cx(e),i+=1,r=cS(n,t,e.flags)}return r||cw(e.session),{snapshot:n.snapshot,analysis:n.data.analysis,freshness:i>0||r?{action:t.action,retryCount:i,staleAfterRetries:!!r,reason:r??void 0}:void 0}}async function cx(e){let t=await cI(e);return{data:t,snapshot:cN(t,e.flags)}}function cS(e,t,n){var r,i;let a=n?.snapshotInteractiveOnly===!0,o=e.data.analysis;if(a&&0===e.snapshot.nodes.length&&o&&o.rawNodeCount>=12)return"empty-interactive";return(r=t.baselineCount,i=e.snapshot.nodes.length,!(r<12)&&i<=Math.floor(.2*r))?e.snapshot.nodes.some(e=>!0===e.hittable||!!e.label?.trim()||!!e.value?.trim()||!!e.identifier?.trim())?null:"sharp-drop":t.routeComparable&&cg(t.action)&&function(e,t){if(!e||0===e.length)return!1;let n=Math.max(e.length,t.length);if(n<12)return!1;let r=cy(t),i=Math.min(e.length,r.length),a=0;for(let t=0;t<i;t+=1)e[t]===r[t]&&(a+=1);let o=Math.max(0,r.length-e.length),s=Math.max(0,e.length-r.length),l=Math.max(3,Math.floor(.15*n));return a>=Math.floor(.9*n)&&o<=l&&s<=l}(t.baselineSignatures,e.snapshot.nodes)?"stuck-route":null}function cN(e,t){let n=e?.nodes??[],r=function(e){let t=new Map;for(let[n,r]of e.entries())t.set(r.index,n);let n=[],r=[];for(let[i,a]of e.entries()){let e=Math.max(0,a.depth??0);for(;r.length>0&&e<=r[r.length-1].depth;)r.pop();let o="number"==typeof a.parentIndex?t.get(a.parentIndex):void 0,s="number"==typeof o&&o<i?o:r[r.length-1]?.index;n.push({...a,index:i,depth:e,parentIndex:s}),r.push({depth:e,index:i})}return n}(t?.snapshotRaw?n:ta(n));return{nodes:ei(t?.snapshotScope&&e?.backend!=="macos-helper"?cM(r,t.snapshotScope):r),truncated:e?.truncated,createdAt:Date.now(),backend:e?.backend,comparisonSafe:e?.backend==="android"&&t?.snapshotInteractiveOnly!==!0&&t?.snapshotCompact!==!0&&"number"!=typeof t?.snapshotDepth&&!t?.snapshotScope}}function c_(e,t){var n,r;let i=e.nodes??[];return t.snapshotScope&&(i=cM(i,t.snapshotScope)),t.snapshotInteractiveOnly&&(i=function(e){if(0===e.length)return e;let t=new Map;for(let n of e)t.set(n.index,n);let n=new Set;for(let r of e){if(!function(e){if(e.hittable||e.rect)return!0;let t=`${e.type??""} ${e.role??""} ${e.subrole??""}`.toLowerCase();return t.includes("button")||t.includes("menu")||t.includes("textfield")||t.includes("searchfield")||t.includes("checkbox")||t.includes("radio")||t.includes("switch")}(r))continue;let e=r;for(;e&&!n.has(e.index);)n.add(e.index),e="number"==typeof e.parentIndex?t.get(e.parentIndex):void 0}return 0===n.size?e:cD(e.filter(e=>n.has(e.index)))}(i)),"number"==typeof t.snapshotDepth&&(n=i,r=t.snapshotDepth,i=cD(n.filter(e=>(e.depth??0)<=r))),{...e,nodes:i}}function cM(e,t){let n=tn(ei(e),t);if(!n)return[];let r=e.findIndex(e=>e.index===n.index);if(-1===r)return[];let i=e[r]?.depth??0,a=[];for(let t=r;t<e.length;t+=1){let n=e[t];if(!n)continue;let o=n.depth??0;if(t>r&&o<=i)break;a.push(n)}return cD(a,i)}function cD(e,t=0){let n=new Map;for(let[t,r]of e.entries())n.set(r.index,t);return e.map((e,r)=>({...e,index:r,depth:Math.max(0,(e.depth??0)-t),parentIndex:"number"==typeof e.parentIndex?n.get(e.parentIndex):void 0}))}function cE(e,t){if(!e||!e.trim().startsWith("@"))return{ok:!0,scope:e};if(!t?.snapshot)return im("INVALID_ARGS","Ref scope requires an existing snapshot in session.");let n=ea(e.trim());if(!n)return im("INVALID_ARGS",`Invalid ref scope: ${e}`);let r=eo(t.snapshot.nodes,n),i=r?tr(r,t.snapshot.nodes):void 0;return i?{ok:!0,scope:i}:im("COMMAND_FAILED",`Ref ${e} not found or has no label`)}let cC=iY(process.env.AGENT_DEVICE_IOS_DEVICE_READY_TIMEOUT_MS,15e3,1e3);async function cO(e){if("ios"===e.platform){if("simulator"===e.kind){let{ensureBootedSimulator:t}=await Promise.resolve(L);await t(e);return}if("device"===e.kind)return void await ck(e.id)}if("android"===e.platform){let{waitForAndroidBoot:t}=await Promise.resolve(k);await t(e.id)}}async function ck(e){let t=o.join(p.tmpdir(),`agent-device-ready-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`),n=Math.max(1,Math.ceil(cC/1e3));try{let r=await M("xcrun",["devicectl","device","info","details","--device",e,"--json-output",t,"--timeout",String(n)],{allowFailure:!0,timeoutMs:cC+3e3}),i=String(r.stdout??""),a=String(r.stderr??""),o=await cL(t);if(0===r.exitCode){if(!o.parsed)throw new _("COMMAND_FAILED","iOS device readiness probe failed",{kind:"probe_inconclusive",deviceId:e,stdout:i,stderr:a,hint:"CoreDevice returned success but readiness JSON output was missing or invalid. Retry; if it persists restart Xcode and the iOS device."});let t=o?.tunnelState?.toLowerCase();if("connecting"===t)throw new _("COMMAND_FAILED","iOS device is not ready for automation",{kind:"not_ready",deviceId:e,tunnelState:t,hint:"Device tunnel is still connecting. Keep the device unlocked and connected by cable until it is fully available in Xcode Devices, then retry."});return}throw new _("COMMAND_FAILED","iOS device is not ready for automation",{kind:"not_ready",deviceId:e,stdout:i,stderr:a,exitCode:r.exitCode,tunnelState:o?.tunnelState,hint:cR(i,a)})}catch(t){if(t instanceof _&&"COMMAND_FAILED"===t.code){if("not_ready"===("string"==typeof t.details?.kind?t.details.kind:""))throw t;let n=t.details??{},r=String(n.stdout??""),i=String(n.stderr??""),a=Number(n.timeoutMs??cC),o=`CoreDevice did not respond within ${a}ms. Keep the device unlocked and trusted, then retry; if it persists restart Xcode and the iOS device.`;throw new _("COMMAND_FAILED","iOS device readiness probe failed",{deviceId:e,cause:t.message,timeoutMs:a,stdout:r,stderr:i,hint:r||i?cR(r,i):o},t)}throw new _("COMMAND_FAILED","iOS device readiness probe failed",{deviceId:e,hint:"Reconnect the device, keep it unlocked, and retry."},t instanceof Error?t:void 0)}finally{await a.rm(t,{force:!0}).catch(()=>{})}}async function cL(e){try{let t=await a.readFile(e,"utf8"),n=JSON.parse(t),r=function(e){let t=e?.result;if(!t||"object"!=typeof t)return{};let n=t.connectionProperties?.tunnelState,r=t.device?.connectionProperties?.tunnelState,i="string"==typeof n?n:"string"==typeof r?r:void 0;return i?{tunnelState:i}:{}}(n);return{parsed:!0,tunnelState:r.tunnelState}}catch{return{parsed:!1}}}function cR(e,t){let n=lI(e,t);return n||(`${e}
|
|
38
|
-
${t}`.toLowerCase().includes("timed out waiting for all destinations")?"Xcode destination did not become available in time. Keep device unlocked and retry.":lv)}async function cT(e,t,n){let r=e.get(t),i=r?.device??await d6(n??{});return r||await cO(i),{session:r,device:i}}async function cP(e,t,n){let r=!e&&"ios"===t.platform;try{return await n()}finally{r&&await aZ(t.id)}}function c$(e,t,n,r){t&&e.recordAction(t,{command:n.command,positionals:n.positionals??[],flags:n.flags??{},result:r})}function cF(e){if(!e)return null;let t=Number(e);return Number.isFinite(t)?t:null}function cU(e){if(0===e.length)return null;let t=cF(e[0]);if(null!==t)return{kind:"sleep",durationMs:t};if("text"===e[0]){let t=cF(e[e.length-1]);return{kind:"text",text:(null!==t?e.slice(1,-1).join(" "):e.slice(1).join(" ")).trim(),timeoutMs:t}}if(e[0].startsWith("@")){let t=cF(e[e.length-1]);return{kind:"ref",rawRef:e[0],timeoutMs:t}}let n=cF(e[e.length-1]),r=e8(null!==n?e.slice(0,-1):e.slice());if(r&&0===r.rest.length){let e=e5(r.selectorExpression);if(e)return{kind:"selector",selector:e,selectorExpression:r.selectorExpression,timeoutMs:n}}return{kind:"text",text:(null!==n?e.slice(0,-1).join(" "):e.join(" ")).trim(),timeoutMs:n}}async function cG(e){let{req:t,logPath:n,sessionStore:r,session:i,device:a}=e,o=(t.positionals?.[0]??"get").toLowerCase(),s=i?"frontmost-app"===i.surface?{surface:"frontmost-app"}:{bundleId:i.appBundleId,surface:i.surface}:{};if(!i_("alert",a))return im("UNSUPPORTED_OPERATION","alert is not supported on this device");if("macos"===a.platform){let e=async()=>await lK("wait"===o?"get":o,s);if("wait"===o){let n=cF(t.positionals?.[1])??1e4,a=Date.now();for(;Date.now()-a<n;){try{let n=await e();return c$(r,i,t,n),{ok:!0,data:n}}catch{}await new Promise(e=>setTimeout(e,300))}return im("COMMAND_FAILED","alert wait timed out")}let n="accept"===o||"dismiss"===o?o:"get";if("accept"===n||"dismiss"===n){let e,a=Date.now();for(;Date.now()-a<2e3;){try{let e=await lK(n,s);return c$(r,i,t,e),{ok:!0,data:e}}catch(n){e=n;let t=String(n?.message??"").toLowerCase();if(!t.includes("alert not found")&&!t.includes("no alert"))break}await new Promise(e=>setTimeout(e,300))}throw cV(e)}let a=await lK("get",s);return c$(r,i,t,a),{ok:!0,data:a}}if("wait"===o){let e=cF(t.positionals?.[1])??1e4,o=Date.now();for(;Date.now()-o<e;){try{let e=await a5(a,{command:"alert",action:"get",appBundleId:i?.appBundleId},{verbose:t.flags?.verbose,logPath:n,traceLogPath:i?.trace?.outPath,requestId:t.meta?.requestId});return c$(r,i,t,e),{ok:!0,data:e}}catch{}await new Promise(e=>setTimeout(e,300))}return im("COMMAND_FAILED","alert wait timed out")}let l="accept"===o||"dismiss"===o?o:"get",u={verbose:t.flags?.verbose,logPath:n,traceLogPath:i?.trace?.outPath,requestId:t.meta?.requestId};if("accept"===l||"dismiss"===l){let e,n=Date.now();for(;Date.now()-n<2e3;){try{let e=await a5(a,{command:"alert",action:l,appBundleId:i?.appBundleId},u);return c$(r,i,t,e),{ok:!0,data:e}}catch(n){e=n;let t=String(n?.message??"").toLowerCase();if(!t.includes("alert not found")&&!t.includes("no alert"))break}await new Promise(e=>setTimeout(e,300))}throw cV(e)}let d=await a5(a,{command:"alert",action:l,appBundleId:i?.appBundleId},u);return c$(r,i,t,d),{ok:!0,data:d}}function cV(e){if(!(e instanceof _))return e;let t=String(e.message??"").toLowerCase();return t.includes("alert not found")||t.includes("no alert")?new _(e.code,e.message,{...e.details??{},hint:"If the permission sheet is visible in snapshot or screenshot but alert reports no alert, take a scoped snapshot around the visible button label and use press @ref."}):e}async function cB(e){let t,{req:n,logPath:r,sessionStore:i,session:a,device:o,parsed:s}=e,{setting:l,state:u,permissionTarget:d}=s;if(!i_("settings",o))return im("UNSUPPORTED_OPERATION","settings is not supported on this device");if("macos"===o.platform&&"appearance"!==(t=l.trim().toLowerCase())&&"permission"!==t)return im("INVALID_ARGS",q(l));let c=a?.appBundleId,p="permission"===l?[l,u,d??"",n.positionals?.[3]??"",c??""]:[l,u,c??""],f=await d9(o,"settings",p,n.flags?.out,{...cb(r,n.flags,c,a?.trace?.outPath)});return c$(i,a,n,f??{setting:l,state:u}),{ok:!0,data:f??{setting:l,state:u}}}async function cj(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e,{session:a,device:o}=await cT(i,n,t.flags);if(!i_("snapshot",o))return im("UNSUPPORTED_OPERATION","snapshot is not supported on this device");let s=cE(t.flags?.snapshotScope,a);return s.ok?await cP(a,o,async()=>{let e=cW({req:t,sessionName:n,logPath:r,sessionStore:i,session:a,device:o,snapshotScope:s.scope}),l=await e.capture.snapshot({session:n,interactiveOnly:t.flags?.snapshotInteractiveOnly,compact:t.flags?.snapshotCompact,depth:t.flags?.snapshotDepth,scope:s.scope,raw:t.flags?.snapshotRaw});return cz({req:t,sessionName:n,sessionStore:i,result:{nodes:l.nodes.length,truncated:l.truncated}}),{ok:!0,data:l}}):s}async function cq(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e,{session:a,device:o}=await cT(i,n,t.flags);if(!i_("diff",o))return im("UNSUPPORTED_OPERATION","diff is not supported on this device");let s=cE(t.flags?.snapshotScope,a);return s.ok?await cP(a,o,async()=>{let e=cW({req:t,sessionName:n,logPath:r,sessionStore:i,session:a,device:o,snapshotScope:s.scope}),l=await e.capture.diffSnapshot({session:n,interactiveOnly:t.flags?.snapshotInteractiveOnly,compact:t.flags?.snapshotCompact,depth:t.flags?.snapshotDepth,scope:s.scope,raw:t.flags?.snapshotRaw});return cz({req:t,sessionName:n,sessionStore:i,result:{mode:"snapshot",baselineInitialized:l.baselineInitialized,summary:l.summary}}),{ok:!0,data:l}}):s}function cW(e){let{req:t,sessionName:n,logPath:r,sessionStore:i,session:a,device:o,snapshotScope:s}=e;return id({backend:function(e){let{req:t,logPath:n,session:r,device:i,snapshotScope:a}=e;return{platform:i.platform,captureSnapshot:async(e,o)=>{let s=await cv({device:i,session:r,flags:t.flags,outPath:o?.outPath??t.flags?.out,logPath:n,snapshotScope:a});return{snapshot:s.snapshot,analysis:s.analysis,freshness:s.freshness,appName:r?.appBundleId?r.appName??r.appBundleId:void 0,appBundleId:r?.appBundleId}}}}({req:t,logPath:r,session:a,device:o,snapshotScope:s}),artifacts:{resolveInput:async()=>{throw new _("UNSUPPORTED_OPERATION","snapshot does not resolve input artifacts")},reserveOutput:async()=>{throw new _("UNSUPPORTED_OPERATION","snapshot does not reserve output artifacts")},createTempFile:async()=>{throw new _("UNSUPPORTED_OPERATION","snapshot does not create temporary files")}},sessions:{get:e=>e===n?function(e){if(e)return{name:e.name,appBundleId:e.appBundleId,appName:e.appName,snapshot:e.snapshot,metadata:{surface:e.surface}}}(i.get(n)):void 0,set:e=>{if(!e.snapshot)throw new _("UNKNOWN","snapshot runtime did not produce session state");let t=function(e){let{session:t,sessionName:n,device:r,snapshot:i,appBundleId:a}=e;return t?{...t,snapshot:i}:{name:n,device:r,createdAt:Date.now(),appBundleId:a,snapshot:i,actions:[]}}({session:i.get(n),sessionName:n,device:o,snapshot:e.snapshot,appBundleId:e.appBundleId});e.appName&&(t.appName=e.appName),i.set(n,t)}},policy:ih()})}function cz(e){let t=e.sessionStore.get(e.sessionName);t&&e.sessionStore.recordAction(t,{command:e.req.command,positionals:e.req.positionals??[],flags:e.req.flags??{},result:e.result})}function cX(e){if(e.length<2)return null;let t=Number(e[0]),n=Number(e[1]);return Number.isFinite(t)&&Number.isFinite(n)?{x:t,y:n}:null}async function cY(e){let{device:t,node:n,flags:r,appBundleId:i,traceOutPath:a,surface:o,contextFromFlags:s}=e,l=X(n),u=function(e){let t=function(e){if(!e)return null;let t=Number(e.x),n=Number(e.y),r=Number(e.width),i=Number(e.height);return Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(i)&&!(r<0)&&!(i<0)?{x:t,y:n,width:r,height:i}:null}(e);if(!t)return null;let n=es(t);return Number.isFinite(n.x)&&Number.isFinite(n.y)?n:null}(n.rect);if(!u)return l;try{let e=await d9(t,"read",[String(u.x),String(u.y)],void 0,{...s(r,i,a),surface:o}),d=e&&"object"==typeof e?e:void 0,c="string"==typeof d?.text?d.text:"";if(c.trim())return c;return eS({level:"warn",phase:"interaction_read_fallback",data:{reason:"empty_backend_text",nodeRef:n.ref,surface:o,platform:t.platform}}),l}catch(e){return eS({level:"warn",phase:"interaction_read_fallback",data:{reason:"backend_read_failed",nodeRef:n.ref,surface:o,platform:t.platform,error:e instanceof Error?e.message:String(e)}}),l}}let cH=[["snapshotDepth","--depth"],["snapshotScope","--scope"],["snapshotRaw","--raw"]];function cJ(e,t){let n=function(e){if(!e)return[];let t=[];for(let[n,r]of cH)void 0!==e[n]&&t.push(r);return t}(t);return 0===n.length?null:im("INVALID_ARGS",`${e} @ref does not support ${n.join(", ")}.`)}function cK(e,t,n,r){let i=e.get(t);i&&e.recordAction(i,{command:n.command,positionals:n.positionals??[],flags:n.flags??{},result:r})}function cZ(e){let t=e.target;return t&&"object"==typeof t?"ref"===t.kind&&"string"==typeof t.ref?{kind:"ref",ref:t.ref}:"selector"===t.kind&&"string"==typeof t.selector?{kind:"selector",selector:t.selector}:void 0:void 0}function cQ(e){return e.startsWith("@")?e.slice(1):e}async function c0(e){var t;let{req:n}=e;if("find"!==n.command)return null;let r=n.positionals??[];if(0===r.length)return im("INVALID_ARGS","find requires a locator or text");let i=tm(r);if(!i.query)return im("INVALID_ARGS","find requires a value");if(n.flags?.findFirst&&n.flags?.findLast)return im("INVALID_ARGS","find accepts only one of --first or --last");let a=i.action;if("exists"!==(t=a)&&"wait"!==t&&"get_text"!==t&&"get_attrs"!==t)return null;let o=await c5(e,{requireSession:!1,capability:"find"});return o.ok?await c9(async()=>{let t=await o.runtime.selectors.find({session:e.sessionName,requestId:n.meta?.requestId,locator:i.locator,query:i.query,action:a,timeoutMs:i.timeoutMs});return cK(e.sessionStore,e.sessionName,n,function(e,t){if("exists"===t)return{found:!0};if("wait"===t)return{found:!0,waitedMs:e.waitedMs};let n="string"==typeof e.ref?e.ref:void 0;return"get_attrs"===t?{ref:n,action:"get attrs"}:{ref:n,action:"get text",text:"string"==typeof e.text?e.text:""}}(t,a)),"found"===t.kind?{found:!0,..."number"==typeof t.waitedMs?{waitedMs:t.waitedMs}:{}}:{..."string"==typeof t.ref?{ref:t.ref}:{},..."string"==typeof t.text?{text:t.text}:{},...t.node&&"object"==typeof t.node?{node:t.node}:{}}}):o.response}async function c1(e){let{req:t}=e;if("get"!==t.command)return null;let n=t.positionals?.[0];if("text"!==n&&"attrs"!==n)return im("INVALID_ARGS","get only supports text or attrs");let r=await c5(e,{requireSession:!0,capability:"get"});if(!r.ok)return r.response;let i=function(e){let t=e.positionals?.[1]??"";if(t.startsWith("@"))return{ok:!0,target:{kind:"ref",ref:t,fallbackLabel:e.positionals.length>2?e.positionals.slice(2).join(" ").trim():""}};let n=e.positionals?.slice(1).join(" ").trim()??"";return n?{ok:!0,target:{kind:"selector",selector:n}}:{ok:!1,response:im("INVALID_ARGS","get requires @ref or selector expression")}}(t);if(!i.ok)return i.response;if("ref"===i.target.kind){let e=cJ("get",t.flags);if(e)return e}return await c9(async()=>{let a,o=await r.runtime.selectors.get({session:e.sessionName,requestId:t.meta?.requestId,property:n,target:i.target});return cK(e.sessionStore,e.sessionName,t,function(e,t){let n=Array.isArray(e.selectorChain)?e.selectorChain:void 0,r=cZ(e),i=r?.kind==="ref"?cQ(r.ref):void 0,a=r?.kind==="selector"?r.selector:void 0,o={...i?{ref:i}:{},...a?{selector:a}:{},...n?{selectorChain:n}:{}};if("attrs"===t)return o;let s="string"==typeof e.text?e.text:"";return{...o,text:s,refLabel:function(e){let t=e.trim();if(!(!t||t.length>80||/[\r\n]/.test(t)))return t}(s)}}(o,n)),a=cZ(o),{...a?.kind==="ref"?{ref:cQ(a.ref)}:{},...a?.kind==="selector"?{selector:a.selector}:{},..."string"==typeof o.text?{text:o.text}:{},...o.node&&"object"==typeof o.node?{node:o.node}:{}}})}async function c2(e){let{req:t}=e;if("is"!==t.command)return null;let n=(t.positionals?.[0]??"").toLowerCase();if(!rb(n))return im("INVALID_ARGS","is requires predicate: visible|hidden|exists|editable|selected|text");let{split:r}=e6(t.positionals??[]);if(!r)return im("INVALID_ARGS","is requires a selector expression");let i=r.rest.join(" ").trim();if("text"===n&&!i)return im("INVALID_ARGS","is text requires expected text value");if("text"!==n&&r.rest.length>0)return im("INVALID_ARGS",`is ${n} does not accept trailing values`);let a=await c5(e,{requireSession:!0,capability:"is"});return a.ok?await c9(async()=>{let o=await a.runtime.selectors.is({session:e.sessionName,requestId:t.meta?.requestId,predicate:n,selector:r.selectorExpression,expectedText:i});return cK(e.sessionStore,e.sessionName,t,o),function(e){let{selectorChain:t,...n}=e;return n}(o)}):a.response}async function c3(e){let{req:t,sessionName:n,sessionStore:r}=e,i=cU(t.positionals??[]);if(!i)return im("INVALID_ARGS","wait requires a duration or text");let{session:a,device:o}=await cT(r,n,t.flags);if("sleep"!==i.kind&&!i_("wait",o))return im("UNSUPPORTED_OPERATION","wait is not supported on this device");let s=async()=>{let s=c4({...e,session:a,device:o});return await c9(async()=>{let e=await s.selectors.wait({session:n,requestId:t.meta?.requestId,target:function(e,t){if("sleep"===e.kind)return{kind:"sleep",durationMs:e.durationMs};if("selector"===e.kind)return{kind:"selector",selector:e.selectorExpression,timeoutMs:e.timeoutMs};if("ref"===e.kind){if(!t?.snapshot)throw new _("INVALID_ARGS","Ref wait requires an existing snapshot in session.");return{kind:"ref",ref:e.rawRef,timeoutMs:e.timeoutMs}}if(!e.text)throw new _("INVALID_ARGS","wait requires text");return{kind:"text",text:e.text,timeoutMs:e.timeoutMs}}(i,a)});return cK(r,n,t,e),{waitedMs:e.waitedMs,..."string"==typeof e.text?{text:e.text}:{},..."string"==typeof e.selector?{selector:e.selector}:{}}})};return"sleep"===i.kind?await s():await cP(a,o,s)}function c4(e){return id({backend:function(e){let t,{req:n,session:r,device:i,logPath:a,sessionName:o,sessionStore:s}=e,l=0;return{platform:i.platform,captureSnapshot:async(e,u)=>{var d;let c,p={...n.flags,...(d=u,c={},d?.interactiveOnly!==void 0&&(c.snapshotInteractiveOnly=d.interactiveOnly),d?.compact!==void 0&&(c.snapshotCompact=d.compact),d?.scope!==void 0&&(c.snapshotScope=d.scope),d?.depth!==void 0&&(c.snapshotDepth=d.depth),d?.raw!==void 0&&(c.snapshotRaw=d.raw),c)},f=u?.scope??n.flags?.snapshotScope,h=Date.now();if(t&&h-l<750&&!cm(r))return t;let m=await cv({device:i,session:r,flags:p,outPath:n.flags?.out,logPath:a??"",snapshotScope:f});return r&&(r.snapshot=m.snapshot,s.set(o,r)),l=h,t={snapshot:m.snapshot}},readText:async(t,o)=>({text:await cY({device:i,node:o,flags:n.flags,appBundleId:r?.appBundleId,traceOutPath:r?.trace?.outPath,surface:r?.surface,contextFromFlags:e.contextFromFlags??((e,t,n)=>cb(a??"",e,t,n))})}),findText:async(t,n)=>({found:await c8(e,n)})}}(e),artifacts:{resolveInput:async()=>{throw new _("UNSUPPORTED_OPERATION","selector commands do not resolve input artifacts")},reserveOutput:async()=>{throw new _("UNSUPPORTED_OPERATION","selector commands do not reserve output artifacts")},createTempFile:async()=>{throw new _("UNSUPPORTED_OPERATION","selector commands do not create temporary files")}},sessions:{get:t=>t===e.sessionName?function(e){if(e)return{name:e.name,appName:e.appName,appBundleId:e.appBundleId,snapshot:e.snapshot,metadata:{surface:e.surface}}}(e.session):void 0,set:t=>{e.session&&t.snapshot&&(e.session.snapshot=t.snapshot,e.sessionStore.set(e.sessionName,e.session))}},policy:ih()})}async function c5(e,t){let n=e.sessionStore.get(e.sessionName);if(!n&&t.requireSession)return{ok:!1,response:im("SESSION_NOT_FOUND","No active session. Run open first.")};let r=n?.device??await d6(e.req.flags??{});return(n||await cO(r),i_(t.capability,r))?{ok:!0,runtime:c4({...e,session:n,device:r})}:{ok:!1,response:im("UNSUPPORTED_OPERATION",`${t.capability} is not supported on this device`)}}async function c8(e,t){let{device:n,session:r,req:i,logPath:a}=e;if("macos"===n.platform&&r?.surface&&"app"!==r.surface)return!!tn((await c6(e)).nodes,t);if(ig(n.platform)){let e=await a5(n,{command:"findText",text:t,appBundleId:r?.appBundleId},{verbose:i.flags?.verbose,logPath:a,traceLogPath:r?.trace?.outPath,requestId:i.meta?.requestId});return e?.found===!0}return!!tn((await c6(e)).nodes,t)}async function c6(e){let t=await cv({device:e.device,session:e.session,flags:{...e.req.flags,snapshotInteractiveOnly:!1,snapshotCompact:!1},outPath:e.req.flags?.out,logPath:e.logPath??""});return e.session&&(e.session.snapshot=t.snapshot,e.sessionStore.set(e.sessionName,e.session)),t.snapshot}async function c9(e){try{return{ok:!0,data:await e()}}catch(t){let e=x(t);return im(e.code,e.message,e.details)}}let c7=new Set(["snapshot","diff","wait","alert","settings"]);async function pe(e){let{req:t,sessionName:n,logPath:r,sessionStore:i}=e,a=t.command;if(!c7.has(a))return null;if("snapshot"===a)return await cj({req:t,sessionName:n,logPath:r,sessionStore:i});if("diff"===a)return t.positionals?.[0]!=="snapshot"?im("INVALID_ARGS","diff currently supports only: diff snapshot"):await cq({req:t,sessionName:n,logPath:r,sessionStore:i});if("wait"===a)return await c3({req:t,sessionName:n,logPath:r,sessionStore:i});if("alert"===a){let{session:e,device:a}=await cT(i,n,t.flags);return await cP(e,a,async()=>await cG({req:t,logPath:r,sessionStore:i,session:e,device:a}))}if("settings"===a){let e,a,o,s=(e=t.positionals?.[0]?.toLowerCase(),a=t.positionals?.[1]?.toLowerCase(),o=t.positionals?.[2]?.toLowerCase(),e&&a&&("permission"!==e||o)?{ok:!0,parsed:{setting:e,state:a,permissionTarget:o}}:im("INVALID_ARGS",j));if(!s.ok)return s;let{session:l,device:u}=await cT(i,n,t.flags);return await cP(l,u,async()=>await cB({req:t,logPath:r,sessionStore:i,session:l,device:u,parsed:s.parsed}))}return null}export{eJ as DEFAULT_BATCH_MAX_STEPS,lv as IOS_DEVICECTL_DEFAULT_HINT,aN as IOS_RUNNER_CONTAINER_BUNDLE_IDS,ld as IOS_SIMCTL_LIST_TIMEOUT_MS,W as SESSION_SURFACES,B as SETTINGS_USAGE_OVERRIDE,aQ as abortAllIosRunnerSessions,tz as adbArgs,sT as appSwitcherAndroid,nl as applyRuntimeHintsToApp,ei as attachRefs,sk as backAndroid,tD as buildAppIdentifiers,tE as buildDeviceIdentifiers,ef as buildMobileSnapshotPresentation,sp as buildScrollGesturePlan,tA as buildSelectorChainForNode,t6 as buildSimctlArgs,t9 as buildSimctlArgsForDevice,J as buildSnapshotDisplayLines,cN as buildSnapshotState,dk as buttonTag,i_ as capabilities_isCommandSupportedOnDevice,cI as captureSnapshotData,es as centerOfRect,tZ as classifyAndroidAppTarget,ij as clearRequestCanceled,nu as clearRuntimeHintsFromApp,o7 as closeAndroidApp,uR as closeIosApp,eX as computeDaemonCodeSignature,cb as context_contextFromFlags,id as createAgentDevice,iz as createRequestCanceledError,eI as createRequestId,nM as decodePng,ig as device_isApplePlatform,oy as waitForAndroidBoot,sZ as dismissAndroidKeyboard,d9 as dispatchCommand,c0 as dispatchFindReadOnlyViaRuntime,c1 as dispatchGetViaRuntime,c2 as dispatchIsViaRuntime,er as displayNodeLabel,eS as emitDiagnostic,tX as ensureAdb,og as ensureAndroidEmulatorBooted,cO as ensureDeviceReady,eP as expandUserHomePath,tu as extractNodeText,sG as fillAndroid,tp as findBestMatchesByLocator,d0 as findBootableIosSimulator,tl as findNearestHittableAncestor,eb as findProjectRoot,e_ as flushDiagnosticsToSessionFile,sU as focusAndroid,tQ as formatAndroidInstalledPackageRequiredMessage,K as formatSnapshotLine,cm as getActiveAndroidSnapshotFreshness,o0 as getAndroidAppState,sK as getAndroidKeyboardState,sq as getAndroidScreenSize,dO as getClickButtonValidationError,ex as getDiagnosticsMeta,iW as getRequestSignal,aH as getRunnerSessionSnapshot,pe as handleSnapshotCommands,no as hasRuntimeTransportHints,sL as homeAndroid,oQ as inferAndroidAppName,sd as installAndroidApp,su as installAndroidInstallablePathAndResolvePackageName,uP as installIosApp,uF as installIosInstallablePath,eO as isAgentDeviceDaemonProcess,a6 as isDeepLinkTarget,iD as isEnvTruthy,cg as isNavigationSensitiveAction,eD as isProcessAlive,iq as isRequestCanceled,oH as listAndroidApps,oc as listAndroidDevices,d5 as listAppleDevices,uj as listIosApps,ly as listIosDeviceApps,lb as listIosDeviceProcesses,ih as localCommandPolicy,sP as longPressAndroid,ch as markAndroidSnapshotFreshness,iB as markRequestCanceled,iy as matchesPlatformSelector,iw as normalizePlatformSelector,eB as normalizeTenantId,to as normalizeType,o2 as openAndroidApp,o9 as openAndroidDevice,uk as openIosApp,uL as openIosDevice,eQ as parseBatchStepsJson,cX as parseCoordinateTarget,dG as parseDeviceRotation,tm as parseFindArgs,t5 as parseSerialAllowlist,z as parseSessionSurface,cU as parseWaitArgs,ap as parseXmlDocumentSync,oG as prepareAndroidInstallArtifact,lC as prepareIosInstallArtifact,sC as pressAndroid,ta as pruneGroupNodes,lr as pushAndroidNotification,uV as pushIosNotification,sQ as readAndroidClipboardText,sH as readAndroidTextAtPoint,tM as readCommandMessage,lE as readInfoPlistString,uU as readIosClipboardText,eC as readProcessCommand,eE as readProcessStartTime,cY as readTextForNode,ey as readVersion,cJ as refSnapshotFlagGuardResponse,iV as registerRequestAbort,sc as reinstallAndroidApp,u$ as reinstallIosApp,oY as resolveAndroidApp,t8 as resolveAndroidSerialAllowlist,ib as resolveAppleSimulatorSetPathForSelector,dC as resolveClickButton,ez as resolveDaemonCodeSignature,eF as resolveDaemonPaths,eU as resolveDaemonServerMode,eG as resolveDaemonTransportPreference,tR as resolveDeployResultTarget,lY as resolveFrontmostMacOsApp,tP as resolveInstallFromSourceResultTarget,uO as resolveIosApp,a9 as resolveIosDeviceDeepLinkBundleId,lI as resolveIosDevicectlHint,t4 as resolveIosSimulatorDeviceSetPath,d$ as resolvePayloadInput,iG as resolveRequestTrackingId,ty as resolveSelectorChain,eV as resolveSessionIsolationMode,d6 as resolveTargetDevice,iY as resolveTimeoutMs,e$ as resolveUserPath,im as response_errorResponse,sR as rotateAndroid,lK as runMacOsAlertAction,a5 as runner_client_runIosRunnerCommand,la as screenshotAndroid,uw as screenshotIos,sj as scrollAndroid,tU as serializeCloseResult,tT as serializeDeployResult,tk as serializeDevice,tL as serializeEnsureSimulatorResult,t$ as serializeInstallFromSourceResult,tF as serializeOpenResult,tO as serializeSessionListEntry,tG as serializeSnapshotResult,s8 as setAndroidSetting,uB as setIosSetting,lM as shutdownSimulator,l_ as ensureBootedSimulator,sx as snapshotAndroid,cv as snapshot_capture_captureSnapshot,tr as snapshot_processing_resolveRefLabel,e6 as splitIsSelectorArgs,e8 as splitSelectorFromArgs,a0 as stopAllIosRunnerSessions,aZ as stopIosRunnerSession,eR as stopProcessForTakeover,tN as successText,sO as swipeAndroid,e5 as tryParseSelectorChain,s$ as typeAndroid,e0 as validateAndNormalizeBatchSteps,eL as waitForProcessExit,eN as withDiagnosticTimer,eA as withDiagnosticsScope,al as withKeyedLock,t_ as withSuccessText,s0 as writeAndroidClipboardText,uG as writeIosClipboardText};
|
|
31
|
+
${a}`.toLowerCase();return i.includes("timeout waiting for screen surfaces")||i.includes("nsposixerrordomain")&&i.includes("code=60")&&i.includes("screenshot")||i.includes("timed out")&&i.includes("screenshot")}let cs={settings:"com.apple.Preferences"},cl=null;function cu(e,t,n){return k("xcrun",t9(e,t),n)}function cd(e){return e.includes("not installed")||e.includes("not found")||e.includes("no such file")}async function cc(e,t){if("macos"===e.platform)return await dG(t);let n=t.trim();if(n.includes("."))return n;let r=cs[n.toLowerCase()];if(r)return r;let a=("simulator"===e.kind?await cN(e):await u6(e,"all")).filter(e=>e.name.toLowerCase()===n.toLowerCase());if(1===a.length)return a[0].bundleId;if(a.length>1)throw new _("INVALID_ARGS",`Multiple apps matched "${t}"`,{matches:a});throw new _("APP_NOT_INSTALLED",`No app found matching "${t}"`)}async function cp(e,t,n){if("macos"===e.platform)return void await dV(e,t,n);let r=n?.url?.trim();if(r){if(!sG(r))throw new _("INVALID_ARGS","open <app> <url> requires a valid URL target");if("simulator"===e.kind){await di(e),await cu(e,["openurl",e.id,r]);return}let a=sV(n?.appBundleId??await cc(e,t),r);if(!a)throw new _("INVALID_ARGS","Deep link open on iOS devices requires an active app bundle ID. Open the app first, then open the URL.");await cR(e,a,{payloadUrl:r});return}let a=t.trim();if(sG(a)){if("simulator"===e.kind){await di(e),await cu(e,["openurl",e.id,a]);return}let t=sV(n?.appBundleId,a);if(!t)throw new _("INVALID_ARGS","Deep link open on iOS devices requires an active app bundle ID. Open the app first, then open the URL.");await cR(e,t,{payloadUrl:a});return}let i=n?.appBundleId??await cc(e,t);"simulator"===e.kind?await cC(e,i):await cR(e,i)}async function cf(e){"macos"===e.platform||"simulator"!==e.kind||"Booted"!==await dl(e)&&await di(e)}async function ch(e,t){if("macos"===e.platform)return void await dB(e,t);let n=await cc(e,t);if("simulator"===e.kind){await di(e);let t=t9(e,["terminate",e.id,n]),r=await k("xcrun",t,{allowFailure:!0});if(0!==r.exitCode){if(r.stderr.toLowerCase().includes("found nothing to terminate"))return;throw new _("COMMAND_FAILED",`xcrun exited with code ${r.exitCode}`,{cmd:"xcrun",args:t,stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode})}return}await u8(["device","process","terminate","--device",e.id,n],{action:"terminate iOS app",deviceId:e.id})}async function cm(e,t){let n=await cc(e,t);if("simulator"!==e.kind){let t=["devicectl","device","uninstall","app","--device",e.id,n],r=await k("xcrun",t,{allowFailure:!0,timeoutMs:u1});if(0!==r.exitCode){let a=String(r.stdout??""),i=String(r.stderr??"");if(!cd(`${a}
|
|
32
|
+
${i}`.toLowerCase()))throw new _("COMMAND_FAILED",`Failed to uninstall iOS app ${n}`,{cmd:"xcrun",args:t,exitCode:r.exitCode,stdout:a,stderr:i,deviceId:e.id,hint:de(a,i)??u7})}return{bundleId:n}}await di(e);let r=await cu(e,["uninstall",e.id,n],{allowFailure:!0});if(0!==r.exitCode&&!cd(`${r.stdout}
|
|
33
|
+
${r.stderr}`.toLowerCase()))throw new _("COMMAND_FAILED",`simctl uninstall failed for ${n}`,{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode});return{bundleId:n}}async function cw(e,t,n){let r=await dd({kind:"path",path:t},n);try{return await cy(e,r.installablePath),{archivePath:r.archivePath,installablePath:r.installablePath,bundleId:r.bundleId,appName:r.appName,launchTarget:r.bundleId}}finally{await r.cleanup()}}async function cg(e,t,n){let{bundleId:r}=await cm(e,t);return await cw(e,n,{appIdentifierHint:t}),{bundleId:r}}async function cy(e,t){"simulator"!==e.kind?await u8(["device","install","app","--device",e.id,t],{action:"install iOS app",deviceId:e.id}):(await di(e),await cu(e,["install",e.id,t]))}async function cb(e){if("macos"===e.platform)return await dj();dr(e,"clipboard"),await di(e);let t=await cu(e,["pbpaste",e.id],{allowFailure:!0});if(0!==t.exitCode)throw new _("COMMAND_FAILED","Failed to read iOS simulator clipboard",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});return t.stdout.replace(/\r\n/g,"\n").replace(/\n$/,"")}async function cv(e,t){if("macos"===e.platform)return void await dq(t);dr(e,"clipboard"),await di(e);let n=await cu(e,["pbcopy",e.id],{allowFailure:!0,stdin:t});if(0!==n.exitCode)throw new _("COMMAND_FAILED","Failed to write iOS simulator clipboard",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode})}async function cI(e,t,n){dr(e,"push"),await di(e);let r=await i.mkdtemp(o.join(p.tmpdir(),"agent-device-ios-push-")),a=o.join(r,"payload.apns");try{await i.writeFile(a,`${JSON.stringify(n)}
|
|
34
|
+
`,"utf8"),await cu(e,["push",e.id,t,a])}finally{await i.rm(r,{recursive:!0,force:!0})}}async function cA(e,t,n,r,a){if("macos"===e.platform){let e=t.toLowerCase();if("appearance"===e)return void await dz(n);if("permission"===e){let e=uT(n);if("deny"===e)throw new _("INVALID_ARGS",q("permission"));let t=function(e){let t=e?.trim().toLowerCase();if("accessibility"===t||"screen-recording"===t||"input-monitoring"===t)return t;throw new _("INVALID_ARGS","Unsupported macOS permission target. Use accessibility|screen-recording|input-monitoring.")}(a?.permissionTarget);return await dE(e,t)}throw new _("INVALID_ARGS",q(t))}dr(e,"settings"),await di(e);let i=t.toLowerCase();switch(i){case"wifi":{let t=cS(n);await cu(e,["status_bar",e.id,"override","--wifiMode",t?"active":"failed"]);return}case"airplane":return void(cS(n)?await cu(e,["status_bar",e.id,"override","--dataNetwork","hide","--wifiMode","failed","--wifiBars","0","--cellularMode","failed","--cellularBars","0","--operatorName",""]):await cu(e,["status_bar",e.id,"clear"]));case"location":{let t=cS(n);if(!r)throw new _("INVALID_ARGS","location setting requires an active app in session");await cu(e,["privacy",e.id,t?"grant":"revoke","location",r]);return}case"faceid":case"touchid":{let t=ck[i],r=function(e,t){let n=e.trim().toLowerCase();if("match"===n)return"match";if("nonmatch"===n)return"nonmatch";if("enroll"===n)return"enroll";if("unenroll"===n)return"unenroll";throw new _("INVALID_ARGS",`Invalid ${t} state: ${e}. Use match|nonmatch|enroll|unenroll.`)}(n,i);await cO(e,r,{settingName:i,label:t.label,modalityAliases:t.modalityAliases});return}case"appearance":{let t=await c_(e,n);await cu(e,["ui",e.id,"appearance",t]);return}case"permission":{var o;if(!r)throw new _("INVALID_ARGS","permission setting requires an active app in session");let t="deny"===(o=uT(n))?"revoke":o,i=function(e,t){let n=u$(e);if("photos"!==n&&t?.trim())throw new _("INVALID_ARGS",`Permission mode is only supported for photos. Received: ${t}.`);if("camera"===n)return"camera";if("microphone"===n)return"microphone";if("contacts"===n)return"contacts";if("contacts-limited"===n)return"contacts-limited";if("notifications"===n)return"notifications";if("calendar"===n)return"calendar";if("location"===n)return"location";if("location-always"===n)return"location-always";if("media-library"===n)return"media-library";if("motion"===n)return"motion";if("reminders"===n)return"reminders";if("siri"===n)return"siri";if("photos"===n){let e=t?.trim().toLowerCase();if(!e||"full"===e)return"photos";if("limited"===e)return"photos-add";throw new _("INVALID_ARGS",`Invalid photos mode: ${t}. Use full|limited.`)}throw new _("INVALID_ARGS",`Unsupported permission target: ${e}. Use camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri.`)}(a?.permissionTarget,a?.permissionMode);await cD(e,t,i,r);return}default:throw new _("INVALID_ARGS",`Unsupported setting: ${t}`)}}async function cx(e,t="all"){return"macos"===e.platform?await dX(t):"simulator"===e.kind?dm(await cN(e),t):await u6(e,t)}async function cN(e){let t=(await cu(e,["listapps",e.id],{allowFailure:!0})).stdout.trim();if(!t)return[];let n=null;if(t.startsWith("{"))try{n=JSON.parse(t)}catch{n=null}if(!n&&t.startsWith("{"))try{let e=await k("plutil",["-convert","json","-o","-","-"],{allowFailure:!0,stdin:t});0===e.exitCode&&e.stdout.trim().startsWith("{")&&(n=JSON.parse(e.stdout))}catch{n=null}return n?Object.entries(n).map(([e,t])=>({bundleId:e,name:t.CFBundleDisplayName??t.CFBundleName??e})):[]}function cS(e){let t=e.toLowerCase();if("on"===t||"true"===t||"1"===t)return!0;if("off"===t||"false"===t||"0"===t)return!1;throw new _("INVALID_ARGS",`Invalid setting state: ${e}`)}async function c_(e,t){let n=uF(t);if("toggle"!==n)return n;let r=await cu(e,["ui",e.id,"appearance"],{allowFailure:!0});if(0!==r.exitCode)throw new _("COMMAND_FAILED","Failed to read current iOS appearance",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode});let a=function(e,t){let n=/\b(light|dark|unsupported|unknown)\b/i.exec(`${e}
|
|
35
|
+
${t}`);if(!n)return null;let r=n[1].toLowerCase();return"dark"===r?"dark":"light"===r?"light":null}(r.stdout,r.stderr);if(!a)throw new _("COMMAND_FAILED","Unable to determine current iOS appearance for toggle",{stdout:r.stdout,stderr:r.stderr});return"dark"===a?"light":"dark"}let ck={faceid:{label:"Face ID",modalityAliases:["face"]},touchid:{label:"Touch ID",modalityAliases:["finger","touch"]}};async function cD(e,t,n,r){let a=await cE(e);if(!a.has(n))throw new _("UNSUPPORTED_OPERATION",`iOS simctl privacy does not support service "${n}" on this runtime.`,{deviceId:e.id,appBundleId:r,hint:`Supported services: ${Array.from(a).sort().join(", ")}`});let i=["privacy",e.id,t,n,r],o="notifications"===n;if(!("reset"===t&&o))try{await cu(e,i);return}catch(t){if(!(o&&cM(t)))throw t;throw new _("UNSUPPORTED_OPERATION","iOS simulator does not support setting notifications permission via simctl privacy on this runtime.",{deviceId:e.id,appBundleId:r,hint:"Use reset notifications for reprompt behavior, or toggle notifications manually in Settings."})}try{await cu(e,i);return}catch(e){if(!cM(e))throw e}try{await cu(e,["privacy",e.id,"reset","all",r])}catch(t){throw new _("COMMAND_FAILED","iOS simulator blocked direct notifications reset. Fallback reset-all also failed.",{deviceId:e.id,appBundleId:r,hint:"Use reinstall to force a fresh notifications prompt, or reset simulator content and settings."},t instanceof Error?t:void 0)}}function cM(e){if(!(e instanceof _)||"COMMAND_FAILED"!==e.code)return!1;let t=String(e.details?.stderr??"").toLowerCase();return(t.includes("failed to grant access")||t.includes("failed to revoke access")||t.includes("failed to reset access"))&&t.includes("operation not permitted")}async function cE(e){let n=t4(e.simulatorSetPath),r=`${process.env.PATH??""}::${n??""}`;if(cl&&t===r)return cl;let a=await cu(e,["privacy","help"],{allowFailure:!0}),i=function(e){let t=new Set,n=!1;for(let r of e.split("\n")){let e=r.trim();if(!e)continue;if("service"===e){n=!0;continue}if(!n)continue;if(e.startsWith("bundle identifier"))break;let a=/^([a-z-]+)\s+-\s+/.exec(e);a&&t.add(a[1])}return t}(`${a.stdout}
|
|
36
|
+
${a.stderr}`);if(0===i.size)throw new _("COMMAND_FAILED","Unable to determine supported simctl privacy services",{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode,hint:"Run `xcrun simctl privacy help` manually to verify available services for this runtime."});return cl=i,t=r,i}async function cO(e,t,n){let r=function(e,t,n){let r=n.length>0?n:["face"];switch(t){case"match":return r.flatMap(t=>[["biometric",e,"match",t],["biometric","match",e,t]]);case"nonmatch":return r.flatMap(t=>[["biometric",e,"nonmatch",t],["biometric",e,"nomatch",t],["biometric","nonmatch",e,t],["biometric","nomatch",e,t]]);case"enroll":return[["biometric",e,"enroll","yes"],["biometric",e,"enroll","1"],["biometric","enroll",e,"yes"],["biometric","enroll",e,"1"]];case"unenroll":return[["biometric",e,"enroll","no"],["biometric",e,"enroll","0"],["biometric","enroll",e,"no"],["biometric","enroll",e,"0"]]}}(e.id,t,n.modalityAliases),a=[];for(let t of r){let n=t9(e,t),r=await k("xcrun",n,{allowFailure:!0});if(0===r.exitCode)return;a.push({args:n,stderr:r.stderr,stdout:r.stdout,exitCode:r.exitCode})}let i=a.map(e=>({args:e.args.join(" "),exitCode:e.exitCode,stderr:e.stderr.slice(0,400)}));if(a.length>0&&a.every(e=>{var t,n;let r;return t=e.stdout,n=e.stderr,(r=`${t}
|
|
37
|
+
${n}`.toLowerCase()).includes("unrecognized subcommand")||r.includes("unknown subcommand")||r.includes("not supported")||r.includes("unavailable")||r.includes("biometric")&&r.includes("invalid")}))throw new _("UNSUPPORTED_OPERATION",`${n.label} simulation is not supported on this simulator runtime.`,{deviceId:e.id,action:t,setting:n.settingName,attempts:i});throw new _("COMMAND_FAILED",`Failed to simulate ${n.settingName}.`,{deviceId:e.id,action:t,setting:n.settingName,attempts:i})}async function cC(e,t){await di(e);let n=0,r=oc.fromTimeoutMs(u0);try{await op(async({deadline:n})=>{var r;if(n?.isExpired())throw new _("COMMAND_FAILED","App launch deadline exceeded",{timeoutMs:u0});let a=(r=["launch",e.id,t],t9(e,r)),i=await k("xcrun",a,{allowFailure:!0});if(0!==i.exitCode)throw new _("COMMAND_FAILED",`xcrun exited with code ${i.exitCode}`,{cmd:"xcrun",args:a,stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode})},{maxAttempts:10,baseDelayMs:1e3,maxDelayMs:5e3,jitter:.2,shouldRetry:e=>!!dt(e)&&(n+=1)<3},{deadline:r})}catch(n){if(dt(n)){var a;let r=(a=await dn(e,t)).installed?!1===a.simulatorCompatible?"ARCH_MISMATCH":"PERSISTENT_LAUNCH_FAIL":"APP_NOT_INSTALLED";n.details={...n.details,hint:function(e){switch(e){case"ARCH_MISMATCH":return"The app binary was not built for the simulator platform. Rebuild with a simulator destination or use a physical device.";case"APP_NOT_INSTALLED":return"The app bundle is not installed on this simulator. Run install before open.";case"PERSISTENT_LAUNCH_FAIL":return"The simulator repeatedly refused to launch the app. Inspect crash logs in Console.app or ~/Library/Logs/DiagnosticReports/ and consider reinstalling the app.";default:return"The simulator failed to launch the app. Retry with --debug and inspect diagnostics log for details."}}(r)}}throw n}}async function cR(e,t,n){let r=["device","process","launch","--device",e.id,t];n?.payloadUrl&&r.push("--payload-url",n.payloadUrl),await u8(r,{action:"launch iOS app",deviceId:e.id})}async function cL(e,t,n,r,a,i,o){if("tv"===t.target)return c$(await e(t,{command:"swipe",direction:function(e){switch(e){case"up":return"down";case"down":return"up";case"left":return"right";case"right":return"left";default:return e}}(a),appBundleId:n.appBundleId},r),i);let s=o??await cP(e,t,n,r),l=l1({direction:a,amount:i?.amount,pixels:i?.pixels,referenceWidth:s.referenceWidth,referenceHeight:s.referenceHeight});return c$(await e(t,{command:"drag",x:s.originX+l.x1,y:s.originY+l.y1,x2:s.originX+l.x2,y2:s.originY+l.y2,appBundleId:n.appBundleId},r),{amount:l.amount,pixels:l.pixels,preferProvidedPixels:!0})}async function cP(e,t,n,r){let a=await e(t,{command:"interactionFrame",appBundleId:n.appBundleId},r),i=cT(a.x),o=cT(a.y),s=cT(a.referenceWidth),l=cT(a.referenceHeight);if(void 0===i||void 0===o||void 0===s||void 0===l)throw new _("COMMAND_FAILED","interactionFrame did not return a usable frame");return{originX:i,originY:o,referenceWidth:s,referenceHeight:l}}function cT(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function c$(e,t){var n;let{x1:r,y1:a,x2:i,y2:o}={x1:cT((n=e).x),y1:cT(n.y),x2:cT(n.x2),y2:cT(n.y2)},s=cT(e.referenceWidth),l=cT(e.referenceHeight),u=void 0!==r&&void 0!==i?Math.round(Math.abs(i-r)):void 0,d=void 0!==a&&void 0!==o?Math.round(Math.abs(o-a)):void 0,c=t?.preferProvidedPixels&&void 0!==t.pixels?t.pixels:u&&u>0?u:d&&d>0?d:void 0;return{...void 0!==r?{x1:r}:{},...void 0!==a?{y1:a}:{},...void 0!==i?{x2:i}:{},...void 0!==o?{y2:o}:{},...void 0!==s?{referenceWidth:s}:{},...void 0!==l?{referenceHeight:l}:{},...t?.amount!==void 0?{amount:t.amount}:{},...void 0!==c?{pixels:c}:{}}}function cF(){return process.env.WAYLAND_DISPLAY||"wayland"===process.env.XDG_SESSION_TYPE?"wayland":"x11"}let cU=null;async function cG(){if(cU)return cU;let e=cF();if("wayland"===e){if(await v("ydotool"))return cU={tool:"ydotool",display:e};throw new _("TOOL_MISSING","ydotool is required for input synthesis on Wayland (xdotool does not work on Wayland). Install it via your package manager.")}if(await v("xdotool"))return cU={tool:"xdotool",display:e};throw new _("TOOL_MISSING","xdotool is required for input synthesis on X11. Install it via your package manager.")}async function cV(...e){await k("xdotool",e,{allowFailure:!1,timeoutMs:1e4})}async function cB(...e){await k("ydotool",e,{allowFailure:!1,timeoutMs:1e4})}async function cj(e,t){let{tool:n}=await cG();"xdotool"===n?await cV("mousemove","--sync",String(e),String(t)):await cB("mousemove","--absolute","-x",String(e),"-y",String(t))}async function cq(e,t){let{tool:n}=await cG();"xdotool"===n?await cV("key","--clearmodifiers",e):await cB("key",...t)}async function cW(e,t,n,r){await cj(e,t);let{tool:a}=await cG();"xdotool"===a?await cV("click",n):await cB("click",r)}async function cz(e,t){await cW(e,t,"1","0xC0")}async function cX(e,t){await cW(e,t,"3","0xC1")}async function cH(e,t){await cW(e,t,"2","0xC2")}async function cY(e,t){let{tool:n}=await cG();await cj(e,t),"xdotool"===n?await cV("click","--repeat","2","1"):(await cB("click","0xC0"),await cB("click","0xC0"))}async function cJ(e,t,n=800){let{tool:r}=await cG();await cj(e,t),"xdotool"===r?(await cV("mousedown","1"),await c2(n),await cV("mouseup","1")):(await cB("click","--down","0xC0"),await c2(n),await cB("click","--up","0xC0"))}async function cK(e,t){await cz(e,t)}async function cZ(e,t,n,r,a=300){let{tool:i}=await cG();await cj(e,t),"xdotool"===i?(await cV("mousedown","1"),await cV("mousemove","--sync",String(n),String(r)),await c2(a),await cV("mouseup","1")):(await cB("click","--down","0xC0"),await cB("mousemove","--absolute","-x",String(n),"-y",String(r)),await c2(a),await cB("click","--up","0xC0"))}async function cQ(e,t){let{tool:n}=await cG(),r=5;if(t?.pixels!=null?r="xdotool"===n?Math.max(1,Math.round(t.pixels/15)):Math.max(1,Math.round(t.pixels/40)):t?.amount!=null&&(r=Math.max(1,Math.round(5*(t.amount/.6)))),"xdotool"===n)await cV("click","--repeat",String(r),"up"===e?"4":"down"===e?"5":"left"===e?"6":"7");else if("up"===e||"down"===e){let t="up"===e?String(-r):String(r);await cB("mousemove","--wheel","-y",t)}else{let t="left"===e?String(-r):String(r);await cB("mousemove","--wheel","-x",t)}}async function c0(e,t=0){let{tool:n}=await cG();if("xdotool"===n){let n=["type"];t>0&&n.push("--delay",String(t)),n.push("--clearmodifiers","--",e),await cV(...n)}else await cB("type","--",e)}async function c1(e,t,n,r=0){await cz(e,t),await c2(100),await cq("ctrl+a",["29:1","30:1","30:0","29:0"]),await c2(50),await c0(n,r)}function c2(e){return new Promise(t=>setTimeout(t,e))}function c3(e){let t=null;return{resolve:async function(){if(t)return t;let n="wayland"===cF()?"wayland":"x11";for(let r of"wayland"===n?e.wayland:e.x11)if(await v(r.command))return t={tool:r.tool,display:n};throw new _("TOOL_MISSING","wayland"===n?e.waylandError:e.x11Error)},resetCache:()=>{t=null}}}let c4=c3({wayland:[{tool:"grim",command:"grim"},{tool:"gnome-screenshot",command:"gnome-screenshot"}],x11:[{tool:"scrot",command:"scrot"},{tool:"import",command:"import"},{tool:"gnome-screenshot",command:"gnome-screenshot"}],waylandError:"grim or gnome-screenshot is required for screenshots on Wayland. Install via your package manager.",x11Error:"scrot, import (ImageMagick), or gnome-screenshot is required for screenshots on X11. Install via your package manager."});async function c5(e){let{tool:t}=await c4.resolve();switch(t){case"grim":await k("grim",[e]);break;case"scrot":await k("scrot",[e]);break;case"import":await k("import",["-window","root",e]);break;case"gnome-screenshot":await k("gnome-screenshot",["-f",e])}}async function c8(e){if(e.includes("://")||e.startsWith("/"))return void await k("xdg-open",[e]);if(await v(e)){k(e,[],{allowFailure:!0}).catch(t=>{eN({level:"warn",phase:"linux_app_launch",data:{app:e,error:String(t)}})}),await new Promise(e=>setTimeout(e,500));return}await k("xdg-open",[e],{allowFailure:!0})}async function c6(e){await v("wmctrl")?await k("wmctrl",["-c",e],{allowFailure:!0}):await k("pkill",["-x",e],{allowFailure:!0})}async function c9(){await cq("alt+Left",["56:1","105:1","105:0","56:0"])}async function c7(){await cq("super+d",["125:1","32:1","32:0","125:0"])}let pe=c3({wayland:[{tool:"wl-clipboard",command:"wl-paste"}],x11:[{tool:"xclip",command:"xclip"},{tool:"xsel",command:"xsel"}],waylandError:"wl-paste (wl-clipboard) is required for clipboard access on Wayland. Install via your package manager.",x11Error:"xclip or xsel is required for clipboard access on X11. Install via your package manager."});async function pt(){let{tool:e}=await pe.resolve();switch(e){case"wl-clipboard":return(await k("wl-paste",["--no-newline"],{allowFailure:!0,timeoutMs:5e3})).stdout;case"xclip":return(await k("xclip",["-selection","clipboard","-o"],{allowFailure:!0,timeoutMs:5e3})).stdout;case"xsel":return(await k("xsel",["--clipboard","--output"],{allowFailure:!0,timeoutMs:5e3})).stdout}}async function pn(e){let{tool:t}=await pe.resolve();switch(t){case"wl-clipboard":await k("wl-copy",["--",e],{allowFailure:!1,timeoutMs:5e3});break;case"xclip":await k("xclip",["-selection","clipboard"],{allowFailure:!1,timeoutMs:5e3,stdin:e});break;case"xsel":await k("xsel",["--clipboard","--input"],{allowFailure:!1,timeoutMs:5e3,stdin:e})}}async function pr(){return"linux"!==process.platform?[]:[{platform:"linux",id:"local",name:f(),kind:"device",target:"desktop",booted:!0}]}pe.resetCache;let pa={"push button":"Button","toggle button":"Button","push button menu":"Button",label:"StaticText",static:"StaticText",caption:"StaticText",text:"TextField",entry:"TextField","password text":"TextField","spin button":"TextField",terminal:"TextArea","document text":"TextArea",paragraph:"TextArea",frame:"Window",window:"Window",dialog:"Dialog",alert:"Alert","file chooser":"Dialog","color chooser":"Dialog","font chooser":"Dialog",panel:"Group",filler:"Group",section:"Group",form:"Group",grouping:"Group","layered pane":"Group","glass pane":"Group","root pane":"Group","option pane":"Group","internal frame":"Group","desktop frame":"Group","block quote":"Group",article:"Group",comment:"Group",landmark:"Group",log:"Group",marquee:"Group",math:"Group",notification:"Group","content deletion":"Group","content insertion":"Group",mark:"Group",suggestion:"Group","scroll pane":"ScrollArea","scroll bar":"ScrollBar","menu bar":"MenuBar",menu:"Menu","popup menu":"Menu","menu item":"MenuItem","check menu item":"MenuItem","radio menu item":"MenuItem","tearoff menu item":"MenuItem","check box":"CheckBox","radio button":"RadioButton",switch:"Switch","combo box":"ComboBox","page tab":"Tab","page tab list":"TabList",table:"Table","tree table":"Table","table cell":"Cell","table row":"Row","table column header":"Cell","table row header":"Cell","column header":"Cell","row header":"Cell",list:"List","list item":"ListItem","list box":"List",tree:"Tree","tree item":"TreeItem","description list":"List","description term":"ListItem","description value":"ListItem","tool bar":"Toolbar","status bar":"StatusBar","info bar":"StatusBar",slider:"Slider","progress bar":"ProgressBar","level bar":"ProgressBar",image:"Image",icon:"Image",animation:"Image",canvas:"Image","drawing area":"Image",video:"Video",audio:"Audio",link:"Link",hyperlink:"Link",separator:"Separator",application:"Application","tool tip":"Tooltip",timer:"Timer",heading:"Heading",footnote:"Footnote","title bar":"TitleBar","date editor":"DateEditor",rating:"Slider"},pi="atspi-dump.py",po=null;async function ps(e,t={}){let n;if("linux"!==process.platform)throw new _("UNSUPPORTED_PLATFORM","AT-SPI2 bridge is only available on Linux");if(!await v("python3"))throw new _("TOOL_MISSING","python3 is required for AT-SPI2 accessibility snapshots on Linux.");let a=t.maxNodes??1500,i=t.maxDepth??12,s=t.maxApps??24,u=[function(){if(po)return po;let e=o.dirname(l(import.meta.url));for(let t=0;t<5;t++){let n=o.join(e,"src","platforms","linux",pi);if(r.existsSync(n))return po=n,n;if(0===t){let t=o.join(e,pi);if(r.existsSync(t))return po=t,t}e=o.dirname(e)}throw new _("TOOL_MISSING",`Cannot find ${pi}. Ensure the agent-device package is installed correctly.`)}(),"--surface",e,"--max-nodes",String(a),"--max-depth",String(i),"--max-apps",String(s)],d=await k("python3",u,{allowFailure:!0,timeoutMs:3e4});if(0!==d.exitCode){let e=d.stderr.trim();if(e.includes("No module named")||e.includes("gi.require_version"))throw new _("TOOL_MISSING","AT-SPI2 Python bindings not found. Install python3-gi and gir1.2-atspi-2.0.",{cause:e});throw new _("COMMAND_FAILED",`AT-SPI2 snapshot failed (exit ${d.exitCode}): ${e||d.stdout}`)}try{n=JSON.parse(d.stdout)}catch{throw new _("COMMAND_FAILED",`AT-SPI2 snapshot returned invalid JSON: ${d.stdout.slice(0,200)}`)}if(n.error)throw new _("COMMAND_FAILED",`AT-SPI2: ${n.error}`);return{nodes:(n.nodes??[]).map(e=>{let t,n;return{index:e.index,type:(n=pa[t=e.role.toLowerCase().trim()])||t.split(/[\s_-]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(""),role:e.role,label:e.label??void 0,value:e.value??void 0,rect:e.rect??void 0,enabled:e.enabled??void 0,selected:e.selected??void 0,hittable:e.hittable??void 0,depth:e.depth,parentIndex:e.parentIndex??void 0,pid:e.pid??void 0,appName:e.appName??void 0,windowTitle:e.windowTitle??void 0}}),truncated:n.truncated,surface:e}}async function pl(e){let t="desktop"===e?"desktop":"frontmost-app"===e||"app"===e?"frontmost-app":("menubar"===e&&eN({level:"warn",phase:"linux_snapshot",data:{message:"menubar surface is not supported on Linux, falling back to desktop"}}),"desktop"),n=await ps(t);return{nodes:n.nodes,truncated:n.truncated}}function pu(e){return e?.clickButton??"primary"}function pd(e){return"primary"===e.button?null:"click"!==e.commandLabel?new _("INVALID_ARGS","--button is supported only for click"):"macos"!==e.platform&&"linux"!==e.platform?new _("UNSUPPORTED_OPERATION",`click --button ${e.button} is supported only on macOS and Linux`):"macos"===e.platform&&"middle"===e.button?new _("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 _("INVALID_ARGS",`click --button ${e.button} does not support repeat or gesture modifier flags`):null}function pc(e){return"primary"===e?{}:{button:e}}let pp=/^[A-Za-z0-9_.:-]{1,64}$/,pf=[[0,0],[1,0],[0,1],[-1,0],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]];async function ph(e,t,n){for(let r=0;r<e;r+=1)await n(r),r<e-1&&t>0&&await pm(t)}async function pm(e){await new Promise(t=>setTimeout(t,e))}function pw(e,t){let n,a=t?.subject??"Payload",i=e.trim();if(!i)throw new _("INVALID_ARGS",`${a} cannot be empty`);let o=t?.expandPath?t.expandPath(i,t.cwd):i;try{if(!r.statSync(o).isFile())throw new _("INVALID_ARGS",`${a} path is not a file: ${o}`);return{kind:"file",path:o}}catch(t){if(t instanceof _)throw t;let e=t.code;if("EACCES"===e||"EPERM"===e)throw new _("INVALID_ARGS",`${a} file is not readable: ${o}`);if(e&&"ENOENT"!==e)throw new _("COMMAND_FAILED",`Unable to read ${a} file: ${o}`,{cause:String(t)})}if((n=i.trim()).startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]"))return{kind:"inline",text:i};throw new _("INVALID_ARGS",`${a} file not found: ${o}`)}async function pg(e){let t=pw(e,{subject:"Push payload"}),n="inline"===t.kind?t.text:await py(t.path);try{let e=JSON.parse(n);if(!e||"object"!=typeof e||Array.isArray(e))throw new _("INVALID_ARGS","push payload must be a JSON object");return e}catch(t){if(t instanceof _)throw t;throw new _("INVALID_ARGS",`Invalid push payload JSON: ${e}`)}}async function py(e){try{return await i.readFile(e,"utf8")}catch(n){let t=n.code;if("ENOENT"===t)throw new _("INVALID_ARGS",`Push payload file not found: ${e}`);if("EISDIR"===t)throw new _("INVALID_ARGS",`Push payload path is not a file: ${e}`);if("EACCES"===t||"EPERM"===t)throw new _("INVALID_ARGS",`Push payload file is not readable: ${e}`);throw new _("COMMAND_FAILED",`Unable to read push payload file: ${e}`,{cause:String(n)})}}function pb(e){if(void 0===e)throw new _("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 _("INVALID_ARGS",`Invalid rotation: ${e}. Use portrait|portrait-upside-down|landscape-left|landscape-right.`)}}let pv=ok(process.env.AGENT_DEVICE_IOS_DEVICECTL_LIST_TIMEOUT_MS,8e3,500),pI=/^(iphone|ipad|ipod|appletv)/i,pA=/\b(iphone|ipad|ipod)\b/i,px=/^appletv/i,pN=["apple tv","appletv","tvos"],pS=/^==\s*(.+?)\s*==$/,p_=/^(?<name>.+?)\s+\[(?<id>[^[\]]+)\]\s*$/;function pk(e){return(e??"").trim().toLowerCase()}function pD(e){return pk(e.hardwareProperties?.platform)}function pM(e){return e.includes("tvos")}function pE(e){let t=pk(e);return pN.some(e=>t.includes(e))}function pO(e){return[e.name??"",e.deviceProperties?.name??"",e.deviceProperties?.deviceType??""]}function pC(e){return e.hardwareProperties?.productType??e.deviceProperties?.productType??""}async function pR(e={}){let t,n,r=t4(e.simulatorSetPath),a=e.target;try{t=await k("xcrun",t6(["list","devices","-j"],{simulatorSetPath:r}))}catch{return null}try{n=JSON.parse(t.stdout)}catch{return null}let i=pL(n,r),o=null,s=null,l=null;for(let e of i)a&&e.target!==a||(e.booted&&(o=o??e),"mobile"===e.target&&(s=s??e),l=l??e);return o??s??l}function pL(e,t){let n=[];for(let[r,a]of Object.entries(e.devices))if(function(e){let t=pk(e);return t.includes("ios")||t.includes("tvos")}(r))for(let e of a)e.isAvailable&&n.push({platform:"ios",id:e.udid,name:e.name,kind:"simulator",target:pM(pk(r))?"tv":"mobile",booted:"Booted"===e.state,...t?{simulatorSetPath:t}:{}});return n}function pP(e,t){let n=new Set(e.map(e=>e.id)),r=[...e];for(let e of t)n.has(e.id)||(n.add(e.id),r.push(e));return r}async function pT(){let e=null;try{e=o.join(p.tmpdir(),`agent-device-devicectl-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);let t=await k("xcrun",["devicectl","list","devices","--json-output",e],{allowFailure:!0,timeoutMs:pv});if(0!==t.exitCode)return[];let n=await i.readFile(e,"utf8");return function(e){let t=[];for(let n of e.result?.devices??[]){if(!function(e){var t;let n=pD(e);return!!(n.includes("ios")||n.includes("tvos"))||(t=pC(e),!!pI.test(t.trim())||pO(e).some(pE))}(n))continue;let e=n.hardwareProperties?.udid??n.identifier??"",r=n.name??n.deviceProperties?.name??e;e&&t.push({platform:"ios",id:e,name:r,kind:"device",target:function(e){var t;return pM(pD(e))?"tv":(t=pC(e),px.test(t.trim())||pO(e).some(pE))?"tv":"mobile"}(n),booted:!0})}return t}(JSON.parse(n))}catch{return[]}finally{e&&await i.rm(e,{force:!0}).catch(()=>{})}}async function p$(){try{let e=await k("xcrun",["xctrace","list","devices"],{allowFailure:!0});if(0!==e.exitCode)return[];return function(e){let t=[],n=null;for(let r of e.split(/\r?\n/)){let e=r.trim();if(!e)continue;let a=pS.exec(e);if(a){n=a[1]?.trim()??null;continue}if("Devices"!==n)continue;let i=p_.exec(e),o=i?.groups?.id?.trim()??"",s=i?.groups?.name?.trim()??"";if(!o||!s)continue;let l=function(e){return pE(e)?"tv":pA.test(e.trim())?"mobile":null}(s);l&&t.push({platform:"ios",id:o,name:s,kind:"device",target:l,booted:!0})}return t}(e.stdout)}catch{return[]}}async function pF(e={}){if("darwin"!==process.platform)throw new _("UNSUPPORTED_PLATFORM","Apple tools are only available on macOS");if(!await v("xcrun"))throw new _("TOOL_MISSING","xcrun not found in PATH");let t=t4(e.simulatorSetPath),n=await k("xcrun",t6(["list","devices","-j"],{simulatorSetPath:t})),r=[];try{let e=JSON.parse(n.stdout);r=pL(e,t)}catch(e){throw new _("COMMAND_FAILED","Failed to parse simctl devices JSON",void 0,e)}if(r.push({platform:"macos",id:"host-macos-local",name:p.hostname(),kind:"device",target:"desktop",booted:!0}),t)return r;let[a,i]=await Promise.all([pT(),p$()]);return r=pP(r,a),pP(r,i)}async function pU(e,t,n){let r,a=!!(t.udid||t.serial||t.deviceName);try{r=await i7(e,t,n)}catch(e){if(a||!(e instanceof _)||"DEVICE_NOT_FOUND"!==e.code)throw e}if(!a&&(!t.platform||"apple"===t.platform||"ios"===t.platform)&&"desktop"!==t.target&&(!r||"device"===r.kind)){let e=await pR({simulatorSetPath:n.simulatorSetPath,target:t.target});if(e)return e}if(r)return r;throw new _("DEVICE_NOT_FOUND","No devices found",{selector:t})}async function pG(e){let t=i5(e.platform),n=i9({simulatorSetPath:t4(e.iosSimulatorDeviceSet),platform:t,target:e.target}),r=t8(e.androidDeviceAllowlist);return await eS("resolve_target_device",async()=>{let a={platform:t,target:e.target,deviceName:e.device,udid:e.udid,serial:e.serial};if(a.target&&!a.platform)throw new _("INVALID_ARGS","Device target selector requires --platform. Use --platform ios|macos|android|linux|apple with --target mobile|tv|desktop.");if("linux"===a.platform){let e=await pr();return await i7(e,a)}if("android"===a.platform){await tX();let e=await s0({serialAllowlist:r});return await i7(e,a)}if(a.platform){let e=await pF({simulatorSetPath:n});return await pU(e,a,{simulatorSetPath:n})}let i=[];try{i.push(...await s0({serialAllowlist:r}))}catch{}try{i.push(...await pF({simulatorSetPath:n}))}catch{}try{i.push(...await pr())}catch{}return await i7(i,a,{simulatorSetPath:n})},{platform:t,target:e.target})}async function pV(e,t,n,r,a){let s={requestId:a?.requestId,appBundleId:a?.appBundleId,verbose:a?.verbose,logPath:a?.logPath,traceLogPath:a?.traceLogPath},l=function(e,t){switch(e.platform){case"android":return{open:(t,n)=>lP(e,t,n?.activity),openDevice:()=>lV(e),close:t=>lB(e,t),tap:(t,n)=>uu(e,t,n),doubleTap:async(t,n)=>{await uu(e,t,n),await uu(e,t,n)},swipe:(t,n,r,a,i)=>ud(e,t,n,r,a,i),longPress:(t,n,r)=>um(e,t,n,r),focus:(t,n)=>uy(e,t,n),type:(t,n)=>uw(e,t,n),fill:(t,n,r,a)=>ub(e,t,n,r,a),scroll:(t,n)=>uA(e,t,n),screenshot:t=>uH(e,t),back:t=>uc(e),home:()=>up(e),rotate:t=>uf(e,t),appSwitcher:()=>uh(e),readClipboard:()=>uC(e),writeClipboard:t=>uR(e,t),setSetting:(t,n,r,a)=>uU(e,t,n,r,a)};case"linux":return{open:e=>c8(e),openDevice:()=>Promise.resolve(),close:e=>c6(e),tap:(e,t)=>cz(e,t),doubleTap:(e,t)=>cY(e,t),swipe:(e,t,n,r,a)=>cZ(e,t,n,r,a),longPress:(e,t,n)=>cJ(e,t,n),focus:(e,t)=>cK(e,t),type:(e,t)=>c0(e,t),fill:(e,t,n,r)=>c1(e,t,n,r),scroll:(e,t)=>cQ(e,t),screenshot:e=>c5(e),back:()=>c9(),home:()=>c7(),rotate:()=>{throw new _("UNSUPPORTED_OPERATION","rotate not supported on Linux")},appSwitcher:()=>{throw new _("UNSUPPORTED_OPERATION","appSwitcher not yet supported on Linux")},readClipboard:()=>pt(),writeClipboard:e=>pn(e),setSetting:()=>{throw new _("UNSUPPORTED_OPERATION","setSetting not supported on Linux")}};case"ios":case"macos":{let n,{overrides:r,runnerOpts:a}={runnerOpts:n={verbose:t.verbose,logPath:t.logPath,traceLogPath:t.traceLogPath,requestId:t.requestId},overrides:{tap:async(r,a)=>await sF(e,{command:"tap",x:r,y:a,appBundleId:t.appBundleId},n),doubleTap:async(r,a)=>await sF(e,{command:"tapSeries",x:r,y:a,count:1,intervalMs:0,doubleTap:!0,appBundleId:t.appBundleId},n),swipe:async(r,a,i,o,s)=>await sF(e,{command:"drag",x:r,y:a,x2:i,y2:o,durationMs:s,appBundleId:t.appBundleId},n),longPress:async(r,a,i)=>await sF(e,{command:"longPress",x:r,y:a,durationMs:i,appBundleId:t.appBundleId},n),focus:async(r,a)=>await sF(e,{command:"tap",x:r,y:a,appBundleId:t.appBundleId},n),type:async(r,a)=>{await sF(e,{command:"type",text:r,delayMs:a,appBundleId:t.appBundleId},n)},fill:async(r,a,i,o)=>{let s=await sF(e,{command:"tap",x:r,y:a,appBundleId:t.appBundleId},n);return await sF(e,{command:"type",text:i,clearFirst:!0,delayMs:o,appBundleId:t.appBundleId},n),s},scroll:async(r,a)=>await cL(sF,e,t,n,r,a)}};return{open:(t,n)=>cp(e,t,{appBundleId:n?.appBundleId,url:n?.url}),openDevice:()=>cf(e),close:t=>ch(e,t),screenshot:async(t,n)=>{"macos"===e.platform&&n?.surface&&"app"!==n.surface?await dP(t,{surface:n.surface,fullscreen:n.fullscreen}):await d8(e,t,n?.appBundleId,n?.fullscreen)},back:async n=>{await sF(e,{command:"system"===n?"backSystem":"backInApp",appBundleId:t.appBundleId},a)},home:async()=>{await sF(e,{command:"home",appBundleId:t.appBundleId},a)},rotate:async n=>{await sF(e,{command:"rotate",orientation:n,appBundleId:t.appBundleId},a)},appSwitcher:async()=>{await sF(e,{command:"appSwitcher",appBundleId:t.appBundleId},a)},readClipboard:()=>cb(e),writeClipboard:t=>cv(e,t),setSetting:(t,n,r,a)=>cA(e,t,n,r,a),...r}}default:throw new _("UNSUPPORTED_PLATFORM",`Unsupported platform: ${e.platform}`)}}(e,s);return eN({level:"debug",phase:"platform_command_prepare",data:{command:t,platform:e.platform,kind:e.kind}}),await eS("platform_command",async()=>{switch(t){case"open":return pB(e,l,n,a);case"close":{let e=n[0];if(!e)return{closed:"session",...tS("Closed session")};return await l.close(e),{app:e,...tS(`Closed: ${e}`)}}case"press":return pj(e,l,n,a,s);case"swipe":return pq(e,l,n,a,s);case"longpress":{let e=Number(n[0]),t=Number(n[1]),r=n[2]?Number(n[2]):void 0;if(Number.isNaN(e)||Number.isNaN(t))throw new _("INVALID_ARGS","longpress requires x y [durationMs]");return await l.longPress(e,t,r),{x:e,y:t,durationMs:r,...tS(`Long pressed (${e}, ${t})`)}}case"focus":{let[e,t]=n.map(Number);if(Number.isNaN(e)||Number.isNaN(t))throw new _("INVALID_ARGS","focus requires x y");return await l.focus(e,t),{x:e,y:t,...tS(`Focused (${e}, ${t})`)}}case"type":{let e=function(e){let t=e[0]?.trim();if(!t||!t.startsWith("@")||t.length<3)return null;let n=t.slice(1);return/^[A-Za-z_-]*\d[\w-]*$/i.test(n)||/^(?:ref|node|element|el)[\w-]*$/i.test(n)?t:null}(n);if(e)throw new _("INVALID_ARGS",`type does not accept a target ref like "${e}"`,{hint:`Use fill ${e} "text" to target that field, or press ${e} then type "text" to append.`});let t=n.join(" ");if(!t)throw new _("INVALID_ARGS","type requires text");let r=rW(a?.delayMs??0,"delay-ms",0,1e4);return await l.type(t,r),{text:t,delayMs:r,...tS(p1("Typed",t))}}case"fill":{let e=Number(n[0]),t=Number(n[1]),r=n.slice(2).join(" ");if(Number.isNaN(e)||Number.isNaN(t)||!r)throw new _("INVALID_ARGS","fill requires x y text");let i=rW(a?.delayMs??0,"delay-ms",0,1e4);return await l.fill(e,t,r,i),{x:e,y:t,text:r,delayMs:i,...tS(p1("Filled",r))}}case"scroll":return pW(l,n,a);case"pinch":return pz(e,n,a,s);case"trigger-app-event":{let{eventName:t,payload:r}=function(e){let t=e[0]?.trim(),n=e[1]?.trim();if(!t)throw new _("INVALID_ARGS","trigger-app-event requires <event> [payloadJson]");if(!pp.test(t))throw new _("INVALID_ARGS",`Invalid trigger-app-event event name: ${t}`,{hint:"Use 1-64 chars: letters, numbers, underscore, dot, colon, or dash."});if(e.length>2)throw new _("INVALID_ARGS","trigger-app-event accepts at most two arguments: <event> [payloadJson]");let r=function(e,t){if(e)try{let n=JSON.parse(e);if(!n||"object"!=typeof n||Array.isArray(n))throw new _("INVALID_ARGS",`trigger-app-event payload for "${t}" must be a JSON object`);let r=JSON.stringify(n);if(Buffer.byteLength(r,"utf8")>8192)throw new _("INVALID_ARGS",`trigger-app-event payload for "${t}" exceeds 8192 bytes`);return n}catch(t){if(t instanceof _)throw t;throw new _("INVALID_ARGS",`Invalid trigger-app-event payload JSON: ${e}`)}}(n,t);return{eventName:t,payload:r}}(n),i=function(e,t,n){var r;let a,i=(a=("ios"===(r=e)?process.env.AGENT_DEVICE_IOS_APP_EVENT_URL_TEMPLATE:"macos"===r?process.env.AGENT_DEVICE_MACOS_APP_EVENT_URL_TEMPLATE:process.env.AGENT_DEVICE_ANDROID_APP_EVENT_URL_TEMPLATE)??process.env.AGENT_DEVICE_APP_EVENT_URL_TEMPLATE,a?.trim()||void 0);if(!i)throw new _("UNSUPPORTED_OPERATION",`No app event URL template configured for ${e}.`,{hint:`Set AGENT_DEVICE_${e.toUpperCase()}_APP_EVENT_URL_TEMPLATE or AGENT_DEVICE_APP_EVENT_URL_TEMPLATE, for example "myapp://agent-device/event?name={event}&payload={payload}".`});let o=n?JSON.stringify(n):"",s=i.replaceAll("{event}",encodeURIComponent(t)).replaceAll("{payload}",encodeURIComponent(o)).replaceAll("{platform}",encodeURIComponent(e));if(s.length>4096)throw new _("INVALID_ARGS","trigger-app-event URL exceeds maximum supported length",{hint:"Reduce payload size or shorten AGENT_DEVICE_*_APP_EVENT_URL_TEMPLATE.",length:s.length,maxLength:4096});return s}(e.platform,t,r);return await l.open(i,{appBundleId:a?.appBundleId}),{event:t,eventUrl:i,transport:"deep-link",...tS(`Triggered app event: ${t}`)}}case"screenshot":{let e=n[0]??r??`./screenshot-${Date.now()}.png`;return await i.mkdir(o.dirname(e),{recursive:!0}),await l.screenshot(e,{appBundleId:a?.appBundleId,fullscreen:a?.screenshotFullscreen,surface:a?.surface}),{path:e,...tS(`Saved screenshot: ${e}`)}}case"back":return await l.back(a?.backMode),{action:"back",mode:a?.backMode??"in-app",...tS("Back")};case"home":return await l.home(),{action:"home",...tS("Home")};case"rotate":{let e=pb(n[0]);return await l.rotate(e),{action:"rotate",orientation:e,...tS(`Rotated to ${e}`)}}case"app-switcher":return await l.appSwitcher(),{action:"app-switcher",...tS("Opened app switcher")};case"clipboard":return pX(l,n);case"keyboard":return pH(e,l,n,a,s);case"settings":return pY(e,l,n,a);case"push":return pJ(e,n,a);case"snapshot":return pK(e,n,a,s);case"read":return pZ(e,n,a,s);default:throw new _("INVALID_ARGS",`Unknown command: ${t}`)}},{command:t,platform:e.platform})}async function pB(e,t,n,r){let a=n[0],i=n[1];if(n.length>2)throw new _("INVALID_ARGS","open accepts at most two arguments: <app|url> [url]");if(!a)return await t.openDevice(),{app:null,...tS("Opened device")};if(void 0!==i){if("android"===e.platform)throw new _("INVALID_ARGS","open <app> <url> is supported only on Apple platforms");if(sG(a))throw new _("INVALID_ARGS","open <app> <url> requires an app target as the first argument");if(!sG(i))throw new _("INVALID_ARGS","open <app> <url> requires a valid URL target");return await t.open(a,{activity:r?.activity,appBundleId:r?.appBundleId,url:i}),{app:a,url:i,...tS(`Opened: ${a}`)}}return await t.open(a,{activity:r?.activity,appBundleId:r?.appBundleId}),{app:a,...tS(`Opened: ${a}`)}}async function pj(e,t,n,r,a){let i,[o,s]=n.map(Number);if(Number.isNaN(o)||Number.isNaN(s))throw new _("INVALID_ARGS","press requires x y");if("macos"===e.platform&&r?.surface&&"app"!==r.surface){let e=pu(r);if("primary"!==e)throw new _("UNSUPPORTED_OPERATION",`${e} click is not supported on macOS ${r.surface} sessions.`);return await dL(o,s,{bundleId:r.appBundleId,surface:r.surface}),{x:o,y:s,...tS(pQ({x:o,y:s}))}}let l=pu(r);if("primary"!==l){let t=pd({commandLabel:"click",platform:e.platform,button:l,count:r?.count,intervalMs:r?.intervalMs,holdMs:r?.holdMs,jitterPx:r?.jitterPx,doubleTap:r?.doubleTap});if(t)throw t;return"linux"===e.platform?"secondary"===l?await cX(o,s):await cH(o,s):await sF(e,{command:"mouseClick",x:o,y:s,button:l,appBundleId:r?.appBundleId},{verbose:r?.verbose,logPath:r?.logPath,traceLogPath:r?.traceLogPath,requestId:r?.requestId}),{x:o,y:s,button:l,...tS(pQ({x:o,y:s,button:l}))}}let u=rW(r?.count??1,"count",1,200),d=rW(r?.intervalMs??0,"interval-ms",0,1e4),c=rW(r?.holdMs??0,"hold-ms",0,1e4),p=rW(r?.jitterPx??0,"jitter-px",0,100),f=r?.doubleTap===!0;if(f&&c>0)throw new _("INVALID_ARGS","double-tap cannot be combined with hold-ms");if(f&&p>0)throw new _("INVALID_ARGS","double-tap cannot be combined with jitter-px");if(("ios"===e.platform||"macos"===e.platform)&&u>1&&0===c&&0===p){let t=await sF(e,{command:"tapSeries",x:o,y:s,count:u,intervalMs:d,doubleTap:f,appBundleId:r?.appBundleId},{verbose:r?.verbose,logPath:r?.logPath,traceLogPath:r?.traceLogPath,requestId:r?.requestId});return{x:o,y:s,count:u,intervalMs:d,holdMs:c,jitterPx:p,doubleTap:f,timingMode:"runner-series",...t,...tS(pQ({x:o,y:s}))}}return await ph(u,d,async e=>{let[n,r]=function(e,t){if(t<=0)return[0,0];let[n,r]=pf[e%pf.length];return[n*t,r*t]}(e,p),a=o+n,l=s+r;if(f){i??=await t.doubleTap(a,l)??void 0;return}c>0?i??=await t.longPress(a,l,c)??void 0:i??=await t.tap(a,l)??void 0}),t_({x:o,y:s,count:u,intervalMs:d,holdMs:c,jitterPx:p,doubleTap:f,...i},pQ({x:o,y:s}))}async function pq(e,t,n,r,a){let i=Number(n[0]),o=Number(n[1]),s=Number(n[2]),l=Number(n[3]);if([i,o,s,l].some(Number.isNaN))throw new _("INVALID_ARGS","swipe requires x1 y1 x2 y2 [durationMs]");let u=rW(n[4]?Number(n[4]):250,"durationMs",16,1e4),d="ios"===e.platform?Math.min(60,Math.max(16,Math.round(u))):u,c=rW(r?.count??1,"count",1,200),p=rW(r?.pauseMs??0,"pause-ms",0,1e4),f=r?.pattern??"one-way";if("one-way"!==f&&"ping-pong"!==f)throw new _("INVALID_ARGS",`Invalid pattern: ${f}`);if(("ios"===e.platform||"macos"===e.platform)&&c>1){let t=await sF(e,{command:"dragSeries",x:i,y:o,x2:s,y2:l,durationMs:d,count:c,pauseMs:p,pattern:f,appBundleId:r?.appBundleId},{verbose:r?.verbose,logPath:r?.logPath,traceLogPath:r?.traceLogPath,requestId:r?.requestId});return{x1:i,y1:o,x2:s,y2:l,durationMs:u,effectiveDurationMs:d,timingMode:"runner-series",count:c,pauseMs:p,pattern:f,...t,...tS(p0(c,f))}}return await ph(c,p,async e=>{"ping-pong"===f&&e%2==1?await t.swipe(s,l,i,o,d):await t.swipe(i,o,s,l,d)}),t_({x1:i,y1:o,x2:s,y2:l,durationMs:u,effectiveDurationMs:d,timingMode:"ios"===e.platform?"safe-normalized":"direct",count:c,pauseMs:p,pattern:f},p0(c,f))}async function pW(e,t,n){let r=t[0],a=t[1]?Number(t[1]):void 0,i=n?.pixels;if(!r)throw new _("INVALID_ARGS","scroll requires direction");if(void 0!==a&&!Number.isFinite(a))throw new _("INVALID_ARGS","scroll amount must be a number");if(void 0!==a&&void 0!==i)throw new _("INVALID_ARGS","scroll accepts either a relative amount or --pixels, not both");let o=function(e){switch(e){case"up":case"down":case"left":case"right":return e;default:throw new _("INVALID_ARGS",`Unknown direction: ${e}`)}}(r),s=await e.scroll(o,{amount:a,pixels:i});return t_({direction:o,...void 0!==a?{amount:a}:{},...void 0!==i?{pixels:i}:{},...s},void 0!==i?`Scrolled ${o} by ${i}px`:void 0!==a?`Scrolled ${o} by ${a}`:`Scrolled ${o}`)}async function pz(e,t,n,r){if("android"===e.platform)throw new _("UNSUPPORTED_OPERATION","Android pinch is not supported in current adb backend; requires instrumentation-based backend.");if("macos"===e.platform&&n?.surface&&"app"!==n.surface)throw new _("UNSUPPORTED_OPERATION","pinch is only supported in macOS app sessions. Re-open the target app without --surface desktop|menubar|frontmost-app first.");let a=Number(t[0]),i=t[1]?Number(t[1]):void 0,o=t[2]?Number(t[2]):void 0;if(Number.isNaN(a)||a<=0)throw new _("INVALID_ARGS","pinch requires scale > 0");return await sF(e,{command:"pinch",scale:a,x:i,y:o,appBundleId:n?.appBundleId},{verbose:n?.verbose,logPath:n?.logPath,traceLogPath:n?.traceLogPath,requestId:n?.requestId}),{scale:a,x:i,y:o,...tS(`Pinched to scale ${a}`)}}async function pX(e,t){let n=(t[0]??"").toLowerCase();if("read"!==n&&"write"!==n)throw new _("INVALID_ARGS","clipboard requires a subcommand: read or write");if("read"===n){if(1!==t.length)throw new _("INVALID_ARGS","clipboard read does not accept additional arguments");return{action:n,text:await e.readClipboard()}}if(t.length<2)throw new _("INVALID_ARGS",'clipboard write requires text (use "" to clear clipboard)');let r=t.slice(1).join(" ");return await e.writeClipboard(r),{action:n,textLength:Array.from(r).length,...tS("Clipboard updated")}}async function pH(e,t,n,r,a){let i=(n[0]??"status").toLowerCase();if("status"!==i&&"get"!==i&&"dismiss"!==i)throw new _("INVALID_ARGS","keyboard requires a subcommand: status, get, or dismiss");if(n.length>1)throw new _("INVALID_ARGS","keyboard accepts at most one subcommand argument");if("android"===e.platform){if("dismiss"===i){let t=await uO(e);return{platform:"android",action:"dismiss",attempts:t.attempts,wasVisible:t.wasVisible,dismissed:t.dismissed,visible:t.visible,inputType:t.inputType,type:t.type}}let t=await uE(e);return{platform:"android",action:"status",visible:t.visible,inputType:t.inputType,type:t.type}}if("ios"===e.platform){if("dismiss"!==i)throw new _("UNSUPPORTED_OPERATION","keyboard status/get is currently supported only on Android; use keyboard dismiss on iOS");let t=await sF(e,{command:"keyboardDismiss",appBundleId:r?.appBundleId},a);return{platform:"ios",action:"dismiss",wasVisible:t.wasVisible,dismissed:t.dismissed,visible:t.visible,...tS(t.dismissed?"Keyboard dismissed":"Keyboard already hidden")}}throw new _("UNSUPPORTED_OPERATION","keyboard is supported only on Android and iOS")}async function pY(e,t,n,r){var a;let[i,o,s,l,u]=n,d="permission"===i?{permissionTarget:s,permissionMode:l}:void 0;eN({level:"debug",phase:"settings_apply",data:{setting:i,state:o,target:s,mode:l,platform:e.platform}});let c=await t.setSetting(i,o,u??r?.appBundleId,d);return c&&"object"==typeof c?t_({setting:i,state:o,...c},("string"==typeof(a=c).message&&a.message.length>0?a.message:void 0)??`Updated setting: ${i}`):{setting:i,state:o,...tS(`Updated setting: ${i}`)}}async function pJ(e,t,n){let r=t[0]?.trim(),a=t[1]?.trim();if(!r||!a)throw new _("INVALID_ARGS","push requires <bundle|package> <payload.json|inline-json>");let i=await pg(a);if("ios"===e.platform)return await cI(e,r,i),{platform:"ios",bundleId:r,...tS(`Pushed notification to ${r}`)};let o=await uz(e,r,i);return{platform:"android",package:r,action:o.action,extrasCount:o.extrasCount,...tS(`Pushed notification to ${r}`)}}async function pK(e,t,n,r){if("linux"===e.platform){let e=await eS("snapshot_capture",async()=>await pl(n?.surface),{backend:"linux-atspi"});return{nodes:e.nodes??[],truncated:e.truncated??!1,backend:"linux-atspi"}}if("android"!==e.platform){let t=await eS("snapshot_capture",async()=>await sF(e,{command:"snapshot",appBundleId:n?.appBundleId,interactiveOnly:n?.snapshotInteractiveOnly,compact:n?.snapshotCompact,depth:n?.snapshotDepth,scope:n?.snapshotScope,raw:n?.snapshotRaw},{verbose:n?.verbose,logPath:n?.logPath,traceLogPath:n?.traceLogPath,requestId:n?.requestId}),{backend:"xctest"}),r=t.nodes??[];if(0===r.length&&"simulator"===e.kind)throw new _("COMMAND_FAILED","XCTest snapshot returned 0 nodes on iOS simulator.");return{nodes:r,truncated:t.truncated??!1,backend:"xctest"}}let a=await eS("snapshot_capture",async()=>await un(e,{interactiveOnly:n?.snapshotInteractiveOnly,compact:n?.snapshotCompact,depth:n?.snapshotDepth,scope:n?.snapshotScope,raw:n?.snapshotRaw}),{backend:"android"});return{nodes:a.nodes??[],truncated:a.truncated??!1,backend:"android",analysis:a.analysis}}async function pZ(e,t,n,r){let[a,i]=t.map(Number);if(Number.isNaN(a)||Number.isNaN(i))throw new _("INVALID_ARGS","read requires x y");if("android"===e.platform)return{action:"read",text:await uD(e,a,i)??""};if("macos"===e.platform&&n?.surface&&"app"!==n.surface)return{action:"read",text:(await dR(a,i,{bundleId:n.appBundleId,surface:n.surface})).text};let o=await sF(e,{command:"readText",x:a,y:i,appBundleId:n?.appBundleId},{verbose:n?.verbose,logPath:n?.logPath,traceLogPath:n?.traceLogPath,requestId:n?.requestId});return{action:"read",text:"string"==typeof o.text?o.text:"string"==typeof o.message?o.message:""}}function pQ(e){return e.button&&"primary"!==e.button?`Clicked ${e.button} (${e.x}, ${e.y})`:`Tapped (${e.x}, ${e.y})`}function p0(e,t){return e<=1?"Swiped":"ping-pong"===t?`Swiped ${e} times (ping-pong)`:`Swiped ${e} times`}function p1(e,t){return`${e} ${Array.from(t).length} chars`}let p2=[250,400];function p3(e,t,n=e.snapshot){if("android"!==e.device.platform)return;let r=n?.comparisonSafe===!0;e.androidSnapshotFreshness={action:t,markedAt:Date.now(),baselineCount:n?.nodes.length??0,baselineSignatures:r?p6(n?.nodes??[]):void 0,routeComparable:r}}function p4(e){if(!e||"android"!==e.device.platform)return;let t=e.androidSnapshotFreshness;if(t)return Date.now()-t.markedAt>2500?void delete e.androidSnapshotFreshness:t}function p5(e){e&&"android"===e.device.platform&&delete e.androidSnapshotFreshness}function p8(e){return"press"===e||"click"===e||"back"===e||"open"===e}function p6(e){return e.map(e=>[e.depth??0,e.type??"",e.role??"",e.label??"",e.value??"",e.identifier??"",!1===e.enabled?"disabled":"enabled",!0===e.selected?"selected":"unselected",!0===e.hittable?"hittable":"not-hittable"].join("|"))}function p9(e,t,n,r,a){return{requestId:a??ex().requestId,appBundleId:n,activity:t?.activity,verbose:t?.verbose,logPath:e,traceLogPath:r,snapshotInteractiveOnly:t?.snapshotInteractiveOnly,snapshotCompact:t?.snapshotCompact,snapshotDepth:t?.snapshotDepth,snapshotScope:t?.snapshotScope,snapshotRaw:t?.snapshotRaw,screenshotFullscreen:t?.screenshotFullscreen,count:t?.count,intervalMs:t?.intervalMs,delayMs:t?.delayMs,holdMs:t?.holdMs,jitterPx:t?.jitterPx,pixels:t?.pixels,doubleTap:t?.doubleTap,clickButton:pu(t),backMode:t?.backMode,pauseMs:t?.pauseMs,pattern:t?.pattern}}async function p7(e){let t=p4(e.session);if(t&&"android"===e.device.platform)return await ft(e,t);let n=await fe(e);return p5(e.session),{snapshot:fa(n,e.flags),analysis:n.analysis}}async function fe(e){let{device:t,session:n,flags:r,outPath:a,logPath:i,snapshotScope:o}=e;if("linux"===t.platform){let e=await pl(n?.surface);return fi({nodes:e.nodes,truncated:e.truncated,backend:"linux-atspi"},{snapshotDepth:r?.snapshotDepth,snapshotInteractiveOnly:r?.snapshotInteractiveOnly,snapshotScope:o})}return"macos"===t.platform&&n?.surface&&"app"!==n.surface?fi(await dC(n.surface,{bundleId:"menubar"===n.surface?n.appBundleId:void 0}),{snapshotDepth:r?.snapshotDepth,snapshotInteractiveOnly:r?.snapshotInteractiveOnly,snapshotScope:o}):await pV(t,"snapshot",[],a,{...p9(i,{...r,snapshotScope:o},n?.appBundleId,n?.trace?.outPath)})}async function ft(e,t){let n=await fn(e),r=fr(n,t,e.flags),a=0;for(let i of p2){if(!r)break;await new Promise(e=>setTimeout(e,i)),n=await fn(e),a+=1,r=fr(n,t,e.flags)}return r||p5(e.session),{snapshot:n.snapshot,analysis:n.data.analysis,freshness:a>0||r?{action:t.action,retryCount:a,staleAfterRetries:!!r,reason:r??void 0}:void 0}}async function fn(e){let t=await fe(e);return{data:t,snapshot:fa(t,e.flags)}}function fr(e,t,n){var r,a;let i=n?.snapshotInteractiveOnly===!0,o=e.data.analysis;if(i&&0===e.snapshot.nodes.length&&o&&o.rawNodeCount>=12)return"empty-interactive";return(r=t.baselineCount,a=e.snapshot.nodes.length,!(r<12)&&a<=Math.floor(.2*r))?e.snapshot.nodes.some(e=>!0===e.hittable||!!e.label?.trim()||!!e.value?.trim()||!!e.identifier?.trim())?null:"sharp-drop":t.routeComparable&&p8(t.action)&&function(e,t){if(!e||0===e.length)return!1;let n=Math.max(e.length,t.length);if(n<12)return!1;let r=p6(t),a=Math.min(e.length,r.length),i=0;for(let t=0;t<a;t+=1)e[t]===r[t]&&(i+=1);let o=Math.max(0,r.length-e.length),s=Math.max(0,e.length-r.length),l=Math.max(3,Math.floor(.15*n));return i>=Math.floor(.9*n)&&o<=l&&s<=l}(t.baselineSignatures,e.snapshot.nodes)?"stuck-route":null}function fa(e,t){let n=e?.nodes??[],r=function(e){let t=new Map;for(let[n,r]of e.entries())t.set(r.index,n);let n=[],r=[];for(let[a,i]of e.entries()){let e=Math.max(0,i.depth??0);for(;r.length>0&&e<=r[r.length-1].depth;)r.pop();let o="number"==typeof i.parentIndex?t.get(i.parentIndex):void 0,s="number"==typeof o&&o<a?o:r[r.length-1]?.index;n.push({...i,index:a,depth:e,parentIndex:s}),r.push({depth:e,index:a})}return n}(t?.snapshotRaw?n:ti(n));return{nodes:ea(t?.snapshotScope&&e?.backend!=="macos-helper"?fo(r,t.snapshotScope):r),truncated:e?.truncated,createdAt:Date.now(),backend:e?.backend,comparisonSafe:e?.backend==="android"&&t?.snapshotInteractiveOnly!==!0&&t?.snapshotCompact!==!0&&"number"!=typeof t?.snapshotDepth&&!t?.snapshotScope}}function fi(e,t){var n,r;let a=e.nodes??[];return t.snapshotScope&&(a=fo(a,t.snapshotScope)),t.snapshotInteractiveOnly&&(a=function(e){if(0===e.length)return e;let t=new Map;for(let n of e)t.set(n.index,n);let n=new Set;for(let r of e){if(!function(e){if(e.hittable||e.rect)return!0;let t=`${e.type??""} ${e.role??""} ${e.subrole??""}`.toLowerCase();return t.includes("button")||t.includes("menu")||t.includes("textfield")||t.includes("searchfield")||t.includes("checkbox")||t.includes("radio")||t.includes("switch")}(r))continue;let e=r;for(;e&&!n.has(e.index);)n.add(e.index),e="number"==typeof e.parentIndex?t.get(e.parentIndex):void 0}return 0===n.size?e:fs(e.filter(e=>n.has(e.index)))}(a)),"number"==typeof t.snapshotDepth&&(n=a,r=t.snapshotDepth,a=fs(n.filter(e=>(e.depth??0)<=r))),{...e,nodes:a}}function fo(e,t){let n=tn(ea(e),t);if(!n)return[];let r=e.findIndex(e=>e.index===n.index);if(-1===r)return[];let a=e[r]?.depth??0,i=[];for(let t=r;t<e.length;t+=1){let n=e[t];if(!n)continue;let o=n.depth??0;if(t>r&&o<=a)break;i.push(n)}return fs(i,a)}function fs(e,t=0){let n=new Map;for(let[t,r]of e.entries())n.set(r.index,t);return e.map((e,r)=>({...e,index:r,depth:Math.max(0,(e.depth??0)-t),parentIndex:"number"==typeof e.parentIndex?n.get(e.parentIndex):void 0}))}function fl(e,t){if(!e||!e.trim().startsWith("@"))return{ok:!0,scope:e};if(!t?.snapshot)return i4("INVALID_ARGS","Ref scope requires an existing snapshot in session.");let n=ei(e.trim());if(!n)return i4("INVALID_ARGS",`Invalid ref scope: ${e}`);let r=eo(t.snapshot.nodes,n),a=r?tr(r,t.snapshot.nodes):void 0;return a?{ok:!0,scope:a}:i4("COMMAND_FAILED",`Ref ${e} not found or has no label`)}let fu=ok(process.env.AGENT_DEVICE_IOS_DEVICE_READY_TIMEOUT_MS,15e3,1e3);async function fd(e){if("ios"===e.platform){if("simulator"===e.kind){let{ensureBootedSimulator:t}=await Promise.resolve(R);await t(e);return}if("device"===e.kind)return void await fc(e.id)}if("android"===e.platform){let{waitForAndroidBoot:t}=await Promise.resolve(C);await t(e.id)}}async function fc(e){let t=o.join(p.tmpdir(),`agent-device-ready-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`),n=Math.max(1,Math.ceil(fu/1e3));try{let r=await k("xcrun",["devicectl","device","info","details","--device",e,"--json-output",t,"--timeout",String(n)],{allowFailure:!0,timeoutMs:fu+3e3}),a=String(r.stdout??""),i=String(r.stderr??""),o=await fp(t);if(0===r.exitCode){if(!o.parsed)throw new _("COMMAND_FAILED","iOS device readiness probe failed",{kind:"probe_inconclusive",deviceId:e,stdout:a,stderr:i,hint:"CoreDevice returned success but readiness JSON output was missing or invalid. Retry; if it persists restart Xcode and the iOS device."});let t=o?.tunnelState?.toLowerCase();if("connecting"===t)throw new _("COMMAND_FAILED","iOS device is not ready for automation",{kind:"not_ready",deviceId:e,tunnelState:t,hint:"Device tunnel is still connecting. Keep the device unlocked and connected by cable until it is fully available in Xcode Devices, then retry."});return}throw new _("COMMAND_FAILED","iOS device is not ready for automation",{kind:"not_ready",deviceId:e,stdout:a,stderr:i,exitCode:r.exitCode,tunnelState:o?.tunnelState,hint:ff(a,i)})}catch(t){if(t instanceof _&&"COMMAND_FAILED"===t.code){if("not_ready"===("string"==typeof t.details?.kind?t.details.kind:""))throw t;let n=t.details??{},r=String(n.stdout??""),a=String(n.stderr??""),i=Number(n.timeoutMs??fu),o=`CoreDevice did not respond within ${i}ms. Keep the device unlocked and trusted, then retry; if it persists restart Xcode and the iOS device.`;throw new _("COMMAND_FAILED","iOS device readiness probe failed",{deviceId:e,cause:t.message,timeoutMs:i,stdout:r,stderr:a,hint:r||a?ff(r,a):o},t)}throw new _("COMMAND_FAILED","iOS device readiness probe failed",{deviceId:e,hint:"Reconnect the device, keep it unlocked, and retry."},t instanceof Error?t:void 0)}finally{await i.rm(t,{force:!0}).catch(()=>{})}}async function fp(e){try{let t=await i.readFile(e,"utf8"),n=JSON.parse(t),r=function(e){let t=e?.result;if(!t||"object"!=typeof t)return{};let n=t.connectionProperties?.tunnelState,r=t.device?.connectionProperties?.tunnelState,a="string"==typeof n?n:"string"==typeof r?r:void 0;return a?{tunnelState:a}:{}}(n);return{parsed:!0,tunnelState:r.tunnelState}}catch{return{parsed:!1}}}function ff(e,t){let n=de(e,t);return n||(`${e}
|
|
38
|
+
${t}`.toLowerCase().includes("timed out waiting for all destinations")?"Xcode destination did not become available in time. Keep device unlocked and retry.":u7)}async function fh(e,t,n){let r=e.get(t),a=r?.device??await pG(n??{});return r||await fd(a),{session:r,device:a}}async function fm(e,t,n){let r=!e&&"ios"===t.platform;try{return await n()}finally{r&&await sO(t.id)}}function fw(e,t,n,r){t&&e.recordAction(t,{command:n.command,positionals:n.positionals??[],flags:n.flags??{},result:r})}function fg(e){if(!e)return null;let t=Number(e);return Number.isFinite(t)?t:null}function fy(e){if(0===e.length)return null;let t=fg(e[0]);if(null!==t)return{kind:"sleep",durationMs:t};if("text"===e[0]){let t=fg(e[e.length-1]);return{kind:"text",text:(null!==t?e.slice(1,-1).join(" "):e.slice(1).join(" ")).trim(),timeoutMs:t}}if(e[0].startsWith("@")){let t=fg(e[e.length-1]);return{kind:"ref",rawRef:e[0],timeoutMs:t}}let n=fg(e[e.length-1]),r=e8(null!==n?e.slice(0,-1):e.slice());if(r&&0===r.rest.length){let e=e5(r.selectorExpression);if(e)return{kind:"selector",selector:e,selectorExpression:r.selectorExpression,timeoutMs:n}}return{kind:"text",text:(null!==n?e.slice(0,-1).join(" "):e.join(" ")).trim(),timeoutMs:n}}async function fb(e){let{req:t,logPath:n,sessionStore:r,session:a,device:i}=e,o=(t.positionals?.[0]??"get").toLowerCase(),s=a?"frontmost-app"===a.surface?{surface:"frontmost-app"}:{bundleId:a.appBundleId,surface:a.surface}:{};if(!oi("alert",i))return i4("UNSUPPORTED_OPERATION","alert is not supported on this device");if("macos"===i.platform){let e=async()=>await dO("wait"===o?"get":o,s);if("wait"===o){let n=fg(t.positionals?.[1])??1e4,i=Date.now();for(;Date.now()-i<n;){try{let n=await e();return fw(r,a,t,n),{ok:!0,data:n}}catch{}await new Promise(e=>setTimeout(e,300))}return i4("COMMAND_FAILED","alert wait timed out")}let n="accept"===o||"dismiss"===o?o:"get";if("accept"===n||"dismiss"===n){let e,i=Date.now();for(;Date.now()-i<2e3;){try{let e=await dO(n,s);return fw(r,a,t,e),{ok:!0,data:e}}catch(n){e=n;let t=String(n?.message??"").toLowerCase();if(!t.includes("alert not found")&&!t.includes("no alert"))break}await new Promise(e=>setTimeout(e,300))}throw fv(e)}let i=await dO("get",s);return fw(r,a,t,i),{ok:!0,data:i}}if("wait"===o){let e=fg(t.positionals?.[1])??1e4,o=Date.now();for(;Date.now()-o<e;){try{let e=await sF(i,{command:"alert",action:"get",appBundleId:a?.appBundleId},{verbose:t.flags?.verbose,logPath:n,traceLogPath:a?.trace?.outPath,requestId:t.meta?.requestId});return fw(r,a,t,e),{ok:!0,data:e}}catch{}await new Promise(e=>setTimeout(e,300))}return i4("COMMAND_FAILED","alert wait timed out")}let l="accept"===o||"dismiss"===o?o:"get",u={verbose:t.flags?.verbose,logPath:n,traceLogPath:a?.trace?.outPath,requestId:t.meta?.requestId};if("accept"===l||"dismiss"===l){let e,n=Date.now();for(;Date.now()-n<2e3;){try{let e=await sF(i,{command:"alert",action:l,appBundleId:a?.appBundleId},u);return fw(r,a,t,e),{ok:!0,data:e}}catch(n){e=n;let t=String(n?.message??"").toLowerCase();if(!t.includes("alert not found")&&!t.includes("no alert"))break}await new Promise(e=>setTimeout(e,300))}throw fv(e)}let d=await sF(i,{command:"alert",action:l,appBundleId:a?.appBundleId},u);return fw(r,a,t,d),{ok:!0,data:d}}function fv(e){if(!(e instanceof _))return e;let t=String(e.message??"").toLowerCase();return t.includes("alert not found")||t.includes("no alert")?new _(e.code,e.message,{...e.details??{},hint:"If the permission sheet is visible in snapshot or screenshot but alert reports no alert, take a scoped snapshot around the visible button label and use press @ref."}):e}async function fI(e){let t,{req:n,logPath:r,sessionStore:a,session:i,device:o,parsed:s}=e,{setting:l,state:u,permissionTarget:d}=s;if(!oi("settings",o))return i4("UNSUPPORTED_OPERATION","settings is not supported on this device");if("macos"===o.platform&&"appearance"!==(t=l.trim().toLowerCase())&&"permission"!==t)return i4("INVALID_ARGS",q(l));let c=i?.appBundleId,p="permission"===l?[l,u,d??"",n.positionals?.[3]??"",c??""]:[l,u,c??""],f=await pV(o,"settings",p,n.flags?.out,{...p9(r,n.flags,c,i?.trace?.outPath)});return fw(a,i,n,f??{setting:l,state:u}),{ok:!0,data:f??{setting:l,state:u}}}function fA(e,t={}){let n=!0===t.plural?"do":"does";return{resolveInput:async()=>{throw new _("UNSUPPORTED_OPERATION",`${e} ${n} not resolve input artifacts`)},reserveOutput:async()=>{throw new _("UNSUPPORTED_OPERATION",`${e} ${n} not reserve output artifacts`)},createTempFile:async()=>{throw new _("UNSUPPORTED_OPERATION",`${e} ${n} not create temporary files`)}}}async function fx(e){let{req:t,sessionName:n,logPath:r,sessionStore:a}=e,{session:i,device:o}=await fh(a,n,t.flags);if(!oi("snapshot",o))return i4("UNSUPPORTED_OPERATION","snapshot is not supported on this device");let s=fl(t.flags?.snapshotScope,i);return s.ok?await fm(i,o,async()=>{let e=fS({req:t,sessionName:n,logPath:r,sessionStore:a,session:i,device:o,snapshotScope:s.scope}),l=await e.capture.snapshot({session:n,interactiveOnly:t.flags?.snapshotInteractiveOnly,compact:t.flags?.snapshotCompact,depth:t.flags?.snapshotDepth,scope:s.scope,raw:t.flags?.snapshotRaw});return f_({req:t,sessionName:n,sessionStore:a,result:{nodes:l.nodes.length,truncated:l.truncated}}),{ok:!0,data:l}}):s}async function fN(e){let{req:t,sessionName:n,logPath:r,sessionStore:a}=e,{session:i,device:o}=await fh(a,n,t.flags);if(!oi("diff",o))return i4("UNSUPPORTED_OPERATION","diff is not supported on this device");let s=fl(t.flags?.snapshotScope,i);return s.ok?await fm(i,o,async()=>{let e=fS({req:t,sessionName:n,logPath:r,sessionStore:a,session:i,device:o,snapshotScope:s.scope}),l=await e.capture.diffSnapshot({session:n,interactiveOnly:t.flags?.snapshotInteractiveOnly,compact:t.flags?.snapshotCompact,depth:t.flags?.snapshotDepth,scope:s.scope,raw:t.flags?.snapshotRaw});return f_({req:t,sessionName:n,sessionStore:a,result:{mode:"snapshot",baselineInitialized:l.baselineInitialized,summary:l.summary}}),{ok:!0,data:l}}):s}function fS(e){let{req:t,sessionName:n,logPath:r,sessionStore:a,session:i,device:o,snapshotScope:s}=e;return i1({backend:function(e){let{req:t,logPath:n,session:r,device:a,snapshotScope:i}=e;return{platform:a.platform,captureSnapshot:async(e,o)=>{let s=await p7({device:a,session:r,flags:t.flags,outPath:o?.outPath??t.flags?.out,logPath:n,snapshotScope:i});return{snapshot:s.snapshot,analysis:s.analysis,freshness:s.freshness,appName:r?.appBundleId?r.appName??r.appBundleId:void 0,appBundleId:r?.appBundleId}}}}({req:t,logPath:r,session:i,device:o,snapshotScope:s}),artifacts:fA("snapshot"),sessions:{get:e=>e===n?function(e){if(e)return{name:e.name,appBundleId:e.appBundleId,appName:e.appName,snapshot:e.snapshot,metadata:{surface:e.surface}}}(a.get(n)):void 0,set:e=>{if(!e.snapshot)throw new _("UNKNOWN","snapshot runtime did not produce session state");let t=function(e){let{session:t,sessionName:n,device:r,snapshot:a,appBundleId:i}=e;return t?{...t,snapshot:a}:{name:n,device:r,createdAt:Date.now(),appBundleId:i,snapshot:a,actions:[]}}({session:a.get(n),sessionName:n,device:o,snapshot:e.snapshot,appBundleId:e.appBundleId});e.appName&&(t.appName=e.appName),a.set(n,t)}},policy:i3()})}function f_(e){let t=e.sessionStore.get(e.sessionName);t&&e.sessionStore.recordAction(t,{command:e.req.command,positionals:e.req.positionals??[],flags:e.req.flags??{},result:e.result})}function fk(e){if(e.length<2)return null;let t=Number(e[0]),n=Number(e[1]);return Number.isFinite(t)&&Number.isFinite(n)?{x:t,y:n}:null}async function fD(e){let{device:t,node:n,flags:r,appBundleId:a,traceOutPath:i,surface:o,contextFromFlags:s}=e,l=X(n),u=function(e){let t=function(e){if(!e)return null;let t=Number(e.x),n=Number(e.y),r=Number(e.width),a=Number(e.height);return Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a)&&!(r<0)&&!(a<0)?{x:t,y:n,width:r,height:a}:null}(e);if(!t)return null;let n=es(t);return Number.isFinite(n.x)&&Number.isFinite(n.y)?n:null}(n.rect);if(!u)return l;try{let e=await pV(t,"read",[String(u.x),String(u.y)],void 0,{...s(r,a,i),surface:o}),d=e&&"object"==typeof e?e:void 0,c="string"==typeof d?.text?d.text:"";if(c.trim())return c;return eN({level:"warn",phase:"interaction_read_fallback",data:{reason:"empty_backend_text",nodeRef:n.ref,surface:o,platform:t.platform}}),l}catch(e){return eN({level:"warn",phase:"interaction_read_fallback",data:{reason:"backend_read_failed",nodeRef:n.ref,surface:o,platform:t.platform,error:e instanceof Error?e.message:String(e)}}),l}}let fM=[["snapshotDepth","--depth"],["snapshotScope","--scope"],["snapshotRaw","--raw"]];function fE(e,t){let n=function(e){if(!e)return[];let t=[];for(let[n,r]of fM)void 0!==e[n]&&t.push(r);return t}(t);return 0===n.length?null:i4("INVALID_ARGS",`${e} @ref does not support ${n.join(", ")}.`)}async function fO(e,t){let n=await fC(e);if(n)throw new _("COMMAND_FAILED",`press ${t} left ${e.appBundleId} and foregrounded ${n.foregroundPackage}. The tap likely escaped the app.`,n)}async function fC(e){var t;if("android"!==e.device.platform||!e.appBundleId)return null;let n=await lR(e.device),r=n.package?.trim();return r&&r!==e.appBundleId&&("com.android.settings"===(t=r)||"com.android.systemui"===t||"com.google.android.permissioncontroller"===t||t.includes("launcher"))?{expectedPackage:e.appBundleId,foregroundPackage:r,activity:n.activity,hint:"com.google.android.permissioncontroller"===r?"Dismiss or allow the permission prompt, then retry the smoke assertion.":"Use screenshot as visual truth, then take a fresh snapshot -i before retrying."}:null}function fR(e){return"COMMAND_FAILED"===e.code&&"string"==typeof e.details?.expectedPackage&&"string"==typeof e.details?.foregroundPackage}function fL(e,t,n,r){let a=e.get(t);a&&e.recordAction(a,{command:n.command,positionals:n.positionals??[],flags:n.flags??{},result:r})}function fP(e){let t=e.target;return t&&"object"==typeof t?"ref"===t.kind&&"string"==typeof t.ref?{kind:"ref",ref:t.ref}:"selector"===t.kind&&"string"==typeof t.selector?{kind:"selector",selector:t.selector}:void 0:void 0}function fT(e){return e.startsWith("@")?e.slice(1):e}async function f$(e){var t;let{req:n}=e;if("find"!==n.command)return null;let r=n.positionals??[];if(0===r.length)return i4("INVALID_ARGS","find requires a locator or text");let a=tm(r);if(!a.query)return i4("INVALID_ARGS","find requires a value");if(n.flags?.findFirst&&n.flags?.findLast)return i4("INVALID_ARGS","find accepts only one of --first or --last");let i=a.action;if("exists"!==(t=i)&&"wait"!==t&&"get_text"!==t&&"get_attrs"!==t)return null;let o=await fB(e,{requireSession:!1,capability:"find"});return o.ok?await fW(async()=>{let t=await o.runtime.selectors.find({session:e.sessionName,requestId:n.meta?.requestId,locator:a.locator,query:a.query,action:i,timeoutMs:a.timeoutMs});return fL(e.sessionStore,e.sessionName,n,function(e,t){if("exists"===t)return{found:!0};if("wait"===t)return{found:!0,waitedMs:e.waitedMs};let n="string"==typeof e.ref?e.ref:void 0;return"get_attrs"===t?{ref:n,action:"get attrs"}:{ref:n,action:"get text",text:"string"==typeof e.text?e.text:""}}(t,i)),"found"===t.kind?{found:!0,..."number"==typeof t.waitedMs?{waitedMs:t.waitedMs}:{}}:{..."string"==typeof t.ref?{ref:t.ref}:{},..."string"==typeof t.text?{text:t.text}:{},...t.node&&"object"==typeof t.node?{node:t.node}:{}}}):o.response}async function fF(e){let{req:t}=e;if("get"!==t.command)return null;let n=t.positionals?.[0];if("text"!==n&&"attrs"!==n)return i4("INVALID_ARGS","get only supports text or attrs");let r=await fB(e,{requireSession:!0,capability:"get"});if(!r.ok)return r.response;let a=function(e){let t=e.positionals?.[1]??"";if(t.startsWith("@"))return{ok:!0,target:{kind:"ref",ref:t,fallbackLabel:e.positionals.length>2?e.positionals.slice(2).join(" ").trim():""}};let n=e.positionals?.slice(1).join(" ").trim()??"";return n?{ok:!0,target:{kind:"selector",selector:n}}:{ok:!1,response:i4("INVALID_ARGS","get requires @ref or selector expression")}}(t);if(!a.ok)return a.response;if("ref"===a.target.kind){let e=fE("get",t.flags);if(e)return e}return await fW(async()=>{let i,o=await r.runtime.selectors.get({session:e.sessionName,requestId:t.meta?.requestId,property:n,target:a.target});return fL(e.sessionStore,e.sessionName,t,function(e,t){let n=Array.isArray(e.selectorChain)?e.selectorChain:void 0,r=fP(e),a=r?.kind==="ref"?fT(r.ref):void 0,i=r?.kind==="selector"?r.selector:void 0,o={...a?{ref:a}:{},...i?{selector:i}:{},...n?{selectorChain:n}:{}};if("attrs"===t)return o;let s="string"==typeof e.text?e.text:"";return{...o,text:s,refLabel:function(e){let t=e.trim();if(!(!t||t.length>80||/[\r\n]/.test(t)))return t}(s)}}(o,n)),i=fP(o),{...i?.kind==="ref"?{ref:fT(i.ref)}:{},...i?.kind==="selector"?{selector:i.selector}:{},..."string"==typeof o.text?{text:o.text}:{},...o.node&&"object"==typeof o.node?{node:o.node}:{}}})}async function fU(e){let{req:t}=e;if("is"!==t.command)return null;let n=(t.positionals?.[0]??"").toLowerCase();if(!r_(n))return i4("INVALID_ARGS","is requires predicate: visible|hidden|exists|editable|selected|text");let{split:r}=e6(t.positionals??[]);if(!r)return i4("INVALID_ARGS","is requires a selector expression");let a=r.rest.join(" ").trim();if("text"===n&&!a)return i4("INVALID_ARGS","is text requires expected text value");if("text"!==n&&r.rest.length>0)return i4("INVALID_ARGS",`is ${n} does not accept trailing values`);let i=await fB(e,{requireSession:!0,capability:"is"});if(!i.ok)return i.response;let o=await fW(async()=>{let o=await i.runtime.selectors.is({session:e.sessionName,requestId:t.meta?.requestId,predicate:n,selector:r.selectorExpression,expectedText:a});return fL(e.sessionStore,e.sessionName,t,o),function(e){let{selectorChain:t,...n}=e;return n}(o)});return await fz(e,o,`is ${n}`)}async function fG(e){let{req:t,sessionName:n,sessionStore:r}=e,a=fy(t.positionals??[]);if(!a)return i4("INVALID_ARGS","wait requires a duration or text");let{session:i,device:o}=await fh(r,n,t.flags);if("sleep"!==a.kind&&!oi("wait",o))return i4("UNSUPPORTED_OPERATION","wait is not supported on this device");let s=async()=>{let s=fV({...e,session:i,device:o}),l=await fW(async()=>{let e=await s.selectors.wait({session:n,requestId:t.meta?.requestId,target:function(e,t){if("sleep"===e.kind)return{kind:"sleep",durationMs:e.durationMs};if("selector"===e.kind)return{kind:"selector",selector:e.selectorExpression,timeoutMs:e.timeoutMs};if("ref"===e.kind){if(!t?.snapshot)throw new _("INVALID_ARGS","Ref wait requires an existing snapshot in session.");return{kind:"ref",ref:e.rawRef,timeoutMs:e.timeoutMs}}if(!e.text)throw new _("INVALID_ARGS","wait requires text");return{kind:"text",text:e.text,timeoutMs:e.timeoutMs}}(a,i)});return fL(r,n,t,e),{waitedMs:e.waitedMs,..."string"==typeof e.text?{text:e.text}:{},..."string"==typeof e.selector?{selector:e.selector}:{}}});return await fz(e,l,"wait")};return"sleep"===a.kind?await s():await fm(i,o,s)}function fV(e){return i1({backend:function(e){let t,{req:n,session:r,device:a,logPath:i,sessionName:o,sessionStore:s}=e,l=0;return{platform:a.platform,captureSnapshot:async(e,u)=>{var d;let c,p={...n.flags,...(d=u,c={},d?.interactiveOnly!==void 0&&(c.snapshotInteractiveOnly=d.interactiveOnly),d?.compact!==void 0&&(c.snapshotCompact=d.compact),d?.scope!==void 0&&(c.snapshotScope=d.scope),d?.depth!==void 0&&(c.snapshotDepth=d.depth),d?.raw!==void 0&&(c.snapshotRaw=d.raw),c)},f=u?.scope??n.flags?.snapshotScope,h=Date.now();if(t&&h-l<750&&!p4(r))return t;let m=await p7({device:a,session:r,flags:p,outPath:n.flags?.out,logPath:i??"",snapshotScope:f});return r&&(r.snapshot=m.snapshot,s.set(o,r)),l=h,t={snapshot:m.snapshot}},readText:async(t,o)=>({text:await fD({device:a,node:o,flags:n.flags,appBundleId:r?.appBundleId,traceOutPath:r?.trace?.outPath,surface:r?.surface,contextFromFlags:e.contextFromFlags??((e,t,n)=>p9(i??"",e,t,n))})}),findText:async(t,n)=>({found:await fj(e,n)})}}(e),artifacts:fA("selector commands",{plural:!0}),sessions:{get:t=>t===e.sessionName?function(e){if(e)return{name:e.name,appName:e.appName,appBundleId:e.appBundleId,snapshot:e.snapshot,metadata:{surface:e.surface}}}(e.session):void 0,set:t=>{e.session&&t.snapshot&&(e.session.snapshot=t.snapshot,e.sessionStore.set(e.sessionName,e.session))}},policy:i3()})}async function fB(e,t){let n=e.sessionStore.get(e.sessionName);if(!n&&t.requireSession)return{ok:!1,response:i4("SESSION_NOT_FOUND","No active session. Run open first.")};let r=n?.device??await pG(e.req.flags??{});return(n||await fd(r),oi(t.capability,r))?{ok:!0,runtime:fV({...e,session:n,device:r})}:{ok:!1,response:i4("UNSUPPORTED_OPERATION",`${t.capability} is not supported on this device`)}}async function fj(e,t){let{device:n,session:r,req:a,logPath:i}=e;if("macos"===n.platform&&r?.surface&&"app"!==r.surface)return!!tn((await fq(e)).nodes,t);if(i8(n.platform)){let e=await sF(n,{command:"findText",text:t,appBundleId:r?.appBundleId},{verbose:a.flags?.verbose,logPath:i,traceLogPath:r?.trace?.outPath,requestId:a.meta?.requestId});return e?.found===!0}return!!tn((await fq(e)).nodes,t)}async function fq(e){let t=await p7({device:e.device,session:e.session,flags:{...e.req.flags,snapshotInteractiveOnly:!1,snapshotCompact:!1},outPath:e.req.flags?.out,logPath:e.logPath??""});return e.session&&(e.session.snapshot=t.snapshot,e.sessionStore.set(e.sessionName,e.session)),t.snapshot}async function fW(e){try{return{ok:!0,data:await e()}}catch(t){let e=x(t);return i4(e.code,e.message,e.details)}}async function fz(e,t,n){var r;let a;if(t.ok)return t;let i=e.sessionStore.get(e.sessionName);if(!i)return t;try{a=await fC(i)}catch{return t}return a?i4(t.error.code,`${n} failed because ${"com.google.android.permissioncontroller"===(r=a).foregroundPackage?`Android permission dialog is blocking ${r.expectedPackage}`:`${r.foregroundPackage} is foreground instead of ${r.expectedPackage}`}.`,{...t.error.details??{},...a,blockedBy:"android_foreground_surface",originalMessage:t.error.message}):t}let fX=new Set(["snapshot","diff","wait","alert","settings"]);async function fH(e){let{req:t,sessionName:n,logPath:r,sessionStore:a}=e,i=t.command;if(!fX.has(i))return null;if("snapshot"===i)return await fx({req:t,sessionName:n,logPath:r,sessionStore:a});if("diff"===i)return t.positionals?.[0]!=="snapshot"?i4("INVALID_ARGS","diff currently supports only: diff snapshot"):await fN({req:t,sessionName:n,logPath:r,sessionStore:a});if("wait"===i)return await fG({req:t,sessionName:n,logPath:r,sessionStore:a});if("alert"===i){let{session:e,device:i}=await fh(a,n,t.flags);return await fm(e,i,async()=>await fb({req:t,logPath:r,sessionStore:a,session:e,device:i}))}if("settings"===i){let e,i,o,s=(e=t.positionals?.[0]?.toLowerCase(),i=t.positionals?.[1]?.toLowerCase(),o=t.positionals?.[2]?.toLowerCase(),e&&i&&("permission"!==e||o)?{ok:!0,parsed:{setting:e,state:i,permissionTarget:o}}:i4("INVALID_ARGS",j));if(!s.ok)return s;let{session:l,device:u}=await fh(a,n,t.flags);return await fm(l,u,async()=>await fI({req:t,logPath:r,sessionStore:a,session:l,device:u,parsed:s.parsed}))}return null}export{eJ as DEFAULT_BATCH_MAX_STEPS,u7 as IOS_DEVICECTL_DEFAULT_HINT,sa as IOS_RUNNER_CONTAINER_BUNDLE_IDS,uQ as IOS_SIMCTL_LIST_TIMEOUT_MS,W as SESSION_SURFACES,B as SETTINGS_USAGE_OVERRIDE,sC as abortAllIosRunnerSessions,tz as adbArgs,uh as appSwitcherAndroid,nl as applyRuntimeHintsToApp,fO as assertAndroidPressStayedInApp,ea as attachRefs,uc as backAndroid,tD as buildAppIdentifiers,tM as buildDeviceIdentifiers,ef as buildMobileSnapshotPresentation,l1 as buildScrollGesturePlan,tA as buildSelectorChainForNode,t6 as buildSimctlArgs,t9 as buildSimctlArgsForDevice,J as buildSnapshotDisplayLines,fa as buildSnapshotState,pc as buttonTag,oi as capabilities_isCommandSupportedOnDevice,fe as captureSnapshotData,es as centerOfRect,tZ as classifyAndroidAppTarget,oA as clearRequestCanceled,nu as clearRuntimeHintsFromApp,lB as closeAndroidApp,ch as closeIosApp,eX as computeDaemonCodeSignature,p9 as context_contextFromFlags,i1 as createAgentDevice,oS as createRequestCanceledError,eI as createRequestId,fA as createUnsupportedArtifactAdapter,nD as decodePng,i8 as device_isApplePlatform,s6 as waitForAndroidBoot,uO as dismissAndroidKeyboard,pV as dispatchCommand,f$ as dispatchFindReadOnlyViaRuntime,fF as dispatchGetViaRuntime,fU as dispatchIsViaRuntime,er as displayNodeLabel,eN as emitDiagnostic,tX as ensureAdb,s8 as ensureAndroidEmulatorBooted,fd as ensureDeviceReady,eT as expandUserHomePath,tu as extractNodeText,ub as fillAndroid,tp as findBestMatchesByLocator,pR as findBootableIosSimulator,tl as findNearestHittableAncestor,eb as findProjectRoot,e_ as flushDiagnosticsToSessionFile,uy as focusAndroid,tQ as formatAndroidInstalledPackageRequiredMessage,K as formatSnapshotLine,p4 as getActiveAndroidSnapshotFreshness,lR as getAndroidAppState,uE as getAndroidKeyboardState,ux as getAndroidScreenSize,pd as getClickButtonValidationError,ex as getDiagnosticsMeta,oN as getRequestSignal,sD as getRunnerSessionSnapshot,fH as handleSnapshotCommands,no as hasRuntimeTransportHints,up as homeAndroid,lC as inferAndroidAppName,lQ as installAndroidApp,lZ as installAndroidInstallablePathAndResolvePackageName,cw as installIosApp,cy as installIosInstallablePath,eO as isAgentDeviceDaemonProcess,fR as isAndroidEscapeError,sG as isDeepLinkTarget,os as isEnvTruthy,p8 as isNavigationSensitiveAction,eD as isProcessAlive,ox as isRequestCanceled,lD as listAndroidApps,s0 as listAndroidDevices,pF as listAppleDevices,cx as listIosApps,u6 as listIosDeviceApps,u9 as listIosDeviceProcesses,i3 as localCommandPolicy,um as longPressAndroid,p3 as markAndroidSnapshotFreshness,oI as markRequestCanceled,i6 as matchesPlatformSelector,i5 as normalizePlatformSelector,eB as normalizeTenantId,to as normalizeType,lP as openAndroidApp,lV as openAndroidDevice,cp as openIosApp,cf as openIosDevice,eQ as parseBatchStepsJson,fk as parseCoordinateTarget,pb as parseDeviceRotation,tm as parseFindArgs,t5 as parseSerialAllowlist,z as parseSessionSurface,fy as parseWaitArgs,o1 as parseXmlDocumentSync,lb as prepareAndroidInstallArtifact,dd as prepareIosInstallArtifact,uu as pressAndroid,ti as pruneGroupNodes,uz as pushAndroidNotification,cI as pushIosNotification,uC as readAndroidClipboardText,uD as readAndroidTextAtPoint,tk as readCommandMessage,du as readInfoPlistString,cb as readIosClipboardText,eE as readProcessCommand,eM as readProcessStartTime,fD as readTextForNode,ey as readVersion,fE as refSnapshotFlagGuardResponse,ov as registerRequestAbort,l0 as reinstallAndroidApp,cg as reinstallIosApp,lk as resolveAndroidApp,t8 as resolveAndroidSerialAllowlist,i9 as resolveAppleSimulatorSetPathForSelector,pu as resolveClickButton,ez as resolveDaemonCodeSignature,eF as resolveDaemonPaths,eU as resolveDaemonServerMode,eG as resolveDaemonTransportPreference,tL as resolveDeployResultTarget,dD as resolveFrontmostMacOsApp,tT as resolveInstallFromSourceResultTarget,cc as resolveIosApp,sV as resolveIosDeviceDeepLinkBundleId,de as resolveIosDevicectlHint,t4 as resolveIosSimulatorDeviceSetPath,pw as resolvePayloadInput,ob as resolveRequestTrackingId,ty as resolveSelectorChain,eV as resolveSessionIsolationMode,pG as resolveTargetDevice,ok as resolveTimeoutMs,e$ as resolveUserPath,i4 as response_errorResponse,uf as rotateAndroid,dO as runMacOsAlertAction,sF as runner_client_runIosRunnerCommand,uH as screenshotAndroid,d8 as screenshotIos,uA as scrollAndroid,tU as serializeCloseResult,tP as serializeDeployResult,tC as serializeDevice,tR as serializeEnsureSimulatorResult,t$ as serializeInstallFromSourceResult,tF as serializeOpenResult,tO as serializeSessionListEntry,tG as serializeSnapshotResult,uU as setAndroidSetting,cA as setIosSetting,ds as shutdownSimulator,di as ensureBootedSimulator,un as snapshotAndroid,p7 as snapshot_capture_captureSnapshot,tr as snapshot_processing_resolveRefLabel,e6 as splitIsSelectorArgs,e8 as splitSelectorFromArgs,sR as stopAllIosRunnerSessions,sO as stopIosRunnerSession,eL as stopProcessForTakeover,tS as successText,ud as swipeAndroid,e5 as tryParseSelectorChain,uw as typeAndroid,e0 as validateAndNormalizeBatchSteps,eR as waitForProcessExit,eS as withDiagnosticTimer,eA as withDiagnosticsScope,oK as withKeyedLock,t_ as withSuccessText,uR as writeAndroidClipboardText,cv as writeIosClipboardText};
|