agent-device 0.12.3 → 0.12.5
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/152.js +1 -1
- package/dist/src/320.js +1 -1
- package/dist/src/57.js +1 -1
- package/dist/src/641.js +38 -0
- package/dist/src/818.js +1 -1
- package/dist/src/974.js +2 -2
- package/dist/src/backend.d.ts +205 -0
- package/dist/src/backend.js +1 -0
- package/dist/src/bin.js +63 -63
- package/dist/src/commands/index.d.ts +908 -0
- package/dist/src/commands/index.js +1 -0
- package/dist/src/contracts.d.ts +1 -1
- package/dist/src/daemon.js +15 -15
- package/dist/src/index.d.ts +898 -3
- package/dist/src/index.js +3 -3
- package/dist/src/io.d.ts +85 -0
- package/dist/src/io.js +1 -0
- package/dist/src/metro-companion.js +1 -1
- package/dist/src/metro.d.ts +10 -0
- package/dist/src/metro.js +1 -1
- package/dist/src/selectors.js +1 -1
- package/dist/src/testing/conformance.d.ts +416 -0
- package/dist/src/testing/conformance.js +1 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +12 -3
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +1 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift +24 -5
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +2 -0
- package/ios-runner/AgentDeviceRunner/RecordingScripts/recording-resize.swift +182 -0
- package/ios-runner/RUNNER_PROTOCOL.md +1 -1
- package/package.json +17 -1
- package/skills/agent-device/references/bootstrap-install.md +13 -0
- package/skills/agent-device/references/remote-tenancy.md +15 -0
- package/skills/agent-device/references/verification.md +1 -0
- package/dist/src/155.js +0 -38
- package/dist/src/940.js +0 -1
package/dist/src/641.js
ADDED
|
@@ -0,0 +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,i,()=>{}),t.traceLogPath&&r.appendFile(t.traceLogPath,i,()=>{}),t.logPath||t.traceLogPath||process.stderr.write(i)}catch{}}async function eN(e,t,n){let r=Date.now();try{let i=await t();return eS({level:"info",phase:e,durationMs:Date.now()-r,data:n}),i}catch(t){throw eS({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),i=o.join(p.homedir(),".agent-device","logs",e,n);r.mkdirSync(i,{recursive:!0});let a=new Date().toISOString().replace(/[:.]/g,"-"),s=o.join(i,`${a}-${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 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 tH(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",ni="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.",na='<?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",i=nb(e.bundleUrl);if(i){var a;let e;try{e=new s(i)}catch(e){throw new _("INVALID_ARGS",`Invalid runtime bundle URL: ${i}`,{},e)}("http:"===e.protocol||"https:"===e.protocol)&&(t??=nb(e.hostname),n??=nI(e.port.length>0?Number(e.port):"https:"===(a=e.protocol)?443:"http:"===a?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 i=ns(r);if(i){if("android"===t.platform)return void await nd(t,n,i);"ios"===t.platform&&"simulator"===t.kind&&await nh(t,n,i)}}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,i,a,o,s,l;let u,d;nv(t);let c=(r=await np(e,t),i=ne,a=`${n.host}:${n.port}`,u=` <string name="${nA(i)}">${nA(a)}</string>`,ng(ny(r,i),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),i=ny(r,nt);i!==n&&await nf(e,t,i)}async function np(e,t){let n=await M("adb",tz(e,["shell","run-as",t,"cat",t7]),{allowFailure:!0});return 0!==n.exitCode?na:nw(n.stdout)}async function nf(e,t,n){let r=tz(e,["shell","run-as",t,"id"]),i=await M("adb",r,{allowFailure:!0});if(0!==i.exitCode){let e=nx(i.stdout,i.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:i.stdout,stderr:i.stderr,exitCode:i.exitCode,hint:e?ni:"adb shell run-as probe failed. Check adb connectivity and that the device is reachable. Inspect stderr/details for more information."})}try{await M("adb",tz(e,["shell","run-as",t,"mkdir","-p","shared_prefs"])),await M("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?ni:"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 M("xcrun",t9(e,["spawn",e.id,"defaults","write",t,nn,"-string",`${n.host}:${n.port}`])),await M("xcrun",t9(e,["spawn",e.id,"defaults","write",t,nr,"-string",n.scheme]))}async function nm(e,t){await M("xcrun",t9(e,["spawn",e.id,"defaults","delete",t,nn]),{allowFailure:!0}),await M("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
|
+
`:na}function ng(e,t){return nw(e).replace("</map>",`${t}
|
|
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 iI=e=>"macos"!==e.platform,iA=e=>"macos"===e.platform||"simulator"===e.kind,ix={device:!0},iS={},iN={alert:{apple:{simulator:!0,device:!0},android:{},linux:iS,supports:iA},pinch:{apple:{simulator:!0,device:!0},android:{},linux:iS,supports:iA},"app-switcher":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:iS,supports:iI},apps:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:iS},back:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:ix},boot:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:iS,supports:iI},click:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:ix},clipboard:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:ix,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:iS,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:ix},fill:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:ix},diff:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:ix},find:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:ix},focus:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:ix},get:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:ix},is:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:ix},home:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:ix,supports:iI},logs:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:iS},network:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:iS},longpress:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:ix},open:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:ix},perf:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:iS},install:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:iS,supports:iI},"install-from-source":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:iS,supports:iI},reinstall:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:iS,supports:iI},press:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:ix},push:{apple:{simulator:!0},android:{emulator:!0,device:!0,unknown:!0},linux:iS,supports:iI},record:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:iS},rotate:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:iS,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:ix},scroll:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:ix},swipe:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:ix},settings:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:iS,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:ix},"trigger-app-event":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:iS},type:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:ix},wait:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:ix}};function i_(e,t){let n=iN[e];if(!n)return!0;let r=ig(t.platform)?n.apple:"linux"===t.platform?n.linux:n.android;return!!r&&(!n.supports||!!n.supports(t))&&!0===r[t.kind??"unknown"]}let iM=iD(process.env.AGENT_DEVICE_RETRY_LOGS);function iD(e){return["1","true","yes","on"].includes((e??"").trim().toLowerCase())}let iE=2e4,iC=12e4,iO=1e4;class ik{startedAtMs;expiresAtMs;constructor(e,t){this.startedAtMs=e,this.expiresAtMs=e+Math.max(0,t)}static fromTimeoutMs(e,t=Date.now()){return new ik(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 iL(e,t={},n={}){let r,i={maxAttempts:t.maxAttempts??3,baseDelayMs:t.baseDelayMs??200,maxDelayMs:t.maxDelayMs??2e3,jitter:t.jitter??.2,shouldRetry:t.shouldRetry};for(let t=1;t<=i.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:i.maxAttempts,deadline:n.deadline});return n.onEvent?.({phase:n.phase,event:"succeeded",attempt:t,maxAttempts:i.maxAttempts,elapsedMs:n.deadline?.elapsedMs(),remainingMs:n.deadline?.remainingMs()}),iT({phase:n.phase,event:"succeeded",attempt:t,maxAttempts:i.maxAttempts,elapsedMs:n.deadline?.elapsedMs(),remainingMs:n.deadline?.remainingMs()}),r}catch(u){r=u;let e=n.classifyReason?.(u),a={phase:n.phase,event:"attempt_failed",attempt:t,maxAttempts:i.maxAttempts,elapsedMs:n.deadline?.elapsedMs(),remainingMs:n.deadline?.remainingMs(),reason:e};if(n.onEvent?.(a),iT(a),t>=i.maxAttempts||i.shouldRetry&&!i.shouldRetry(u,t))break;let o=function(e,t,n,r){let i=Math.min(t,e*2**(r-1));return Math.max(0,i+i*n*(2*Math.random()-1))}(i.baseDelayMs,i.maxDelayMs,i.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:i.maxAttempts,delayMs:s,elapsedMs:n.deadline?.elapsedMs(),remainingMs:n.deadline?.remainingMs(),reason:e};n.onEvent?.(l),iT(l),await function(e,t){return new Promise(n=>{if(t?.aborted)return void n();let r=!1,i=()=>{r||(r=!0,t&&t.removeEventListener("abort",o),n())},a=setTimeout(i,e);function o(){clearTimeout(a),i()}t&&t.addEventListener("abort",o,{once:!0})})}(s,n.signal)}}let a={phase:n.phase,event:"exhausted",attempt:i.maxAttempts,maxAttempts:i.maxAttempts,elapsedMs:n.deadline?.elapsedMs(),remainingMs:n.deadline?.remainingMs(),reason:n.classifyReason?.(r)};if(n.onEvent?.(a),iT(a),r)throw r;throw new _("COMMAND_FAILED","retry failed")}async function iR(e,t={}){return iL(()=>e(),{maxAttempts:t.attempts,baseDelayMs:t.baseDelayMs,maxDelayMs:t.maxDelayMs,jitter:t.jitter,shouldRetry:t.shouldRetry})}function iT(e){eS({level:"attempt_failed"===e.event||"exhausted"===e.event?"warn":"debug",phase:"retry",data:{...e}}),iM&&process.stderr.write(`[agent-device][retry] ${JSON.stringify(e)}
|
|
9
|
+
`)}let iP=new Set,i$=new Map,iF="request_canceled",iU="request canceled";function iG(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 iV(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++}}(i$);let t=new AbortController;i$.set(e,t),iP.has(e)&&t.abort()}function iB(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++}}(iP),iP.add(e),i$.get(e)?.abort())}function ij(e){e&&(iP.delete(e),i$.delete(e))}function iq(e){return!!e&&iP.has(e)}function iW(e){if(e)return i$.get(e)?.signal}function iz(){return new _("COMMAND_FAILED",iU,{reason:iF})}function iX(e){return e instanceof _&&"COMMAND_FAILED"===e.code&&(e.details?.reason===iF||e.message===iU)}function iY(e,t,n){if(!e)return t;let r=Number(e);return Number.isFinite(r)?Math.max(n,Math.floor(r)):t}function iH(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 i=t?.details??{},a="string"==typeof i.message?i.message:void 0,o="string"==typeof i.stdout?i.stdout:void 0,s="string"==typeof i.stderr?i.stderr:void 0,l=i.boot&&"object"==typeof i.boot?i.boot:null,u=i.bootstatus&&"object"==typeof i.bootstatus?i.bootstatus:null,d=[e.message,t?.message,e.stdout,e.stderr,a,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 iJ(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 iK(e){return!(e instanceof _)||"COMMAND_FAILED"!==e.code||!String(e.message??"").toLowerCase().includes("xcodebuild exited early")}function iZ(e){let{port:t,endpoints:n,logPath:r,lastError:i}=e,a="Runner did not accept connection";return new _("COMMAND_FAILED",a,{port:t,endpoints:n,logPath:r,lastError:i?String(i):void 0,reason:iH({error:i,message:a,context:{platform:"ios",phase:"connect"}}),hint:iJ("IOS_RUNNER_CONNECT_TIMEOUT")})}async function iQ(e){var t,n;let r,{session:i,port:a,logPath:o}=e,s=await i.testPromise,l="Runner did not accept connection (xcodebuild exited early)",u=iH({message:l,stdout:s.stdout,stderr:s.stderr,context:{platform:"ios",phase:"connect"}});return new _("COMMAND_FAILED",l,{port:a,logPath:o,xcodebuild:{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr},reason:u,hint:(t=s.stdout,n=s.stderr,(r=`${l}
|
|
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:i})}finally{await s?.release()}}function aU(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 aG(){return"arm64"===process.arch?"arm64":"x86_64"}function aV(e){return"macos"===e.platform||"device"===e.kind?"-maximum-concurrent-test-device-destinations":"-maximum-concurrent-test-simulator-destinations"}function aB(e,t=process.env){if(t.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim()&&!function(e=process.env){return iD(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 aj(e,t,n){eS({level:"rebuild"===e?"warn":"info",phase:"runner_xctestrun_cache",data:{action:e,reason:t,...n}})}function aq(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,i,a=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,i]of Object.entries(e))if(t.has(r)){if("string"==typeof i){n.add(i);continue}if(Array.isArray(i))for(let e of i)"string"==typeof e&&n.add(e)}return Array.from(n)}(t))e.add(n)};r(a);let o=a.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(a))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"),i=ap(n),t=new Set,af(i,(e,n)=>{if(ab.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),i=new Set,a=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;i.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&&a.add(o.join(n,l));continue}e.startsWith("__TESTHOST__/")&&s.push(e.slice(13))}for(let e of s){let t=Array.from(a).find(t=>r.existsSync(o.join(t,e)));if(!t)return null;i.add(o.join(t,e))}return Array.from(i)}let aW=new Map,az=new Map;async function aX(e,t){return await al(az,e.id,async()=>{var n;let r,i,a=aW.get(e.id);if(a){if(function(e){return!!e&&eD(e)}(a.child.pid))return a;await aK(e.id,a)}await ("simulator"!==(n=e).kind?Promise.resolve():a2(n)),await aY(e);let o=await aO(e,t),s=await ai(),{xctestrunPath:l,jsonPath:u}=await a$(o,{AGENT_DEVICE_RUNNER_PORT:String(s)},`session-${e.id}-${s}`),d=await aM(e);try{let t;({child:r,wait:i}=N("xcodebuild",["test-without-building","-only-testing","AgentDeviceRunnerUITests/RunnerTests/testCommand","-parallel-testing-enabled","NO","-test-timeouts-enabled","NO","-collect-test-diagnostics","never",aV(e),"1","-destination-timeout",String(i9),"-xctestrun",l,"-destination",(t=aU(e),"macOS"===t?`platform=macOS,arch=${aG()}`:"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=>{aa(e,t.logPath,t.traceLogPath,t.verbose)}),r.stderr?.on("data",e=>{aa(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:i,child:r,ready:!1,simulatorSetRedirect:d??void 0};return aW.set(e.id,c),c})}async function aY(e){if("simulator"===e.kind)for(let t of aN){let n=await M("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 aH(e){let t=aW.get(e);return t?{sessionId:t.sessionId,alive:function(e){return!!e&&eD(e)}(t.child.pid)}:null}async function aJ(e){await al(az,e.deviceId,async()=>{await aK(e.deviceId,e)})}async function aK(e,t){let n=t??aW.get(e);if(n){try{await i7(n.device,n.port,{command:"shutdown"},void 0,15e3)}catch{await a1(n.child.pid,"SIGTERM")}try{await Promise.race([n.testPromise,new Promise(e=>setTimeout(e,1e4))])}catch{}await a1(n.child.pid,"SIGKILL"),ao(n.xctestrunPath),ao(n.jsonPath),await n.simulatorSetRedirect?.release(),aW.get(e)===n&&aW.delete(e)}}async function aZ(e){await al(az,e,async()=>{await aK(e)})}async function aQ(){let e=Array.from(aW.values()),t=Array.from(aI);await Promise.allSettled(e.map(async e=>{await a1(e.child.pid,"SIGINT")})),await Promise.allSettled(t.map(async e=>{await a1(e.pid,"SIGINT")})),await Promise.allSettled(e.map(async e=>{await a1(e.child.pid,"SIGTERM")})),await Promise.allSettled(t.map(async e=>{await a1(e.pid,"SIGTERM")})),await Promise.allSettled(e.map(async e=>{await a1(e.child.pid,"SIGKILL")})),await Promise.allSettled(t.map(async e=>{await a1(e.pid,"SIGKILL"),aI.delete(e)})),await Promise.allSettled(e.map(async e=>{await e.simulatorSetRedirect?.release()}))}async function a0(){await aQ();let e=Array.from(aW.keys());await Promise.allSettled(e.map(async e=>{await aZ(e)}));let t=Array.from(aI);await Promise.allSettled(t.map(async e=>{try{await a1(e.pid,"SIGTERM"),await a1(e.pid,"SIGKILL")}finally{aI.delete(e)}}))}async function a1(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 M("pkill",[`-${n}`,"-P",String(e)],{allowFailure:!0})}catch{}}async function a2(e){await M("xcrun",t9(e,["bootstatus",e.id,"-b"]),{timeoutMs:i1})}async function a3(e,t,n,r,i,a){let o=await i7(e,t.port,n,r,i,t,a);return await a4(o,t,r)}async function a4(e,t,n){let r=await e.text(),i={};try{i=JSON.parse(r)}catch{throw new _("COMMAND_FAILED","Invalid runner response",{text:r})}if(!i.ok)throw new _("string"==typeof i.error?.code&&i.error.code.trim().length>0?i.error.code:"COMMAND_FAILED",i.error?.message??"Runner error",{runner:i,xcodebuild:{exitCode:1,stdout:"",stderr:""},logPath:n});return t.ready=!0,i.data??{}}async function a5(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(i0(n.requestId),"interactionFrame"===(r=t.command)||"snapshot"===r||"screenshot"===r||"findText"===r||"readText"===r||"alert"===r||"uptime"===r)?iR(()=>(i0(n.requestId),a8(e,t,n)),{shouldRetry:e=>{i0(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"))}}):a8(e,t,n)}async function a8(e,t,n={}){let r;i0(n.requestId);let i=iW(n.requestId);try{let a=(r=await aX(e,n)).ready?i2:i1;return await a3(e,r,t,n.logPath,a,i)}catch(o){let a=o instanceof _?o:new _("COMMAND_FAILED",String(o));if("COMMAND_FAILED"===a.code&&"string"==typeof a.message&&a.message.includes("Runner did not accept connection")&&iK(a)&&r?.ready){i0(n.requestId),r?await aJ(r):await aZ(e.id),r=await aX(e,n);let a=await i7(r.device,r.port,t,n.logPath,i1,void 0,i);return await a4(a,r,n.logPath)}throw o}}function a6(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(),i=n[2]??"";return"http"!==r&&"https"!==r&&"ws"!==r&&"wss"!==r&&"ftp"!==r&&"ftps"!==r||i.startsWith("//")}function a9(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 a7=["android.software.leanback","android.software.leanback_only","android.hardware.type.television"];function oe(e){return`${e.stdout}
|
|
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
|
+
${i}`,!/Error:.*(?:Activity not started|unable to resolve Intent)/i.test(a)))return;let d=await o6(e,s.value);if(!d){if(!await o4(e,s.value))throw o3(s.value);throw new _("COMMAND_FAILED",`Failed to launch ${s.value}`,{stdout:u.stdout,stderr:u.stderr})}await M("adb",tz(e,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",oz,"-c",l,"-n",d]))}function o3(e){return new _("APP_NOT_INSTALLED",`No package found matching "${e}"`,{package:e,hint:oX})}async function o4(e,t){let n=await M("adb",tz(e,["shell","pm","path",t]),{allowFailure:!0}),r=`${n.stdout}
|
|
16
|
+
${n.stderr}`;return!!(0===n.exitCode&&/\bpackage:/i.test(r))||(o8(r),!1)}async function o5(e,t,n){if(o8(n instanceof _?`${String(n.details?.stdout??"")}
|
|
17
|
+
${String(n.details?.stderr??"")}`:"")||!await o4(e,t))throw o3(t)}function o8(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 o6(e,t){for(let n of Array.from(new Set(oK(e,{includeFallbackWhenUnknown:!0})))){let r=await M("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 i=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(i)return i}return null}async function o9(e){e.booted||await oy(e.id)}async function o7(e,t){if("settings"===t.trim().toLowerCase())return void await M("adb",tz(e,["shell","am","force-stop","com.android.settings"]));let n=await oY(e,t);if("intent"===n.type)throw new _("INVALID_ARGS","Close requires a package name, not an intent");await M("adb",tz(e,["shell","am","force-stop",n.value]))}async function se(e,t){let n=await oY(e,t);if("intent"===n.type)throw new _("INVALID_ARGS","App uninstall requires a package name, not an intent");let r=await M("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 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}`,a=/dumped to:\s*(\S+)/i.exec(i),a?.[1]??t),c=await M("adb",tz(e,["shell","cat",d])),p=sM(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 sM(e,t){let n=`${e}
|
|
20
|
+
${t}`,r=n.indexOf("<?xml"),i=r>=0?r:n.indexOf("<hierarchy");if(i<0)return null;let a=n.lastIndexOf("</hierarchy>");if(a<0||a<i)return null;let o=n.slice(i,a+12).trim();return o.length>0?o:null}function sD(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 sE(e){try{let t=await M("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 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 s9(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 s7(e,t){let n=s5(t);if("toggle"!==n)return n;let r=await M("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 i=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(!i)throw new _("COMMAND_FAILED","Unable to determine current Android appearance for toggle",{stdout:r.stdout,stderr:r.stderr});return"auto"===i?"dark":"dark"===i?"light":"dark"}async function le(e,t,n){let r=await ln(e),i=[];for(let a 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 M("adb",tz(e,["shell","pm",n,t,a]),{allowFailure:!0});if(0===r.exitCode)return;i.push({permission:a,stderr:r.stderr,exitCode:r.exitCode})}throw new _("COMMAND_FAILED",`Failed to ${n} Android photos permission`,{appPackage:t,sdkInt:r,attempts:i})}async function lt(e,t,n,r){"grant"===n?await M("adb",tz(e,["shell","pm","grant",t,r.permission]),{allowFailure:!0}):(await M("adb",tz(e,["shell","pm","revoke",t,r.permission]),{allowFailure:!0}),"reset"===n&&(await M("adb",tz(e,["shell","pm","clear-permission-flags",t,r.permission,"user-set"]),{allowFailure:!0}),await M("adb",tz(e,["shell","pm","clear-permission-flags",t,r.permission,"user-fixed"]),{allowFailure:!0}))),await M("adb",tz(e,["shell","appops","set",t,r.appOps,"grant"===n?"allow":"deny"===n?"deny":"default"]))}async function ln(e){let t=await M("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 lr(e,t,n){let r="string"==typeof n.action&&n.action.trim()?n.action.trim():`${t}.TEST_PUSH`,i=["shell","am","broadcast","-a",r,"-p",t],a="string"==typeof n.receiver?n.receiver.trim():"";a&&i.push("-n",a);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.`)}(i,e,t),s+=1);return await M("adb",tz(e,i)),{action:r,extrasCount:s}}let li=Buffer.from([137,80,78,71,13,10,26,10]);async function la(e,t){await lo(e);try{await tH(1e3),await ll(e,t)}finally{await ls(e).catch(()=>{})}}async function lo(e){let t=t=>M("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 ls(e){await M("adb",tz(e,["shell","am broadcast -a com.android.systemui.demo -e command exit"]),{allowFailure:!0})}async function ll(e,t){let n=await M("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(li);if(r<0)throw new _("COMMAND_FAILED","Screenshot data does not contain a valid PNG header");let i=function(e,t){let n=t+li.length;for(;n+8<=e.length;){let t=e.readUInt32BE(n),r=n+4,i=e.toString("ascii",r,r+4),a=n+12+t;if(a>e.length)break;if("IEND"===i)return a;n=a}return null}(n.stdoutBuffer,r);if(!i)throw new _("COMMAND_FAILED","Screenshot data does not contain a complete PNG payload");await a.writeFile(t,n.stdoutBuffer.subarray(r,i))}let lu=iY(process.env.AGENT_DEVICE_IOS_BOOT_TIMEOUT_MS,iC,5e3),ld=iY(process.env.AGENT_DEVICE_IOS_SIMCTL_LIST_TIMEOUT_MS,iE,1e3),lc=iY(process.env.AGENT_DEVICE_IOS_APP_LAUNCH_TIMEOUT_MS,3e4,5e3),lp=iY(process.env.AGENT_DEVICE_IOS_DEVICECTL_TIMEOUT_MS,2e4,1e3),lf=iY(process.env.AGENT_DEVICE_IOS_SIMULATOR_FOCUS_TIMEOUT_MS,1e4,1e3),lh=iY(process.env.AGENT_DEVICE_IOS_SIMULATOR_SCREENSHOT_TIMEOUT_MS,2e4,1e3),lm=iY(process.env.AGENT_DEVICE_IOS_RUNNER_SCREENSHOT_COPY_TIMEOUT_MS,2e4,1e3),lw=iD(process.env.AGENT_DEVICE_IOS_SIMULATOR_SCREENSHOT_RUNNER_FALLBACK);async function lg(e,t){let n=["devicectl",...e],r=await M("xcrun",n,{allowFailure:!0,timeoutMs:lp});if(0===r.exitCode)return;let i=String(r.stdout??""),a=String(r.stderr??"");throw new _("COMMAND_FAILED",`Failed to ${t.action}`,{cmd:"xcrun",args:n,exitCode:r.exitCode,stdout:i,stderr:a,deviceId:t.deviceId,hint:lI(i,a)??lv})}async function ly(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],i=await M("xcrun",r,{allowFailure:!0,timeoutMs:lp});try{var s,l;if(0!==i.exitCode){let t=String(i.stdout??""),n=String(i.stderr??"");throw new _("COMMAND_FAILED","Failed to list iOS apps",{cmd:"xcrun",args:r,exitCode:i.exitCode,stdout:t,stderr:n,deviceId:e.id,hint:lI(t,n)??lv})}let o=await a.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,i="string"==typeof e.url&&e.url.trim().length>0?e.url.trim():void 0;n.push({bundleId:t,name:r,url:i})}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 a.unlink(n).catch(()=>{})}}async function lb(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 M("xcrun",n,{allowFailure:!0,timeoutMs:lp});try{if(0!==r.exitCode){let t=String(r.stdout??""),i=String(r.stderr??"");throw new _("COMMAND_FAILED","Failed to list iOS processes",{cmd:"xcrun",args:n,exitCode:r.exitCode,stdout:t,stderr:i,deviceId:e.id,hint:lI(t,i)??lv})}let i=await a.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(i))}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 a.unlink(t).catch(()=>{})}}let lv="Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.";function lI(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 lA(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 lx(e,t){let n=await M("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 i=await M("plutil",["-extract","CFBundleExecutable","raw","-o","-",`${r}/Info.plist`],{allowFailure:!0});if(0!==i.exitCode||!i.stdout.trim())return{installed:!0};let a=i.stdout.trim(),o=`${r}/${a}`,s=await M("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 lS(e,t){if("simulator"!==e.kind)throw new _("UNSUPPORTED_OPERATION",`${t} is only supported on iOS simulators`)}async function lN(){await M("open",["-a","Simulator"],{allowFailure:!0,timeoutMs:lf})}async function l_(e){let t,n;if("simulator"!==e.kind||"Booted"===await lD(e))return;let r=ik.fromTimeoutMs(lu);try{await iL(async({deadline:r})=>{if(r?.isExpired())throw new _("COMMAND_FAILED","iOS simulator boot deadline exceeded",{timeoutMs:lu});let i=Math.max(1e3,r?.remainingMs()??lu),a=await M("xcrun",t9(e,["boot",e.id]),{allowFailure:!0,timeoutMs:i});t={stdout:String(a.stdout??""),stderr:String(a.stderr??""),exitCode:a.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 M("xcrun",t9(e,["bootstatus",e.id,"-b"]),{allowFailure:!0,timeoutMs:i});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 lD(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=iH({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=>iH({error:e,stdout:n?.stdout??t?.stdout,stderr:n?.stderr??t?.stderr,context:{platform:"ios",phase:"boot"}})})}catch(a){let i=iH({error:a,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:lu,elapsedMs:r.elapsedMs(),reason:i,hint:iJ(i),boot:t,bootstatus:n})}await lN()}async function lM(e){let t=t9(e,["shutdown",e.id]),n=await M("xcrun",t,{allowFailure:!0,timeoutMs:15e3});return{success:0===n.exitCode,exitCode:n.exitCode,stdout:String(n.stdout??""),stderr:String(n.stderr??"")}}async function lD(e){let t="string"==typeof e?e:e.id,n="string"==typeof e?t6(["list","devices","-j"]):t9(e,["list","devices","-j"]),r=await M("xcrun",n,{allowFailure:!0,timeoutMs:ld});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 lE(e,t){try{let n=await M("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 i;return n=await a.readFile(e,"utf8"),r=t,af(ap(n),(e,t)=>{void 0===i&&e===r&&"string"===t.name&&(i=t.text??void 0)}),i}catch{return}}async function lC(e,t){if("url"===e.kind&&!o_(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 oA({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||o_(e.url),signal:t?.signal}),r=await lk(n.installablePath,t),i=await lO(r.installPath);return{archivePath:n.archivePath??(n.installablePath.toLowerCase().endsWith(".ipa")?n.installablePath:void 0),installablePath:r.installPath,bundleId:i.bundleId,appName:i.appName,cleanup:async()=>{await r.cleanup(),await n.cleanup()}}}async function lO(e){let t=o.join(e,"Info.plist"),[n,r,i]=await Promise.all([lE(t,"CFBundleIdentifier"),lE(t,"CFBundleDisplayName"),lE(t,"CFBundleName")]);return{bundleId:n,appName:r??i}}async function lk(e,t){if(!e.toLowerCase().endsWith(".ipa"))return{installPath:e,cleanup:async()=>{}};let n=await a.mkdtemp(o.join(p.tmpdir(),"agent-device-ios-ipa-")),r=async()=>{await a.rm(n,{recursive:!0,force:!0})};try{await M("unzip",["-q",e,"-d",n]);let i=o.join(n,"Payload"),s=(await a.readdir(i,{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(i,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 lL(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(lR).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(lR).join(", ")}`)}catch(e){throw await r(),e}}async function lL(e){await Promise.all(e.map(async e=>{if(e.bundleId&&e.appName)return;let t=await lO(e.installPath);e.bundleId=e.bundleId??t.bundleId,e.appName=e.appName??t.appName}))}function lR(e){let t=e.bundleId??e.appName;return t?`${e.bundleName}.app (${t})`:`${e.bundleName}.app`}function lT(e,t){return"user-installed"===t?e.filter(e=>!e.bundleId.startsWith("com.apple.")):e}let lP="agent-device-macos-helper",l$="AGENT_DEVICE_MACOS_HELPER_BIN",lF=o.join(p.homedir(),".agent-device","macos-helper","current"),lU=o.join(lF,"manifest.json"),lG=/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+$/;function lV(e){let t=e.trim();if(!lG.test(t))throw new _("INVALID_ARGS","macOS bundle id must use reverse-DNS form like com.example.App",{bundleId:e});return t}function lB(){return function(e){let t=o.dirname(e);for(;;){let e=o.join(t,"macos-helper");if(i(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 lj(e){let t=await a.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 lj(n):t.isFile()&&(t.name.endsWith(".swift")||"Package.swift"===t.name)?[n]:[]}))).flat().sort()}async function lq(e){let t=await lj(e),n=c("sha256");for(let r of t)n.update(o.relative(e,r)),n.update("\0"),n.update(await a.readFile(r)),n.update("\0");let r=await M("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 lW(){try{let e=JSON.parse(await a.readFile(lU,"utf8"));return"string"==typeof e.fingerprint?e.fingerprint:null}catch{return null}}async function lz(){let e=await C(process.env[l$],l$);if(e)return e;let t=lB(),n=await lq(t),r=o.join(lF,lP);try{if(await lW()===n)return await a.access(r),r}catch{}let i=o.join(lB(),".build","release",lP);process.stderr.write("agent-device: building macOS helper (first run or helper update)\n"),await M("swift",["build","-c","release","--package-path",t],{cwd:t,timeoutMs:12e4}),await a.mkdir(lF,{recursive:!0});let s=`${r}.tmp`;return await a.copyFile(i,s),await a.rename(s,r),await a.chmod(r,493),await a.writeFile(lU,`${JSON.stringify({fingerprint:n},null,2)}
|
|
26
|
+
`,"utf8"),r}async function lX(e){let t=process.env[l$]?.trim();if("darwin"!==process.platform&&!t)throw new _("UNSUPPORTED_PLATFORM","macOS helper is only available on macOS");let n=await lz(),r=await M(n,e,{allowFailure:!0,timeoutMs:3e4}),i=r.stdout.trim(),a=null;if(i)try{a=JSON.parse(i)}catch{a=null}if(0===r.exitCode&&a?.ok)return a.data;throw new _("COMMAND_FAILED",a&&!a.ok?a.error?.message??`macOS helper exited with code ${r.exitCode}`:i||r.stderr.trim()||`macOS helper exited with code ${r.exitCode}`,{helperPath:n,args:e,stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode,...a&&!a.ok?a.error?.details:{}})}async function lY(){return await lX(["app","frontmost"])}async function lH(e){return await lX(["app","quit","--bundle-id",lV(e)])}async function lJ(e,t){return await lX(["permission",e,t])}async function lK(e,t={}){let n=["alert",e];return t.bundleId&&n.push("--bundle-id",lV(t.bundleId)),t.surface&&n.push("--surface",t.surface),await lX(n)}async function lZ(e,t={}){let n=["snapshot","--surface",e];return t.bundleId&&n.push("--bundle-id",lV(t.bundleId)),await lX(n)}async function lQ(e,t,n={}){let r=["read","--x",String(e),"--y",String(t)];return n.bundleId&&r.push("--bundle-id",lV(n.bundleId)),n.surface&&r.push("--surface",n.surface),await lX(r)}async function l0(e,t,n={}){let r=["press","--x",String(e),"--y",String(t)];return n.bundleId&&r.push("--bundle-id",lV(n.bundleId)),n.surface&&r.push("--surface",n.surface),await lX(r)}async function l1(e,t={}){let n=["screenshot","--out",e];return t.surface&&n.push("--surface",t.surface),t.fullscreen&&n.push("--fullscreen"),await lX(n)}let l2={settings:"com.apple.systempreferences"},l3=/^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/;function l4(e,t){let n=["-b",e];return t&&n.push(t),n}async function l5(e){for(let t of[o.join(e,"Contents","Info.plist"),o.join(e,"Info.plist")]){let[e,n,r]=await Promise.all([lE(t,"CFBundleIdentifier"),lE(t,"CFBundleDisplayName"),lE(t,"CFBundleName")]);if(e||n||r)return{bundleId:e,appName:n??r}}return{}}async function l8(e){let t=e.trim(),n=l2[t.toLowerCase()];if(n)return n;if(l3.test(t))return t;let r=(await ur("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 l6(e,t,n){let r=n?.url?.trim();if(r){if(!a6(r))throw new _("INVALID_ARGS","open <app> <url> requires a valid URL target");let e=n?.appBundleId??await l8(t);await M("open",l4(e,r));return}let i=t.trim();if(a6(i))return void await M("open",[i]);let a=n?.appBundleId??await l8(i);await M("open",l4(a))}async function l9(e,t){let n=await l8(t),r=await lH(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 l7(){let e=await M("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 ue(e){let t=await M("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 ut(){let e=await M("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 un(e){let t=s5(e),n="toggle"===t?!await ut():"dark"===t,r=`tell application "System Events" to tell appearance preferences to set dark mode to ${n?"true":"false"}`,i=await M("osascript",["-e",r],{allowFailure:!0});if(0!==i.exitCode)throw new _("COMMAND_FAILED","Failed to set macOS appearance",{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode})}async function ur(e="all"){let t=["/Applications","/System/Applications",o.join(p.homedir(),"Applications")],n=new Set;for(let e of t){let t=await a.stat(e).catch(()=>null);if(!t?.isDirectory())continue;let r=await M("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 lT((await Promise.all(Array.from(n).map(async e=>{let t=await l5(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 ui=["--time","9:41","--dataNetwork","wifi","--wifiMode","active","--wifiBars","3","--batteryState","charged","--batteryLevel","100"],ua={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"},uo={1:"searching",2:"failed",3:"active"},us={0:"notSupported",1:"searching",2:"failed",3:"active"};function ul(e,t,n){return M("xcrun",t9(e,t),n)}async function uu(e,t){var n,r;let i;await uc(e),t&&await up(e,(i=[],(n=t).dataNetwork&&i.push("--dataNetwork",n.dataNetwork),n.wifiMode&&i.push("--wifiMode",n.wifiMode),void 0!==n.wifiBars&&("wifi"===n.dataNetwork||n.wifiMode)&&i.push("--wifiBars",n.wifiBars),n.cellularMode&&i.push("--cellularMode",n.cellularMode),void 0!==n.cellularBars&&(n.cellularMode||(r=n.dataNetwork)&&"hide"!==r&&"wifi"!==r||void 0!==n.operatorName)&&i.push("--cellularBars",n.cellularBars),void 0!==n.operatorName&&i.push("--operatorName",n.operatorName),i))}async function ud(e){let t=await ul(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=ua[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=uo[Number(r[1])];e&&(t.wifiMode=e),t.wifiBars=r[2];continue}let i=/^Cell Mode:\s+(\d+),\s+Cell Bars:\s+(\d+)$/.exec(n);if(i){let e=Number(i[1]),n=us[e];if(!n)throw new _("COMMAND_FAILED",`Unsupported simulator cellular mode: ${e}`);t.cellularMode=n,t.cellularBars=i[2];continue}let a=/^Operator Name:\s*(.*)$/.exec(n);if(a){t.operatorName=a[1]??"";continue}}return 0===Object.keys(t).length?null:t}(t.stdout)}async function uc(e){await ul(e,["status_bar",e.id,"clear"])}async function up(e,t){0!==t.length&&await ul(e,["status_bar",e.id,"override",...t])}function uf(e,t,n){eS({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 uh(e,t,n){return M("xcrun",t9(e,t),n)}let um={ensureBooted:l_,prepareStatusBarForScreenshot:async function e(e){let t=null,n=!1;try{t=await ud(e),n=!0}catch(t){uf(e,"snapshot_failed",t)}try{await uc(e),await up(e,ui)}catch(t){uf(e,"prepare_failed",t)}return async()=>{await uu(e,n?t:null)}},captureWithRetry:uy,runnerFallbackEnabled:lw,captureWithRunner:ub,shouldFallbackToRunner:u_};async function uw(e,t,n,r){if("macos"===e.platform)return void await ub(e,t,n,r);if("simulator"===e.kind)return void await ug(e,t,n,r);try{await lg(["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:"",i=`${e.message}
|
|
27
|
+
${n}
|
|
28
|
+
${r}`.toLowerCase();return i.includes("unknown option '--device'")||i.includes("unknown subcommand")&&i.includes("screenshot")||i.includes("unrecognized subcommand")&&i.includes("screenshot")}(t))throw t;ux(e,"devicectl_screenshot",t)}await ub(e,t,n,r)}async function ug(e,t,n,r,i=um){if("simulator"!==e.kind)throw new _("UNSUPPORTED_OPERATION","Simulator screenshot fallback flow supports only iOS simulators");let a="object"==typeof r&&null!==r?r:i;await a.ensureBooted(e);let o=async()=>{};try{o=await a.prepareStatusBarForScreenshot(e)}catch(t){uS(e,"prepare_failed",t)}try{try{await a.captureWithRetry(e,t);return}catch(t){if(!a.shouldFallbackToRunner(t))throw t;if(!a.runnerFallbackEnabled){var s,l,u;let n,r;throw s=e,l=t,n=uN(l),eS({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)}ux(e,"simctl_screenshot",t)}await a.captureWithRunner(e,t,n,"boolean"==typeof r?r:void 0)}finally{await o().catch(t=>uS(e,"restore_failed",t))}}async function uy(e,t){let n=ik.fromTimeoutMs(lh);await iL(async({deadline:n})=>{await uh(e,["io",e.id,"screenshot",t],{timeoutMs:Math.max(1e3,n?.remainingMs()??lh)})},{maxAttempts:5,baseDelayMs:1e3,maxDelayMs:5e3,jitter:.2,shouldRetry:e=>u_(e)},{deadline:n,phase:"ios_simulator_screenshot"})}async function ub(e,t,n,r){let i=(await a5(e,{command:"screenshot",appBundleId:n,fullscreen:r})).message;if(!i)throw new _("COMMAND_FAILED","Failed to capture iOS screenshot: runner returned no file path");"macos"===e.platform?await a.copyFile(i,t):"simulator"===e.kind?await uI(e,i,t):await uv(e,i,t)}async function uv(e,t,n){let r=ik.fromTimeoutMs(lm),i={exitCode:1,stdout:"",stderr:""};for(let a of aN)if(0===(i=await M("xcrun",["devicectl","device","copy","from","--device",e.id,"--source",t,"--destination",n,"--domain-type","appDataContainer","--domain-identifier",a],{allowFailure:!0,timeoutMs:uA(r,lm,"runner screenshot copy")})).exitCode)return;let a=i.stderr.trim()||i.stdout.trim()||`devicectl exited with code ${i.exitCode}`;throw new _("COMMAND_FAILED",`Failed to capture iOS screenshot: ${a}`)}async function uI(e,t,n){let r=ik.fromTimeoutMs(lm),i="Unable to locate runner container for simulator screenshot";for(let s of aN){let l=await uh(e,["get_app_container",e.id,s,"data"],{allowFailure:!0,timeoutMs:uA(r,lm,"runner screenshot container lookup")});if(0!==l.exitCode){let e=l.stderr.trim();e&&(i=e);continue}let u=l.stdout.trim();if(!u){i="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 i=[],a=new Set,s=e=>{let t=o.normalize(e);a.has(t)||(a.add(t),i.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)),i}(u,t))try{await a.copyFile(e,n);return}catch(e){i=e instanceof Error?e.message:String(e)}}throw new _("COMMAND_FAILED",`Failed to capture iOS screenshot: ${i}`)}function uA(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 ux(e,t,n){let r=uN(n);eS({level:"warn",phase:"ios_screenshot_fallback",data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,from:t,to:"runner",...r}})}function uS(e,t,n){eS({level:"warn",phase:`ios_screenshot_status_bar_${t}`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,...uN(n)}})}function uN(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 u_(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:"",i=Array.isArray(t.args)?t.args.filter(e=>"string"==typeof e).join(" "):"",a=`${e.message}
|
|
29
|
+
${n}
|
|
30
|
+
${r}
|
|
31
|
+
${i}`.toLowerCase();return a.includes("timeout waiting for screen surfaces")||a.includes("nsposixerrordomain")&&a.includes("code=60")&&a.includes("screenshot")||a.includes("timed out")&&a.includes("screenshot")}let uM={settings:"com.apple.Preferences"},uD=null;function uE(e,t,n){return M("xcrun",t9(e,t),n)}function uC(e){return e.includes("not installed")||e.includes("not found")||e.includes("no such file")}async function uO(e,t){if("macos"===e.platform)return await l8(t);let n=t.trim();if(n.includes("."))return n;let r=uM[n.toLowerCase()];if(r)return r;let i=("simulator"===e.kind?await uq(e):await ly(e,"all")).filter(e=>e.name.toLowerCase()===n.toLowerCase());if(1===i.length)return i[0].bundleId;if(i.length>1)throw new _("INVALID_ARGS",`Multiple apps matched "${t}"`,{matches:i});throw new _("APP_NOT_INSTALLED",`No app found matching "${t}"`)}async function uk(e,t,n){if("macos"===e.platform)return void await l6(e,t,n);let r=n?.url?.trim();if(r){if(!a6(r))throw new _("INVALID_ARGS","open <app> <url> requires a valid URL target");if("simulator"===e.kind){await l_(e),await uE(e,["openurl",e.id,r]);return}let i=a9(n?.appBundleId??await uO(e,t),r);if(!i)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 uQ(e,i,{payloadUrl:r});return}let i=t.trim();if(a6(i)){if("simulator"===e.kind){await l_(e),await uE(e,["openurl",e.id,i]);return}let t=a9(n?.appBundleId,i);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 uQ(e,t,{payloadUrl:i});return}let a=n?.appBundleId??await uO(e,t);"simulator"===e.kind?await uZ(e,a):await uQ(e,a)}async function uL(e){"macos"===e.platform||"simulator"!==e.kind||"Booted"!==await lD(e)&&await l_(e)}async function uR(e,t){if("macos"===e.platform)return void await l9(e,t);let n=await uO(e,t);if("simulator"===e.kind){await l_(e);let t=t9(e,["terminate",e.id,n]),r=await M("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 lg(["device","process","terminate","--device",e.id,n],{action:"terminate iOS app",deviceId:e.id})}async function uT(e,t){let n=await uO(e,t);if("simulator"!==e.kind){let t=["devicectl","device","uninstall","app","--device",e.id,n],r=await M("xcrun",t,{allowFailure:!0,timeoutMs:lp});if(0!==r.exitCode){let i=String(r.stdout??""),a=String(r.stderr??"");if(!uC(`${i}
|
|
32
|
+
${a}`.toLowerCase()))throw new _("COMMAND_FAILED",`Failed to uninstall iOS app ${n}`,{cmd:"xcrun",args:t,exitCode:r.exitCode,stdout:i,stderr:a,deviceId:e.id,hint:lI(i,a)??lv})}return{bundleId:n}}await l_(e);let r=await uE(e,["uninstall",e.id,n],{allowFailure:!0});if(0!==r.exitCode&&!uC(`${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 uP(e,t,n){let r=await lC({kind:"path",path:t},n);try{return await uF(e,r.installablePath),{archivePath:r.archivePath,installablePath:r.installablePath,bundleId:r.bundleId,appName:r.appName,launchTarget:r.bundleId}}finally{await r.cleanup()}}async function u$(e,t,n){let{bundleId:r}=await uT(e,t);return await uP(e,n,{appIdentifierHint:t}),{bundleId:r}}async function uF(e,t){"simulator"!==e.kind?await lg(["device","install","app","--device",e.id,t],{action:"install iOS app",deviceId:e.id}):(await l_(e),await uE(e,["install",e.id,t]))}async function uU(e){if("macos"===e.platform)return await l7();lS(e,"clipboard"),await l_(e);let t=await uE(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 uG(e,t){if("macos"===e.platform)return void await ue(t);lS(e,"clipboard"),await l_(e);let n=await uE(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 uV(e,t,n){lS(e,"push"),await l_(e);let r=await a.mkdtemp(o.join(p.tmpdir(),"agent-device-ios-push-")),i=o.join(r,"payload.apns");try{await a.writeFile(i,`${JSON.stringify(n)}
|
|
34
|
+
`,"utf8"),await uE(e,["push",e.id,t,i])}finally{await a.rm(r,{recursive:!0,force:!0})}}async function uB(e,t,n,r,i){if("macos"===e.platform){let e=t.toLowerCase();if("appearance"===e)return void await un(n);if("permission"===e){let e=s3(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.")}(i?.permissionTarget);return await lJ(e,t)}throw new _("INVALID_ARGS",q(t))}lS(e,"settings"),await l_(e);let a=t.toLowerCase();switch(a){case"wifi":{let t=uW(n);await uE(e,["status_bar",e.id,"override","--wifiMode",t?"active":"failed"]);return}case"airplane":return void(uW(n)?await uE(e,["status_bar",e.id,"override","--dataNetwork","hide","--wifiMode","failed","--wifiBars","0","--cellularMode","failed","--cellularBars","0","--operatorName",""]):await uE(e,["status_bar",e.id,"clear"]));case"location":{let t=uW(n);if(!r)throw new _("INVALID_ARGS","location setting requires an active app in session");await uE(e,["privacy",e.id,t?"grant":"revoke","location",r]);return}case"faceid":case"touchid":{let t=uX[a],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,a);await uK(e,r,{settingName:a,label:t.label,modalityAliases:t.modalityAliases});return}case"appearance":{let t=await uz(e,n);await uE(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=s3(n))?"revoke":o,a=function(e,t){let n=s4(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.`)}(i?.permissionTarget,i?.permissionMode);await uY(e,t,a,r);return}default:throw new _("INVALID_ARGS",`Unsupported setting: ${t}`)}}async function uj(e,t="all"){return"macos"===e.platform?await ur(t):"simulator"===e.kind?lT(await uq(e),t):await ly(e,t)}async function uq(e){let t=(await uE(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 M("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 uW(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 uz(e,t){let n=s5(t);if("toggle"!==n)return n;let r=await uE(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 i=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(!i)throw new _("COMMAND_FAILED","Unable to determine current iOS appearance for toggle",{stdout:r.stdout,stderr:r.stderr});return"dark"===i?"light":"dark"}let uX={faceid:{label:"Face ID",modalityAliases:["face"]},touchid:{label:"Touch ID",modalityAliases:["finger","touch"]}};async function uY(e,t,n,r){let i=await uJ(e);if(!i.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(i).sort().join(", ")}`});let a=["privacy",e.id,t,n,r],o="notifications"===n;if(!("reset"===t&&o))try{await uE(e,a);return}catch(t){if(!(o&&uH(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 uE(e,a);return}catch(e){if(!uH(e))throw e}try{await uE(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 uH(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 uJ(e){let n=t4(e.simulatorSetPath),r=`${process.env.PATH??""}::${n??""}`;if(uD&&t===r)return uD;let i=await uE(e,["privacy","help"],{allowFailure:!0}),a=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 i=/^([a-z-]+)\s+-\s+/.exec(e);i&&t.add(i[1])}return t}(`${i.stdout}
|
|
36
|
+
${i.stderr}`);if(0===a.size)throw new _("COMMAND_FAILED","Unable to determine supported simctl privacy services",{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode,hint:"Run `xcrun simctl privacy help` manually to verify available services for this runtime."});return uD=a,t=r,a}async function uK(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),i=[];for(let t of r){let n=t9(e,t),r=await M("xcrun",n,{allowFailure:!0});if(0===r.exitCode)return;i.push({args:n,stderr:r.stderr,stdout:r.stdout,exitCode:r.exitCode})}let a=i.map(e=>({args:e.args.join(" "),exitCode:e.exitCode,stderr:e.stderr.slice(0,400)}));if(i.length>0&&i.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: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};
|