agent-device 0.16.0 → 0.16.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.16.0.apk → agent-device-android-multitouch-helper-0.16.2.apk} +0 -0
  2. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.16.2.apk.sha256 +1 -0
  3. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.16.0.manifest.json → agent-device-android-multitouch-helper-0.16.2.manifest.json} +4 -4
  4. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.16.0.apk → agent-device-android-snapshot-helper-0.16.2.apk} +0 -0
  5. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.16.2.apk.sha256 +1 -0
  6. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.16.0.manifest.json → agent-device-android-snapshot-helper-0.16.2.manifest.json} +6 -6
  7. package/dist/src/1769.js +7 -7
  8. package/dist/src/6277.js +4 -0
  9. package/dist/src/7519.js +1 -1
  10. package/dist/src/89.js +1 -1
  11. package/dist/src/9542.js +3 -2
  12. package/dist/src/batch.d.ts +1 -0
  13. package/dist/src/cli.js +8 -11
  14. package/dist/src/contracts.d.ts +1 -0
  15. package/dist/src/contracts.js +1 -1
  16. package/dist/src/index.d.ts +1 -0
  17. package/dist/src/internal/daemon.js +51 -50
  18. package/dist/src/server.js +1 -1
  19. package/package.json +1 -4
  20. package/server.json +2 -2
  21. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.16.0.apk.sha256 +0 -1
  22. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.16.0.apk.sha256 +0 -1
  23. package/dist/src/2099.js +0 -1
@@ -1,37 +1,37 @@
1
- let e,t,r,n,a;import{__webpack_require__ as i}from"../rslib-runtime.js";import o,{createHash as s}from"node:crypto";import l,{existsSync as u,promises as d}from"node:fs";import c,{hostname as p}from"node:os";import f from"node:path";import m from"node:net";import{AsyncLocalStorage as h}from"node:async_hooks";import{XMLParser as w}from"fast-xml-parser";import g from"node:http";import{fileURLToPath as y,pathToFileURL as v}from"node:url";import"node:https";import{once as I}from"node:events";import{Transform as b}from"node:stream";import{pipeline as A}from"node:stream/promises";import S from"node:fs/promises";import{PNG as _}from"pngjs";import{setTimeout as x}from"node:timers/promises";import{parseAllDocuments as N}from"yaml";import M from"node:vm";import{toAppErrorCode as k,asAppError as D,normalizeError as P,AppError as O}from"../9152.js";import{runCmdBackground as R,runCmdStreaming as C,runCmd as E,runCmdSync as L,whichCmd as $,resolveExecutableOverridePath as T}from"../9818.js";import{getAndroidBlockingDialogFocus as F,withRetry as U,listAndroidDevices as V,classifyBootFailure as G,isEnvTruthy as q,streamAndroidLogcatWithAdb as j,writeAndroidClipboardText as B,openAndroidApp as H,closeAndroidApp as W,listAndroidApps as z,openAndroidDevice as K,androidDeviceForSerial as J,captureAndroidLogcatWithAdb as X,readAndroidClipboardText as Y,formatAndroidInstalledPackageRequiredMessage as Z,runAndroidAdb as Q,resolveIosSimulatorDeviceSetPath as ee,dismissAndroidKeyboard as et,resolveIosDeviceDeepLinkBundleId as er,Deadline as en,ensureAdb as ea,bootFailureHint as ei,getAndroidKeyboardState as eo,parseSerialAllowlist as es,retryWithPolicy as el,getAndroidAppState as eu,classifyAndroidAppTarget as ed,isAndroidInputMethodOwnedNode as ec,resolveAndroidSerialAllowlist as ep,createAppResolutionCache as ef,isDeepLinkTarget as em}from"../1769.js";import{readProcessStartTime as eh,trimRuntimeValue as ew,readProcessCommand as eg,resolveRuntimeTransportHints as ey,isProcessGroupAlive as ev,isAgentDeviceDaemonProcess as eI,isProcessAlive as eb}from"../8656.js";import{withDiagnosticsScope as eA,assertResolvedAppsFilter as eS,getDiagnosticsMeta as e_,flushDiagnosticsToSessionFile as ex,withDiagnosticTimer as eN,emitDiagnostic as eM}from"../3622.js";import{DAEMON_COMMAND_GROUPS as ek,readLocationCoordinate as eD,PUBLIC_COMMANDS as eP,normalizeTenantId as eO,readInteractionTargetFromPositionals as eR,resolveSessionIsolationMode as eC,readVersion as eE,findProjectRoot as eL,requireLocationCoordinates as e$,appendScreenshotScriptFlags as eT,readScreenshotScriptFlag as eF,screenshotOptionsFromFlags as eU,successText as eV,parseWaitPositionals as eG,resolveDeployResultTarget as eq,parseTimeout as ej,GESTURE_SUBCOMMAND_ERROR as eB,withSuccessText as eH,screenshotFlagsFromOptions as eW,resolveDaemonPaths as ez,splitNonEmptyTrimmedLines as eK,INTERNAL_COMMANDS as eJ,resolveDaemonServerMode as eX,parseDeviceRotation as eY,readFillTargetFromPositionals as eZ,resolveInstallFromSourceResultTarget as eQ,resolveDaemonCodeSignature as e0,SCREENSHOT_ACTION_FLAG_KEYS as e1}from"../2099.js";import{sleep as e2}from"../4829.js";import{resolveUserPath as e3}from"../3267.js";import{withAndroidAdbProvider as e5,pullAndroidAdbFile as e4,resolveAndroidTextInjector as e8,resolveAndroidAdbProvider as e6,resolveAndroidTouchInjector as e9,resolveAndroidAdbExecutor as e7,installAndroidAdbPackage as te}from"../9639.js";import{isScrollableType as tt}from"../2842.js";import{parseUiHierarchy as tr,ensureAndroidSnapshotHelper as tn,parseUiHierarchyTree as ta,captureAndroidSnapshotWithHelper as ti,parseAndroidSnapshotHelperManifest as to,androidUiNodes as ts,forgetAndroidSnapshotHelperInstall as tl,buildUiHierarchySnapshot as tu}from"../221.js";import{detectReactNativeOverlay as td,parseSessionSurface as tc,applyCommandDefaults as tp,isKeyboardAction as tf,isMacOsSettingSupported as tm,isSystemScrollIndicatorLabel as th,isReactNativeCollapsedWarningLabel as tw,formatScrollEdgeMessage as tg,deriveMobileSnapshotHiddenContentHints as ty,SETTINGS_INVALID_ARGS_MESSAGE as tv,resolveRectCenter as tI,resolveActionableTouchNode as tb,resolveReactNativeOverlayDismissTarget as tA,inferVerticalScrollIndicatorDirections as tS,captureScrollEdgeState as t_,normalizeSnapshotTree as tx,resolveActionableTouchResolution as tN,createAgentDevice as tM,runScrollEdgePasses as tk,getUnsupportedMacOsSettingMessage as tD,requireIntInRange as tP,localCommandPolicy as tO,isSupportedPredicate as tR,decodePng as tC,evaluateIsPredicate as tE,findMistargetedTypeRefToken as tL}from"../7519.js";import{snapshotPresentationOptionsFromFlags as t$,normalizeRef as tT,findNodeByRef as tF,buildSnapshotPresentationKey as tU,centerOfRect as tV,attachRefs as tG}from"../4057.js";import{materializeInstallablePath as tq,isTrustedInstallSourceUrl as tj}from"../989.js";import{splitSelectorFromArgs as tB,extractNodeText as tH,tryParseSelectorChain as tW,extractNodeReadText as tz,splitIsSelectorArgs as tK,findNodeByLabel as tJ,resolveRefLabel as tX,parseSelectorChain as tY,findNearestAncestor as tZ,resolveSelectorChain as tQ,matchesSelector as t0,normalizeType as t1,buildSelectorChainForNode as t2,pruneGroupNodes as t3}from"../940.js";import{findBestMatchesByLocator as t5,normalizeText as t4,parseFindArgs as t8}from"../7556.js";import{runBatch as t6,mergeParentFlags as t9}from"../1231.js";var t7={};i.r(t7),i.d(t7,{dH:()=>uL,TM:()=>uE,installIosApp:()=>uT,installIosInstallablePath:()=>uU,YO:()=>uB,L5:()=>uR,IJ:()=>uC,TJ:()=>uq,J7:()=>uV,reinstallIosApp:()=>uF,resolveIosApp:()=>uO,kc:()=>uh,Cm:()=>uj,ap:()=>uG});var re={};i.r(re),i.d(re,{prepareIosInstallArtifact:()=>lN});var rt={};i.r(rt),i.d(rt,{ensureBootedSimulator:()=>lA,SA:()=>l_,EB:()=>lI,N3:()=>lS});let rr=new Set,rn=new Map,ra="request_canceled",ri="request canceled";function ro(e,t){if("string"==typeof e&&e.length>0)return e;let r=("string"==typeof t?t:"number"==typeof t&&Number.isFinite(t)?String(t):"generated").trim().replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,32)||"generated",n=Math.random().toString(36).slice(2,10);return`req:${r}:${process.pid}:${Date.now()}:${n}`}function rs(e){if(!e)return;!function(e){if(e.size<=5e4)return;let t=0;for(let r of e.keys()){if(t>=1e4)break;e.delete(r),t++}}(rn);let t=new AbortController;rn.set(e,t),rr.has(e)&&t.abort()}function rl(e){e&&(!function(e){if(e.size<=5e4)return;let t=0;for(let r of e){if(t>=1e4)break;e.delete(r),t++}}(rr),rr.add(e),rn.get(e)?.abort())}function ru(e){e&&(rr.delete(e),rn.delete(e))}function rd(e){return!!e&&rr.has(e)}function rc(e){if(e)return rn.get(e)?.signal}function rp(){return new O("COMMAND_FAILED",ri,{reason:ra})}function rf(e){if(rd(e))throw rp()}function rm(e){return e instanceof O&&"COMMAND_FAILED"===e.code&&(e.details?.reason===ra||e.message===ri)}function rh(e,t=e=>e){let r=new h;return{resolve:n=>n?t(n):r.getStore()??e,run:async(e,n)=>e?await r.run(t(e),n):await n(),hasScope:()=>!!r.getStore()}}function rw(e,t){return"user-installed"===t?e.filter(e=>!e.bundleId.startsWith("com.apple.")):e}function rg(e,t){return{openBundle:async(t,r)=>{var n,a;let i;await e("open",(n=t,a=r,i=["-b",n],a&&i.push(a),i))},openTarget:async t=>{await e("open",[t])},readClipboard:async()=>{let t=await e("pbpaste",[],{allowFailure:!0});if(0!==t.exitCode)throw new O("COMMAND_FAILED","Failed to read macOS clipboard",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});return t.stdout.replace(/\r\n/g,"\n").replace(/\n$/,"")},writeClipboard:async t=>{let r=await e("pbcopy",[],{allowFailure:!0,stdin:t});if(0!==r.exitCode)throw new O("COMMAND_FAILED","Failed to write macOS clipboard",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode})},readDarkMode:async()=>{let t=await e("osascript",["-e",'tell application "System Events" to tell appearance preferences to get dark mode'],{allowFailure:!0});if(0!==t.exitCode)throw new O("COMMAND_FAILED","Failed to read macOS appearance",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});let r=t.stdout.trim().toLowerCase();if("true"===r)return!0;if("false"===r)return!1;throw new O("COMMAND_FAILED",`Unable to determine current macOS appearance from osascript output: ${t.stdout.trim()}`)},setDarkMode:async t=>{let r=`tell application "System Events" to tell appearance preferences to set dark mode to ${t?"true":"false"}`,n=await e("osascript",["-e",r],{allowFailure:!0});if(0!==n.exitCode)throw new O("COMMAND_FAILED","Failed to set macOS appearance",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode})},listApps:async r=>await ry(e,t,r)}}async function ry(e,t,r){let n=["/Applications","/System/Applications",f.join(c.homedir(),"Applications")],a=new Set;for(let t of n){let r=await d.stat(t).catch(()=>null);if(!r?.isDirectory())continue;let n=await e("find",[t,"-maxdepth","4","-type","d","-name","*.app"],{allowFailure:!0});if(0===n.exitCode)for(let e of n.stdout.split("\n")){let t=e.trim();t&&a.add(t)}}return rw((await Promise.all(Array.from(a).map(async e=>{let r=await rv(e,t).catch(()=>({})),n=r.bundleId;return n?{bundleId:n,name:r.appName??f.basename(e,".app")}:null}))).filter(e=>null!==e).sort((e,t)=>e.name.localeCompare(t.name)),r)}async function rv(e,t){for(let r of[f.join(e,"Contents","Info.plist"),f.join(e,"Info.plist")]){let e=await t(r),n=rI(e,"CFBundleIdentifier"),a=rI(e,"CFBundleDisplayName"),i=rI(e,"CFBundleName");if(n||a||i)return{bundleId:n,appName:a??i}}return{}}function rI(e,t){let r=e?.[t];return"string"==typeof r&&r.trim()?r.trim():void 0}let rb={runCommand:E,simctl:{run:async(e,t)=>await E("xcrun",["simctl",...e],t)},devicectl:{run:async(e,t)=>await E("xcrun",["devicectl",...e],t)},plist:{readJson:async e=>await rD(E,e)},macosHost:rg(E,async e=>await rD(E,e)),whichCommand:$},rA=rh(rb,function(e){return"function"==typeof e?rS({runCommand:e}):rS(e)});function rS(e={}){let t={...rb,...e},r=e.plist??{readJson:async e=>await rD(t.runCommand,e)};return{...t,simctl:e.simctl??{run:async(e,r)=>await t.runCommand("xcrun",["simctl",...e],r)},devicectl:e.devicectl??{run:async(e,r)=>await t.runCommand("xcrun",["devicectl",...e],r)},plist:r,macosHost:e.macosHost??rg(t.runCommand,async e=>await r.readJson(e))}}function r_(e){return rA.resolve(e)}async function rx(e,t){return await rA.run(e,t)}async function rN(e,t,r){return await r_().runCommand(e,t,r)}async function rM(e,t){let r=r_(),[n,...a]=e;return"simctl"===n?await (r.simctl?.run(a,t)??r.runCommand("xcrun",e,t)):"devicectl"===n?await (r.devicectl?.run(a,t)??r.runCommand("xcrun",e,t)):await rN("xcrun",e,t)}async function rk(e){return await r_().plist?.readJson(e)??null}async function rD(e,t){try{let r=await e("plutil",["-convert","json","-o","-",t],{allowFailure:!0});if(0!==r.exitCode||!r.stdout.trim())return null;return JSON.parse(r.stdout)}catch{return null}}function rP(e,t={}){let r=ee(t.simulatorSetPath);return r?["simctl","--set",r,...e]:["simctl",...e]}function rO(e,t){return"ios"!==e.platform||"simulator"!==e.kind?["simctl",...t]:rP(t,{simulatorSetPath:e.simulatorSetPath})}let rR="If runner build products look stale or corrupted, run `pnpm clean:xcuitest` in a local checkout, or remove ~/.agent-device/ios-runner/derived, then retry.";function rC(e){if(!(e instanceof O)||"COMMAND_FAILED"!==e.code)return!1;let t=`${e.message??""}`.toLowerCase();return!(t.includes("xcodebuild exited early")||t.includes("device is busy")&&t.includes("connecting"))&&!!(t.includes("runner did not accept connection")||t.includes("fetch failed")||t.includes("econnrefused")||t.includes("socket hang up"))}function rE(e){return!(e instanceof O)||"COMMAND_FAILED"!==e.code||!String(e.message??"").toLowerCase().includes("xcodebuild exited early")}function rL(e){let{port:t,endpoints:r,logPath:n,lastError:a}=e,i="Runner did not accept connection";return new O("COMMAND_FAILED",i,{port:t,endpoints:r,logPath:n,lastError:a?String(a):void 0,reason:G({error:a,message:i,context:{platform:"ios",phase:"connect"}}),hint:ei("IOS_RUNNER_CONNECT_TIMEOUT")})}async function r$(e){var t,r;let n,{session:a,port:i,logPath:o}=e,s=await a.testPromise,l="Runner did not accept connection (xcodebuild exited early)",u=G({message:l,stdout:s.stdout,stderr:s.stderr,context:{platform:"ios",phase:"connect"}});return new O("COMMAND_FAILED",l,{port:i,logPath:o,xcodebuild:{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr},reason:u,hint:(t=s.stdout,r=s.stderr,(n=`${l}
1
+ let e,t,r,n,a;import{__webpack_require__ as i}from"../rslib-runtime.js";import o,{createHash as s}from"node:crypto";import l,{existsSync as u,promises as d}from"node:fs";import c,{hostname as p}from"node:os";import f from"node:path";import m from"node:net";import{AsyncLocalStorage as h}from"node:async_hooks";import w from"node:http";import{fileURLToPath as g,pathToFileURL as y}from"node:url";import"node:https";import{once as v}from"node:events";import{Transform as I}from"node:stream";import{pipeline as b}from"node:stream/promises";import A from"node:fs/promises";import{setTimeout as S}from"node:timers/promises";import{parseAllDocuments as x}from"yaml";import _ from"node:vm";import{toAppErrorCode as N,asAppError as M,normalizeError as k,AppError as D}from"../9152.js";import{runCmdBackground as P,runCmdStreaming as O,runCmd as R,runCmdSync as E,whichCmd as C,resolveExecutableOverridePath as L}from"../9818.js";import{getAndroidBlockingDialogFocus as T,withRetry as $,listAndroidDevices as F,classifyBootFailure as U,isEnvTruthy as V,streamAndroidLogcatWithAdb as G,writeAndroidClipboardText as q,openAndroidApp as B,closeAndroidApp as j,listAndroidApps as H,openAndroidDevice as W,androidDeviceForSerial as z,captureAndroidLogcatWithAdb as K,readAndroidClipboardText as J,formatAndroidInstalledPackageRequiredMessage as X,runAndroidAdb as Y,resolveIosSimulatorDeviceSetPath as Z,dismissAndroidKeyboard as Q,resolveIosDeviceDeepLinkBundleId as ee,Deadline as et,ensureAdb as er,bootFailureHint as en,getAndroidKeyboardState as ea,parseSerialAllowlist as ei,isInfrastructureBootFailureReason as eo,retryWithPolicy as es,getAndroidAppState as el,isAndroidInputMethodOwnedNode as eu,classifyAndroidAppTarget as ed,resolveAndroidSerialAllowlist as ec,createAppResolutionCache as ep,isDeepLinkTarget as ef}from"../1769.js";import{readProcessStartTime as em,trimRuntimeValue as eh,readProcessCommand as ew,resolveRuntimeTransportHints as eg,isProcessGroupAlive as ey,isAgentDeviceDaemonProcess as ev,isProcessAlive as eI}from"../8656.js";import{withDiagnosticsScope as eb,assertResolvedAppsFilter as eA,getDiagnosticsMeta as eS,flushDiagnosticsToSessionFile as ex,withDiagnosticTimer as e_,emitDiagnostic as eN}from"../3622.js";import{resolveDaemonCodeSignature as eM,DAEMON_COMMAND_GROUPS as ek,PUBLIC_COMMANDS as eD,readInteractionTargetFromPositionals as eP,normalizeTenantId as eO,consumeTextLines as eR,parseTimeout as eE,appendScreenshotScriptFlags as eC,resolveDeployResultTarget as eL,serializeDaemonRpcResponseEnvelope as eT,GESTURE_SUBCOMMAND_ERROR as e$,serializeDaemonResponseEnvelope as eF,shouldStreamRequestProgress as eU,withSuccessText as eV,splitNonEmptyTrimmedLines as eG,INTERNAL_COMMANDS as eq,readLocationCoordinate as eB,resolveSessionIsolationMode as ej,readVersion as eH,findProjectRoot as eW,requireLocationCoordinates as ez,readScreenshotScriptFlag as eK,successText as eJ,screenshotOptionsFromFlags as eX,parseWaitPositionals as eY,screenshotFlagsFromOptions as eZ,resolveDaemonPaths as eQ,resolveDaemonServerMode as e0,parseDeviceRotation as e1,readFillTargetFromPositionals as e2,resolveInstallFromSourceResultTarget as e3,serializeDaemonProgressEnvelope as e5,SCREENSHOT_ACTION_FLAG_KEYS as e4}from"../6277.js";import{sleep as e8}from"../4829.js";import{resolveUserPath as e6}from"../3267.js";import{withAndroidAdbProvider as e9,pullAndroidAdbFile as e7,resolveAndroidTextInjector as te,resolveAndroidAdbProvider as tt,resolveAndroidTouchInjector as tr,resolveAndroidAdbExecutor as tn,installAndroidAdbPackage as ta}from"../9639.js";import{isScrollableType as ti}from"../2842.js";import{parseUiHierarchy as to,ensureAndroidSnapshotHelper as ts,parseUiHierarchyTree as tl,captureAndroidSnapshotWithHelper as tu,parseAndroidSnapshotHelperManifest as td,androidUiNodes as tc,forgetAndroidSnapshotHelperInstall as tp,buildUiHierarchySnapshot as tf}from"../221.js";import{detectReactNativeOverlay as tm,parseSessionSurface as th,applyCommandDefaults as tw,isKeyboardAction as tg,isMacOsSettingSupported as ty,isSystemScrollIndicatorLabel as tv,isReactNativeCollapsedWarningLabel as tI,formatScrollEdgeMessage as tb,deriveMobileSnapshotHiddenContentHints as tA,SETTINGS_INVALID_ARGS_MESSAGE as tS,resolveRectCenter as tx,resolveActionableTouchNode as t_,resolveReactNativeOverlayDismissTarget as tN,inferVerticalScrollIndicatorDirections as tM,captureScrollEdgeState as tk,normalizeSnapshotTree as tD,resolveActionableTouchResolution as tP,PNG as tO,createAgentDevice as tR,runScrollEdgePasses as tE,getUnsupportedMacOsSettingMessage as tC,requireIntInRange as tL,localCommandPolicy as tT,isSupportedPredicate as t$,decodePng as tF,evaluateIsPredicate as tU,findMistargetedTypeRefToken as tV}from"../7519.js";import{snapshotPresentationOptionsFromFlags as tG,normalizeRef as tq,findNodeByRef as tB,buildSnapshotPresentationKey as tj,centerOfRect as tH,attachRefs as tW}from"../4057.js";import{materializeInstallablePath as tz,isTrustedInstallSourceUrl as tK}from"../989.js";import{splitSelectorFromArgs as tJ,extractNodeText as tX,tryParseSelectorChain as tY,extractNodeReadText as tZ,splitIsSelectorArgs as tQ,findNodeByLabel as t0,resolveRefLabel as t1,parseSelectorChain as t2,findNearestAncestor as t3,resolveSelectorChain as t5,matchesSelector as t4,normalizeType as t8,buildSelectorChainForNode as t6,pruneGroupNodes as t9}from"../940.js";import{findBestMatchesByLocator as t7,normalizeText as re,parseFindArgs as rt}from"../7556.js";import{runBatch as rr,mergeParentFlags as rn}from"../1231.js";var ra={};i.r(ra),i.d(ra,{dH:()=>uK,TM:()=>uz,installIosApp:()=>uX,installIosInstallablePath:()=>uZ,YO:()=>u3,L5:()=>uH,IJ:()=>uW,TJ:()=>u1,J7:()=>uQ,reinstallIosApp:()=>uY,resolveIosApp:()=>uj,kc:()=>uk,Cm:()=>u2,ap:()=>u0});var ri={};i.r(ri),i.d(ri,{prepareIosInstallArtifact:()=>lU});var ro={};i.r(ro),i.d(ro,{ensureBootedSimulator:()=>lL,SA:()=>l$,EB:()=>lE,N3:()=>lT});let rs=new Set,rl=new Map,ru="request_canceled",rd="request canceled";function rc(e,t){if("string"==typeof e&&e.length>0)return e;let r=("string"==typeof t?t:"number"==typeof t&&Number.isFinite(t)?String(t):"generated").trim().replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,32)||"generated",n=Math.random().toString(36).slice(2,10);return`req:${r}:${process.pid}:${Date.now()}:${n}`}function rp(e){if(!e)return;!function(e){if(e.size<=5e4)return;let t=0;for(let r of e.keys()){if(t>=1e4)break;e.delete(r),t++}}(rl);let t=new AbortController;rl.set(e,t),rs.has(e)&&t.abort()}function rf(e){e&&(!function(e){if(e.size<=5e4)return;let t=0;for(let r of e){if(t>=1e4)break;e.delete(r),t++}}(rs),rs.add(e),rl.get(e)?.abort())}function rm(e){e&&(rs.delete(e),rl.delete(e))}function rh(e){return!!e&&rs.has(e)}function rw(e){if(e)return rl.get(e)?.signal}function rg(){return new D("COMMAND_FAILED",rd,{reason:ru})}function ry(e){if(rh(e))throw rg()}function rv(e){return e instanceof D&&"COMMAND_FAILED"===e.code&&(e.details?.reason===ru||e.message===rd)}function rI(e,t=e=>e){let r=new h;return{resolve:n=>n?t(n):r.getStore()??e,run:async(e,n)=>e?await r.run(t(e),n):await n(),hasScope:()=>!!r.getStore()}}function rb(e,t){return"user-installed"===t?e.filter(e=>!e.bundleId.startsWith("com.apple.")):e}function rA(e,t){return{openBundle:async(t,r)=>{var n,a;let i;await e("open",(n=t,a=r,i=["-b",n],a&&i.push(a),i))},openTarget:async t=>{await e("open",[t])},readClipboard:async()=>{let t=await e("pbpaste",[],{allowFailure:!0});if(0!==t.exitCode)throw new D("COMMAND_FAILED","Failed to read macOS clipboard",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});return t.stdout.replace(/\r\n/g,"\n").replace(/\n$/,"")},writeClipboard:async t=>{let r=await e("pbcopy",[],{allowFailure:!0,stdin:t});if(0!==r.exitCode)throw new D("COMMAND_FAILED","Failed to write macOS clipboard",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode})},readDarkMode:async()=>{let t=await e("osascript",["-e",'tell application "System Events" to tell appearance preferences to get dark mode'],{allowFailure:!0});if(0!==t.exitCode)throw new D("COMMAND_FAILED","Failed to read macOS appearance",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});let r=t.stdout.trim().toLowerCase();if("true"===r)return!0;if("false"===r)return!1;throw new D("COMMAND_FAILED",`Unable to determine current macOS appearance from osascript output: ${t.stdout.trim()}`)},setDarkMode:async t=>{let r=`tell application "System Events" to tell appearance preferences to set dark mode to ${t?"true":"false"}`,n=await e("osascript",["-e",r],{allowFailure:!0});if(0!==n.exitCode)throw new D("COMMAND_FAILED","Failed to set macOS appearance",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode})},listApps:async r=>await rS(e,t,r)}}async function rS(e,t,r){let n=["/Applications","/System/Applications",f.join(c.homedir(),"Applications")],a=new Set;for(let t of n){let r=await d.stat(t).catch(()=>null);if(!r?.isDirectory())continue;let n=await e("find",[t,"-maxdepth","4","-type","d","-name","*.app"],{allowFailure:!0});if(0===n.exitCode)for(let e of n.stdout.split("\n")){let t=e.trim();t&&a.add(t)}}return rb((await Promise.all(Array.from(a).map(async e=>{let r=await rx(e,t).catch(()=>({})),n=r.bundleId;return n?{bundleId:n,name:r.appName??f.basename(e,".app")}:null}))).filter(e=>null!==e).sort((e,t)=>e.name.localeCompare(t.name)),r)}async function rx(e,t){for(let r of[f.join(e,"Contents","Info.plist"),f.join(e,"Info.plist")]){let e=await t(r),n=r_(e,"CFBundleIdentifier"),a=r_(e,"CFBundleDisplayName"),i=r_(e,"CFBundleName");if(n||a||i)return{bundleId:n,appName:a??i}}return{}}function r_(e,t){let r=e?.[t];return"string"==typeof r&&r.trim()?r.trim():void 0}let rN={runCommand:R,simctl:{run:async(e,t)=>await R("xcrun",["simctl",...e],t)},devicectl:{run:async(e,t)=>await R("xcrun",["devicectl",...e],t)},plist:{readJson:async e=>await rC(R,e)},macosHost:rA(R,async e=>await rC(R,e)),whichCommand:C},rM=rI(rN,function(e){return"function"==typeof e?rk({runCommand:e}):rk(e)});function rk(e={}){let t={...rN,...e},r=e.plist??{readJson:async e=>await rC(t.runCommand,e)};return{...t,simctl:e.simctl??{run:async(e,r)=>await t.runCommand("xcrun",["simctl",...e],r)},devicectl:e.devicectl??{run:async(e,r)=>await t.runCommand("xcrun",["devicectl",...e],r)},plist:r,macosHost:e.macosHost??rA(t.runCommand,async e=>await r.readJson(e))}}function rD(e){return rM.resolve(e)}async function rP(e,t){return await rM.run(e,t)}async function rO(e,t,r){return await rD().runCommand(e,t,r)}async function rR(e,t){let r=rD(),[n,...a]=e;return"simctl"===n?await (r.simctl?.run(a,t)??r.runCommand("xcrun",e,t)):"devicectl"===n?await (r.devicectl?.run(a,t)??r.runCommand("xcrun",e,t)):await rO("xcrun",e,t)}async function rE(e){return await rD().plist?.readJson(e)??null}async function rC(e,t){try{let r=await e("plutil",["-convert","json","-o","-",t],{allowFailure:!0});if(0!==r.exitCode||!r.stdout.trim())return null;return JSON.parse(r.stdout)}catch{return null}}function rL(e,t={}){let r=Z(t.simulatorSetPath);return r?["simctl","--set",r,...e]:["simctl",...e]}function rT(e,t){return"ios"!==e.platform||"simulator"!==e.kind?["simctl",...t]:rL(t,{simulatorSetPath:e.simulatorSetPath})}let r$="If runner build products look stale or corrupted, run `pnpm clean:xcuitest` in a local checkout, or remove ~/.agent-device/ios-runner/derived, then retry.";function rF(e){if(!(e instanceof D)||"COMMAND_FAILED"!==e.code)return!1;let t=`${e.message??""}`.toLowerCase();return!(t.includes("xcodebuild exited early")||t.includes("device is busy")&&t.includes("connecting"))&&!!(t.includes("runner did not accept connection")||t.includes("fetch failed")||t.includes("econnrefused")||t.includes("socket hang up"))}function rU(e){return!(e instanceof D)||"COMMAND_FAILED"!==e.code||!String(e.message??"").toLowerCase().includes("xcodebuild exited early")}function rV(e){let{port:t,endpoints:r,logPath:n,lastError:a}=e,i="Runner did not accept connection";return new D("COMMAND_FAILED",i,{port:t,endpoints:r,logPath:n,lastError:a?String(a):void 0,reason:U({error:a,message:i,context:{platform:"ios",phase:"connect"}}),hint:en("IOS_RUNNER_CONNECT_TIMEOUT")})}async function rG(e){var t,r;let n,{session:a,port:i,logPath:o}=e,s=await a.testPromise,l="Runner did not accept connection (xcodebuild exited early)",u=U({message:l,stdout:s.stdout,stderr:s.stderr,context:{platform:"ios",phase:"connect"}});return new D("COMMAND_FAILED",l,{port:i,logPath:o,xcodebuild:{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr},reason:u,hint:(t=s.stdout,r=s.stderr,(n=`${l}
2
2
  ${t}
3
- ${r}`.toLowerCase()).includes("device is busy")&&n.includes("connecting")?"Target iOS device is still connecting. Keep it unlocked, wait for device trust/connection to settle, then retry.":`${ei("IOS_RUNNER_CONNECT_TIMEOUT")} ${rR}`)})}function rT(e){return"interactionFrame"===e||"snapshot"===e||"screenshot"===e||"findText"===e||"querySelector"===e||"readText"===e||"alert"===e||"uptime"===e}function rF(e){if(rd(e))throw rp()}let rU=new Map;async function rV(e,t,r,n,a=45e3,i,o){let s=en.fromTimeoutMs(a),{getEndpoints:l}=rq(e,t),{endpoints:u}=await l(s.remainingMs()),d=null,c=Math.max(1,Math.ceil(a/250));try{return await el(async({deadline:s})=>{if(s?.isExpired())throw new O("COMMAND_FAILED","Runner connection deadline exceeded",{port:t,timeoutMs:a});if(i&&null!==i.child.exitCode&&void 0!==i.child.exitCode)throw await r$({session:i,port:t,logPath:n});let c=!1;if("device"===e.kind){let e=await l(s?.remainingMs());u=e.endpoints,c=e.cached}let p=c?u[0]:null,f=await rj(u,{command:r,port:t,timeoutMs:a,signal:o,attemptDeadline:s,onError:(t,r)=>{var n;d=r,"device"===e.kind&&t===p&&(n=e.id,rU.delete(n))}});if(f)return f;if("device"===e.kind&&c){var m;m=e.id,rU.delete(m),u=(await l(s?.remainingMs(),!0)).endpoints;let n=await rj(u,{command:r,port:t,timeoutMs:a,signal:o,attemptDeadline:s,onError:(e,t)=>{d=t}});if(n)return n}if(o?.aborted)throw rp();throw new O("COMMAND_FAILED","Runner endpoint probe failed",{port:t,endpoints:u,lastError:d?String(d):void 0})},{maxAttempts:c,baseDelayMs:300,maxDelayMs:2e3,jitter:.2,shouldRetry:rE},{deadline:s,phase:"ios_runner_connect",signal:o})}catch(e){if(o?.aborted||rm(e))throw rp();d||(d=e)}if(o?.aborted)throw rp();if("simulator"===e.kind){let a=s.remainingMs();if(a<=0)throw rL({port:t,endpoints:u,logPath:n,lastError:d});let i=await rz(e,t,r,a,o);return new Response(i.body,{status:i.status})}throw rL({port:t,endpoints:u,logPath:n,lastError:d})}async function rG(e,t,r,n=45e3,a){if(a?.aborted)throw rp();let i=en.fromTimeoutMs(n),{getEndpoints:o}=rq(e,t),{endpoints:s}=await o(i.remainingMs()),l=s[0];if(!l)throw new O("COMMAND_FAILED","Runner command endpoint not available",{port:t,endpoints:s});let u=i.remainingMs();if(u<=0)throw new O("COMMAND_FAILED","Runner command deadline exceeded",{timeoutMs:n});return await rH(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},u,a)}function rq(e,t){let r;return{getEndpoints:async(n,a=!1)=>{var i,o,s;let l,u=await rB({device:e,timeoutBudgetMs:n,forceRefresh:a,requestTunnelIp:r,setRequestTunnelIp:e=>{r=e}});return{endpoints:(i=e,o=t,s=u.ip,l=[`http://127.0.0.1:${o}/command`],"device"!==i.kind||s&&l.unshift(`http://[${s}]:${o}/command`),l),cached:u.sharedCacheHit}}}}async function rj(e,t){let{command:r,port:n,timeoutMs:a,signal:i,attemptDeadline:o,onError:s}=t;for(let t of e)try{let e=o?.remainingMs()??a;if(e<=0)throw new O("COMMAND_FAILED","Runner connection deadline exceeded",{port:n,timeoutMs:a});return await rH(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},Math.min(2e4,e),i)}catch(e){if(i?.aborted||rm(e))throw rp();s(t,e)}return null}async function rB(e){var t,r,n;let{device:a,timeoutBudgetMs:i,forceRefresh:o,requestTunnelIp:s,setRequestTunnelIp:l}=e;if("device"!==a.kind)return{ip:null,sharedCacheHit:!1};if(!o){let e,r=(t=a.id,(e=rU.get(t))?e.expiresAt<=Date.now()?(rU.delete(t),null):e.ip:null);if(r)return{ip:r,sharedCacheHit:!0};if(void 0!==s)return{ip:s,sharedCacheHit:!1}}let u=await rW(a.id,i);return l(u),u&&(r=a.id,n=u,rU.set(r,{ip:n,expiresAt:Date.now()+3e4})),{ip:u,sharedCacheHit:!1}}async function rH(e,t,r,n){let a=AbortSignal.timeout(r),i=n?AbortSignal.any([n,a]):a;return await fetch(e,{...t,signal:i})}async function rW(e,t){if("number"==typeof t&&t<=0)return null;let r="number"==typeof t?Math.max(1,Math.min(1e4,t)):1e4,n=f.join(c.tmpdir(),`agent-device-devicectl-info-${process.pid}-${Date.now()}.json`);try{let t=Math.max(1,Math.ceil(r/1e3)),a=await rM(["devicectl","device","info","details","--device",e,"--json-output",n,"--timeout",String(t)],{allowFailure:!0,timeoutMs:r});if(0!==a.exitCode||!l.existsSync(n))return null;let i=JSON.parse(l.readFileSync(n,"utf8"));if(i.info?.outcome&&"success"!==i.info.outcome)return null;let o=(i.result?.connectionProperties?.tunnelIPAddress??i.result?.device?.connectionProperties?.tunnelIPAddress)?.trim();return o&&o.length>0?o:null}catch{return null}finally{rZ(n)}}async function rz(e,t,r,n,a){let i=JSON.stringify(r),o=rO(e,["spawn",e.id,"/usr/bin/curl","-s","-X","POST","-H","Content-Type: application/json","--data",i,`http://127.0.0.1:${t}/command`]),s=await rM(o,{allowFailure:!0,timeoutMs:n,signal:a}),l=s.stdout;if(0!==s.exitCode){let e=G({message:"Runner did not accept connection (simctl spawn)",stdout:s.stdout,stderr:s.stderr,context:{platform:"ios",phase:"connect"}});throw new O("COMMAND_FAILED","Runner did not accept connection (simctl spawn)",{port:t,stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode,reason:e,hint:ei(e)})}return{status:200,body:l}}async function rK(){return await new Promise((e,t)=>{let r=m.createServer();r.listen(0,"127.0.0.1",()=>{let n=r.address();if("object"==typeof n&&n?.port){let t=n.port;r.close(()=>e(t))}else r.close(()=>t(new O("COMMAND_FAILED","Failed to allocate port")))}),r.on("error",t)})}function rJ(e,t,r,n){t&&rY(t,e),r&&rY(r,e),n&&process.stderr.write(e)}let rX=new Map;function rY(e,t){let r=(rX.get(e)??Promise.resolve()).catch(()=>{}).then(()=>l.promises.appendFile(e,t)).catch(()=>{}).finally(()=>{rX.get(e)===r&&rX.delete(e)});rX.set(e,r)}function rZ(e){try{l.existsSync(e)&&l.unlinkSync(e)}catch{}}let rQ=new h;async function r0(e,t,r){let n=rQ.getStore()??[];if(n.some(r=>r.locks===e&&r.key===t))return await r();let a=(e.get(t)??Promise.resolve()).catch(()=>{}).then(()=>rQ.run([...n,{locks:e,key:t}],r));return e.set(t,a),a.finally(()=>{e.get(t)===a&&e.delete(t)})}function r1(e){return"apple"===e||"ios"===e||"macos"===e}function r2(e,t){return!t||("apple"===t?r1(e):e===t)}function r3(e){let{simulatorSetPath:t,platform:r,target:n}=e;if(t&&"macos"!==r&&"desktop"!==n)return t}async function r5(e,t,r={}){let n=e,a=e=>e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim();if(t.platform&&(n=n.filter(e=>r2(e.platform,t.platform))),t.target&&(n=n.filter(e=>(e.target??"mobile")===t.target)),t.udid){let e=n.find(e=>e.id===t.udid&&r1(e.platform));if(!e)throw new O("DEVICE_NOT_FOUND",`No Apple device with UDID ${t.udid}`);return e}if(t.serial){let e=n.find(e=>e.id===t.serial&&"android"===e.platform);if(!e)throw new O("DEVICE_NOT_FOUND",`No Android device with serial ${t.serial}`);return e}if(t.deviceName){let e=a(t.deviceName),r=n.find(t=>a(t.name)===e);if(!r)throw new O("DEVICE_NOT_FOUND",`No device named ${t.deviceName}`);return r}let i=n[0];if(void 0!==i&&1===n.length)return i;if(0===n.length){var o;let e=r.simulatorSetPath;if(e&&(!(o=t.platform)||"apple"===o||"ios"===o))throw new O("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:
4
- xcrun simctl --set "${e}" create "iPhone 16" com.apple.CoreSimulator.SimDeviceType.iPhone-16 com.apple.CoreSimulator.SimRuntime.iOS-18-0`,selector:t});throw new O("DEVICE_NOT_FOUND","No devices found",{selector:t})}let s=n.filter(e=>"device"!==e.kind);s.length>0&&(n=s);let l=n.filter(e=>e.booted),u=l[0];if(void 0!==u&&1===l.length)return u;let d=l[0]??n[0];if(void 0===d)throw new O("DEVICE_NOT_FOUND","No devices found",{selector:t});return d}let r4=new Set(["RUNNER_PRODUCT_MISSING","RUNNER_PRODUCT_REPAIR_FAILED"]);async function r8(e,t,r){if("macos"!==e.platform)return;if(0===t.length)throw new O("COMMAND_FAILED","Missing macOS runner product",{reason:"RUNNER_PRODUCT_MISSING",xctestrunPath:r});let n=Array.from(new Set(t)).sort((e,t)=>t.length-e.length);for(let e of n)if(!l.existsSync(e))throw new O("COMMAND_FAILED","Missing macOS runner product",{reason:"RUNNER_PRODUCT_MISSING",productPath:e,xctestrunPath:r});for(let e of n)if(!await r6(e)){await rN("codesign",["--remove-signature",e],{allowFailure:!0});try{await rN("codesign",["--force","--sign","-",e])}catch(n){let t=n instanceof O?n:new O("COMMAND_FAILED",String(n));throw new O("COMMAND_FAILED","Failed to repair macOS runner product signature",{reason:"RUNNER_PRODUCT_REPAIR_FAILED",productPath:e,xctestrunPath:r,error:t.message,details:t.details})}}}async function r6(e){return 0===(await rN("codesign",["--verify","--deep","--strict",e],{allowFailure:!0})).exitCode}let r9=null;function r7(e){return function e(t){if(!Array.isArray(t))return[];let r=[];for(let n of t)if(!(!n||"object"!=typeof n||Array.isArray(n)))for(let[t,a]of Object.entries(n))":@"!==t&&"#text"!==t&&r.push({name:t,attributes:function(e){if(!e||"object"!=typeof e||Array.isArray(e))return{};let t={};for(let[r,n]of Object.entries(e))"string"==typeof n&&(t[r]=n);return t}(n[":@"]),text:nt(a)??nt(n["#text"]),children:e(a)});return r}((r9??=new w({ignoreAttributes:!1,attributeNamePrefix:"",preserveOrder:!0,trimValues:!0,parseTagValue:!1})).parse(e))}function ne(e,t){for(let r of e){if("dict"===r.name)for(let e=0;e<r.children.length-1;e+=1){let n=r.children[e],a=r.children[e+1];n?.name==="key"&&n.text&&a&&t(n.text,a)}ne(r.children,t)}}function nt(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 nr=new Set(["ProductPaths","DependentProductPaths","TestHostPath","TestBundlePath","UITargetAppPath"]);async function nn(e){var t;let r=await na(e);if(!r||0===r.length)return null;let n=f.dirname(e),a=new Set,i=function(e,t){let r=[],n=new Set,a=[];for(let i of e){if(i.startsWith("__TESTHOST__/")){a.push(i.slice(13));continue}if(!i.startsWith("__TESTROOT__/"))continue;let e=i.slice(13);r.push(f.join(t,e));let o=function(e){let t=/\.app(?:\/|$)/.exec(e);return t&&void 0!==t.index?e.slice(0,t.index+4):null}(e);o&&n.add(f.join(t,o))}return{testRootPaths:r,hostRoots:Array.from(n),hostRelativePaths:a}}(r,n);for(let e of i.testRootPaths){if(!l.existsSync(e))return null;a.add(e)}for(let e of(t=i).hostRelativePaths.map(e=>{let r=t.hostRoots.find(t=>l.existsSync(f.join(t,e)));return r?f.join(r,e):null})){if(!e)return null;a.add(e)}return Array.from(a)}async function na(e){let t=await rk(e);if(t){var r,n,a,i=t;let e=new Set;for(let t of[a=i,...function(e){let t=e.TestConfigurations;if(!Array.isArray(t))return[];let r=[];for(let e of t){if(!ni(e))continue;let t=e.TestTargets;Array.isArray(t)&&r.push(...t.filter(ni))}return r}(a),...Object.values(a).filter(e=>ni(e)&&"TestBundlePath"in e)])for(let r of function(e){let t=new Set;for(let[r,n]of Object.entries(e))if(nr.has(r)){if("string"==typeof n){t.add(n);continue}if(Array.isArray(n))for(let e of n)"string"==typeof e&&t.add(e)}return Array.from(t)}(t))e.add(r);return Array.from(e)}if("darwin"===process.platform)return null;try{let t;return r=l.readFileSync(e,"utf8"),n=r7(r),t=new Set,ne(n,(e,r)=>{if(nr.has(e)){if("string"===r.name&&r.text)return void t.add(r.text);if("array"===r.name)for(let e of r.children)"string"===e.name&&e.text&&t.add(e.text)}}),Array.from(t)}catch{return null}}function ni(e){return!!e&&"object"==typeof e}let no="XCTestDevices",ns=".agent-device-backup",nl=".agent-device-xctestdevices-backup-",nu=f.join(c.homedir(),".agent-device","ios-runner"),nd=".agent-device-runner-cache.json",nc={PreferredScreenCaptureFormat:"screenshots",SystemAttachmentLifetime:"keepNever",UserAttachmentLifetime:"keepNever"},np=new Map,nf=new Set;function nm(e){return e?.trim()??""}function nh(e=process.env){return nm(e.AGENT_DEVICE_IOS_BUNDLE_ID)||nm(e.AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID)||"com.callstack.agentdevice.runner"}function nw(e=process.env){let t=nm(e.AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID);return t||`${nh(e)}.uitests`}let ng=function(e=process.env){let t=nh(e),r=nw(e);return Array.from(new Set([nm(e.AGENT_DEVICE_IOS_RUNNER_CONTAINER_BUNDLE_ID),`${r}.xctrunner`,t].filter(e=>e.length>0)))}(process.env);function ny(e=c.homedir()){return f.join(e,"Library","Developer","XCTestDevices")}async function nv(e,t={}){if("ios"!==e.platform||"simulator"!==e.kind)return null;let r=ee(e.simulatorSetPath);if(!r)return null;let n=f.resolve(r),a=f.resolve(t.xctestDeviceSetPath??ny()),i=f.resolve(t.backupPath??function(e=ny()){return`${e}${ns}`}(a)),o=f.resolve(t.lockDirPath??function(e=c.homedir()){return f.join(e,".agent-device","xctest-device-set.lock")}()),s=t.ownerStartTime??eh(process.pid),u=await nA({lockDirPath:o,owner:{pid:t.ownerPid??process.pid,startTime:s,acquiredAtMs:t.nowMs??Date.now()}});try{if(nI({xctestDeviceSetPath:a,backupPath:i}),function(e,t){if(f.resolve(e)===f.resolve(t))return!0;try{return l.realpathSync.native(e)===l.realpathSync.native(t)}catch{return!1}}(n,a))return await u(),null;l.mkdirSync(n,{recursive:!0}),l.existsSync(a)&&l.renameSync(a,i),function(e){let{requestedSetPath:t,xctestDeviceSetPath:r}=e,n=f.dirname(r),a=f.join(n,`${no}.agent-device-link-${process.pid}-${Date.now()}`);l.mkdirSync(n,{recursive:!0});try{l.symlinkSync(t,a,"dir"),l.renameSync(a,r)}catch(e){throw l.existsSync(a)&&nb(a),e}}({requestedSetPath:n,xctestDeviceSetPath:a})}catch(e){throw nI({xctestDeviceSetPath:a,backupPath:i}),await u(),new O("COMMAND_FAILED","Failed to redirect XCTest device set path",{requestedSetPath:n,xctestDeviceSetPath:a,backupPath:i,error:String(e)})}let d=!1;return{release:async()=>{if(!d){d=!0;try{nI({xctestDeviceSetPath:a,backupPath:i})}finally{await u()}}}}}function nI(e){let{xctestDeviceSetPath:t,backupPath:r}=e,n=[r,...function(e){let t=f.dirname(e),r=f.basename(e).replace(ns,""),n=r===no?nl:`${r}${nl}`;try{return l.readdirSync(t).filter(e=>e.startsWith(n)).sort().map(e=>f.join(t,e))}catch{return[]}}(r)],a=n.find(e=>l.existsSync(e)),i=l.existsSync(t)&&l.lstatSync(t).isSymbolicLink();if(a){if(i&&nb(t),l.existsSync(t))if(!i)return void eM({level:"warn",phase:"ios_runner_xctest_device_set_restore_collision",data:{xctestDeviceSetPath:t,activeBackupPath:a}});else a!==r?l.rmSync(a,{recursive:!0,force:!0}):l.rmSync(r,{recursive:!0,force:!0});else l.mkdirSync(f.dirname(t),{recursive:!0}),l.renameSync(a,t);for(let e of n)e!==a&&l.existsSync(e)&&l.rmSync(e,{recursive:!0,force:!0});return}i&&(eM({level:"warn",phase:"ios_runner_xctest_device_set_orphaned_symlink",data:{xctestDeviceSetPath:t}}),nb(t))}function nb(e){!l.existsSync(e)||l.lstatSync(e).isSymbolicLink()&&l.unlinkSync(e)}async function nA(e){let{lockDirPath:t,owner:r}=e,n=f.join(t,"owner.json"),a=Date.now()+3e4;for(l.mkdirSync(f.dirname(t),{recursive:!0});Date.now()<a;)try{l.mkdirSync(t),function(e,t){let r=`${e}.${process.pid}.${Date.now()}.tmp`;l.writeFileSync(r,JSON.stringify(t),"utf8"),l.renameSync(r,e)}(n,r);let e=!1;return async()=>{e||(e=!0,l.rmSync(t,{recursive:!0,force:!0}))}}catch(e){if("EEXIST"!==e.code)throw e;if(function(e,t){let r=null;try{r=l.statSync(e)}catch{return!0}let n=function(e){try{return JSON.parse(l.readFileSync(e,"utf8"))}catch{return null}}(t);if(n){var a;return!(Number.isInteger((a=n).pid)&&!(a.pid<=0)&&eb(a.pid)&&(!a.startTime||eh(a.pid)===a.startTime))&&(l.rmSync(e,{recursive:!0,force:!0}),!0)}return!(Date.now()-r.mtimeMs<5e3)&&(l.rmSync(e,{recursive:!0,force:!0}),!0)}(t,n))continue;await e2(100)}throw new O("COMMAND_FAILED","Timed out waiting for XCTest device set lock",{lockDirPath:t})}async function nS(e,t){var r;let n,a=(r=e,(n=process.env.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim())?f.resolve(n):"macos"===r.platform?f.join(nu,"derived","macos"):"simulator"===r.kind?f.join(nu,"derived"):f.join(nu,"derived",r.kind)),i=eL();return await r0(np,a,async()=>{let r=function(e,t=eL()){var r;let n;return{schemaVersion:1,packageVersion:eE(),runnerSourceFingerprint:function(e){let t=f.join(e,"ios-runner","AgentDeviceRunner"),r=function(e){if(!l.existsSync(e))return[];let t=[],r=[e];for(;r.length>0;){let e=r.pop();for(let i of l.readdirSync(e,{withFileTypes:!0})){var n,a;let o=f.join(e,i.name);if(i.isDirectory()){if("xcuserdata"===i.name)continue;r.push(o);continue}i.isFile()&&(n=i.name,a=o,"project.pbxproj"===n?a.includes(`${f.sep}.xcodeproj${f.sep}`):[".swift",".plist",".entitlements",".xctestplan",".xcconfig",".storyboard",".xib"].includes(f.extname(n)))&&t.push(o)}}return t.sort((e,t)=>e.localeCompare(t))}(t),n=function(e,t){let r=o.createHash("sha256");for(let n of t){let t=f.relative(e,n),a=l.statSync(n);r.update(t),r.update("\0"),r.update(String(a.size)),r.update("\0"),r.update(String(Math.trunc(a.mtimeMs))),r.update("\0")}return r.digest("hex")}(t,r),a=nO.get(t);if(a?.fileStatsFingerprint===n)return a.sourceFingerprint;let i=o.createHash("sha256");for(let e of r){let r=f.relative(t,e);i.update(r),i.update("\0"),i.update(l.readFileSync(e)),i.update("\0")}let s=i.digest("hex");return nO.set(t,{fileStatsFingerprint:n,sourceFingerprint:s}),s}(t),platformName:nG(e),deviceKind:e.kind,target:e.target??"phone",buildDestinationFamily:"macOS"===(n=nG(r=e))?`platform=macOS,arch=${nq()}`:"simulator"===r.kind?`generic/platform=${n} Simulator`:`generic/platform=${n}`,runnerBundleBuildSettings:nH(process.env),runnerSigningBuildSettings:nB(process.env,"device"===e.kind,e.platform),runnerPerformanceBuildSettings:nW()}}(e,i);q(process.env.AGENT_DEVICE_IOS_CLEAN_DERIVED)&&(nJ("clean","forced_clean",{derived:a}),nz(a),n_(a));let n=await nK({derived:a,projectRoot:i,expectedCacheMetadata:r,findXctestrun:t=>nR(t,e),xctestrunReferencesProjectRoot:nE,resolveExistingXctestrunProductPaths:nn});if("reuse_ready"!==n.reason&&nJ("rebuild",n.reason,{derived:a,xctestrunPath:n.xctestrunPath}),"reuse_ready"===n.reason)try{return await r8(e,n.productPaths,n.xctestrunPath),nJ("reuse","reuse_ready",{derived:a,xctestrunPath:n.xctestrunPath}),nN(a,nk(r,n.xctestrunPath,n.productPaths)),n.xctestrunPath}catch(e){if(!function(e){if(!(e instanceof O))return!1;let t=e.details&&"object"==typeof e.details?e.details.reason:void 0;return"string"==typeof t&&r4.has(t)}(e))throw e;nJ("rebuild","repair_failed",{derived:a,xctestrunPath:n.xctestrunPath})}n.xctestrunPath&&(nz(a),n_(a));let s=f.join(i,"ios-runner","AgentDeviceRunner","AgentDeviceRunner.xcodeproj");if(!l.existsSync(s))throw new O("COMMAND_FAILED","iOS runner project not found",{projectPath:s});await nV(e,s,a,t);let u=nR(a,e);if(!u)throw new O("COMMAND_FAILED","Failed to locate .xctestrun after build");let d=await nn(u);if(!d)throw new O("COMMAND_FAILED","Runner build is missing expected products",{xctestrunPath:u});return await r8(e,d,u),nN(a,nk(r,u,d)),nJ("build","built_new",{derived:a,xctestrunPath:u}),u})}function n_(e){try{if(!l.existsSync(e))return;if("derived"!==f.basename(e))return void l.rmSync(e,{recursive:!0,force:!0});for(let r of l.readdirSync(e,{withFileTypes:!0})){var t;t=r.name,nx.has(t)&&l.rmSync(f.join(e,r.name),{recursive:!0,force:!0})}}catch{}}let nx=new Set([nd,"Build","BuildCache.noindex","Index.noindex","Logs","ModuleCache.noindex","SDKStatCaches.noindex","SourcePackages","TextBasedInstallAPI","info.plist"]);function nN(e,t){l.mkdirSync(e,{recursive:!0}),l.writeFileSync(f.join(e,nd),`${JSON.stringify(t,null,2)}
5
- `)}function nM(e){let{artifacts:t,...r}=e;return r}function nk(e,t,r){let n=function(e,t){let r=nP(e);if(null===r||0===t.length)return null;let n=[];for(let e of t){let t=nP(e);if(null===t)return null;n.push({path:e,mtimeMs:t})}return{xctestrunPath:e,xctestrunMtimeMs:r,productPaths:n}}(t,r);return n?{...e,artifacts:n}:e}function nD(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"string"==typeof e.path&&Number.isInteger(e.mtimeMs)}function nP(e){try{return Math.trunc(l.statSync(e).mtimeMs)}catch{return null}}let nO=new Map;function nR(e,t){if(!l.existsSync(e))return null;let r=[],n=[e];for(;n.length>0;){let e=n.pop();for(let t of l.readdirSync(e,{withFileTypes:!0})){let a=f.join(e,t.name);if(t.isDirectory()){n.push(a);continue}if(t.isFile()&&t.name.endsWith(".xctestrun"))try{let e=l.statSync(a);r.push({path:a,mtimeMs:e.mtimeMs})}catch{}}}return 0===r.length?null:(r.sort((e,r)=>{if(t){let n=nC(r.path,t)-nC(e.path,t);if(0!==n)return n}return r.mtimeMs-e.mtimeMs||e.path.localeCompare(r.path)}),r[0]?.path??null)}function nC(e,t){var r;let n=0,a=e.toLowerCase();f.basename(a).startsWith("agentdevicerunner.env.")&&(n-=1e3),a.includes(`${f.sep}macos${f.sep}`)&&(n-=5e3);let i="macos"===(r=t).platform?{preferred:["macos"],disallowed:["iphoneos","iphonesimulator","appletvos","appletvsimulator"]}:"tv"===r.target?"simulator"===r.kind?{preferred:["appletvsimulator"],disallowed:["appletvos","iphoneos","iphonesimulator","macos"]}:{preferred:["appletvos"],disallowed:["appletvsimulator","iphoneos","iphonesimulator","macos"]}:"simulator"===r.kind?{preferred:["iphonesimulator"],disallowed:["iphoneos","appletvos","appletvsimulator","macos"]}:{preferred:["iphoneos"],disallowed:["iphonesimulator","appletvos","appletvsimulator","macos"]};return i.preferred.length>0&&(i.preferred.some(e=>a.includes(e))?n+=2e3:n-=500),i.disallowed.some(e=>a.includes(e))&&(n-=2500),n}function nE(e,t){try{let r=l.readFileSync(e,"utf8"),n=new Set([t]);try{n.add(l.realpathSync(t))}catch{}for(let e of n)if(r.includes(e))return!0;return!1}catch{return!1}}async function nL(e,t,r){let n=f.dirname(e),a=r.replace(/[^a-zA-Z0-9._-]/g,"_"),i=f.join(n,`AgentDeviceRunner.env.${a}.json`),o=f.join(n,`AgentDeviceRunner.env.${a}.xctestrun`),s=await n$(e);return nF(s,e=>{var r,n;return r=e,n=t,void(r.EnvironmentVariables={...r.EnvironmentVariables??{},...n},r.UITestEnvironmentVariables={...r.UITestEnvironmentVariables??{},...n},r.UITargetAppEnvironmentVariables={...r.UITargetAppEnvironmentVariables??{},...n},r.TestingEnvironmentVariables={...r.TestingEnvironmentVariables??{},...n})}),nF(s,e=>Object.assign(e,nc),{requireTestBundlePath:!0}),await nT(s,i,o),{xctestrunPath:o,jsonPath:i}}async function n$(e){let t=await rN("plutil",["-convert","json","-o","-",e],{allowFailure:!0});if(0!==t.exitCode||!t.stdout.trim())throw new O("COMMAND_FAILED","Failed to read xctestrun plist",{xctestrunPath:e,stderr:t.stderr});try{let e=JSON.parse(t.stdout);if(!e||"object"!=typeof e||Array.isArray(e))throw Error("Root must be an object");return e}catch(t){throw new O("COMMAND_FAILED","Failed to parse xctestrun JSON",{xctestrunPath:e,error:String(t)})}}async function nT(e,t,r){l.writeFileSync(t,JSON.stringify(e,null,2));let n=await rN("plutil",["-convert","xml1","-o",r,t],{allowFailure:!0});if(0!==n.exitCode)throw new O("COMMAND_FAILED","Failed to write xctestrun plist",{tmpXctestrunPath:r,stderr:n.stderr})}function nF(e,t,r={}){let n=e.TestConfigurations;if(Array.isArray(n))for(let e of n)e&&"object"==typeof e&&function(e,t,r){if(Array.isArray(e))for(let n of e){let e=nU(n,r);e&&t(e)}}(e.TestTargets,t,r);for(let r of Object.values(e)){let e=nU(r,{requireTestBundlePath:!0});e&&t(e)}}function nU(e,t){return!e||"object"!=typeof e||Array.isArray(e)||t.requireTestBundlePath&&!e.TestBundlePath?null:e}async function nV(e,t,r,n){let a=nH(process.env),i=nB(process.env,"device"===e.kind,e.platform),o="device"===e.kind?["-allowProvisioningUpdates"]:[],s=nW(),l=await nv(e);try{var u;let l;await C("xcodebuild",["build-for-testing","-project",t,"-scheme","AgentDeviceRunner","-parallel-testing-enabled","NO",nj(e),"1","-destination",(u=e,l=nG(u),"macOS"===l?`platform=macOS,arch=${nq()}`:"simulator"===u.kind?`platform=${l} Simulator,id=${u.id}`:`generic/platform=${l}`),"-derivedDataPath",r,...s,...a,...o,...i],{detached:!0,onSpawn:e=>{nf.add(e),e.on("close",()=>{nf.delete(e)})},onStdoutChunk:e=>{rJ(e,n.logPath,n.traceLogPath,n.verbose)},onStderrChunk:e=>{rJ(e,n.logPath,n.traceLogPath,n.verbose)}})}catch(i){let e,t,r=i instanceof O?i:new O("COMMAND_FAILED",String(i)),a=(e=r.details?JSON.stringify(r.details):"",((t=`${r.message}
6
- ${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)??rR);throw new O("COMMAND_FAILED","xcodebuild build-for-testing failed",{error:r.message,details:r.details,logPath:n.logPath,hint:a})}finally{await l?.release()}}function nG(e){var t;if("ios"!==e.platform&&"macos"!==e.platform)throw new O("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 nq(){return"arm64"===process.arch?"arm64":"x86_64"}function nj(e){return"macos"===e.platform||"device"===e.kind?"-maximum-concurrent-test-device-destinations":"-maximum-concurrent-test-simulator-destinations"}function nB(e=process.env,t=!1,r="ios"){if("macos"===r)return["CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO","CODE_SIGN_IDENTITY=","DEVELOPMENT_TEAM="];if(!t)return[];let n=e.AGENT_DEVICE_IOS_TEAM_ID?.trim()||"",a=e.AGENT_DEVICE_IOS_SIGNING_IDENTITY?.trim()||"",i=e.AGENT_DEVICE_IOS_PROVISIONING_PROFILE?.trim()||"",o=["CODE_SIGN_STYLE=Automatic"];return n&&o.push(`DEVELOPMENT_TEAM=${n}`),a&&o.push(`CODE_SIGN_IDENTITY=${a}`),i&&o.push(`PROVISIONING_PROFILE_SPECIFIER=${i}`),o}function nH(e=process.env){let t=nh(e),r=nw(e);return[`AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID=${t}`,`AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID=${r}`]}function nW(){return["COMPILER_INDEX_STORE_ENABLE=NO","ENABLE_CODE_COVERAGE=NO"]}function nz(e,t=process.env){if(t.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim()){var r;let t,n;if(r=e,t=f.resolve(eL(),".tmp"),""===(n=f.relative(t,f.resolve(r)))||n.startsWith("..")||f.isAbsolute(n))throw new O("COMMAND_FAILED","Refusing to clean AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH automatically",{derivedPath:e,hint:`Unset AGENT_DEVICE_IOS_CLEAN_DERIVED, or move AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH under a subdirectory of ${f.join(eL(),".tmp")}.`})}}async function nK(e){var t,r;let n,a=(t=e.derived,r=e.expectedCacheMetadata,(n=function(e){try{let t=JSON.parse(l.readFileSync(f.join(e,nd),"utf8"));if(!t||"object"!=typeof t||Array.isArray(t))return null;return t}catch{return null}}(t))?JSON.stringify(nM(n))!==JSON.stringify(nM(r))?{ok:!1,reason:"cache_metadata_mismatch"}:{ok:!0,metadata:n}:{ok:!1,reason:"cache_metadata_missing"}),i=a.ok?function(e){var t;let r=e?.artifacts;if(!(!(!(t=r)||"object"!=typeof t||Array.isArray(t))&&"string"==typeof t.xctestrunPath&&Number.isInteger(t.xctestrunMtimeMs)&&Array.isArray(t.productPaths)&&t.productPaths.length>0&&t.productPaths.every(nD))||nP(r.xctestrunPath)!==r.xctestrunMtimeMs)return null;let n=[];for(let e of r.productPaths){if(nP(e.path)!==e.mtimeMs)return null;n.push(e.path)}return{xctestrunPath:r.xctestrunPath,productPaths:n}}(a.metadata):null,o=i?.xctestrunPath??e.findXctestrun(e.derived);if(!o)return{reason:"missing_xctestrun",xctestrunPath:null};let s=i?.xctestrunPath===o?i.productPaths:await e.resolveExistingXctestrunProductPaths(o);return s?e.xctestrunReferencesProjectRoot(o,e.projectRoot)?a.ok?{reason:"reuse_ready",xctestrunPath:o,productPaths:s}:{reason:a.reason,xctestrunPath:o,productPaths:s}:{reason:"project_root_mismatch",xctestrunPath:o,productPaths:s}:{reason:"missing_products",xctestrunPath:o,productPaths:[]}}function nJ(e,t,r){eM({level:"rebuild"===e?"warn":"info",phase:"runner_xctestrun_cache",data:{action:e,reason:t,...r}})}let nX=new Map,nY=new Map;async function nZ(e,t){return await r0(nY,e.id,async()=>{let r,n,a=nX.get(e.id);if(a){if(n4(a.child.pid))return eM({level:"debug",phase:"ios_runner_session_reuse",data:{deviceId:e.id,sessionId:a.sessionId,ready:a.ready}}),a;await ae({},"stop_stale_session",async()=>{await n1(e.id,a)})}let i={};await ae(i,"ensure_booted",async()=>{var t;await ("simulator"!==(t=e).kind?Promise.resolve():t.booted?(eM({level:"debug",phase:"ios_runner_startup_ensure_booted_skipped",data:{deviceId:t.id}}),Promise.resolve()):n6(t))}),t.cleanStaleBundles?await ae(i,"cleanup_stale_bundles",async()=>{await nQ(e)}):(i.cleanup_stale_bundles=0,eM({level:"debug",phase:"ios_runner_startup_cleanup_stale_bundles_skipped"}));let o=await ae(i,"ensure_xctestrun",async()=>await nS(e,t)),s=await ae(i,"allocate_port",async()=>await rK()),{xctestrunPath:l,jsonPath:u}=await ae(i,"prepare_xctestrun_env",async()=>await nL(o,{AGENT_DEVICE_RUNNER_PORT:String(s)},`session-${e.id}-${s}`)),d=await ae(i,"simulator_set_redirect",async()=>await nv(e));try{({child:r,wait:n}=await ae(i,"launch_xcodebuild",()=>{let t;return R("xcodebuild",["test-without-building","-only-testing","AgentDeviceRunnerUITests/RunnerTests/testCommand","-parallel-testing-enabled","NO","-test-timeouts-enabled","NO","-collect-test-diagnostics","never",nj(e),"1","-destination-timeout",String(20),"-xctestrun",l,"-destination",(t=nG(e),"macOS"===t?`platform=macOS,arch=${nq()}`:"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=>{rJ(e,t.logPath,t.traceLogPath,t.verbose)}),r.stderr?.on("data",e=>{rJ(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:n,child:r,ready:!1,startupTimings:i,simulatorSetRedirect:d??void 0};return nX.set(e.id,c),c})}async function nQ(e){if("simulator"===e.kind)for(let t of ng){let r=await rM(rO(e,["uninstall",e.id,t]),{allowFailure:!0});if(0!==r.exitCode){let e=`${r.stdout}
7
- ${r.stderr}`.toLowerCase();if(!e.includes("not installed")&&!e.includes("found nothing")&&!e.includes("no such file")&&!e.includes("invalid device")&&!e.includes("could not find"))continue}}}async function n0(e,t){await r0(nY,e.deviceId,async()=>{nX.get(e.deviceId)===e&&(eM({level:"warn",phase:"ios_runner_session_invalidated",data:{deviceId:e.deviceId,sessionId:e.sessionId,reason:t}}),await n1(e.deviceId,e,{graceful:!1,waitTimeoutMs:1e3}))})}async function n1(e,t,r={}){let n=t??nX.get(e);if(n){var a;if(!1!==r.graceful)try{await rV(n.device,n.port,{command:"shutdown"},void 0,15e3)}catch{await n8(n.child.pid,"SIGTERM")}else await n8(n.child.pid,"SIGTERM");try{await Promise.race([n.testPromise,new Promise(e=>setTimeout(e,r.waitTimeoutMs??1e4))])}catch{}(a=n.child.pid)&&(n4(a)||ev(a))&&await n8(n.child.pid,"SIGKILL"),rZ(n.xctestrunPath),rZ(n.jsonPath),await n.simulatorSetRedirect?.release(),nX.get(e)===n&&nX.delete(e)}}async function n2(e){await r0(nY,e,async()=>{await n1(e)})}async function n3(){let e=Array.from(nX.values()),t=Array.from(nf);await Promise.allSettled(e.map(async e=>{await n8(e.child.pid,"SIGINT")})),await Promise.allSettled(t.map(async e=>{await n8(e.pid,"SIGINT")})),await Promise.allSettled(e.map(async e=>{await n8(e.child.pid,"SIGTERM")})),await Promise.allSettled(t.map(async e=>{await n8(e.pid,"SIGTERM")})),await Promise.allSettled(e.map(async e=>{await n8(e.child.pid,"SIGKILL")})),await Promise.allSettled(t.map(async e=>{await n8(e.pid,"SIGKILL"),nf.delete(e)})),await Promise.allSettled(e.map(async e=>{await e.simulatorSetRedirect?.release()}))}async function n5(){await n3();let e=Array.from(nX.keys());await Promise.allSettled(e.map(async e=>{await n2(e)}));let t=Array.from(nf);await Promise.allSettled(t.map(async e=>{try{await n8(e.pid,"SIGTERM"),await n8(e.pid,"SIGKILL")}finally{nf.delete(e)}}))}function n4(e){return!!e&&eb(e)}async function n8(e,t){if(!e||e<=0)return;try{process.kill(-e,t)}catch{}try{process.kill(e,t)}catch{}let r="SIGINT"===t?"INT":"SIGTERM"===t?"TERM":"KILL";try{await rN("pkill",[`-${r}`,"-P",String(e)],{allowFailure:!0})}catch{}}async function n6(e){await rM(rO(e,["bootstatus",e.id,"-b"]),{timeoutMs:45e3})}async function n9(e,t,r,n,a,i){var o,s;if(o=t,s=r.command,o.startupTimingsReported||!o.startupTimings||(o.startupTimingsReported=!0,eM({level:"info",phase:"ios_runner_session_startup_timings",durationMs:Object.values(o.startupTimings).reduce((e,t)=>e+t,0),data:{command:s,sessionId:o.sessionId,ready:o.ready,timings:o.startupTimings}})),rT(r.command)){let o=await eN("ios_runner_command_send",async()=>await rV(e,t.port,r,n,a,t,i),{command:r.command,readOnly:!0,sessionReady:t.ready,timeoutMs:a});return await n7(o,t,n)}let l=en.fromTimeoutMs(a);if(function(e,t){if(!e.ready||"tap"!==t.command&&"tapSeries"!==t.command)return!0;let r=e.lastSuccessfulRunnerResponseAtMs;return void 0===r||Date.now()-r>1e4}(t,r)){let a=t.ready?Math.min(5e3,l.remainingMs()):Math.min(45e3,l.remainingMs()),o=await eN("ios_runner_readiness_preflight",async()=>await rV(e,t.port,{command:"uptime"},n,a,t,i),{command:r.command,sessionReady:t.ready,timeoutMs:a});await n7(o,t,n)}else eM({level:"debug",phase:"ios_runner_readiness_preflight_skipped",data:{command:r.command,lastSuccessfulRunnerResponseAgeMs:void 0===t.lastSuccessfulRunnerResponseAtMs?void 0:Date.now()-t.lastSuccessfulRunnerResponseAtMs,sessionReady:t.ready}});let u=l.remainingMs();if(u<=0)throw new O("COMMAND_FAILED","Runner command deadline exceeded",{timeoutMs:a});let d=await eN("ios_runner_command_send",async()=>await rG(e,t.port,r,u,i),{command:r.command});return await n7(d,t,n)}async function n7(e,t,r){let n,a=await e.text();try{let e=JSON.parse(a);n=e&&"object"==typeof e?e:{}}catch{throw new O("COMMAND_FAILED","Invalid runner response",{text:a})}if(!n.ok){let e=n.error?.code;throw new O("string"==typeof e&&e.trim().length>0?k(e):"COMMAND_FAILED",("string"==typeof n.error?.message?n.error.message:void 0)??"Runner error",{runner:n,xcodebuild:{exitCode:1,stdout:"",stderr:""},logPath:r})}return(t.ready=!0,t.lastSuccessfulRunnerResponseAtMs=Date.now(),n.data&&"object"==typeof n.data&&!Array.isArray(n.data))?n.data:{}}async function ae(e,t,r){let n=Date.now();try{return await r()}finally{let r=Date.now()-n;e[t]=r,eM({level:"debug",phase:`ios_runner_startup_${t}`,durationMs:r})}}let at=new h;function ar(e,t={}){return void 0!==an(e,t)}function an(e,t={}){let r=at.getStore();return r&&r.deviceId===e.id&&(r.requestId?r.requestId===t.requestId:!t.requestId)?r:void 0}async function aa(e,t,r){if(!e)return await r();let n={provider:ai(e),deviceId:t.deviceId,requestId:t.requestId};return await at.run(n,r)}function ai(e){return"function"==typeof e?{runCommand:e}:e}async function ao(e,t,r={}){if("ios"!==e.platform&&"macos"!==e.platform)throw new O("UNSUPPORTED_PLATFORM",`Unsupported platform for iOS runner: ${e.platform}`);if("simulator"!==e.kind&&"device"!==e.kind)throw new O("UNSUPPORTED_OPERATION",`Unsupported iOS device kind for runner: ${e.kind}`);rF(r.requestId);let n=function(e,t,r,n={}){if(r)return ai(r);let a=an(e,n);return a?ai(a.provider):ai(t)}(e,{runCommand:as},void 0,{requestId:r.requestId});return rT(t.command)?U(()=>(rF(r.requestId),n.runCommand(e,t,r)),{shouldRetry:e=>(rF(r.requestId),rC(e))}):n.runCommand(e,t,r)}async function as(e,t,r){let n;rF(r.requestId);let a=rc(r.requestId);try{let i=((n=await nZ(e,r)).ready,45e3);return await n9(e,n,t,r.logPath,i,a)}catch(o){let i=o instanceof O?o:new O("COMMAND_FAILED",String(o));if("COMMAND_FAILED"===i.code&&"string"==typeof i.message&&i.message.includes("Runner did not accept connection")&&rE(i)&&n){rF(r.requestId),await n0(n,"runner_connect_failed_before_command_send"),n=await nZ(e,{...r,cleanStaleBundles:!0});try{return await n9(e,n,t,r.logPath,45e3,a)}catch(e){throw rC(e instanceof O?e:new O("COMMAND_FAILED",String(e)))&&await n0(n,"transport_error_after_retry_command_send"),e}}throw!n&&i.message.includes("Runner did not accept connection")&&await n2(e.id),n&&rC(i)&&await n0(n,"transport_error_after_command_send"),o}}function al(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}let au=["platform","device","udid","serial","out","verbose","metroHost","metroPort","bundleUrl","launchUrl","snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw",...e1,"relaunch","saveScript","noRecord","fps","quality","hideTouches","count","intervalMs","delayMs","holdMs","jitterPx","doubleTap","clickButton","pauseMs","pattern"];function ad(e){let t=e.result?.text;if("string"==typeof t&&t.trim().length>0)return t;let r=e.positionals??[];if(0===r.length)return"";let n=r[0];return n?.startsWith("@")?r.length>=3?r.slice(2).join(" ").trim():r.slice(1).join(" ").trim():!(r.length>=3)||Number.isNaN(Number(r[0]))||Number.isNaN(Number(r[1]))?r.slice(1).join(" ").trim():r.slice(2).join(" ").trim()}function ac(e){let t=new Set,r=[];for(let n of e)t.has(n)||(t.add(n),r.push(n));return r}let ap=/^-?\d+(\.\d+)?$/,af=/^[^\s"\\]+$/,am=new Map([["--count","count"],["--interval-ms","intervalMs"],["--hold-ms","holdMs"],["--jitter-px","jitterPx"]]),ah=new Map([["--count","count"],["--pause-ms","pauseMs"]]),aw=new Map([["--delay-ms","delayMs"]]);function ag(e){return"click"===e||"press"===e}function ay(e){return ag(e)||"longpress"===e}function av(e){return"type"===e||"fill"===e}function aI(e){return aA(e,aS)}function ab(e){return JSON.stringify(e)}function aA(e,t){return t(e)?e:ab(e)}function aS(e){return a_(e)&&e.startsWith("@")||ap.test(e)}function a_(e){return af.test(e)}function ax(e,t){let r=t.flags??{};if(ag(t.command)){"number"==typeof r.count&&e.push("--count",String(r.count)),"number"==typeof r.intervalMs&&e.push("--interval-ms",String(r.intervalMs)),"number"==typeof r.holdMs&&e.push("--hold-ms",String(r.holdMs)),"number"==typeof r.jitterPx&&e.push("--jitter-px",String(r.jitterPx)),!0===r.doubleTap&&e.push("--double-tap");let t=r.clickButton;t&&"primary"!==t&&e.push("--button",t);return}if("swipe"===t.command){"number"==typeof r.count&&e.push("--count",String(r.count)),"number"==typeof r.pauseMs&&e.push("--pause-ms",String(r.pauseMs)),("one-way"===r.pattern||"ping-pong"===r.pattern)&&e.push("--pattern",r.pattern);return}av(t.command)&&"number"==typeof r.delayMs&&e.push("--delay-ms",String(r.delayMs))}function aN(e,t){t&&(("ios"===t.platform||"android"===t.platform)&&e.push("--platform",t.platform),"string"==typeof t.metroHost&&t.metroHost.length>0&&e.push("--metro-host",aA(t.metroHost,a_)),"number"==typeof t.metroPort&&e.push("--metro-port",String(t.metroPort)),"string"==typeof t.bundleUrl&&t.bundleUrl.length>0&&e.push("--bundle-url",aA(t.bundleUrl,a_)),"string"==typeof t.launchUrl&&t.launchUrl.length>0&&e.push("--launch-url",aA(t.launchUrl,a_)))}function aM(e,t){let r=[],n={},a=ag(e)?am:"swipe"===e?ah:av(e)?aw:void 0;for(let i=0;i<t.length;i+=1){let o=t[i];if(ag(e)&&"--double-tap"===o){n.doubleTap=!0;continue}let s=t[i+1];if(ag(e)&&"--button"===o&&void 0!==s){("primary"===s||"secondary"===s||"middle"===s)&&(n.clickButton=s),i+=1;continue}let l=a?.get(o);if(l&&void 0!==s){let e=aD(s);if(null!==e){n[l]=e,i+=1;continue}}if("swipe"===e&&"--pattern"===o&&void 0!==s){("one-way"===s||"ping-pong"===s)&&(n.pattern=s),i+=1;continue}r.push(o)}return{positionals:r,flags:n}}function ak(e){let t=[],r={};for(let n=0;n<e.length;n+=1){let a=e[n],i=e[n+1];if("--platform"===a&&void 0!==i){("ios"===i||"android"===i)&&(r.platform=i),n+=1;continue}if("--metro-host"===a&&void 0!==i){r.metroHost=i,n+=1;continue}if("--metro-port"===a&&void 0!==i){let e=aD(i);null!==e&&(r.metroPort=e),n+=1;continue}if("--bundle-url"===a&&void 0!==i){r.bundleUrl=i,n+=1;continue}if("--launch-url"===a&&void 0!==i){r.launchUrl=i,n+=1;continue}t.push(a)}return{positionals:t,flags:r}}function aD(e){if(!e)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}function aP(e,t={}){let r=[e.command];if("snapshot"===e.command)e.flags?.snapshotInteractiveOnly&&r.push("-i"),e.flags?.snapshotCompact&&r.push("-c"),"number"==typeof e.flags?.snapshotDepth&&r.push("-d",String(e.flags.snapshotDepth)),e.flags?.snapshotScope&&r.push("-s",aI(e.flags.snapshotScope)),e.flags?.snapshotRaw&&r.push("--raw");else if("open"===e.command){for(let t of e.positionals??[])r.push(aI(t));e.flags?.relaunch&&r.push("--relaunch"),aN(r,e.runtime)}else if("runtime"===e.command)!function(e,t,r={}){let n=t.positionals??[];for(let t of r.includeAllPositionals?n:n.slice(0,1))e.push(aA(t,a_));aN(e,t.flags)}(r,e,{includeAllPositionals:t.runtimeIncludeAllPositionals});else if("record"===e.command)!function(e,t){let[r,...n]=t.positionals??[];for(let t of(r&&e.push(aA(r,a_)),n))e.push(aI(t));"number"==typeof t.flags?.fps&&e.push("--fps",String(t.flags.fps)),"number"==typeof t.flags?.quality&&e.push("--quality",String(t.flags.quality)),t.flags?.hideTouches&&e.push("--hide-touches")}(r,e);else if("screenshot"===e.command){for(let t of e.positionals??[])r.push(aI(t));eT(r,e.flags)}else{for(let t of e.positionals??[])r.push(aI(t));ax(r,e)}return r.join(" ")}class aO{sessionsDir;constructor(e){this.sessionsDir=e}write(e){let t;try{if(!e.recordSession)return{written:!1};t=this.resolveScriptPath(e);let r=f.dirname(t);l.existsSync(r)||l.mkdirSync(r,{recursive:!0});let n=function(e){var t=e,r=function(e){let t=[];for(let r of e.actions){if("snapshot"===r.command)continue;let n=function(e){let t=function(e){let t=Array.isArray(e.result?.selectorChain)&&e.result.selectorChain.every(e=>"string"==typeof e)?e.result.selectorChain:[];return t.length>0?t.join(" || "):void 0}(e);if(t&&aR(e.command))return ag(e.command)?{...e,positionals:[t]}:"longpress"===e.command?function(e,t){let r="number"==typeof e.result?.durationMs?String(e.result.durationMs):function(e){let t=e.at(-1);if(!(e.length<=1)&&void 0!==t&&""!==t.trim())return Number.isFinite(Number(t))?t:void 0}(e.positionals??[]);return{...e,positionals:r?[t,r]:[t]}}(e,t):"fill"===e.command?function(e,t){let r=ad(e);return r.length>0?{...e,positionals:[t,r]}:void 0}(e,t):function(e,t){let r=e.positionals?.[0];return"text"===r||"attrs"===r?{...e,positionals:[r,t]}:void 0}(e,t)}(r);if(n){t.push(n);continue}let a=function(e,t){if(!aR(t.command))return;let r=t.result?.refLabel;if("string"!=typeof r||0===r.trim().length)return;let n=r.trim();return{ts:t.ts,command:"snapshot",positionals:[],flags:{platform:e.device.platform,snapshotInteractiveOnly:!0,snapshotCompact:!0,snapshotScope:n},result:{scope:n}}}(e,r);a&&t.push(a),t.push(r)}return t}(e);let n=[],a=t.device.kind?` kind=${t.device.kind}`:"";for(let e of(n.push(`context platform=${t.device.platform} device=${ab(t.device.name)}${a} theme=unknown`),r))e.flags?.noRecord||n.push(function(e){var t,r;let n=(t=[e.command],r=e,ag(r.command)?function(e,t){let r=t.positionals?.[0];if(r){if(r.startsWith("@"))return e.push(aI(r)),aC(e,t),ax(e,t),e.join(" ");if(1===t.positionals.length)return e.push(aI(r)),ax(e,t),e.join(" ")}}(t,r):"fill"===r.command?function(e,t){let r=t.positionals?.[0];if(!r?.startsWith("@"))return;e.push(aI(r)),aC(e,t);let n=t.positionals.slice(1).join(" ");return t.positionals.length>1&&e.push(aI(n)),ax(e,t),e.join(" ")}(t,r):"get"===r.command?function(e,t){let r=t.positionals?.[0],n=t.positionals?.[1];if(r&&n)return e.push(aI(r)),e.push(aI(n)),n.startsWith("@")&&aC(e,t),e.join(" ")}(t,r):void 0);return n||aP(e)}(e));return`${n.join("\n")}
8
- `}(e);return l.writeFileSync(t,n),{written:!0,path:t}}catch(r){return eM({level:"warn",phase:"session_script_write_failed",data:{session:e.name,path:t,error:r instanceof Error?r.message:String(r)}}),{written:!1}}}resolveScriptPath(e){if(e.saveScriptPath)return e3(e.saveScriptPath,{cwd:void 0});l.existsSync(this.sessionsDir)||l.mkdirSync(this.sessionsDir,{recursive:!0});let t=al(e.name),r=new Date(e.createdAt).toISOString().replace(/[:.]/g,"-");return f.join(this.sessionsDir,`${t}-${r}.ad`)}}function aR(e){return ay(e)||"fill"===e||"get"===e}function aC(e,t){let r=t.result?.refLabel;"string"==typeof r&&r.trim().length>0&&e.push(aI(r))}class aE{sessions=new Map;runtimeHints=new Map;sessionsDir;scriptWriter;constructor(e){this.sessionsDir=e,this.scriptWriter=new aO(e)}get(e){return this.sessions.get(e)}has(e){return this.sessions.has(e)}set(e,t){this.sessions.set(e,t)}delete(e){return this.runtimeHints.delete(e),this.sessions.delete(e)}values(){return this.sessions.values()}toArray(){return Array.from(this.sessions.values())}getRuntimeHints(e){return this.runtimeHints.get(e)}setRuntimeHints(e,t){this.runtimeHints.set(e,t)}clearRuntimeHints(e){return this.runtimeHints.delete(e)}recordAction(e,t){t.flags?.noRecord||(t.flags?.saveScript&&(e.recordSession=!0,"string"==typeof t.flags.saveScript&&(e.saveScriptPath=e3(t.flags.saveScript,{cwd:void 0}))),e.actions.push({ts:Date.now(),command:t.command,positionals:t.positionals,runtime:t.runtime,flags:function(e){if(!e)return{};let t={};for(let r of au)void 0!==e[r]&&(t[r]=e[r]);return t}(t.flags),result:t.result}),eM({level:"debug",phase:"record_action",data:{command:t.command,session:e.name}}))}writeSessionLog(e){let t=this.scriptWriter.write(e);t.written&&eM({level:"info",phase:"session_script_written",data:{session:e.name,path:t.path}})}defaultTracePath(e){let t=al(e.name),r=new Date().toISOString().replace(/[:.]/g,"-");return f.join(this.sessionsDir,`${t}-${r}.trace.log`)}resolveAppLogPath(e){return f.join(this.sessionsDir,al(e),"app.log")}resolveAppLogPidPath(e){return f.join(this.sessionsDir,al(e),"app-log.pid")}static expandHome(e,t){return e3(e,{cwd:t})}}let aL="app-log.pid";function a$(e){let t=e.trim();if(!t)return null;if(/^\d+$/.test(t))return{pid:Number.parseInt(t,10)};try{let e=JSON.parse(t);if(!Number.isInteger(e.pid)||e.pid<=0)return null;return e}catch{return null}}function aT(e,t){if(!e)return;let r=f.dirname(e);l.existsSync(r)||l.mkdirSync(r,{recursive:!0});let n={pid:t,startTime:eh(t)??void 0,command:eg(t)??void 0};l.writeFileSync(e,`${JSON.stringify(n)}
9
- `)}function aF(e){if(e&&l.existsSync(e))try{l.unlinkSync(e)}catch{}}async function aU(e,t=2e3){await Promise.race([e.then(()=>void 0).catch(()=>void 0),new Promise(e=>setTimeout(e,t))])}function aV(e,t){let r=t.includeTokens?.filter(e=>e.length>0)??[],n="",a=n=>{(!(r.length>0)||r.some(e=>n.includes(e)))&&e.write(function(e,t){if(0===t.length)return e;let r=e;for(let e of t)r=r.replace(e,"[REDACTED]");return r}(n,t.redactionPatterns))};return{onChunk:e=>{let t=`${n}${e}`.split("\n");for(let e of(n=t.pop()??"",t))a(`${e}
10
- `)},flush:()=>{n&&(a(n),n="")}}}function aG(e,t,r){let n=e.stdout,a=e.stderr;return n&&a?(n.setEncoding("utf8"),a.setEncoding("utf8"),n.on("data",r.writer.onChunk),a.on("data",r.writer.onChunk),t.on("error",()=>{e.killed||e.kill("SIGKILL")}),e.on("error",()=>t.destroy()),new Promise(n=>{e.on("close",e=>{r.writer.flush(),r.endStreamOnClose&&t.end(),n({stdout:"",stderr:"",exitCode:e??1})})})):Promise.resolve({stdout:"",stderr:"missing stdio pipes",exitCode:1})}function aq(e){if(!/^[a-zA-Z0-9._:-]+$/.test(e))throw new O("INVALID_ARGS",`Invalid Android package name for logs: ${e}`)}async function aj(e,t){let r=(await e7(J(e))(["shell","pidof",t],{allowFailure:!0})).stdout.trim().split(/\s+/)[0];return r&&/^\d+$/.test(r)?r:null}async function aB(e,t){var r,n;let a;aq(t);let i=await aj(e,t),o=e7(J(e)),s=await X(o,{lines:4e3,timeoutMs:3e3}).catch(()=>"");if(0===s.trim().length)return null;let l=function(e,t,r){let n=new Set;for(let a of(r&&n.add(r),e.split("\n")))if(a.includes(t))for(let e of function(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=[RegExp(`\\bStart proc\\s+(\\d+):${r}(?:\\b|/)`,"i"),RegExp(`\\b(\\d+):${r}(?:\\b|/)`,"i"),RegExp(`${r}.*?\\bpid\\s*[=:]?\\s*(\\d+)\\b`,"i"),RegExp(`\\bpid\\s*[=:]?\\s*(\\d+)\\b.*${r}`,"i")],a=[];for(let t of n){let r=t.exec(e),n=r?.[1];n&&/^\d+$/.test(n)&&a.push(n)}return a}(a,t))n.add(e);return[...n]}(s,t,i);if(0===l.length)return null;let u=(r=s,n=t,a=new Set(l),r.split("\n").filter(e=>{var t;let r;if(!e.trim())return!1;if(e.includes(n))return!0;let i=(t=e,r=/\(\s*(\d+)\)\s*:/.exec(t),r?.[1]??null);return!!i&&a.has(i)}).join("\n"));return 0===u.trim().length?null:{pid:i,text:u,recoveredPids:l}}async function aH(e,t,r,n,a){let i,o,s="recovering",l=!1,u=(async()=>{try{for(;!l;){let u=await aj(e,t);if(!u){s="recovering",await e2(1e3);continue}let d=e6(J(e)),c=j(d,{pid:u});i=c;let p=aV(r,{redactionPatterns:n});if(o=aG(c,r,{endStreamOnClose:!1,writer:p}),"number"==typeof c.pid&&aT(a,c.pid),s="active",await o,aF(a),i=void 0,o=void 0,l)break;s="recovering",await e2(500)}return{stdout:"",stderr:"",exitCode:0}}finally{r.end(),aF(a)}})();return{backend:"android",getState:()=>s,startedAt:Date.now(),wait:u,stop:async()=>{l=!0,i&&!i.killed&&i.kill("SIGINT"),o&&await aU(o),i&&!i.killed&&i.kill("SIGKILL"),await aU(u),aF(a)}}}function aW(e,t){let r=aJ(e),n=[`subsystem == "${r}"`,`subsystem CONTAINS "${r}"`,`processImagePath ENDSWITH[c] "/${r}"`,`senderImagePath ENDSWITH[c] "/${r}"`];if(t){let e=aJ(t);n.push(`process == "${e}"`,`processImagePath ENDSWITH[c] "/${e}"`,`senderImagePath ENDSWITH[c] "/${e}"`,`processImagePath CONTAINS[c] "/${e}.app/"`,`senderImagePath CONTAINS[c] "/${e}.app/"`)}return n.join(" OR ")}async function az(e){let{deviceId:t,appBundleId:r,executableName:n,startedAt:a,simulatorSetPath:i}=e,o=rP(["spawn",t,"log","show","--style","compact","--info","--predicate",aW(r,n)],{simulatorSetPath:i});"number"==typeof a&&Number.isFinite(a)&&a>0?o.push("--start",`@${Math.floor(a/1e3)}`):o.push("--last","5m");let s=await rM(o,{allowFailure:!0,timeoutMs:4e3});if(0!==s.exitCode||0===s.stdout.trim().length)return null;let l=s.stdout.split("\n").map(e=>e.trimEnd()).filter(e=>{let t=e.trim();return t.length>0&&!t.startsWith("Timestamp Ty Process[PID:TID]")});return 0===l.length?null:{text:`${l.join("\n")}
11
- `,recoveredLineCount:l.length}}async function aK(e,t,r,n,a,i){let o=await aX({deviceId:e,appBundleId:t,simulatorSetPath:a});return aQ({backend:"ios-simulator",cmd:"xcrun",args:function(e){let{deviceId:t,appBundleId:r,executableName:n,simulatorSetPath:a}=e;return rP(["spawn",t,"log","stream","--style","compact","--level","info","--predicate",aW(r,n)],{simulatorSetPath:a})}({deviceId:e,appBundleId:t,executableName:o,simulatorSetPath:a}),stream:r,redactionPatterns:n,pidPath:i})}function aJ(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}async function aX(e){let{deviceId:t,appBundleId:r,simulatorSetPath:n}=e,a=await rM(rP(["get_app_container",t,r,"app"],{simulatorSetPath:n}),{allowFailure:!0,timeoutMs:4e3});if(0!==a.exitCode)return;let i=a.stdout.trim();if(!i)return;let o=f.join(i,"Info.plist"),s=await E("plutil",["-extract","CFBundleExecutable","raw","-o","-",o],{allowFailure:!0,timeoutMs:4e3});if(0===s.exitCode)return s.stdout.trim()||void 0}async function aY(e,t,r,n){return aQ({backend:"macos",cmd:"log",args:["stream","--style","compact","--predicate",aW(e)],stream:t,redactionPatterns:r,pidPath:n})}async function aZ(e,t,r,n){return aQ({backend:"ios-device",cmd:"xcrun",args:["devicectl","device","log","stream","--device",e],stream:t,redactionPatterns:r,pidPath:n})}function aQ(e){let t="active",r=R(e.cmd,e.args,{allowFailure:!0,captureOutput:!1});r.wait.catch(()=>{});let n=r.child,a=aV(e.stream,{redactionPatterns:e.redactionPatterns});"number"==typeof n.pid&&aT(e.pidPath,n.pid);let i=aG(n,e.stream,{endStreamOnClose:!0,writer:a}).then(r=>(0!==r.exitCode&&(t="failed"),aF(e.pidPath),r),r=>{throw t="failed",aF(e.pidPath),r});return{backend:e.backend,getState:()=>t,startedAt:Date.now(),wait:i,stop:async()=>{n.killed||n.kill("SIGINT"),await aU(i),n.killed||n.kill("SIGKILL"),await aU(i),aF(e.pidPath)}}}let a0=RegExp("\\b(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\\b\\s+https?:\\/\\/","i"),a1=/https?:\/\/[^\s"'<>\])]+/i,a2=[/\bstatus(?:Code)?["'=: ]+([1-5]\d{2})\b/i,/\bresponse(?:\s+code)?["'=: ]+([1-5]\d{2})\b/i,/\bHTTP\/[0-9.]+\s+([1-5]\d{2})\b/i];function a3(e,t,r=e.limits.maxEntries){let n=[...e.entries],a=new Set(n.map(e=>a4(e)));for(let e of t.entries){let t=a4(e);if(!a.has(t)&&(a.add(t),n.push(e),n.length>=r))break}return{...e,matchedLines:n.length,entries:n}}function a5(e,t){let r=io(t?.maxEntries,25,1,200),n=t?.backend,a=t?.include??"summary",i=io(t?.maxPayloadChars,2048,64,16384),o=io(t?.maxScanLines,4e3,100,2e4),s=e.split("\n"),l=Math.max(0,s.length-o),u=s.slice(l),d=[];for(let e=u.length-1;e>=0&&d.length<r;e-=1){let t=u[e];if(!t?.trim())continue;let r=function(e,t,r,n,a,i){let o=e[t]?.trim();if(!o)return null;let s=function(e){let t=e.indexOf("{");if(t<0)return null;let r=e.lastIndexOf("}");if(r<=t)return null;let n=e.slice(t,r+1);try{let e=JSON.parse(n);return e&&"object"==typeof e?e:null}catch{return null}}(o),l=it(s,["method","httpMethod"]),u=it(s,["url","requestUrl"]),d=function(e,t){if(!e)return null;for(let r of t){let t=e[r];if("number"==typeof t&&Number.isInteger(t))return t;if("string"==typeof t&&/^\d{3}$/.test(t.trim()))return Number.parseInt(t.trim(),10)}return null}(s,["status","statusCode","responseCode"]),c=a0.exec(o),p=/\bmethod["'=: ]+([A-Z]+)\b/i.exec(o),f=(l??p?.[1]??c?.[1])?.toUpperCase(),m=a1.exec(o),h=u??m?.[0];if(!h)return null;let w=d??a6(o)??void 0;if(!(l||p?.[1]||c?.[1]||void 0!==w||/\bURL["'=: ]+https?:\/\//i.test(o)||/\bheaders?["'=: ]+/i.test(o)||/\b(?:requestBody|responseBody|payload|request|response)["'=: ]+/i.test(o)))return null;let g={method:f,url:h,status:w,timestamp:a9(o),packetId:a7(o)??void 0,durationMs:ie(o)??void 0,raw:ii(o,i),line:r};if("android"===n&&function(e,t,r){let n=a8(t,r,5),a=e.packetId??n.map(e=>a7(e)).find(e=>"string"==typeof e&&e.length>0);a&&(e.packetId=a);let i=a?a8(t,r,12).filter(e=>a7(e)===a):n;e.timestamp||(e.timestamp=i.map(e=>a9(e)).find(e=>"string"==typeof e&&e.length>0)),void 0===e.status&&(e.status=i.map(e=>a6(e)).find(e=>"number"==typeof e)),void 0===e.durationMs&&(e.durationMs=i.map(e=>ie(e)).find(e=>"number"==typeof e))}(g,e,t),"headers"===a||"all"===a){let e=function(e,t){if(t){let e=t.headers??t.requestHeaders??t.responseHeaders;if(void 0!==e)return ia(e)}let r=/\bheaders?["'=: ]+(\{.*\})/i.exec(e);return r?.[1]?.trim()}(o,s);e&&(g.headers=ii(e,i))}if("body"===a||"all"===a){let e=ir(o,s,["requestBody","body","payload","request"]),t=ir(o,s,["responseBody","response"]);e&&(g.requestBody=ii(e,i)),t&&(g.responseBody=ii(t,i))}return g}(u,e,l+e+1,n,a,i);r&&d.push(r)}return{path:t?.path??"<memory>",exists:!0,scannedLines:u.length,matchedLines:d.length,entries:d,include:a,limits:{maxEntries:r,maxPayloadChars:i,maxScanLines:o}}}function a4(e){return`${e.timestamp??""}|${e.method??""}|${e.url}|${e.status??""}|${e.raw}`}function a8(e,t,r){let n=[],a=Math.max(0,t-r),i=Math.min(e.length-1,t+r);for(let t=a;t<=i;t+=1){let r=e[t]?.trim();r&&n.push(r)}return n}function a6(e){for(let t of a2){let r=t.exec(e);if(!r)continue;let n=Number.parseInt(r[1]??"",10);if(Number.isInteger(n))return n}return null}function a9(e){let t=/\b\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z)?\b/.exec(e);if(t)return t[0];let r=/\b\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+\b/.exec(e);return r?.[0]}function a7(e){let t=/\bpacket id (\d+)\b/i.exec(e);return t?.[1]??null}function ie(e){let t=/\b(?:duration|elapsed request\/response time, ms)[:= ]+(\d+)\b/i.exec(e);if(!t)return null;let r=Number.parseInt(t[1]??"",10);return Number.isInteger(r)?r:null}function it(e,t){if(e)for(let r of t){let t=e[r];if("string"==typeof t&&t.trim().length>0)return t.trim()}}function ir(e,t,r){if(t){for(let e of r)if(void 0!==t[e])return ia(t[e])}for(let t of r){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=RegExp(`\\b${r}["'=: ]+(.+)$`,"i").exec(e);if(n?.[1])return n[1].trim()}}function ia(e){if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}}function ii(e,t){return e.length<=t?e:`${e.slice(0,t)}...<truncated>`}function io(e,t,r,n){return void 0!==e&&Number.isInteger(e)?Math.max(r,Math.min(n,e)):t}let is={start:async e=>await iw(e)},il=rh(is,function(e={}){return{...is,...e}});async function iu(e,t){return await il.run(e,t)}function id(e,t){let r=process.env[e];if(!r)return t;let n=Number.parseInt(r,10);return Number.isInteger(n)&&n>0?n:t}function ic(e){let t=f.dirname(e);l.existsSync(t)||l.mkdirSync(t,{recursive:!0}),function(e,t){if(l.existsSync(e)&&!(l.statSync(e).size<t.maxBytes))for(let r=t.maxRotatedFiles;r>=1;r-=1){let t=1===r?e:`${e}.${r-1}`,n=`${e}.${r}`;l.existsSync(t)&&(l.existsSync(n)&&l.unlinkSync(n),l.renameSync(t,n))}}(e,{maxBytes:id("AGENT_DEVICE_APP_LOG_MAX_BYTES",5242880),maxRotatedFiles:id("AGENT_DEVICE_APP_LOG_MAX_FILES",1)})}async function ip(e){var t,r,n,a;let i,o,s,u,{device:d,appBundleId:c,appLogState:p,appLogStartedAt:f,appLogPath:m,maxEntries:h,include:w,maxPayloadChars:g,maxScanLines:y}=e,v="macos"===d.platform?"macos":"ios"===d.platform?"device"===d.kind?"ios-device":"ios-simulator":"android",I=(t={backend:v,maxEntries:h,include:w,maxPayloadChars:g,maxScanLines:y},i=io(t?.maxEntries,25,1,200),o=t?.include??"summary",s=io(t?.maxPayloadChars,2048,64,16384),u=io(t?.maxScanLines,4e3,100,2e4),l.existsSync(m)?a5(l.readFileSync(m,"utf8"),{...t,path:m}):{path:m,exists:!1,scannedLines:0,matchedLines:0,entries:[],include:o,limits:{maxEntries:i,maxPayloadChars:s,maxScanLines:u}}),b=[],A=await im({device:d,appBundleId:c,appLogPath:m,appLogState:p});if(A){let e=await aB(d.id,c);if(e){let t=a5(e.text,{path:`${m} (adb logcat recovery)`,backend:"android",maxEntries:h,include:w,maxPayloadChars:g,maxScanLines:y});t.entries.length>0&&(I=a3(t,I,h),b.push((r=A,n=e.recoveredPids,"stale-active"===r.reason?`Session app log stream was still bound to prior Android PID ${r.trackedPid}. Recovered recent Android HTTP entries from adb logcat for PID set ${n.join(", ")}.`:`Session app log stream was inactive. Recovered recent Android HTTP entries from adb logcat for PID set ${n.join(", ")}.`)))}}if("ios"===d.platform&&"simulator"===d.kind&&c&&0===I.entries.length){let e=await ig({deviceId:d.id,appBundleId:c,startedAt:f,simulatorSetPath:d.simulatorSetPath,appLogPath:m,maxEntries:h,include:w,maxPayloadChars:g,maxScanLines:y});e&&(e.dump.entries.length>0?(I=a3(e.dump,I,h),b.push(`Recovered ${e.dump.entries.length} iOS simulator HTTP entr${1===e.dump.entries.length?"y":"ies"} from simctl log show (${e.recoveredLineCount} app log lines scanned).`)):e.recoveredLineCount>0&&b.push(`Recovered ${e.recoveredLineCount} recent iOS simulator app log lines from simctl log show, but none looked like HTTP traffic. This app may not emit request URLs, status, or timing into Unified Logging for this repro window.`))}return void 0===p?b.push("Capture uses the session app log file. For fresh traffic, run logs clear --restart before reproducing requests."):"active"!==p&&0===b.length&&("ios"===d.platform&&"simulator"===d.kind?b.push("Session app log stream is inactive. The iOS simulator recovery path scanned recent simctl log history, but a fresh logs clear --restart window is still the most reliable repro loop."):b.push("Session app log stream is inactive. Run logs clear --restart, reproduce the request window again, then rerun network dump.")),0===I.entries.length&&b.push("ios"===(a=d).platform&&"simulator"===a.kind?"No HTTP(s) entries were found in recent iOS simulator app logs. If the app only emits non-HTTP diagnostics, inspect logs path or add app-side URLSession/network logging for per-request timing and payload details.":"ios"===a.platform?"No HTTP(s) entries were found in recent iOS device app logs. iOS network dump only sees what the app emits into Unified Logging for this process.":"No HTTP(s) entries were found in recent session app logs."),{backend:v,dump:I,notes:b}}async function im(e){let{device:t,appBundleId:r,appLogPath:n,appLogState:a}=e;if("android"!==t.platform||!r)return null;if(void 0!==a&&"active"!==a)return{reason:"inactive"};if("active"!==a)return null;let i=function(e){let t=function(e){if(!e||!l.existsSync(e))return null;try{return a$(l.readFileSync(e,"utf8"))}catch{return null}}(e)?.command;if(!t)return null;let r=/(?:^|\s)--pid\s+(\d+)(?:\s|$)/.exec(t);return r?.[1]??null}(f.join(f.dirname(n),aL));if(!i)return null;let o=await aj(t.id,r);return o&&o!==i?{reason:"stale-active",trackedPid:i}:null}async function ih(e,t,r,n){return await il.resolve(void 0).start({device:e,appBundleId:t,outPath:r,pidPath:n})}async function iw({device:e,appBundleId:t,outPath:r,pidPath:n}){ic(r);let a=l.createWriteStream(r,{flags:"a"}),i=function(){let e=process.env.AGENT_DEVICE_APP_LOG_REDACT_PATTERNS;if(!e)return[];let t=e.split(",").map(e=>e.trim()).filter(e=>e.length>0),r=[];for(let e of t)try{r.push(RegExp(e,"gi"))}catch{}return r}();if("ios"===e.platform)return"device"===e.kind?await aZ(e.id,a,i,n):await aK(e.id,t,a,i,e.simulatorSetPath,n);if("android"===e.platform)return aq(t),await aH(e.id,t,a,i,n);if("macos"===e.platform)return await aY(t,a,i,n);throw a.end(),new O("UNSUPPORTED_PLATFORM",`unsupported platform: ${e.platform}`)}async function ig(e){let t=await az({deviceId:e.deviceId,appBundleId:e.appBundleId,startedAt:e.startedAt,simulatorSetPath:e.simulatorSetPath});return t?{dump:a5(t.text,{path:`${e.appLogPath} (simctl log show recovery)`,backend:"ios-simulator",maxEntries:e.maxEntries,include:e.include,maxPayloadChars:e.maxPayloadChars,maxScanLines:e.maxScanLines}),recoveredLineCount:t.recoveredLineCount}:null}async function iy(e){await e.stop(),await aU(e.wait)}async function iv(e,t){let r={},n=[];if(t||n.push("No app bundle is tracked in this session. Run open <app> first for app-scoped logs."),"android"===e.platform){try{let t=await Q(e,["shell","echo","ok"],{allowFailure:!0,timeoutMs:1e3});r.adbAvailable=0===t.exitCode}catch{r.adbAvailable=!1}if(t)try{r.androidPidVisible=(await Q(e,["shell","pidof",t],{allowFailure:!0,timeoutMs:1e3})).stdout.trim().length>0}catch{r.androidPidVisible=!1}}if("ios"===e.platform&&"simulator"===e.kind)try{let e=await rM(["simctl","help"],{allowFailure:!0});r.simctlAvailable=0===e.exitCode}catch{r.simctlAvailable=!1}if("ios"===e.platform&&"device"===e.kind)try{let e=await rM(["devicectl","--version"],{allowFailure:!0});r.devicectlAvailable=0===e.exitCode}catch{r.devicectlAvailable=!1}if("macos"===e.platform)try{let e=await E("log",["help"],{allowFailure:!0});r.logAvailable=0===e.exitCode}catch{r.logAvailable=!1}return{checks:r,notes:n}}function iI(e){let t=f.dirname(e),r=f.basename(e);l.existsSync(t)||l.mkdirSync(t,{recursive:!0}),l.existsSync(e)?l.truncateSync(e,0):l.writeFileSync(e,"","utf8");let n=0;for(let e of l.readdirSync(t)){if(!e.startsWith(`${r}.`))continue;let a=e.slice(r.length+1);if(/^\d+$/.test(a))try{l.unlinkSync(f.join(t,e)),n+=1}catch{}}return{path:e,cleared:!0,removedRotatedFiles:n}}let ib=new Map;function iA(e){let t=o.randomUUID(),r=setTimeout(()=>{iS(t)},9e5);return r.unref(),ib.set(t,{artifactPath:e.artifactPath,tenantId:e.tenantId,fileName:e.fileName,deleteAfterDownload:!1!==e.deleteAfterDownload,timer:r}),t}function iS(e){let t=ib.get(e);if(t&&(clearTimeout(t.timer),ib.delete(e),t.deleteAfterDownload))try{l.rmSync(t.artifactPath,{force:!0})}catch{}}let i_=new Map;function ix(e,t){let r=i_.get(e);if(!r)throw new O("INVALID_ARGS",`Uploaded artifact not found: ${e}`);if(r.tenantId&&r.tenantId!==t)throw new O("UNAUTHORIZED","Uploaded artifact belongs to a different tenant");return clearTimeout(r.timer),r.artifactPath}function iN(e){let t=i_.get(e);t&&(clearTimeout(t.timer),i_.delete(e),l.rmSync(t.tempDir,{recursive:!0,force:!0}))}async function iM(e){let t=await ik(e);await E("tar",["xf",e.archivePath,"-C",e.tempDir]);let r=f.join(e.tempDir,t);if(!l.existsSync(r))throw new O("INVALID_ARGS",`Expected extracted bundle "${t}" not found in archive`);return r}async function ik(e){let t=await E("tar",["-tf",e.archivePath],{allowFailure:!0});if(0!==t.exitCode)throw new O("INVALID_ARGS","Artifact is not a valid tar archive",{archivePath:e.archivePath,stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});let r=t.stdout.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);if(0===r.length)throw new O("INVALID_ARGS","Uploaded app bundle archive is empty");let n=r.map(iD),a=e.expectedRootName??function(e,t){let r=new Set;for(let t of e){let[e]=t.split("/");e&&r.add(e)}let n=[...r];if("ios"===t){let e=n.filter(e=>e.toLowerCase().endsWith(".app")),t=e[0];if(void 0!==t&&1===e.length)return t;if(0===e.length)throw new O("INVALID_ARGS","iOS app bundle archives must contain a single top-level .app directory");throw new O("INVALID_ARGS",`iOS app bundle archives must contain exactly one top-level .app directory, found: ${e.join(", ")}`)}let a=n[0];if(void 0!==a&&1===n.length)return a;throw new O("INVALID_ARGS",`Archive must contain a single top-level bundle, found: ${n.join(", ")}`)}(n,e.platform);if(!n.some(e=>e===a||e.startsWith(`${a}/`)))throw new O("INVALID_ARGS",`Uploaded archive must contain a top-level "${a}" bundle`);for(let e of n){var i=e,o=a;if(i!==o&&!i.startsWith(`${o}/`))throw new O("INVALID_ARGS",`Archive entry must stay inside top-level "${o}" bundle: ${i}`)}for(let t of(await E("tar",["-tvf",e.archivePath])).stdout.split(/\r?\n/).filter(Boolean))if("l"===t[0]||"h"===t[0])throw new O("INVALID_ARGS","Uploaded app bundle archive cannot contain symlinks or hard links");return a}function iD(e){if(e.includes("\0"))throw new O("INVALID_ARGS",`Invalid archive entry: ${e}`);if(f.posix.isAbsolute(e))throw new O("INVALID_ARGS",`Archive entry must be relative: ${e}`);let t=f.posix.normalize(e).replace(/^(\.\/)+/,"");if(!t||"."===t||t.startsWith("../"))throw new O("INVALID_ARGS",`Archive entry escapes bundle root: ${e}`);return t}function iP(e,t){return new Promise((r,n)=>{let a,i=!1,o=0,s=l.createWriteStream(t),u=e=>{if(!i){if(i=!0,a&&clearTimeout(a),e)return void iO(s,t).finally(()=>n(e));r()}},d=()=>{a&&clearTimeout(a),a=setTimeout(()=>{let t=new O("COMMAND_FAILED","Artifact transfer timed out due to inactivity",{timeoutMs:6e4});"destroy"in e&&"function"==typeof e.destroy&&e.destroy(t),c.destroy(t),u(t)},6e4)},c=new b({transform(e,t,r){d();let n=Buffer.isBuffer(e)?e.length:Buffer.byteLength(e,t);(o+=n)>0x80000000?r(new O("INVALID_ARGS","Upload exceeds maximum size of 2147483648 bytes")):r(null,e)}});e.on("aborted",()=>{u(new O("COMMAND_FAILED","Artifact transfer was interrupted"))}),d(),A(e,c,s).then(()=>u(),e=>u(e))})}async function iO(e,t){if(e.destroy(),!e.closed)try{await I(e,"close")}catch{}await l.promises.rm(t,{force:!0}).catch(()=>{})}async function iR(e){let t,r=e.headers["x-artifact-type"],n=e.headers["x-artifact-filename"];if(!r||!n)throw new O("INVALID_ARGS","Missing required headers: x-artifact-type and x-artifact-filename");if("file"!==r&&"app-bundle"!==r)throw new O("INVALID_ARGS",`Invalid x-artifact-type: ${r}. Must be "file" or "app-bundle".`);!function(e){if(void 0===e)return;let t=Number(e);if(Number.isFinite(t)&&t>0x80000000)throw new O("INVALID_ARGS","Upload exceeds maximum size of 2147483648 bytes")}(e.headers["content-length"]);let a=function(e){let t=e.trim(),r=f.basename(t);if(!r||"."===r||".."===r)throw new O("INVALID_ARGS",`Invalid artifact filename: ${e}`);return r}(n),i=(t=function(e){let t=e?.trim();if(!t)return"request";let r=t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");return r.length>0?r.slice(0,48):"request"}("upload"),l.mkdtempSync(f.join(c.tmpdir(),`agent-device-artifact-${t}-`)));try{if("file"===r){let t=f.join(i,a);return await iP(e,t),{artifactPath:t,tempDir:i}}let t=f.join(i,"artifact.tar");await iP(e,t);let n=await iM({archivePath:t,tempDir:i,platform:"ios",expectedRootName:a});return l.rmSync(t,{force:!0}),{artifactPath:n,tempDir:i}}catch(e){throw l.rmSync(i,{recursive:!0,force:!0}),e}}let iC=new Set(["agent_device.command","agent-device.command"]),iE=new Set(["agent_device.install_from_source","agent-device.install_from_source"]),iL=new Set(["agent_device.release_materialized_paths","agent-device.release_materialized_paths"]),i$={"agent_device.lease.allocate":"lease_allocate","agent-device.lease.allocate":"lease_allocate","agent_device.lease.heartbeat":"lease_heartbeat","agent-device.lease.heartbeat":"lease_heartbeat","agent_device.lease.release":"lease_release","agent-device.lease.release":"lease_release"},iT=new Set([...iC,...iE,...iL,...Object.keys(i$)]);function iF(e,t,r,n){return{jsonrpc:"2.0",id:e,error:{code:t,message:r,data:n}}}function iU(e,t,r=200){e.statusCode=r,e.setHeader("content-type","application/json"),e.end(JSON.stringify(t))}function iV(e){switch(e){case"INVALID_ARGS":return 400;case"UNAUTHORIZED":return 401;case"SESSION_NOT_FOUND":return 404;default:return 500}}function iG(e,t){let r="string"==typeof t.authorization?t.authorization:"",n=r.toLowerCase().startsWith("bearer ")?r.slice(7):void 0,a="string"==typeof t["x-agent-device-token"]?t["x-agent-device-token"]:void 0;return("string"==typeof e.token?e.token:void 0)??a??n??""}function iq(e,t){let r=e[t];return"string"==typeof r?r:void 0}function ij(e,t){let r=e[t];return Number.isInteger(r)?Number(r):void 0}function iB(e,t){let r="string"==typeof e[t]?e[t].trim():"";if(!r)throw new O("INVALID_ARGS",`Invalid params: source.${t} is required for github-actions-artifact sources`);return r}function iH(e,t){let r=e[t],n="number"==typeof r?r:"string"==typeof r?Number(r):NaN;if(!Number.isInteger(n))throw new O("INVALID_ARGS",`Invalid params: source.${t} must be an integer`);return n}async function iW(e,t){if(!e)return{ok:!0};let r=await e(t);if(void 0===r||!0===r)return{ok:!0};if(!1===r){let e=P(new O("UNAUTHORIZED","Request rejected by auth hook"));return{ok:!1,statusCode:401,response:iF(t.rpcRequest.id??null,-32001,e.message,e)}}if(!1===r.ok){let e=P(new O(k(r.code,"UNAUTHORIZED"),r.message??"Request rejected by auth hook",r.details));return{ok:!1,statusCode:401,response:iF(t.rpcRequest.id??null,-32001,e.message,e)}}if("string"==typeof r.tenantId&&r.tenantId.length>0){let e=eO(r.tenantId);if(!e){let e=P(new O("INVALID_ARGS","Auth hook returned invalid tenantId"));return{ok:!1,statusCode:500,response:iF(t.rpcRequest.id??null,-32e3,e.message,e)}}return{ok:!0,tenantId:e}}return{ok:!0}}async function iz(){let e,t=process.env.AGENT_DEVICE_HTTP_AUTH_HOOK;if(!t)return null;let r=process.env.AGENT_DEVICE_HTTP_AUTH_EXPORT||"default",n=f.isAbsolute(t)?t:f.resolve(t);try{e=await import(v(n).href)}catch(e){throw new O("COMMAND_FAILED","Failed to load AGENT_DEVICE_HTTP_AUTH_HOOK module",{hookPath:n,error:e instanceof Error?e.message:String(e)})}let a=e[r];if("function"!=typeof a)throw new O("INVALID_ARGS",`Auth hook export ${r} is not a function`,{hookPath:n,exportName:r});return a}async function iK(e){let t=await iz(),{handleRequest:r,token:n}=e;return g.createServer((e,a)=>{if("GET"===e.method&&"/health"===e.url){a.statusCode=200,a.setHeader("content-type","application/json"),a.end(JSON.stringify({ok:!0}));return}if("POST"===e.method&&"/upload"===e.url)return void iJ(e,a,t,n);if("GET"===e.method&&e.url?.startsWith("/artifacts/"))return void iX(e,a,t,n);if("POST"!==e.method||"/rpc"!==e.url){a.statusCode=404,a.end("Not found");return}let i="";e.setEncoding("utf8"),e.on("data",t=>{(i+=t).length>1048576&&e.destroy(Error("request too large"))}),e.on("error",()=>{a.headersSent||iU(a,iF(null,-32700,"Parse error"),400)}),e.on("end",async()=>{let n,o;try{n=JSON.parse(i)}catch{iU(a,iF(null,-32700,"Parse error"),400);return}if("2.0"!==n.jsonrpc||"string"!=typeof n.method)return void iU(a,iF(n.id??null,-32600,"Invalid Request"),400);if(!iT.has(n.method))return void iU(a,iF(n.id??null,-32601,`Method not found: ${n.method}`),404);if(!n.params||"object"!=typeof n.params)return void iU(a,iF(n.id??null,-32602,"Invalid params"),400);try{var s;let i=n.params,l=function(e,t,r){if(iC.has(e))return{token:iG(t,r),session:t.session??"default",command:t.command??"",positionals:Array.isArray(t.positionals)?t.positionals:[],flags:t.flags,runtime:t.runtime,meta:t.meta};if(iE.has(e)){let e,n=iq(t,"platform");if("ios"!==n&&"android"!==n)throw new O("INVALID_ARGS",'Invalid params: platform must be "ios" or "android"');return{token:iG(t,r),session:iq(t,"session")??"default",command:"install_source",positionals:[],flags:{platform:n},meta:{requestId:iq(t,"requestId"),installSource:function(e){let t=e.source;if(!t||"object"!=typeof t)throw new O("INVALID_ARGS","Invalid params: source is required");if("url"===t.kind){let e="string"==typeof t.url?t.url.trim():"";if(!e)throw new O("INVALID_ARGS","Invalid params: source.url is required for url sources");let r=t.headers,n={};if(void 0!==r){if(!r||"object"!=typeof r||Array.isArray(r))throw new O("INVALID_ARGS","Invalid params: source.headers must be a string map");for(let[e,t]of Object.entries(r)){if("string"!=typeof t)throw new O("INVALID_ARGS","Invalid params: source.headers values must be strings");n[e]=t}}return Object.keys(n).length>0?{kind:"url",url:e,headers:n}:{kind:"url",url:e}}if("path"===t.kind){let e="string"==typeof t.path?t.path.trim():"";if(!e)throw new O("INVALID_ARGS","Invalid params: source.path is required for path sources");return{kind:"path",path:e}}if("github-actions-artifact"===t.kind)return function(e){let t,r=iB(e,"owner"),n=iB(e,"repo"),a=void 0!==e.artifactId,i=void 0!==e.runId,o=void 0!==e.artifactName;if(a&&(i||o))throw new O("INVALID_ARGS","Invalid params: source must specify either artifactId or artifactName, not both");if(!a&&i&&!o)throw new O("INVALID_ARGS","Invalid params: source.artifactName is required when source.runId is specified");if(!a&&!o)throw new O("INVALID_ARGS","Invalid params: source must specify artifactId or artifactName");return a?{kind:"github-actions-artifact",owner:r,repo:n,artifactId:iH(e,"artifactId")}:(i&&(t=iH(e,"runId")),{kind:"github-actions-artifact",owner:r,repo:n,...i?{runId:t}:{},artifactName:iB(e,"artifactName")})}(t);throw new O("INVALID_ARGS",'Invalid params: source.kind must be "url", "path", or "github-actions-artifact"')}(t),retainMaterializedPaths:(e=t.retainPaths,"boolean"==typeof e?e:void 0),materializedPathRetentionMs:ij(t,"retentionMs")}}}if(iL.has(e)){let e=iq(t,"materializationId")?.trim();if(!e)throw new O("INVALID_ARGS","Invalid params: materializationId is required");return{token:iG(t,r),session:iq(t,"session")??"default",command:"release_materialized_paths",positionals:[],meta:{requestId:iq(t,"requestId"),materializationId:e}}}let n=i$[e];if(n)return{token:iG(t,r),session:iq(t,"session")??"default",command:n,positionals:[],meta:{tenantId:iq(t,"tenantId")??iq(t,"tenant"),runId:iq(t,"runId"),leaseId:iq(t,"leaseId"),leaseTtlMs:ij(t,"ttlMs"),leaseBackend:iq(t,"backend")}};throw new O("INVALID_ARGS",`Method not found: ${e}`)}(n.method,i,e.headers);if(s=n.method,iC.has(s)&&("string"!=typeof l.command||0===l.command.length))return void iU(a,iF(n.id??null,-32602,"Invalid params: command is required"),400);o=ro(l.meta?.requestId,n.id),l.meta={...l.meta,requestId:o},rs(o);let u=()=>{a.writableFinished||rl(o)};e.on("aborted",u),a.on("close",u);let d=await iW(t,{headers:e.headers,rpcRequest:n,daemonRequest:l});if(!d.ok)return void iU(a,d.response,d.statusCode);d.tenantId&&(l.meta={...l.meta,tenantId:d.tenantId,sessionIsolation:l.meta?.sessionIsolation??l.flags?.sessionIsolation??"tenant"});let c=await r(l);if(c.ok)return void iU(a,{jsonrpc:"2.0",id:n.id??null,result:c});iU(a,iF(n.id??null,-32e3,c.error.message,c.error),iV(c.error.code))}catch(t){let e=P(t);iU(a,iF(n.id??null,-32e3,e.message,e),iV(e.code))}finally{ru(o)}})})}async function iJ(e,t,r,n){try{var a;let i,s,l=iG({},e.headers),u=iY(l,n);if(u){t.statusCode=iV(u.code),t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!1,error:u.message,code:u.code}));return}let d=await iW(r,{headers:e.headers,rpcRequest:{jsonrpc:"2.0",id:null,method:"agent_device.command"},daemonRequest:{token:l,session:"default",command:"upload",positionals:[]}});if(!d.ok){t.statusCode=d.statusCode,t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!1,error:d.response.error?.data?.message??d.response.error?.message??"Unauthorized"}));return}let c=await iR(e),p=(a={artifactPath:c.artifactPath,tempDir:c.tempDir,tenantId:d.tenantId},i=o.randomUUID(),(s=setTimeout(()=>{iN(i)},3e5)).unref(),i_.set(i,{artifactPath:a.artifactPath,tempDir:a.tempDir,tenantId:a.tenantId,timer:s}),i);t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!0,uploadId:p}))}catch(r){let e=P(r);t.statusCode=iV(e.code),t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!1,error:e.message,code:e.code}))}}async function iX(e,t,r,n){let a=e.url?.slice("/artifacts/".length)??"";if(!a){t.statusCode=400,t.end("Missing artifact id");return}try{let i=iG({},e.headers),o=iY(i,n);if(o){t.statusCode=iV(o.code),t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!1,error:o.message,code:o.code}));return}let s=await iW(r,{headers:e.headers,rpcRequest:{jsonrpc:"2.0",id:null,method:"agent_device.command"},daemonRequest:{token:i,session:"default",command:"download_artifact",positionals:[a]}});if(!s.ok){t.statusCode=s.statusCode,t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!1,error:s.response.error?.data?.message??s.response.error?.message??"Unauthorized"}));return}let u=function(e,t){let r=ib.get(e);if(!r)throw new O("INVALID_ARGS",`Artifact not found: ${e}`);if(r.tenantId&&r.tenantId!==t)throw new O("UNAUTHORIZED","Artifact belongs to a different tenant");if(!l.existsSync(r.artifactPath))throw iS(e),new O("COMMAND_FAILED",`Artifact file is missing: ${r.artifactPath}`);return{artifactPath:r.artifactPath,fileName:r.fileName,deleteAfterDownload:r.deleteAfterDownload}}(a,s.tenantId),d=l.createReadStream(u.artifactPath);t.statusCode=200,t.setHeader("content-type","application/octet-stream"),u.fileName&&t.setHeader("content-disposition",`attachment; filename="${u.fileName.replace(/"/g,"")}"`),d.on("error",e=>{if(t.headersSent)t.destroy(e);else{let r=P(e);t.statusCode=iV(r.code),t.end(r.message)}}),t.on("close",()=>{t.writableFinished&&iS(a)}),d.pipe(t)}catch(r){let e=P(r);t.statusCode=iV(e.code),t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!1,error:e.message,code:e.code}))}}function iY(e,t){return t&&e!==t?P(new O("UNAUTHORIZED","Invalid token")):null}function iZ(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}function iQ(e){if(!e)return;let t=e.trim();if(t&&/^[a-f0-9]{16,128}$/i.test(t))return t.toLowerCase()}function i0(e){let t=(e??"").trim().toLowerCase();if(!t||"ios-simulator"===t)return"ios-simulator";if("ios-instance"===t||"android-instance"===t)return t;throw new O("INVALID_ARGS",`Unsupported lease backend: ${e??""}`)}class i1{leases=new Map;runBindings=new Map;maxActiveSimulatorLeases;defaultLeaseTtlMs;minLeaseTtlMs;maxLeaseTtlMs;now;constructor(e={}){this.maxActiveSimulatorLeases=Number.isInteger(e.maxActiveSimulatorLeases)?Math.max(0,Number(e.maxActiveSimulatorLeases)):0,this.defaultLeaseTtlMs=Number.isInteger(e.defaultLeaseTtlMs)?Math.max(1,Number(e.defaultLeaseTtlMs)):6e4,this.minLeaseTtlMs=Number.isInteger(e.minLeaseTtlMs)?Math.max(1,Number(e.minLeaseTtlMs)):5e3,this.maxLeaseTtlMs=Number.isInteger(e.maxLeaseTtlMs)?Math.max(this.minLeaseTtlMs,Number(e.maxLeaseTtlMs)):6e5,this.now=e.now??(()=>Date.now())}allocateLease(e){let t=i0(e.backend),r=eO(e.tenantId);if(!r)throw new O("INVALID_ARGS","Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");let n=iZ(e.runId);if(!n)throw new O("INVALID_ARGS","Invalid run id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");this.cleanupExpiredLeases();let a=this.resolveLeaseTtlMs(e.ttlMs),i=this.bindingKey(r,n,t),s=this.runBindings.get(i);if(s){let e=this.leases.get(s);if(e)return this.refreshLease(e,a);this.runBindings.delete(i)}this.enforceCapacity(t);let l=this.now(),u={leaseId:o.randomBytes(16).toString("hex"),tenantId:r,runId:n,backend:t,createdAt:l,heartbeatAt:l,expiresAt:l+a};return this.leases.set(u.leaseId,u),this.runBindings.set(i,u.leaseId),{...u}}heartbeatLease(e){let t=iQ(e.leaseId);if(!t)throw new O("INVALID_ARGS","Invalid lease id.");this.cleanupExpiredLeases();let r=this.leases.get(t);if(!r)throw new O("UNAUTHORIZED","Lease is not active",{reason:"LEASE_NOT_FOUND"});this.assertOptionalScopeMatch(r,e.tenantId,e.runId);let n=this.resolveLeaseTtlMs(e.ttlMs);return this.refreshLease(r,n)}releaseLease(e){let t=iQ(e.leaseId);if(!t)throw new O("INVALID_ARGS","Invalid lease id.");this.cleanupExpiredLeases();let r=this.leases.get(t);return r?(this.assertOptionalScopeMatch(r,e.tenantId,e.runId),this.leases.delete(t),this.runBindings.delete(this.bindingKey(r.tenantId,r.runId,r.backend)),{released:!0}):{released:!1}}assertLeaseAdmission(e){let t=i0(e.backend),r=eO(e.tenantId);if(!r)throw new O("INVALID_ARGS","tenant isolation requires tenant id.");let n=iZ(e.runId);if(!n)throw new O("INVALID_ARGS","tenant isolation requires run id.");let a=iQ(e.leaseId);if(!a)throw new O("INVALID_ARGS","tenant isolation requires lease id.");this.cleanupExpiredLeases();let i=this.leases.get(a);if(!i)throw new O("UNAUTHORIZED","Lease is not active",{reason:"LEASE_NOT_FOUND"});if(i.backend!==t||i.tenantId!==r||i.runId!==n)throw new O("UNAUTHORIZED","Lease does not match tenant/run scope",{reason:"LEASE_SCOPE_MISMATCH"})}listActiveLeases(){return this.cleanupExpiredLeases(),Array.from(this.leases.values()).map(e=>({...e}))}cleanupExpiredLeases(){let e=this.now();for(let t of this.leases.values())t.expiresAt>e||(this.leases.delete(t.leaseId),this.runBindings.delete(this.bindingKey(t.tenantId,t.runId,t.backend)))}enforceCapacity(e){if("ios-simulator"!==e||this.maxActiveSimulatorLeases<=0)return;let t=Array.from(this.leases.values()).filter(e=>"ios-simulator"===e.backend).length;if(!(t<this.maxActiveSimulatorLeases))throw new O("COMMAND_FAILED","No simulator lease capacity available",{reason:"LEASE_CAPACITY_EXCEEDED",activeLeases:t,maxActiveLeases:this.maxActiveSimulatorLeases,backend:e,hint:"Retry after releasing another simulator lease."})}resolveLeaseTtlMs(e){if(!Number.isInteger(e))return this.defaultLeaseTtlMs;let t=Number(e);if(t<this.minLeaseTtlMs||t>this.maxLeaseTtlMs)throw new O("INVALID_ARGS",`Lease ttlMs must be between ${this.minLeaseTtlMs} and ${this.maxLeaseTtlMs}.`);return t}refreshLease(e,t){let r=this.now(),n={...e,heartbeatAt:r,expiresAt:r+t};return this.leases.set(n.leaseId,n),this.runBindings.set(this.bindingKey(n.tenantId,n.runId,n.backend),n.leaseId),{...n}}bindingKey(e,t,r){return`${e}:${t}:${r}`}assertOptionalScopeMatch(e,t,r){let n=eO(t),a=iZ(r);if(t&&!n)throw new O("INVALID_ARGS","Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");if(r&&!a)throw new O("INVALID_ARGS","Invalid run id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");if(n&&e.tenantId!==n||a&&e.runId!==a)throw new O("UNAUTHORIZED","Lease does not match tenant/run scope",{reason:"LEASE_SCOPE_MISMATCH"})}}function i2(){return{platform:"macos",id:"host-macos-local",name:c.hostname(),kind:"device",target:"desktop",booted:!0}}async function i3(){return[i2()]}let i5=/^(iphone|ipad|ipod|appletv)/i,i4=/\b(iphone|ipad|ipod)\b/i,i8=/^appletv/i,i6=["apple tv","appletv","tvos"],i9=/^==\s*(.+?)\s*==$/,i7=/^(?<name>.+?)\s+\[(?<id>[^[\]]+)\]\s*$/;function oe(e){return(e??"").trim().toLowerCase()}function ot(e){return oe(e.hardwareProperties?.platform)}function or(e){return e.includes("tvos")}function on(e){let t=oe(e);return i6.some(e=>t.includes(e))}function oa(e){return[e.name??"",e.deviceProperties?.name??"",e.deviceProperties?.deviceType??""]}function oi(e){return e.hardwareProperties?.productType??e.deviceProperties?.productType??""}async function oo(e={}){let t,r,n=ee(e.simulatorSetPath),a=e.target;try{t=await rM(rP(["list","devices","-j"],{simulatorSetPath:n}))}catch{return null}try{r=JSON.parse(t.stdout)}catch{return null}let i=os(r,n),o=null,s=null,l=null;for(let e of i)a&&e.target!==a||(e.booted&&(o=o??e),"mobile"===e.target&&(s=s??e),l=l??e);return o??s??l}function os(e,t){let r=[];for(let[n,a]of Object.entries(e.devices))if(function(e){let t=oe(e);return t.includes("ios")||t.includes("tvos")}(n))for(let e of a)e.isAvailable&&r.push({platform:"ios",id:e.udid,name:e.name,kind:"simulator",target:or(oe(n))?"tv":"mobile",booted:"Booted"===e.state,...t?{simulatorSetPath:t}:{}});return r}function ol(e,t){let r=new Set(e.map(e=>e.id)),n=[...e];for(let e of t)r.has(e.id)||(r.add(e.id),n.push(e));return n}async function ou(){let e=null;try{e=f.join(c.tmpdir(),`agent-device-devicectl-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);let t=await rM(["devicectl","list","devices","--json-output",e],{allowFailure:!0,timeoutMs:8e3});if(0!==t.exitCode)return[];let r=await d.readFile(e,"utf8");return function(e){let t=[];for(let r of e.result?.devices??[]){if(!function(e){var t;let r=ot(e);return!!(r.includes("ios")||r.includes("tvos"))||(t=oi(e),!!i5.test(t.trim())||oa(e).some(on))}(r))continue;let e=r.hardwareProperties?.udid??r.identifier??"",n=r.name??r.deviceProperties?.name??e;e&&t.push({platform:"ios",id:e,name:n,kind:"device",target:function(e){var t;return or(ot(e))?"tv":(t=oi(e),i8.test(t.trim())||oa(e).some(on))?"tv":"mobile"}(r),booted:!0})}return t}(JSON.parse(r))}catch{return[]}finally{e&&await d.rm(e,{force:!0}).catch(()=>{})}}async function od(){try{let e=await rM(["xctrace","list","devices"],{allowFailure:!0});if(0!==e.exitCode)return[];return function(e){let t=[],r=null;for(let n of e.split(/\r?\n/)){let e=n.trim();if(!e)continue;let a=i9.exec(e);if(a){r=a[1]?.trim()??null;continue}if("Devices"!==r)continue;let i=i7.exec(e),o=i?.groups?.id?.trim()??"",s=i?.groups?.name?.trim()??"";if(!o||!s)continue;let l=function(e){return on(e)?"tv":i4.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 oc(e={}){if("darwin"!==process.platform)throw new O("UNSUPPORTED_PLATFORM","Apple tools are only available on macOS");if(!await r_().whichCommand("xcrun"))throw new O("TOOL_MISSING","xcrun not found in PATH");let t=ee(e.simulatorSetPath),r=await rM(rP(["list","devices","-j"],{simulatorSetPath:t})),n=[];try{let e=JSON.parse(r.stdout);n=os(e,t)}catch(e){throw new O("COMMAND_FAILED","Failed to parse simctl devices JSON",void 0,e)}if(n.push(i2()),e.udid&&n.some(t=>"ios"===t.platform&&t.id===e.udid)||t)return n;let[a,i]=await Promise.all([ou(),od()]);return n=ol(n,a),ol(n,i)}async function op(){return"linux"!==process.platform?[]:[{platform:"linux",id:"local",name:p(),kind:"device",target:"desktop",booted:!0}]}let of=new h,om=new h;async function oh(e,t,r){var n,a;let i=await ow(e,t,r);if(n=t,a=i,!og(n)&&(!n.platform||"apple"===n.platform||"ios"===n.platform)&&"desktop"!==n.target&&(!a||"device"===a.kind)){let e=await oo({simulatorSetPath:r.simulatorSetPath,target:t.target});if(e)return e}if(i)return i;throw new O("DEVICE_NOT_FOUND","No devices found",{selector:t})}async function ow(e,t,r){try{return await r5(e,t,r)}catch(e){var n;if(n=e,!og(t)&&n instanceof O&&"DEVICE_NOT_FOUND"===n.code)return;throw e}}function og(e){return!!(e.udid||e.serial||e.deviceName)}async function oy(e){let t=e.platform,r=r3({simulatorSetPath:ee(e.iosSimulatorDeviceSet),platform:t,target:e.target}),n=ep(e.androidDeviceAllowlist),a=function(e){let{flags:t,normalizedPlatform:r,iosSimulatorSetPath:n,androidSerialAllowlist:a}=e;return JSON.stringify({platform:r,target:t.target,device:t.device,udid:t.udid,serial:t.serial,iosSimulatorSetPath:n,androidSerialAllowlist:a?Array.from(a).sort():void 0})}({flags:e,normalizedPlatform:t,iosSimulatorSetPath:r,androidSerialAllowlist:n}),i={platform:t,target:e.target,cacheHit:!1};return await eN("resolve_target_device",async()=>{let o=function(e){let t=of.getStore(),r=t?.get(e);if(r)return{...r}}(a);if(o)return i.cacheHit=!0,o;let s={platform:t,target:e.target,deviceName:e.device,udid:e.udid,serial:e.serial};if(s.target&&!s.platform)throw new O("INVALID_ARGS","Device target selector requires --platform. Use --platform ios|macos|android|linux|apple with --target mobile|tv|desktop.");let l=await oS({...s,iosSimulatorSetPath:r,androidSerialAllowlist:n?Array.from(n).sort():void 0});if(l)return ox(s)?oN(a,await oh(l,s,{simulatorSetPath:r})):oN(a,await r5(l,s,{simulatorSetPath:r}));"android"===s.platform&&await ea();let u=await o_({...s,iosSimulatorSetPath:r,androidSerialAllowlist:n?Array.from(n).sort():void 0});return ox(s)?oN(a,await oh(u,s,{simulatorSetPath:r})):oN(a,await r5(u,s,{simulatorSetPath:r}))},i)}async function ov(e){return of.getStore()?await e():await of.run(new Map,e)}async function oI(e,t){return e?await om.run(e,t):await t()}async function ob(e,t){return await oI(e,async()=>await ov(t))}async function oA(e){return await oS(e)??await o_(e)}async function oS(e){let t=om.getStore();if(!t)return null;let r=await t(e);return null==r?null:r.map(e=>({...e}))}async function o_(e){if("macos"===e.platform||"apple"===e.platform&&"desktop"===e.target)return await i3();if("linux"===e.platform)return await op();if("android"===e.platform)return await V({serialAllowlist:e.androidSerialAllowlist?new Set(e.androidSerialAllowlist):void 0});if(e.platform)return await oc({simulatorSetPath:e.iosSimulatorSetPath,udid:e.udid});let t=[];try{t.push(...await V({serialAllowlist:e.androidSerialAllowlist?new Set(e.androidSerialAllowlist):void 0}))}catch{}try{t.push(...await oc({simulatorSetPath:e.iosSimulatorSetPath,udid:e.udid}))}catch{}try{t.push(...await op())}catch{}return t}function ox(e){return!!e.platform&&"android"!==e.platform&&"linux"!==e.platform}function oN(e,t){return of.getStore()?.set(e,{...t}),t}let oM={runCommand:E,whichCommand:$,desktop:oR(E,$),clipboard:oC(E,$),screenshot:oE(E,$)},ok=rh(oM,function(e={}){let t={...oM,...e};return{...t,desktop:e.desktop??oR(t.runCommand,t.whichCommand),clipboard:e.clipboard??oC(t.runCommand,t.whichCommand),screenshot:e.screenshot??oE(t.runCommand,t.whichCommand)}});function oD(e){return ok.resolve(e)}async function oP(e,t){return await ok.run(e,t)}async function oO(e,t,r){return await oD().runCommand(e,t,r)}function oR(e,t){return{async openTarget(r){if(r.includes("://")||r.startsWith("/"))return void await e("xdg-open",[r]);if(await t(r)){e(r,[],{allowFailure:!0}).catch(e=>{eM({level:"warn",phase:"linux_app_launch",data:{app:r,error:String(e)}})}),await e2(500);return}await e("xdg-open",[r],{allowFailure:!0})},async closeApp(r){await t("wmctrl")?await e("wmctrl",["-c",r],{allowFailure:!0}):await e("pkill",["-x",r],{allowFailure:!0})}}}function oC(e,t){return{async readText(){let r=oT[await oV(t,oL)];return(await e(r.cmd,r.args,r.options)).stdout},async writeText(r){let n=oF[await oV(t,oL)](r);await e(n.cmd,n.args,n.options)}}}function oE(e,t){return{async capture(r){let n=oU[await oV(t,o$)](r);await e(n.cmd,n.args,n.options)}}}let oL={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."},o$={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."},oT={"wl-clipboard":{cmd:"wl-paste",args:["--no-newline"],options:{allowFailure:!0,timeoutMs:5e3}},xclip:{cmd:"xclip",args:["-selection","clipboard","-o"],options:{allowFailure:!0,timeoutMs:5e3}},xsel:{cmd:"xsel",args:["--clipboard","--output"],options:{allowFailure:!0,timeoutMs:5e3}}},oF={"wl-clipboard":e=>({cmd:"wl-copy",args:["--",e],options:{allowFailure:!1,timeoutMs:5e3}}),xclip:e=>({cmd:"xclip",args:["-selection","clipboard"],options:{allowFailure:!1,timeoutMs:5e3,stdin:e}}),xsel:e=>({cmd:"xsel",args:["--clipboard","--input"],options:{allowFailure:!1,timeoutMs:5e3,stdin:e}})},oU={grim:e=>({cmd:"grim",args:[e]}),scrot:e=>({cmd:"scrot",args:[e]}),import:e=>({cmd:"import",args:["-window","root",e]}),"gnome-screenshot":e=>({cmd:"gnome-screenshot",args:["-f",e]})};async function oV(e,t){let r=process.env.WAYLAND_DISPLAY||"wayland"===process.env.XDG_SESSION_TYPE?"wayland":"x11";for(let n of t[r])if(await e(n.command))return n.tool;throw new O("TOOL_MISSING","wayland"===r?t.waylandError:t.x11Error)}async function oG(e,t){let r=["devicectl",...e],n=await rM(r,{allowFailure:!0,timeoutMs:2e4});if(0===n.exitCode)return;let a=String(n.stdout??""),i=String(n.stderr??"");throw new O("COMMAND_FAILED",`Failed to ${t.action}`,{cmd:"xcrun",args:r,exitCode:n.exitCode,stdout:a,stderr:i,deviceId:t.deviceId,hint:oW(a,i)??oH})}async function oq(e,t){var r;return r=function(e){let t=e?.result?.apps;if(!Array.isArray(t))return[];let r=[];for(let e of t){if(!e||"object"!=typeof e)continue;let t="string"==typeof e.bundleIdentifier?e.bundleIdentifier.trim():"";if(!t)continue;let n="string"==typeof e.name&&e.name.trim().length>0?e.name.trim():t,a="string"==typeof e.url&&e.url.trim().length>0?e.url.trim():void 0;r.push({bundleId:t,name:n,url:a})}return r}(await oB(e,{jsonPrefix:"agent-device-ios-apps",args:["devicectl","device","info","apps","--device",e.id,"--include-all-apps"],failureMessage:"Failed to list iOS apps",parseFailureMessage:"Failed to parse iOS apps list"})),"user-installed"===t?r.filter(e=>!e.bundleId.startsWith("com.apple.")):r}async function oj(e){return function(e){let t=e?.result?.runningProcesses;if(!Array.isArray(t))return[];let r=[];for(let e of t){if(!e||"object"!=typeof e)continue;let t="string"==typeof e.executable?e.executable.trim():"",n="number"==typeof e.processIdentifier&&Number.isFinite(e.processIdentifier)?e.processIdentifier:NaN;t&&Number.isFinite(n)&&r.push({executable:t,pid:n})}return r}(await oB(e,{jsonPrefix:"agent-device-ios-processes",args:["devicectl","device","info","processes","--device",e.id],failureMessage:"Failed to list iOS processes",parseFailureMessage:"Failed to parse iOS process list"}))}async function oB(e,t){let r=f.join(c.tmpdir(),`${t.jsonPrefix}-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`),n=[...t.args,"--json-output",r],a=await rM(n,{allowFailure:!0,timeoutMs:2e4});try{if(0!==a.exitCode){let r=String(a.stdout??""),i=String(a.stderr??"");throw new O("COMMAND_FAILED",t.failureMessage,{cmd:"xcrun",args:n,exitCode:a.exitCode,stdout:r,stderr:i,deviceId:e.id,hint:oW(r,i)??oH})}return JSON.parse(await d.readFile(r,"utf8"))}catch(r){if(r instanceof O)throw r;throw new O("COMMAND_FAILED",t.parseFailureMessage,{deviceId:e.id,cause:String(r)})}finally{await d.unlink(r).catch(()=>{})}}let oH="Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.";function oW(e,t){let r=`${e}
12
- ${t}`.toLowerCase();return r.includes("device is busy")&&r.includes("connecting")?"iOS device is still connecting. Keep it unlocked and connected by cable until it is fully available in Xcode Devices, then retry.":r.includes("coredeviceservice")&&r.includes("timed out")?"CoreDevice service timed out. Reconnect the device and retry; if it persists restart Xcode and the iOS device.":null}let oz=new Map;async function oK(e){var t;let r,n=(r="simulator"===(t=e).kind?t.simulatorSetPath??"":"",JSON.stringify([t.platform,t.kind,t.id,t.target??"",r])),a=oz.get(n);if(void 0!==a){if(a>Date.now())return;oz.delete(n)}if("ios"===e.platform){if("simulator"===e.kind){let{ensureBootedSimulator:t}=await Promise.resolve(rt);await t(e),oJ(n);return}if("device"===e.kind){await oX(e.id),oJ(n);return}}if("android"===e.platform){let{waitForAndroidBoot:t}=await import("../1769.js");await t(e.id),oJ(n)}}function oJ(e){oz.set(e,Date.now()+5e3)}async function oX(e){let t=f.join(c.tmpdir(),`agent-device-ready-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`),r=Math.max(1,Math.ceil(15));try{let n=await rM(["devicectl","device","info","details","--device",e,"--json-output",t,"--timeout",String(r)],{allowFailure:!0,timeoutMs:18e3}),a=String(n.stdout??""),i=String(n.stderr??""),o=await oY(t);if(0===n.exitCode){if(!o.parsed)throw new O("COMMAND_FAILED","iOS device readiness probe failed",{kind:"probe_inconclusive",deviceId:e,stdout:a,stderr:i,hint:"CoreDevice returned success but readiness JSON output was missing or invalid. Retry; if it persists restart Xcode and the iOS device."});let t=o?.tunnelState?.toLowerCase();if("connecting"===t)throw new O("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 O("COMMAND_FAILED","iOS device is not ready for automation",{kind:"not_ready",deviceId:e,stdout:a,stderr:i,exitCode:n.exitCode,tunnelState:o?.tunnelState,hint:oZ(a,i)})}catch(t){if(t instanceof O&&"COMMAND_FAILED"===t.code){if("not_ready"===("string"==typeof t.details?.kind?t.details.kind:""))throw t;let r=t.details??{},n=String(r.stdout??""),a=String(r.stderr??""),i=Number(r.timeoutMs??15e3),o=`CoreDevice did not respond within ${i}ms. Keep the device unlocked and trusted, then retry; if it persists restart Xcode and the iOS device.`;throw new O("COMMAND_FAILED","iOS device readiness probe failed",{deviceId:e,cause:t.message,timeoutMs:i,stdout:n,stderr:a,hint:n||a?oZ(n,a):o},t)}throw new O("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 d.rm(t,{force:!0}).catch(()=>{})}}async function oY(e){try{let t=await d.readFile(e,"utf8"),r=JSON.parse(t),n=function(e){let t=e?.result;if(!t||"object"!=typeof t)return{};let r=t.connectionProperties?.tunnelState,n=t.device?.connectionProperties?.tunnelState,a="string"==typeof r?r:"string"==typeof n?n:void 0;return a?{tunnelState:a}:{}}(r);return{parsed:!0,tunnelState:n.tunnelState}}catch{return{parsed:!1}}}function oZ(e,t){let r=oW(e,t);return r||(`${e}
13
- ${t}`.toLowerCase().includes("timed out waiting for all destinations")?"Xcode destination did not become available in time. Keep device unlocked and retry.":oH)}function oQ(e){let t=e.direction,r="up"===t||"down"===t?e.referenceHeight:e.referenceWidth,n=function(e){if(void 0===e)return .6;if(!Number.isFinite(e)||e<=0)throw new O("INVALID_ARGS","scroll amount must be a positive number");return e}(e.amount),a=void 0!==e.pixels?function(e){if(!Number.isFinite(e)||e<=0)throw new O("INVALID_ARGS","scroll pixels must be a positive integer");return Math.max(1,Math.round(e))}(e.pixels):Math.round(r*n),i=Math.max(1,Math.round(.05*r)),o=Math.max(1,Math.min(a,Math.max(1,r-2*i))),s=Math.round(o/2),l=Math.round(e.referenceWidth/2),u=Math.round(e.referenceHeight/2),d=(r,n,a,i)=>({direction:t,x1:r,y1:n,x2:a,y2:i,referenceWidth:e.referenceWidth,referenceHeight:e.referenceHeight,amount:e.amount,pixels:o});switch(t){case"up":return d(l,u-s,l,u+s);case"down":return d(l,u+s,l,u-s);case"left":return d(l-s,u,l+s,u);case"right":return d(l+s,u,l-s,u)}}function o0(e){var t;return!!e&&(!!e.password||!!(t=e.text)&&Array.from(t).every(o2))}function o1(e){if(!e)return null;let t=o0(e);return{...e,text:t?null:e.text,...t?{textRedacted:!0}:{}}}function o2(e){return"•"===e||"*"===e||"●"===e}function o3(e){if(0===e.length)return null;let t=[...e].sort((e,t)=>e-t);return t[Math.floor(t.length/2)]??null}function o5(e,t){let r=Math.max(24,Math.round(.2*Math.min(e.size,t.size))),n=Math.max(48,Math.round(.15*Math.min(e.crossSize,t.crossSize)));return Math.abs(e.size-t.size)<=r&&Math.abs(e.crossSize-t.crossSize)<=n}function o4(e,t){return{start:e.y-t.y,size:e.height,crossSize:e.width}}let o8=["device offline","device not found","transport error","connection reset","broken pipe","timed out","no such file or directory"];async function o6(e,t={}){let r=e7(e,t.helperAdb),n=await o9(e,t,r),a=n.xml,i=!1!==t.includeHiddenContentHints;if(!t.interactiveOnly){let o=tr(a,800,t);return i&&function(e,t){for(let[r,n]of e){let e=t[r];e&&(n.hiddenContentAbove&&(e.hiddenContentAbove=!0),n.hiddenContentBelow&&(e.hiddenContentBelow=!0))}}(await ss(e,o.nodes,r),o.nodes),{...o,androidSnapshot:n.metadata}}let o=ta(a),s=tu(o,800,{...t,interactiveOnly:!1}),l=tu(o,800,t);if(i){let t=await ss(e,s.nodes,r);sf(t,s,l),0===t.size&&sf(ty(tG(s.nodes)),s,l)}let{sourceNodes:u,...d}=l;return{...d,androidSnapshot:n.metadata}}async function o9(e,t,r){let n=await eN("android_snapshot_helper_artifact_resolution",async()=>await si(t.helperArtifact));return n.artifact?await o7(e,t,r,n.artifact):(eM({level:n.fallbackReason?"warn":"info",phase:"android_snapshot_helper_unavailable",data:{reason:n.fallbackReason??"artifact_not_found"}}),await so(e,n.fallbackReason,r))}async function o7(e,t,r,n){var a,i,o,s;let l=(a=e,`${a.platform}:${a.id}`);try{let a=await se(e,t,r,n,l);return i=await st(t,r,n),o=n,s=a.reason,{xml:i.xml,metadata:{backend:"android-helper",helperVersion:o.manifest.version,helperApiVersion:i.metadata.helperApiVersion,installReason:s,waitForIdleTimeoutMs:i.metadata.waitForIdleTimeoutMs,waitForIdleQuietMs:i.metadata.waitForIdleQuietMs,timeoutMs:i.metadata.timeoutMs,maxDepth:i.metadata.maxDepth,maxNodes:i.metadata.maxNodes,rootPresent:i.metadata.rootPresent,captureMode:i.metadata.captureMode,windowCount:i.metadata.windowCount,nodeCount:i.metadata.nodeCount,helperTruncated:i.metadata.truncated,elapsedMs:i.metadata.elapsedMs}}}catch(t){return await sr({error:t,helperDeviceKey:l,artifact:n,device:e,adb:r})}}async function se(e,t,r,n,a){let i=await eN("android_snapshot_helper_install",async()=>await tn({adb:r,adbProvider:e6(e,t.helperAdb),artifact:n,deviceKey:a,installPolicy:t.helperInstallPolicy,timeoutMs:3e4}),{packageName:n.manifest.packageName,versionCode:n.manifest.versionCode,installPolicy:t.helperInstallPolicy??"missing-or-outdated"});return eM({phase:"android_snapshot_helper_install_decision",data:{packageName:i.packageName,versionCode:i.versionCode,installedVersionCode:i.installedVersionCode,installed:i.installed,reason:i.reason}}),i}async function st(e,t,r){return await eN("android_snapshot_helper_capture",async()=>await ti({adb:t,packageName:r.manifest.packageName,instrumentationRunner:r.manifest.instrumentationRunner,waitForIdleTimeoutMs:e.helperWaitForIdleTimeoutMs??500,timeoutMs:5e3,commandTimeoutMs:3e4}),{packageName:r.manifest.packageName,version:r.manifest.version,timeoutMs:5e3,commandTimeoutMs:3e4})}async function sr(e){let t=function(e){var t,r;let n=P(e);if(!function(e,t){if(!e||"object"!=typeof e)return!1;let r="errorType"in e?String(e.errorType):"",n=sa(e)??t;return/TimeoutException/.test(r)||/timed out/i.test(n)}(n.details?.helper,n.message)&&(t=n,!(t.details?.exitCode===137&&/Android snapshot helper (failed before returning parseable output|output could not be parsed)/.test(t.message)))&&(r=n.message,!/Android snapshot helper output could not be parsed/.test(r)))return;let a=sn(e);return new O(k(n.code),`${a}. Stock UIAutomator fallback was skipped because this usually means the Android accessibility tree is busy or stalled.`,{...n.details,hint:"Android accessibility snapshots can be blocked by busy or continuously changing app UI. Use screenshot as visual truth after this timeout and report the busy UI if it persists."},e)}(e.error);if(t)throw t;let r=sn(e.error);return eM({level:"warn",phase:"android_snapshot_helper_fallback",data:{reason:r}}),tl({deviceKey:e.helperDeviceKey,packageName:e.artifact.manifest.packageName,versionCode:e.artifact.manifest.versionCode}),await so(e.device,r,e.adb)}function sn(e){let t=P(e),r=sa(t.details?.helper);if(r&&r!==t.message)return`${t.message}: ${r}`;if(r)return r;let n=("string"==typeof t.details?.stderr?t.details.stderr.trim():"").split(/\r?\n/).find(e=>e.trim());return n?`${t.message}: ${n}`:t.message}function sa(e){if(!e||"object"!=typeof e||!("message"in e))return;let t=String(e.message).trim();return t&&"null"!==t?t:void 0}async function si(e){if(e)return{artifact:e};let t=eE(),r=f.join(eL(),"android-snapshot-helper","dist"),n=f.join(r,`agent-device-android-snapshot-helper-${t}.manifest.json`);try{await S.access(n)}catch{return{}}try{let e=to(JSON.parse(await S.readFile(n,"utf8"))),t=f.join(r,e.assetName??`agent-device-android-snapshot-helper-${e.version}.apk`);return await S.access(t),{artifact:{apkPath:t,manifest:e}}}catch(e){return{fallbackReason:P(e).message}}}async function so(e,t,r){let n;try{n=await eN("android_snapshot_stock_capture",async()=>await sl(e,r),{fallbackReason:t,timeoutMs:8e3})}catch(e){if(t){var a,i;let r;throw a=e,i=t,new O(k((r=P(a)).code),`${r.message} Android snapshot helper failed before stock fallback: ${i}`,{...r.details,androidSnapshotHelperFallbackReason:i,...r.hint?{hint:r.hint}:{}},a)}throw e}return{xml:n,metadata:{backend:"uiautomator-dump",...t?{fallbackReason:t}:{}}}}async function ss(e,t,r){if(!t.some(e=>tt(e.type)))return new Map;let n=await sp(e,r);return n?function(e,t){let r=function(e){let t={className:"root",rect:{x:0,y:0,width:0,height:0},children:[]},r=[{indent:-1,node:t}],n=/^(\s*)([\w.$]+)\{[^}]* (-?\d+),(-?\d+)-(-?\d+),(-?\d+) #/;for(let t of e.split("\n")){let e=n.exec(t);if(!e)continue;let[a,i,o,s,l,u]=e.slice(1);if(void 0===a||void 0===i||void 0===o||void 0===s||void 0===l||void 0===u)continue;let d=a.length,c=Number(o),p=Number(s),f={className:i,rect:{x:c,y:p,width:Math.max(0,Number(l)-c),height:Math.max(0,Number(u)-p)},children:[]};for(;r.length>1&&d<=r[r.length-1].indent;)r.pop();r[r.length-1].node.children.push(f),r.push({indent:d,node:f})}return t.children.length>0?t:null}(t);if(!r)return new Map;let n=function(e){let t=[],r=[e];for(;r.length>0;){let e=r.pop();if(tt(e.className)){let r=function(e){let t=e.children[0];if(!t)return null;let r=Math.max(t.rect.height,...t.children.map(e=>e.rect.y+e.rect.height)),n=t.children.filter(e=>e.rect.height>0).map(t=>o4(t.rect,e.rect)).sort((e,t)=>e.start-t.start);return 0===n.length?null:{rect:e.rect,contentExtent:r,contentBlocks:n}}(e);r&&t.push(r)}r.push(...e.children)}return t}(r);if(0===n.length)return new Map;let a=new Map;for(let t of e){if(!t.rect||!tt(t.type))continue;let r=function(e,t){let r=null,n=1/0;for(let a of t){let t=Math.abs(a.rect.width-e.width)+Math.abs(a.rect.height-e.height);if(t>32)continue;let i=4*t+(Math.abs(a.rect.x-e.x)+Math.abs(a.rect.y-e.y));i<n&&(r=a,n=i)}return r}(t.rect,n);if(!r)continue;let i=function(e,t){let r=function(e,t){let r=t,n=new Set;for(;!n.has(r.index);){var a,i;n.add(r.index);let o=e.filter(e=>e.parentIndex===r.index&&e.rect);if(1!==o.length)return r;let s=o[0];if(a=s.rect,i=t.rect,a.x!==i.x||a.y!==i.y||a.width!==i.width||a.height!==i.height)return r;r=s}return t}(e,t);return e.filter(e=>e.parentIndex===r.index&&e.rect).map(e=>e.rect).filter(e=>e.height>0).sort((e,t)=>e.y-t.y).map(e=>o4(e,t.rect))}(e,t),o=function(e){let{viewportRect:t,visibleBlocks:r,nativeScrollView:n}=e;if(0===r.length||0===n.contentBlocks.length)return null;let a=function(e){if(0===e.contentBlocks.length)return null;let t=e.contentBlocks[0],r=e.contentBlocks[e.contentBlocks.length-1];if(!t||!r)return null;let n=o3(e.contentBlocks.map(e=>e.size))??e.rect.height,a=Math.max(48,Math.round(.5*n)),i=Math.max(24,Math.round(.25*n)),o=t.start>=a,s=e.contentExtent-(r.start+r.size)>=i;return o||s?{above:o,below:s}:null}(n),i=function(e,t){let r=new Map;for(let n of e)for(let e of t){if(!o5(n,e))continue;let t=n.start-e.start,a=8*Math.round(t/8),i=r.get(a)??[];i.push(t),r.set(a,i)}let n=null;for(let e of r.values())(!n||e.length>n.length)&&(n=e);if(!n||n.length<2)return null;let a=[...n].sort((e,t)=>e-t);return a[Math.floor(a.length/2)]??null}(n.contentBlocks,r)??function(e){let{nativeBlocks:t,visibleBlocks:r,viewportExtent:n,contentExtent:a}=e,i=[],o=[];for(let e of t)for(let t of r){if(!o5(e,t))continue;let r=e.start-t.start;16>=Math.abs(r)&&i.push(r),16>=Math.abs(r+n-a)&&o.push(r)}return o.length>0?o3(o):i.length>0?o3(i):null}({nativeBlocks:n.contentBlocks,visibleBlocks:r,viewportExtent:t.height,contentExtent:n.contentExtent});if(null===i)return a;let o=t.height;return{above:(a?.above??!1)||i>16,below:(a?.below??!1)||i+o<n.contentExtent-16}}({viewportRect:t.rect,visibleBlocks:i,nativeScrollView:r});if(!o)continue;let s={};o.above&&(s.hiddenContentAbove=!0),o.below&&(s.hiddenContentBelow=!0),(s.hiddenContentAbove||s.hiddenContentBelow)&&a.set(t.index,s)}return a}(t,n):new Map}async function sl(e,t=e7(e)){try{return await U(()=>su(t),{shouldRetry:sc})}catch(t){var r,n;let e;if((r=t)instanceof O&&"COMMAND_FAILED"===r.code&&"number"==typeof r.details?.timeoutMs&&r.details?.cmd==="adb"&&(e=Array.isArray(n=r.details?.args)?n.map(String):"string"==typeof n?n.split(/\s+/):[]).includes("uiautomator")&&e.includes("dump")){let e="Android accessibility snapshots can be blocked by busy or continuously changing app UI. Use screenshot as visual truth after this timeout. Stock Android UIAutomator may still time out on app-owned infinite animations.";throw new O("COMMAND_FAILED",`Android UI hierarchy dump timed out while waiting for the UI to become idle. ${e}`,{...t.details??{},hint:e},t)}throw t}}async function su(e){var t,r;let n,a,i=await e(["exec-out","uiautomator","dump","/dev/tty"],{allowFailure:!0,timeoutMs:8e3}),o=sd(i.stdout,i.stderr);if(o)return o;let s="/sdcard/window_dump.xml",l=await e(["shell","uiautomator","dump",s],{allowFailure:!0,timeoutMs:8e3}),u=(t=l.stdout,r=l.stderr,n=`${t}
14
- ${r}`,a=/dumped to:\s*(\S+)/i.exec(n),a?.[1]);if(0!==l.exitCode&&!u)throw new O("COMMAND_FAILED","uiautomator dump did not return XML",{stdout:l.stdout,stderr:l.stderr,exitCode:l.exitCode,reason:"missing_fresh_dump"});let d=await e(["shell","cat",u??s]),c=sd(d.stdout,d.stderr);if(!c)throw new O("COMMAND_FAILED","uiautomator dump did not return XML",{stdout:d.stdout,stderr:d.stderr});return c}function sd(e,t){let r=`${e}
15
- ${t}`,n=r.indexOf("<?xml"),a=n>=0?n:r.indexOf("<hierarchy");if(a<0)return null;let i=r.lastIndexOf("</hierarchy>");if(i<0||i<a)return null;let o=r.slice(a,i+12).trim();return o.length>0?o:null}function sc(e){if(!(e instanceof O)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details?.stderr,r=("string"==typeof t?t:"").toLowerCase();return o8.some(e=>r.includes(e))}async function sp(e,t=e7(e)){try{let e=await t(["shell","dumpsys","activity","top"],{allowFailure:!0,timeoutMs:8e3}),r=`${e.stdout}
16
- ${e.stderr}`.trim();return r.length>0?r:null}catch{return null}}function sf(e,t,r){if(0===e.size)return;let n=new Map;for(let[e,t]of r.sourceNodes.entries()){let a=r.nodes[e];a&&n.set(t,a)}for(let[r,a]of e){let e=t.sourceNodes[r];if(!e)continue;let i=n.get(e);i&&(a.hiddenContentAbove&&(i.hiddenContentAbove=!0),a.hiddenContentBelow&&(i.hiddenContentBelow=!0))}}async function sm(e,t,r,n){let a=null,i=null,o=await sv(e);for(let s of[0,150,350]){s>0&&await e2(s);let l=await sw(e,t,r,n,o);if(a=l,"ime_capture"===l.reason)return l;i=l.ok?l:null}return i??a??{ok:!1,actual:null,reason:"text_mismatch",targetInput:null,actualInput:null}}async function sh(e,t,r){var n,a,i;return n=await sl(e),a=t,i=r,sg(n,a,i).actualInput?.text??null}async function sw(e,t,r,n,a){return function(e,t,r,n,a={}){var i,o;let s,l=sg(e,t,r,a);return!function(e){let{targetInput:t,actualInput:r}=e;return!!t&&!!r&&r!==t&&r.inputMethodOwned&&!t.inputMethodOwned}(l)?function(e,t){let r=e.actualInput;if(!r||!o0(r))return null;let n=r.text??null,a=Array.from(n??"").length,i=Array.from(t).length,o=null!==n&&a>0&&i>0&&a===i;return{ok:o,actual:n,reason:o?void 0:"masked_unverified",masked:!0,targetInput:e.targetInput,actualInput:r}}(l,n)??(i=l,o=n,{ok:function(e,t){if(e===t)return!0;let r=sy(e),n=sy(t);return!!r&&!!n&&!!(r===n||function(e,t){if(e.length!==t.length||0===e.length||e.slice(1)!==t.slice(1))return!1;let r=e[0],n=t[0];return!!r&&!!n&&n.toLowerCase()===n&&r===n.toUpperCase()}(r,n))}(s=i.actualInput?.text??null,o),actual:s,reason:"text_mismatch",targetInput:i.targetInput,actualInput:i.actualInput}):{ok:!1,actual:l.actualInput?.text??null,reason:"ime_capture",targetInput:l.targetInput,actualInput:l.actualInput}}(await sl(e),t,r,n,a)}function sg(e,t,r,n={}){var a;let i,o={focusedEdit:null,editAtPoint:null,anyAtPoint:null};for(let a of ts(e)){let e=function(e,t){if(!e.rect)return null;let r=e.text??"",n=Math.max(1,e.rect.width*e.rect.height);return{text:r||null,className:e.className,resourceId:e.resourceId,packageName:e.packageName,rect:e.rect,focused:e.focused??!1,password:!0===e.password,inputMethodOwned:ec({packageName:e.packageName,resourceId:e.resourceId,activeInputMethodPackage:t.activeInputMethodPackage}),area:n,editText:function(e){let t=e.toLowerCase();return t.includes("edittext")||t.includes("textfield")}(e.className??"")}}(a,n);e&&function(e,t,r,n){var a,i,o;let s=(a=t.rect,i=r,o=n,i>=a.x&&i<=a.x+a.width&&o>=a.y&&o<=a.y+a.height);if(s&&t.editText&&(e.editAtPoint=sI(e.editAtPoint,t)),t.focused&&t.editText){e.focusedEdit=sI(e.focusedEdit,t);return}s&&t.text&&(e.anyAtPoint=sI(e.anyAtPoint,t))}(o,e,t,r)}return{targetInput:i=(a=o).editAtPoint??a.anyAtPoint,actualInput:(a.focusedEdit?.text?a.focusedEdit:null)??i}}function sy(e){return(e??"").replace(/\s+/g," ").trim()}async function sv(e){try{return{activeInputMethodPackage:(await eo(e)).inputMethodPackage}}catch(e){return eM({level:"warn",phase:"android_fill_verification_input_method_probe_failed",data:{error:e instanceof Error?e.message:String(e)}}),{}}}function sI(e,t){return e&&e.area<t.area?e:t}async function sb(e,t,r){await Q(e,["shell","input","tap",String(t),String(r)])}async function sA(e,t,r,n,a,i=250){await Q(e,["shell","input","swipe",String(t),String(r),String(n),String(a),String(i)])}async function sS(e){await Q(e,["shell","input","keyevent","4"])}async function s_(e){await Q(e,["shell","input","keyevent","3"])}async function sx(e){await Q(e,["shell","input","keyevent","ENTER"])}async function sN(e,t){let r=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 O("INVALID_ARGS",`Unsupported Android rotation: ${e}`)}}(t);await Q(e,["shell","settings","put","system","accelerometer_rotation","0"]),await Q(e,["shell","settings","put","system","user_rotation",r])}async function sM(e){await Q(e,["shell","input","keyevent","187"])}async function sk(e,t,r,n=800){await Q(e,["shell","input","swipe",String(t),String(r),String(t),String(r),String(n)])}async function sD(e,t,r=0){let n=e8(e);if(n){await n({action:"type",text:t,delayMs:r}),sG("type","provider-native",t);return}(sU(t),await sE(e,"type"),r>0&&Array.from(t).length>1)?await sT(e,{action:"type",text:t,chunkSize:1,delayMs:r}):await sT(e,{action:"type",text:t,chunkSize:s$,delayMs:0})}async function sP(e,t,r){await sb(e,t,r)}async function sO(e,t,r,n,a=0){let i=e8(e);if(i){await i({action:"fill",target:{x:t,y:r},text:n,delayMs:a}),sG("fill","provider-native",n);let o=await sm(e,t,r,n);if(o.ok)return;sR(n,o)}sU(n);let o=Array.from(n).length,s=null;for(let i of[{clearPadding:12,minClear:8,maxClear:48,chunkSize:a>0?1:s$,inputDelayMs:a},{clearPadding:24,minClear:16,maxClear:96,chunkSize:a>0?1:4,inputDelayMs:a>0?a:15}]){var l,u;await sP(e,t,r),await sE(e,"fill");let a=(l=o+i.clearPadding,u=i.minClear,Math.max(u,Math.min(i.maxClear,l)));await sq(e,a),await sT(e,{action:"fill",text:n,chunkSize:i.chunkSize,delayMs:i.inputDelayMs});let d=await sm(e,t,r,n);if(s=d,d.ok)return;"ime_capture"===d.reason&&sR(n,d)}sR(n,s)}function sR(e,t){let r;throw new O("COMMAND_FAILED",t?.reason==="ime_capture"?"Android fill input was captured by the active keyboard instead of the app field":t?.reason==="masked_unverified"?"Android fill verification could not confirm masked text value":"Android fill verification failed",(r=function(e,t){var r;if(!t)return{expected:e,actual:null,failureReason:"text_mismatch",targetInput:null,actualInput:null};let n=!0===(r=t).masked||o0(r.targetInput)||o0(r.actualInput),a={failureReason:t.reason??"text_mismatch",targetInput:o1(t.targetInput),actualInput:o1(t.actualInput)};return n?{...a,expectedLength:Array.from(e).length,actual:null,masked:!0,actualLength:Array.from(t.actual??"").length}:{...a,expected:e,actual:t.actual}}(e,t),t?.reason==="ime_capture"&&(r.hint="The focused input belongs to the Android keyboard/IME, not the app field. Disable handwriting/stylus input or switch to a standard IME, then retry fill."),r))}async function sC(e,t,r){let n=await sL(e),a=oQ({direction:t,amount:r?.amount,pixels:r?.pixels,referenceWidth:n.width,referenceHeight:n.height});return await Q(e,["shell","input","swipe",String(a.x1),String(a.y1),String(a.x2),String(a.y2),"300"]),a}async function sE(e,t){let r;try{r=await eo(e)}catch(e){eM({level:"warn",phase:"android_input_ownership_probe_failed",data:{action:t,error:e instanceof Error?e.message:String(e)}});return}if("ime"===r.inputOwner)throw new O("COMMAND_FAILED","KEYBOARD_OVERLAY_BLOCKING: Android text input is blocked because the focused input belongs to the active keyboard/IME.",{failureReason:"ime_capture",action:t,inputOwner:r.inputOwner,inputType:r.inputType,type:r.type,inputMethodPackage:r.inputMethodPackage,focusedPackage:r.focusedPackage,focusedResourceId:r.focusedResourceId,nextAction:"Focused input appears to be owned by the keyboard/IME; dismiss or change the IME before retrying text entry."})}async function sL(e){let t=(await Q(e,["shell","wm","size"])).stdout.match(/Physical size:\s*(\d+)x(\d+)/);if(!t)throw new O("COMMAND_FAILED","Unable to read screen size");return{width:Number(t[1]),height:Number(t[2])}}let s$=8;async function sT(e,t){let r=t.text.split("\n");for(let[n,a]of r.entries()){let i=function(e,t){let r=Math.max(1,Math.floor(t)),n=[],a=Array.from(e);for(let e=0;e<a.length;e+=r)n.push(a.slice(e,e+r).join(""));return n.length>0?n:[""]}(a,t.chunkSize);for(let[a,o]of i.entries())await sF(e,o),t.delayMs>0&&(a+1<i.length||n+1<r.length)&&await e2(t.delayMs);n+1<r.length&&await Q(e,["shell","input","keyevent","ENTER"])}sG(t.action,"adb-shell",t.text)}async function sF(e,t){if(t)try{await Q(e,["shell","input","text",t.replace(/ /g,"%s")])}catch(e){if(function(e){if(!(e instanceof O)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details?.stderr,r=("string"==typeof t?t:"").toLowerCase();return!!(r.includes("exception occurred while executing 'text'")||r.includes("nullpointerexception")&&r.includes("inputshellcommand.sendtext"))}(e))throw sV(t,e);throw e}}function sU(e){if(!function(e){for(let t of e){let e=t.codePointAt(0);if(void 0!==e&&"\n"!==t&&(e<32||e>126))return!1}return!0}(e))throw sV(e)}function sV(e,t){return new O("COMMAND_FAILED","Android text input requires provider-native text injection for non-ASCII/control characters; the current adb-shell fallback supports ASCII text only.",{backend:"adb-shell",textLength:Array.from(e).length,textPreview:e.slice(0,32)},t instanceof Error?t:void 0)}function sG(e,t,r){eM({phase:"android_text_injection",data:{action:e,backend:t,textLength:Array.from(r).length}})}async function sq(e,t){let r=Math.max(0,t);await Q(e,["shell","input","keyevent","KEYCODE_MOVE_END"],{allowFailure:!0});for(let t=0;t<r;t+=24){let n=Math.min(24,r-t);await Q(e,["shell","input","keyevent",...Array(n).fill("KEYCODE_DEL")],{allowFailure:!0})}}async function sj(e,t,r){let n="string"==typeof r.action&&r.action.trim()?r.action.trim():`${t}.TEST_PUSH`,a=["shell","am","broadcast","-a",n,"-p",t],i="string"==typeof r.receiver?r.receiver.trim():"";i&&a.push("-n",i);let o=r.extras;if(void 0!==o&&("object"!=typeof o||null===o||Array.isArray(o)))throw new O("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,r){if("string"==typeof r)return e.push("--es",t,r);if("boolean"==typeof r)return e.push("--ez",t,r?"true":"false");if("number"==typeof r&&Number.isFinite(r))return Number.isInteger(r)?e.push("--ei",t,String(r)):e.push("--ef",t,String(r));throw new O("INVALID_ARGS",`Unsupported Android broadcast extra type for "${t}". Use string, boolean, or number.`)}(a,e,t),s+=1);return await Q(e,a),{action:n,extrasCount:s}}let sB="android-multitouch-helper-v1",sH="ANDROID_MULTITOUCH_HELPER_NO_FINAL_RESULT",sW="ANDROID_MULTITOUCH_HELPER_REPORTED_FAILURE";async function sz(e,t){if(!Number.isFinite(t.scale)||t.scale<=0)throw new O("INVALID_ARGS","gesture pinch requires scale > 0");let r=await sX(e,t.x,t.y);return await sY(e,{kind:"pinch",x:r.x,y:r.y,scale:t.scale,durationMs:t.durationMs})}async function sK(e,t){if(!Number.isFinite(t.degrees))throw new O("INVALID_ARGS","gesture rotate requires finite degrees");if(void 0!==t.velocity&&(!Number.isFinite(t.velocity)||0===t.velocity))throw new O("INVALID_ARGS","gesture rotate velocity must be a non-zero number");let r=await sX(e,t.x,t.y),n=t.degrees;return await sY(e,{kind:"rotate",x:r.x,y:r.y,degrees:n,durationMs:t.durationMs})}async function sJ(e,t){if(!Number.isFinite(t.scale)||t.scale<=0)throw new O("INVALID_ARGS","gesture transform requires scale > 0");if(!Number.isFinite(t.degrees))throw new O("INVALID_ARGS","gesture transform requires finite degrees");if(![t.x,t.y,t.dx,t.dy].every(Number.isFinite))throw new O("INVALID_ARGS","gesture transform requires finite x y dx dy");return await sY(e,{kind:"transform",x:t.x,y:t.y,dx:t.dx,dy:t.dy,scale:t.scale,degrees:t.degrees,durationMs:t.durationMs})}async function sX(e,t,r){if(void 0!==t&&void 0!==r)return{x:t,y:r};let n=await sL(e);return{x:Math.round(n.width/2),y:Math.round(n.height/2)}}async function sY(e,t){let r=e9(e);if(r)return{backend:"provider-native-touch",...await r(t)??{}};let n=e7(e),a=await s0(),i=e6(e),o=await eN("android_multitouch_helper_install",async()=>{var t;return await s1({adb:n,adbProvider:i,artifact:a,deviceKey:(t=e,`${t.platform}:${t.id}`)})},{packageName:a.manifest.packageName,versionCode:a.manifest.versionCode});eM({phase:"android_multitouch_helper_install_decision",data:o});let s=await eN("android_multitouch_helper_gesture",async()=>await sZ({adb:n,request:function(e){var t;let r=Math.round(void 0!==(t=e).durationMs?t.durationMs:"pinch"===t.kind?300:Math.min(Math.max(300,16*Math.ceil(Math.abs(t.degrees)/3)),2400));switch(e.kind){case"pinch":return{kind:"pinch",x:Math.round(e.x),y:Math.round(e.y),scale:e.scale,radius:160,durationMs:r};case"rotate":return{kind:"rotate",x:Math.round(e.x),y:Math.round(e.y),degrees:e.degrees,radius:160,durationMs:r};case"transform":return{kind:"transform",x:Math.round(e.x),y:Math.round(e.y),dx:Math.round(e.dx),dy:Math.round(e.dy),scale:e.scale,degrees:e.degrees,durationMs:r}}}(t),packageName:a.manifest.packageName,instrumentationRunner:a.manifest.instrumentationRunner}),{packageName:a.manifest.packageName,version:a.manifest.version});return{backend:"android-multitouch-helper",helperVersion:a.manifest.version,installReason:o.reason,...s}}async function sZ(e){let t,r=Buffer.from(JSON.stringify({protocol:sB,...e.request})).toString("base64"),n=await e.adb(["shell","am","instrument","-w","-e","payloadBase64",r,e.instrumentationRunner],{allowFailure:!0,timeoutMs:45e3});try{t=function(e){let t=(function(e){let t=[],r=null;for(let n of e.split(/\r?\n/))n.startsWith("INSTRUMENTATION_RESULT: ")?(r??={},function(e,t){let r=e.indexOf("=");r>=0&&(t[e.slice(0,r)]=e.slice(r+1))}(n.slice(24),r)):n.startsWith("INSTRUMENTATION_CODE: ")&&r&&(t.push(r),r=null);return r&&t.push(r),t})(e).find(e=>e.agentDeviceProtocol===sB);if(!t)throw new O(sH,"Android multi-touch helper did not return a final result");if("true"!==t.ok){var r;throw new O(sW,(r=t).message&&"null"!==r.message?r.message:r.errorType||"Android multi-touch helper returned an error",{errorType:t.errorType,helper:t})}return{kind:t.kind,helperApiVersion:t.helperApiVersion,injectedEvents:sQ(t.injectedEvents),elapsedMs:sQ(t.elapsedMs)}}(`${n.stdout}
17
- ${n.stderr}`)}catch(e){if(e instanceof O){if(e.code===sW)throw new O("COMMAND_FAILED",e.message,e.details,e);if(e.code!==sH)throw e}throw new O("COMMAND_FAILED",0===n.exitCode?"Android multi-touch helper output could not be parsed":"Android multi-touch helper failed before returning parseable output",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode},e)}if(0!==n.exitCode)throw new O("COMMAND_FAILED","Android multi-touch helper failed",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode,helper:t});return t}function sQ(e){if(void 0===e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}async function s0(){let e=eE(),t=f.join(eL(),"android-multitouch-helper","dist"),r=f.join(t,`agent-device-android-multitouch-helper-${e}.manifest.json`);try{let e=function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new O("INVALID_ARGS","Android multi-touch helper manifest must be an object.");return{name:s6(e.name,"name","android-multitouch-helper"),version:s8(e.version,"version"),assetName:s8(e.assetName,"assetName"),sha256:function(e){let t=s8(e,"sha256").trim().toLowerCase();if(64!==t.length||!/^[0-9a-f]+$/.test(t))throw new O("INVALID_ARGS","Android multi-touch helper manifest sha256 must be a 64-character hex string.");return t}(e.sha256),packageName:s6(e.packageName,"packageName","com.callstack.agentdevice.multitouchhelper"),versionCode:function(e,t){if(!Number.isInteger(e))throw new O("INVALID_ARGS",`Android multi-touch helper manifest ${t} must be an integer.`);return e}(e.versionCode,"versionCode"),instrumentationRunner:s6(e.instrumentationRunner,"instrumentationRunner","com.callstack.agentdevice.multitouchhelper/.MultiTouchInstrumentation"),statusProtocol:s6(e.statusProtocol,"statusProtocol",sB)}}(JSON.parse(await S.readFile(r,"utf8"))),n=f.join(t,e.assetName);return await S.access(n),{apkPath:n,manifest:e}}catch(e){throw new O("UNSUPPORTED_OPERATION","gesture pinch/rotate/transform on Android requires the bundled Android multi-touch helper artifact, but it was not found or could not be read",{manifestPath:r,error:P(e).message},e)}}async function s1(e){let{adb:t,artifact:r}=e,n=r.manifest.packageName,a=r.manifest.versionCode,i=`${e.deviceKey}\0${n}\0${a}`;if(s2.has(i))return{packageName:n,versionCode:a,installed:!1,reason:"current"};let o=await s3(t,n);if(void 0!==o&&o>=a)return s2.add(i),{packageName:n,versionCode:a,installedVersionCode:o,installed:!1,reason:"current"};await s5(r);let s=await te(r.apkPath,{provider:e.adbProvider,replace:!0,allowTestPackages:!0,allowFailure:!0,timeoutMs:3e4});if(0!==s.exitCode)throw new O("COMMAND_FAILED","Failed to install Android multi-touch helper",{packageName:n,versionCode:a,stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode});return s2.add(i),{packageName:n,versionCode:a,installedVersionCode:o,installed:!0,reason:void 0===o?"missing":"outdated"}}let s2=new Set;async function s3(e,t){let r=await e(["shell","cmd","package","list","packages","--show-versioncode",t],{allowFailure:!0,timeoutMs:5e3});if(0!==r.exitCode)return;let n=RegExp(`package:${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:\\s|$).*versionCode:(\\d+)`).exec(`${r.stdout}
18
- ${r.stderr}`);return n?Number(n[1]):void 0}async function s5(e){let t=await s4(e.apkPath);if(t!==e.manifest.sha256)throw new O("COMMAND_FAILED","Android multi-touch helper APK checksum mismatch",{apkPath:e.apkPath,expectedSha256:e.manifest.sha256,actualSha256:t})}async function s4(e){let t=o.createHash("sha256");return t.update(await S.readFile(e)),t.digest("hex")}function s8(e,t){if("string"!=typeof e||0===e.length)throw new O("INVALID_ARGS",`Android multi-touch helper manifest ${t} is required.`);return e}function s6(e,t,r){if(e!==r)throw new O("INVALID_ARGS",`Android multi-touch helper manifest ${t} must be "${r}".`);return r}function s9(e){return e.map(e=>({args:e.args.join(" "),exitCode:e.exitCode,stderr:e.stderr.slice(0,400)}))}let s7=["camera","microphone","photos","contacts","contacts-limited","notifications","calendar","location","location-always","media-library","motion","reminders","siri"];function le(e){let t=e.trim().toLowerCase();if("grant"===t)return"grant";if("deny"===t)return"deny";if("reset"===t)return"reset";throw new O("INVALID_ARGS",`Invalid permission action: ${e}. Use grant|deny|reset.`)}function lt(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 O("INVALID_ARGS",`permission setting requires a target: ${s7.join("|")}`)}function lr(e){let t=e.trim().toLowerCase();if("light"===t)return"light";if("dark"===t)return"dark";if("toggle"===t)return"toggle";throw new O("INVALID_ARGS",`Invalid appearance state: ${e}. Use light|dark|toggle.`)}function ln(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 O("INVALID_ARGS",`Invalid setting state: ${e}`)}let la=["window_animation_scale","transition_animation_scale","animator_duration_scale"];async function li(e,t,r,n,a){switch(t.toLowerCase()){case"wifi":{let t=ln(r);await Q(e,["shell","svc","wifi",t?"enable":"disable"]);return}case"airplane":{let t=ln(r);await Q(e,["shell","settings","put","global","airplane_mode_on",t?"1":"0"]),await Q(e,["shell","am","broadcast","-a","android.intent.action.AIRPLANE_MODE","--ez","state",t?"true":"false"]);return}case"location":{if("set"===r.toLowerCase()){if("emulator"!==e.kind)throw new O("UNSUPPORTED_OPERATION","Android precise location coordinates are supported only on emulators.",{deviceId:e.id,hint:"Use an Android emulator for adb emu geo fix, or configure location through device/provider tooling."});let{latitude:t,longitude:r}=e$(a);return await Q(e,["emu","geo","fix",String(r),String(t)]),{latitude:t,longitude:r}}let t=ln(r);await Q(e,["shell","settings","put","secure","location_mode",t?"3":"0"]);return}case"animations":{let t=ln(r)?"1":"0";for(let r of la)await Q(e,["shell","settings","put","global",r,t]);return{scale:t,keys:[...la]}}case"appearance":{let t=await ls(e,r);await Q(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 O("INVALID_ARGS",`Invalid fingerprint state: ${e}. Use match|nonmatch.`)}(r);await lo(e,t);return}case"permission":{if(!n)throw new O("INVALID_ARGS","permission setting requires an active app in session");let t=le(r),i=function(e,t){let r=lt(e);if(t?.trim())throw new O("INVALID_ARGS",`Permission mode is only supported for photos. Received: ${t}.`);if("camera"===r)return{kind:"pm",value:"android.permission.CAMERA",type:"camera"};if("microphone"===r)return{kind:"pm",value:"android.permission.RECORD_AUDIO",type:"microphone"};if("photos"===r)return{kind:"pm",value:"android.permission.READ_MEDIA_IMAGES",type:"photos"};if("contacts"===r)return{kind:"pm",value:"android.permission.READ_CONTACTS",type:"contacts"};if("notifications"===r)return{kind:"notifications",appOps:"POST_NOTIFICATION",permission:"android.permission.POST_NOTIFICATIONS"};throw new O("INVALID_ARGS",`Unsupported permission target on Android: ${e}. Use camera|microphone|photos|contacts|notifications.`)}(a?.permissionTarget,a?.permissionMode);if("notifications"===i.kind)return void await lu(e,n,t,i);let o="grant"===t?"grant":"revoke";if("photos"===i.type)return void await ll(e,n,o);await Q(e,["shell","pm",o,n,i.value]);return}default:throw new O("INVALID_ARGS",`Unsupported setting: ${t}`)}}async function lo(e,t){var r;let n,a,i=(r=e,a=[["shell","cmd","fingerprint","touch",n="match"===t?"1":"9999"],["shell","cmd","fingerprint","finger",n]],"emulator"===r.kind&&a.push(["emu","finger","touch",n]),a),o=[];for(let t of i){let r=await Q(e,t,{allowFailure:!0});if(0===r.exitCode)return;o.push({args:t,stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode})}let s=s9(o);if(o.length>0&&o.every(e=>{var t,r;let n;return t=e.stdout,r=e.stderr,(n=`${t}
19
- ${r}`.toLowerCase()).includes("unknown command")||n.includes("can't find service: fingerprint")||n.includes("service fingerprint was not found")||n.includes("fingerprint cmd unavailable")||n.includes("emu command is not supported")||n.includes("emulator console is not running")||n.includes("fingerprint")&&n.includes("not found")}))throw new O("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 O("COMMAND_FAILED","Failed to simulate Android fingerprint.",{deviceId:e.id,action:t,attempts:s})}async function ls(e,t){let r=lr(t);if("toggle"!==r)return r;let n=await Q(e,["shell","cmd","uimode","night"],{allowFailure:!0});if(0!==n.exitCode)throw new O("COMMAND_FAILED","Failed to read current Android appearance",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode});let a=function(e,t){let r=/night mode:\s*(yes|no|auto)\b/i.exec(`${e}
20
- ${t}`);if(!r)return null;let n=r[1]?.toLowerCase();return"yes"===n?"dark":"no"===n?"light":"auto"===n?"auto":null}(n.stdout,n.stderr);if(!a)throw new O("COMMAND_FAILED","Unable to determine current Android appearance for toggle",{stdout:n.stdout,stderr:n.stderr});return"auto"===a?"dark":"dark"===a?"light":"dark"}async function ll(e,t,r){let n=await ld(e),a=[];for(let i of null!==n&&n>=33?["android.permission.READ_MEDIA_IMAGES","android.permission.READ_EXTERNAL_STORAGE"]:["android.permission.READ_EXTERNAL_STORAGE","android.permission.READ_MEDIA_IMAGES"]){let n=await Q(e,["shell","pm",r,t,i],{allowFailure:!0});if(0===n.exitCode)return;a.push({permission:i,stderr:n.stderr,exitCode:n.exitCode})}throw new O("COMMAND_FAILED",`Failed to ${r} Android photos permission`,{appPackage:t,sdkInt:n,attempts:a})}async function lu(e,t,r,n){"grant"===r?await Q(e,["shell","pm","grant",t,n.permission],{allowFailure:!0}):(await Q(e,["shell","pm","revoke",t,n.permission],{allowFailure:!0}),"reset"===r&&(await Q(e,["shell","pm","clear-permission-flags",t,n.permission,"user-set"],{allowFailure:!0}),await Q(e,["shell","pm","clear-permission-flags",t,n.permission,"user-fixed"],{allowFailure:!0}))),await Q(e,["shell","appops","set",t,n.appOps,"grant"===r?"allow":"deny"===r?"deny":"default"])}async function ld(e){let t=await Q(e,["shell","getprop","ro.build.version.sdk"],{allowFailure:!0});if(0!==t.exitCode)return null;let r=Number.parseInt(t.stdout.trim(),10);return!Number.isFinite(r)||r<=0?null:r}let lc=Buffer.from([137,80,78,71,13,10,26,10]);async function lp(e,t,r={}){if(!1===r.stabilize)return void await lh(e,t);await lf(e);try{await e2(1e3),await lh(e,t)}finally{await lm(e).catch(()=>{})}}async function lf(e){let t=t=>Q(e,["shell",t],{allowFailure:!0});await t("settings put global sysui_demo_allowed 1");let r=e=>t(`am broadcast -a com.android.systemui.demo -e command ${e}`);await r("clock -e hhmm 0941"),await r("notifications -e visible false")}async function lm(e){await Q(e,["shell","am broadcast -a com.android.systemui.demo -e command exit"],{allowFailure:!0})}async function lh(e,t){let r=await Q(e,["exec-out","screencap","-p"],{binaryStdout:!0});if(!r.stdoutBuffer)throw new O("COMMAND_FAILED","Failed to capture screenshot");let n=r.stdoutBuffer.indexOf(lc);if(n<0)throw new O("COMMAND_FAILED","Screenshot data does not contain a valid PNG header");let a=function(e,t){let r=t+lc.length;for(;r+8<=e.length;){let t=e.readUInt32BE(r),n=r+4,a=e.toString("ascii",n,n+4),i=r+12+t;if(i>e.length)break;if("IEND"===a)return i;r=i}return null}(r.stdoutBuffer,n);if(!a)throw new O("COMMAND_FAILED","Screenshot data does not contain a complete PNG payload");await d.writeFile(t,r.stdoutBuffer.subarray(n,a))}let lw="--launch-console is supported only for iOS simulator app launches",lg="--launch-console requires a direct app launch and cannot be used with URL opens";function ly(e){if(!(e instanceof O)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{};if(4!==t.exitCode)return!1;let r=String(t.stderr??"").toLowerCase();return r.includes("fbsopenapplicationserviceerrordomain")&&r.includes("the request to open")}async function lv(e,t){let r=await rM(rO(e,["get_app_container",e.id,t]),{allowFailure:!0});if(0!==r.exitCode)return{installed:!1};let n=r.stdout.trim();if(!n)return{installed:!1};let a=await rN("plutil",["-extract","CFBundleExecutable","raw","-o","-",`${n}/Info.plist`],{allowFailure:!0});if(0!==a.exitCode||!a.stdout.trim())return{installed:!0};let i=a.stdout.trim(),o=`${n}/${i}`,s=await rN("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 lI(e,t){if("simulator"!==e.kind)throw new O("UNSUPPORTED_OPERATION",`${t} is only supported on iOS simulators`)}async function lb(){await rN("open",["-a","Simulator"],{allowFailure:!0,timeoutMs:1e4})}async function lA(e){let t,r;if("simulator"!==e.kind||"Booted"===await l_(e))return;let n=en.fromTimeoutMs(18e4);try{await el(async({deadline:n})=>{if(n?.isExpired())throw new O("COMMAND_FAILED","iOS simulator boot deadline exceeded",{timeoutMs:18e4});let a=Math.max(1e3,n?.remainingMs()??18e4),i=await rM(rO(e,["boot",e.id]),{allowFailure:!0,timeoutMs:a});t={stdout:String(i.stdout??""),stderr:String(i.stderr??""),exitCode:i.exitCode};let o=`${t.stdout}
21
- ${t.stderr}`.toLowerCase(),s=o.includes("already booted")||o.includes("current state: booted");if(0!==t.exitCode&&!s)throw new O("COMMAND_FAILED","simctl boot failed",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});let l=await rM(rO(e,["bootstatus",e.id,"-b"]),{allowFailure:!0,timeoutMs:a});if(r={stdout:String(l.stdout??""),stderr:String(l.stderr??""),exitCode:l.exitCode},0!==r.exitCode)throw new O("COMMAND_FAILED","simctl bootstatus failed",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode});let u=await l_(e);if("Booted"!==u)throw new O("COMMAND_FAILED","Simulator is still booting",{state:u})},{maxAttempts:3,baseDelayMs:500,maxDelayMs:2e3,jitter:.2,shouldRetry:e=>{let n=G({error:e,stdout:r?.stdout??t?.stdout,stderr:r?.stderr??t?.stderr,context:{platform:"ios",phase:"boot"}});return"IOS_BOOT_TIMEOUT"!==n&&"CI_RESOURCE_STARVATION_SUSPECTED"!==n}},{deadline:n,phase:"boot",classifyReason:e=>G({error:e,stdout:r?.stdout??t?.stdout,stderr:r?.stderr??t?.stderr,context:{platform:"ios",phase:"boot"}})})}catch(i){let a=G({error:i,stdout:r?.stdout??t?.stdout,stderr:r?.stderr??t?.stderr,context:{platform:"ios",phase:"boot"}});throw new O("COMMAND_FAILED","iOS simulator failed to boot",{platform:"ios",deviceId:e.id,timeoutMs:18e4,elapsedMs:n.elapsedMs(),reason:a,hint:ei(a),boot:t,bootstatus:r})}await lb()}async function lS(e){let t=rO(e,["shutdown",e.id]),r=await rM(t,{allowFailure:!0,timeoutMs:15e3});return{success:0===r.exitCode,exitCode:r.exitCode,stdout:String(r.stdout??""),stderr:String(r.stderr??"")}}async function l_(e){let t="string"==typeof e?e:e.id,r="string"==typeof e?rP(["list","devices","-j"]):rO(e,["list","devices","-j"]),n=await rM(r,{allowFailure:!0,timeoutMs:6e4});if(0!==n.exitCode)return null;try{let e=JSON.parse(String(n.stdout??""));for(let r of Object.values(e.devices??{})){let e=r.find(e=>e.udid===t);if(e)return e.state}return null}catch{return null}}async function lx(e,t){try{let r=await rk(e),n=r?.[t];if("string"==typeof n&&n.length>0)return n}catch{}try{let r=await rN("plutil",["-extract",t,"raw","-o","-",e],{allowFailure:!0});if(0===r.exitCode){let e=String(r.stdout??"").trim();if(e.length>0)return e}}catch{}try{var r,n;let a;return r=await d.readFile(e,"utf8"),n=t,ne(r7(r),(e,t)=>{void 0===a&&e===n&&"string"===t.name&&(a=t.text??void 0)}),a}catch{return}}async function lN(e,t){let r;if("url"===e.kind&&!tj(e.url))throw new O("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 tq({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||tj(e.url),signal:t?.signal});try{let e=r=await lk(n.installablePath,t),a=await lM(e.installPath);return{archivePath:n.archivePath??(n.installablePath.toLowerCase().endsWith(".ipa")?n.installablePath:void 0),installablePath:e.installPath,bundleId:a.bundleId,appName:a.appName,cleanup:async()=>{await e.cleanup(),await n.cleanup()}}}catch(e){try{await r?.cleanup()}finally{await n.cleanup()}throw e}}async function lM(e){let t=f.join(e,"Info.plist"),[r,n,a]=await Promise.all([lx(t,"CFBundleIdentifier"),lx(t,"CFBundleDisplayName"),lx(t,"CFBundleName")]);return{bundleId:r,appName:n??a}}async function lk(e,t){if(!e.toLowerCase().endsWith(".ipa"))return{installPath:e,cleanup:async()=>{}};let r=await d.mkdtemp(f.join(c.tmpdir(),"agent-device-ios-ipa-")),n=async()=>{await d.rm(r,{recursive:!0,force:!0})};try{await E("unzip",["-q",e,"-d",r]);let a=f.join(r,"Payload"),i=(await d.readdir(a,{withFileTypes:!0}).catch(()=>{throw new O("INVALID_ARGS","Invalid IPA: missing Payload directory")})).filter(e=>e.isDirectory()&&e.name.toLowerCase().endsWith(".app")).map(e=>({installPath:f.join(a,e.name),bundleName:e.name.replace(/\.app$/i,"")})),o=i[0];if(void 0!==o&&1===i.length)return{installPath:o.installPath,cleanup:n};if(0===i.length)throw new O("INVALID_ARGS","Invalid IPA: expected at least one .app under Payload, found 0");await lD(i);let s=t?.appIdentifierHint?.trim();if(s){let e=function(e,t){let r=t.toLowerCase(),n=e.filter(e=>e.bundleName.toLowerCase()===r);if(1===n.length)return n[0];if(n.length>1)throw new O("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()===r);if(1===t.length)return t[0]}}(i,s);if(e)return{installPath:e.installPath,cleanup:n};throw new O("INVALID_ARGS",`Invalid IPA: found ${i.length} .app bundles under Payload and none matched "${s}". Available bundles: ${i.map(lP).join(", ")}`)}throw new O("INVALID_ARGS",`Invalid IPA: found ${i.length} .app bundles under Payload. Pass an app identifier or bundle name matching one of: ${i.map(lP).join(", ")}`)}catch(e){throw await n(),e}}async function lD(e){await Promise.all(e.map(async e=>{if(e.bundleId&&e.appName)return;let t=await lM(e.installPath);e.bundleId=e.bundleId??t.bundleId,e.appName=e.appName??t.appName}))}function lP(e){let t=e.bundleId??e.appName;return t?`${e.bundleName}.app (${t})`:`${e.bundleName}.app`}let lO="agent-device-macos-helper",lR="AGENT_DEVICE_MACOS_HELPER_BIN",lC=f.join(c.homedir(),".agent-device","macos-helper","current"),lE=f.join(lC,"manifest.json"),lL=/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+$/;function l$(e){let t=e.trim();if(!lL.test(t))throw new O("INVALID_ARGS","macOS bundle id must use reverse-DNS form like com.example.App",{bundleId:e});return t}function lT(e,t){t.bundleId&&e.push("--bundle-id",l$(t.bundleId)),t.surface&&e.push("--surface",t.surface)}function lF(){return function(e){let t=f.dirname(e);for(;;){let e=f.join(t,"macos-helper");if(u(f.join(e,"Package.swift")))return e;let r=f.dirname(t);if(r===t)break;t=r}throw new O("COMMAND_FAILED","Unable to locate macOS helper package root",{modulePath:e})}(y(import.meta.url))}async function lU(e){let t=await d.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(async t=>{let r=f.join(e,t.name);return t.isDirectory()?".build"===t.name?[]:await lU(r):t.isFile()&&(t.name.endsWith(".swift")||"Package.swift"===t.name)?[r]:[]}))).flat().sort()}async function lV(e){let t=await lU(e),r=s("sha256");for(let n of t)r.update(f.relative(e,n)),r.update("\0"),r.update(await d.readFile(n)),r.update("\0");let n=await rN("swift",["--version"],{allowFailure:!0,cwd:e,timeoutMs:1e4});return r.update("swift-version"),r.update("\0"),r.update(n.stdout||n.stderr||`exit:${n.exitCode}`),r.update("\0"),r.digest("hex")}async function lG(){try{let e=JSON.parse(await d.readFile(lE,"utf8"));return"string"==typeof e.fingerprint?e.fingerprint:null}catch{return null}}async function lq(){let e=await T(process.env[lR],lR);if(e)return e;let t=lF(),r=await lV(t),n=f.join(lC,lO);try{if(await lG()===r)return await d.access(n),n}catch{}let a=f.join(lF(),".build","release",lO);process.stderr.write("agent-device: building macOS helper (first run or helper update)\n"),await rN("swift",["build","-c","release","--package-path",t],{cwd:t,timeoutMs:12e4}),await d.mkdir(lC,{recursive:!0});let i=`${n}.tmp`;return await d.copyFile(a,i),await d.rename(i,n),await d.chmod(n,493),await d.writeFile(lE,`${JSON.stringify({fingerprint:r},null,2)}
22
- `,"utf8"),n}async function lj(){let e=process.env[lR]?.trim();if(e){let t=await T(e,lR);if(t)return t}if(rA.hasScope())return lO;if("darwin"!==process.platform)throw new O("UNSUPPORTED_PLATFORM","macOS helper is only available on macOS");return await lq()}async function lB(e){let t={allowFailure:!0,timeoutMs:3e4},r=r_().macosHelper,n=r?lO:await lj(),a=r?await r.run(e,t):await rN(n,e,t),i=a.stdout.trim(),o=null;if(i)try{o=JSON.parse(i)}catch{o=null}if(0===a.exitCode&&o?.ok)return o.data;throw new O("COMMAND_FAILED",o&&!o.ok?o.error?.message??`macOS helper exited with code ${a.exitCode}`:i||a.stderr.trim()||`macOS helper exited with code ${a.exitCode}`,{helperPath:n,args:e,stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode,...o&&!o.ok?o.error?.details:{}})}async function lH(){return await lB(["app","frontmost"])}async function lW(e){return await lB(["app","quit","--bundle-id",l$(e)])}async function lz(e,t){return await lB(["permission",e,t])}async function lK(e,t={}){let r=["alert",e];return lT(r,t),await lB(r)}async function lJ(e,t={}){let r=["snapshot","--surface",e];return lT(r,t),await lB(r)}async function lX(e,t,r={}){let n=["read","--x",String(e),"--y",String(t)];return lT(n,r),await lB(n)}async function lY(e,t,r={}){let n=["press","--x",String(e),"--y",String(t)];return lT(n,r),await lB(n)}async function lZ(e,t={}){let r=["screenshot","--out",e];return lT(r,t),t.fullscreen&&r.push("--fullscreen"),await lB(r)}let lQ={settings:"com.apple.systempreferences"},l0=/^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/,l1={platform:"macos",deviceId:"host",variant:"all"},l2=ef();async function l3(e){let t=e.trim(),r=lQ[t.toLowerCase()];if(r)return r;if(l0.test(t))return t;let n=l2.get(l1,t);if(n)return n;let a=(await ue("all")).filter(e=>e.name.toLowerCase()===t.toLowerCase()),i=a[0];if(void 0!==i&&1===a.length)return l2.set(l1,t,i.bundleId);if(a.length>1)throw new O("INVALID_ARGS",`Multiple apps matched "${e}"`,{matches:a});throw new O("APP_NOT_INSTALLED",`No app found matching "${e}"`)}async function l5(e,t,r){let n=r?.url?.trim();if(n){if(!em(n))throw new O("INVALID_ARGS","open <app> <url> requires a valid URL target");let e=r?.appBundleId??await l3(t);await ut().openBundle(e,n);return}let a=t.trim();if(em(a))return void await ut().openTarget(a);let i=r?.appBundleId??await l3(a);await ut().openBundle(i)}async function l4(e,t){let r=await l3(t),n=await lW(r);if(n.running&&!n.terminated&&!n.forceTerminated)throw new O("COMMAND_FAILED",`Failed to close macOS app ${t}`,{bundleId:r,running:n.running,terminated:n.terminated,forceTerminated:n.forceTerminated})}async function l8(){return await ut().readClipboard()}async function l6(e){await ut().writeClipboard(e)}async function l9(){return await ut().readDarkMode()}async function l7(e){let t=lr(e),r="toggle"===t?!await l9():"dark"===t;await ut().setDarkMode(r)}async function ue(e){return await ut().listApps(e)}function ut(){let e=r_().macosHost;if(!e)throw new O("UNSUPPORTED_OPERATION","macOS host provider is not available");return e}function ur(e){if(!(e instanceof O))return{reason:e instanceof Error?e.message:String(e)};let t=e.details??{},r=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:r}}let un=["--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"},ui={1:"searching",2:"failed",3:"active"},uo={0:"notSupported",1:"searching",2:"failed",3:"active"};function us(e,t,r){return rM(rO(e,t),r)}async function ul(e,t){var r,n;let a;await ud(e),t&&await uc(e,(a=[],(r=t).dataNetwork&&a.push("--dataNetwork",r.dataNetwork),r.wifiMode&&a.push("--wifiMode",r.wifiMode),void 0!==r.wifiBars&&("wifi"===r.dataNetwork||r.wifiMode)&&a.push("--wifiBars",r.wifiBars),r.cellularMode&&a.push("--cellularMode",r.cellularMode),void 0!==r.cellularBars&&(r.cellularMode||(n=r.dataNetwork)&&"hide"!==n&&"wifi"!==n||void 0!==r.operatorName)&&a.push("--cellularBars",r.cellularBars),void 0!==r.operatorName&&a.push("--operatorName",r.operatorName),a))}async function uu(e){let t=await us(e,["status_bar",e.id,"list"],{allowFailure:!0});if(0!==t.exitCode)throw new O("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 r 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(r);if(e){let r=Number(e[1]),n=ua[r];if(!n)throw new O("COMMAND_FAILED",`Unsupported simulator data network type: ${r}`);t.dataNetwork=n;continue}let n=/^WiFi Mode:\s+(\d+),\s+WiFi Bars:\s+(\d+)$/.exec(r);if(n){let e=ui[Number(n[1])];e&&(t.wifiMode=e),t.wifiBars=n[2];continue}let a=/^Cell Mode:\s+(\d+),\s+Cell Bars:\s+(\d+)$/.exec(r);if(a){let e=Number(a[1]),r=uo[e];if(!r)throw new O("COMMAND_FAILED",`Unsupported simulator cellular mode: ${e}`);t.cellularMode=r,t.cellularBars=a[2];continue}let i=/^Operator Name:\s*(.*)$/.exec(r);if(i){t.operatorName=i[1]??"";continue}}return 0===Object.keys(t).length?null:t}(t.stdout)}async function ud(e){await us(e,["status_bar",e.id,"clear"])}async function uc(e,t){0!==t.length&&await us(e,["status_bar",e.id,"override",...t])}function up(e,t,r){eM({level:"warn",phase:`ios_screenshot_status_bar_${t}`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,...ur(r)}})}function uf(e,t,r){return rM(rO(e,t),r)}let um={ensureBooted:lA,prepareStatusBarForScreenshot:async function e(e){let t=null,r=!1;try{t=await uu(e),r=!0}catch(t){up(e,"snapshot_failed",t)}try{await ud(e),await uc(e,un)}catch(t){up(e,"prepare_failed",t)}return async()=>{await ul(e,r?t:null)}},captureWithRetry:ug,captureWithRunner:uy,shouldFallbackToRunner:u_};async function uh(e,t,r,n,a){if("macos"===e.platform)return void await uy(e,t,r,n,a);if("simulator"===e.kind)return void await uw(e,t,r,n,void 0,a);try{await oG(["device","screenshot","--device",e.id,t],{action:"capture iOS screenshot",deviceId:e.id});return}catch(t){if(!function(e){if(!(e instanceof O)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{},r="string"==typeof t.stdout?t.stdout:"",n="string"==typeof t.stderr?t.stderr:"",a=`${e.message}
3
+ ${r}`.toLowerCase()).includes("device is busy")&&n.includes("connecting")?"Target iOS device is still connecting. Keep it unlocked, wait for device trust/connection to settle, then retry.":`${en("IOS_RUNNER_CONNECT_TIMEOUT")} ${r$}`)})}function rq(e){return"interactionFrame"===e||"snapshot"===e||"screenshot"===e||"findText"===e||"querySelector"===e||"readText"===e||"alert"===e||"uptime"===e}function rB(e){if(rh(e))throw rg()}let rj=new Map;async function rH(e,t,r,n,a=45e3,i,o){let s=et.fromTimeoutMs(a),{getEndpoints:l}=rz(e,t),{endpoints:u}=await l(s.remainingMs()),d=null,c=Math.max(1,Math.ceil(a/250));try{return await es(async({deadline:s})=>{if(s?.isExpired())throw new D("COMMAND_FAILED","Runner connection deadline exceeded",{port:t,timeoutMs:a});if(i&&null!==i.child.exitCode&&void 0!==i.child.exitCode)throw await rG({session:i,port:t,logPath:n});let c=!1;if("device"===e.kind){let e=await l(s?.remainingMs());u=e.endpoints,c=e.cached}let p=c?u[0]:null,f=await rK(u,{command:r,port:t,timeoutMs:a,signal:o,attemptDeadline:s,onError:(t,r)=>{var n;d=r,"device"===e.kind&&t===p&&(n=e.id,rj.delete(n))}});if(f)return f;if("device"===e.kind&&c){var m;m=e.id,rj.delete(m),u=(await l(s?.remainingMs(),!0)).endpoints;let n=await rK(u,{command:r,port:t,timeoutMs:a,signal:o,attemptDeadline:s,onError:(e,t)=>{d=t}});if(n)return n}if(o?.aborted)throw rg();throw new D("COMMAND_FAILED","Runner endpoint probe failed",{port:t,endpoints:u,lastError:d?String(d):void 0})},{maxAttempts:c,baseDelayMs:300,maxDelayMs:2e3,jitter:.2,shouldRetry:rU},{deadline:s,phase:"ios_runner_connect",signal:o})}catch(e){if(o?.aborted||rv(e))throw rg();d||(d=e)}if(o?.aborted)throw rg();if("simulator"===e.kind){let a=s.remainingMs();if(a<=0)throw rV({port:t,endpoints:u,logPath:n,lastError:d});let i=await rZ(e,t,r,a,o);return new Response(i.body,{status:i.status})}throw rV({port:t,endpoints:u,logPath:n,lastError:d})}async function rW(e,t,r,n=45e3,a){if(a?.aborted)throw rg();let i=et.fromTimeoutMs(n),{getEndpoints:o}=rz(e,t),{endpoints:s}=await o(i.remainingMs()),l=s[0];if(!l)throw new D("COMMAND_FAILED","Runner command endpoint not available",{port:t,endpoints:s});let u=i.remainingMs();if(u<=0)throw new D("COMMAND_FAILED","Runner command deadline exceeded",{timeoutMs:n});return await rX(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},u,a)}function rz(e,t){let r;return{getEndpoints:async(n,a=!1)=>{var i,o,s;let l,u=await rJ({device:e,timeoutBudgetMs:n,forceRefresh:a,requestTunnelIp:r,setRequestTunnelIp:e=>{r=e}});return{endpoints:(i=e,o=t,s=u.ip,l=[`http://127.0.0.1:${o}/command`],"device"!==i.kind||s&&l.unshift(`http://[${s}]:${o}/command`),l),cached:u.sharedCacheHit}}}}async function rK(e,t){let{command:r,port:n,timeoutMs:a,signal:i,attemptDeadline:o,onError:s}=t;for(let t of e)try{let e=o?.remainingMs()??a;if(e<=0)throw new D("COMMAND_FAILED","Runner connection deadline exceeded",{port:n,timeoutMs:a});return await rX(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},Math.min(2e4,e),i)}catch(e){if(i?.aborted||rv(e))throw rg();s(t,e)}return null}async function rJ(e){var t,r,n;let{device:a,timeoutBudgetMs:i,forceRefresh:o,requestTunnelIp:s,setRequestTunnelIp:l}=e;if("device"!==a.kind)return{ip:null,sharedCacheHit:!1};if(!o){let e,r=(t=a.id,(e=rj.get(t))?e.expiresAt<=Date.now()?(rj.delete(t),null):e.ip:null);if(r)return{ip:r,sharedCacheHit:!0};if(void 0!==s)return{ip:s,sharedCacheHit:!1}}let u=await rY(a.id,i);return l(u),u&&(r=a.id,n=u,rj.set(r,{ip:n,expiresAt:Date.now()+3e4})),{ip:u,sharedCacheHit:!1}}async function rX(e,t,r,n){let a=AbortSignal.timeout(r),i=n?AbortSignal.any([n,a]):a;return await fetch(e,{...t,signal:i})}async function rY(e,t){if("number"==typeof t&&t<=0)return null;let r="number"==typeof t?Math.max(1,Math.min(1e4,t)):1e4,n=f.join(c.tmpdir(),`agent-device-devicectl-info-${process.pid}-${Date.now()}.json`);try{let t=Math.max(1,Math.ceil(r/1e3)),a=await rR(["devicectl","device","info","details","--device",e,"--json-output",n,"--timeout",String(t)],{allowFailure:!0,timeoutMs:r});if(0!==a.exitCode||!l.existsSync(n))return null;let i=JSON.parse(l.readFileSync(n,"utf8"));if(i.info?.outcome&&"success"!==i.info.outcome)return null;let o=(i.result?.connectionProperties?.tunnelIPAddress??i.result?.device?.connectionProperties?.tunnelIPAddress)?.trim();return o&&o.length>0?o:null}catch{return null}finally{r3(n)}}async function rZ(e,t,r,n,a){let i=JSON.stringify(r),o=rT(e,["spawn",e.id,"/usr/bin/curl","-s","-X","POST","-H","Content-Type: application/json","--data",i,`http://127.0.0.1:${t}/command`]),s=await rR(o,{allowFailure:!0,timeoutMs:n,signal:a}),l=s.stdout;if(0!==s.exitCode){let e=U({message:"Runner did not accept connection (simctl spawn)",stdout:s.stdout,stderr:s.stderr,context:{platform:"ios",phase:"connect"}});throw new D("COMMAND_FAILED","Runner did not accept connection (simctl spawn)",{port:t,stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode,reason:e,hint:en(e)})}return{status:200,body:l}}async function rQ(){return await new Promise((e,t)=>{let r=m.createServer();r.listen(0,"127.0.0.1",()=>{let n=r.address();if("object"==typeof n&&n?.port){let t=n.port;r.close(()=>e(t))}else r.close(()=>t(new D("COMMAND_FAILED","Failed to allocate port")))}),r.on("error",t)})}function r0(e,t,r,n){t&&r2(t,e),r&&r2(r,e),n&&process.stderr.write(e)}let r1=new Map;function r2(e,t){let r=(r1.get(e)??Promise.resolve()).catch(()=>{}).then(()=>l.promises.appendFile(e,t)).catch(()=>{}).finally(()=>{r1.get(e)===r&&r1.delete(e)});r1.set(e,r)}function r3(e){try{l.existsSync(e)&&l.unlinkSync(e)}catch{}}let r5=new h;async function r4(e,t,r){let n=r5.getStore()??[];if(n.some(r=>r.locks===e&&r.key===t))return await r();let a=(e.get(t)??Promise.resolve()).catch(()=>{}).then(()=>r5.run([...n,{locks:e,key:t}],r));return e.set(t,a),a.finally(()=>{e.get(t)===a&&e.delete(t)})}function r8(e){return"apple"===e||"ios"===e||"macos"===e}function r6(e,t){return!t||("apple"===t?r8(e):e===t)}function r9(e){let{simulatorSetPath:t,platform:r,target:n}=e;if(t&&"macos"!==r&&"desktop"!==n)return t}async function r7(e,t,r={}){let n=e,a=e=>e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim();if(t.platform&&(n=n.filter(e=>r6(e.platform,t.platform))),t.target&&(n=n.filter(e=>(e.target??"mobile")===t.target)),t.udid){let e=n.find(e=>e.id===t.udid&&r8(e.platform));if(!e)throw new D("DEVICE_NOT_FOUND",`No Apple device with UDID ${t.udid}`);return e}if(t.serial){let e=n.find(e=>e.id===t.serial&&"android"===e.platform);if(!e)throw new D("DEVICE_NOT_FOUND",`No Android device with serial ${t.serial}`);return e}if(t.deviceName){let e=a(t.deviceName),r=n.find(t=>a(t.name)===e);if(!r)throw new D("DEVICE_NOT_FOUND",`No device named ${t.deviceName}`);return r}let i=n[0];if(void 0!==i&&1===n.length)return i;if(0===n.length){var o;let e=r.simulatorSetPath;if(e&&(!(o=t.platform)||"apple"===o||"ios"===o))throw new D("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:
4
+ xcrun simctl --set "${e}" create "iPhone 16" com.apple.CoreSimulator.SimDeviceType.iPhone-16 com.apple.CoreSimulator.SimRuntime.iOS-18-0`,selector:t});throw new D("DEVICE_NOT_FOUND","No devices found",{selector:t})}let s=n.filter(e=>"device"!==e.kind);s.length>0&&(n=s);let l=n.filter(e=>e.booted),u=l[0];if(void 0!==u&&1===l.length)return u;let d=l[0]??n[0];if(void 0===d)throw new D("DEVICE_NOT_FOUND","No devices found",{selector:t});return d}let ne=new Set(["RUNNER_PRODUCT_MISSING","RUNNER_PRODUCT_REPAIR_FAILED"]);async function nt(e,t,r){if("macos"!==e.platform)return;if(0===t.length)throw new D("COMMAND_FAILED","Missing macOS runner product",{reason:"RUNNER_PRODUCT_MISSING",xctestrunPath:r});let n=Array.from(new Set(t)).sort((e,t)=>t.length-e.length);for(let e of n)if(!l.existsSync(e))throw new D("COMMAND_FAILED","Missing macOS runner product",{reason:"RUNNER_PRODUCT_MISSING",productPath:e,xctestrunPath:r});for(let e of n)if(!await nr(e)){await rO("codesign",["--remove-signature",e],{allowFailure:!0});try{await rO("codesign",["--force","--sign","-",e])}catch(n){let t=n instanceof D?n:new D("COMMAND_FAILED",String(n));throw new D("COMMAND_FAILED","Failed to repair macOS runner product signature",{reason:"RUNNER_PRODUCT_REPAIR_FAILED",productPath:e,xctestrunPath:r,error:t.message,details:t.details})}}}async function nr(e){return 0===(await rO("codesign",["--verify","--deep","--strict",e],{allowFailure:!0})).exitCode}let nn=new Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.:-"),na=new Set([" "," ","\n","\r"]),ni=new Set(["__defineGetter__","__defineSetter__","__proto__","constructor","prototype"]);function no(e,t={}){let r=t.maxDocumentChars??0x8000000;if(e.length>r)throw Error(`XML document exceeds maximum supported size of ${r} characters.`);return new nl(e).parse()}function ns(e,t){for(let r of e){if("dict"===r.name)for(let e=0;e<r.children.length-1;e+=1){let n=r.children[e],a=r.children[e+1];n?.name==="key"&&n.text&&a&&t(n.text,a)}ns(r.children,t)}}class nl{roots=[];stack=[];index=0;xml;constructor(e){this.xml=e}parse(){for(this.skipByteOrderMark();this.index<this.xml.length;)this.readNextToken();return this.assertFullyClosed(),this.roots}readNextToken(){"<"!==this.xml[this.index]?this.readText():this.resolveMarkupReader()()}resolveMarkupReader(){return this.startsWith("\x3c!--")?()=>this.skipUntil("--\x3e","Comment is not closed."):this.startsWith("<?")?()=>this.skipUntil("?>","Processing instruction is not closed."):this.startsWith("<![CDATA[")?()=>this.readCdata():this.startsWith("<!")?()=>this.skipDeclaration():this.startsWith("</")?()=>this.readClosingTag():()=>this.readOpeningTag()}assertFullyClosed(){if(this.stack.length>0){let e=this.stack[this.stack.length-1];throw Error(`Unclosed XML tag <${e?.name??"unknown"}>.`)}}skipByteOrderMark(){65279===this.xml.charCodeAt(0)&&(this.index=1)}readOpeningTag(){this.index+=1,this.skipWhitespace();let e=this.readRequiredName(`Missing XML tag name at offset ${this.index}.`),{attributes:t,selfClosing:r}=this.readOpeningTagBody(),n={name:e,attributes:t,text:null,children:[]};this.addNode(n),r||this.pushOpenNode(n)}readOpeningTagBody(){let e={};for(;;){this.skipWhitespace();let t=this.readOpeningTagEnd();if(t)return{attributes:e,selfClosing:"self-closing"===t};let r=this.readAttribute();e[r.name]=r.value}}readOpeningTagEnd(){if(this.index>=this.xml.length)throw Error("Opening XML tag is not closed.");return">"===this.xml[this.index]?(this.index+=1,"open"):"/"===this.xml[this.index]&&">"===this.xml[this.index+1]?(this.index+=2,"self-closing"):null}readAttribute(){let e=this.readRequiredName(`Invalid XML attribute at offset ${this.index}.`);if(function(e){if(ni.has(e))throw Error(`Unsupported XML attribute name "${e}".`)}(e),this.skipWhitespace(),"="!==this.xml[this.index])throw Error(`Missing value for XML attribute "${e}".`);return this.index+=1,this.skipWhitespace(),{name:e,value:this.readAttributeValue(e)}}pushOpenNode(e){if(this.stack.length>=256)throw Error("Maximum XML nesting depth of 256 exceeded.");this.stack.push(e)}readClosingTag(){this.index+=2,this.skipWhitespace();let e=this.readName();if(this.skipWhitespace(),">"!==this.xml[this.index])throw Error(`Closing XML tag </${e}> is not closed.`);this.index+=1;let t=this.stack.pop();if(!t)throw Error(`Unexpected closing XML tag </${e}>.`);if(t.name!==e)throw Error(`Expected </${t.name}> before </${e}>.`)}readText(){let e=this.xml.indexOf("<",this.index),t=-1===e?this.xml.length:e;this.appendText(this.xml.slice(this.index,t),!0),this.index=t}readCdata(){let e=this.index+9,t=this.xml.indexOf("]]>",e);if(-1===t)throw Error("CDATA section is not closed.");this.appendText(this.xml.slice(e,t),!1),this.index=t+3}appendText(e,t){let r=e.trim();if(!r)return;let n=this.stack[this.stack.length-1];n&&(n.text=`${n.text??""}${t?nu(r):r}`)}addNode(e){let t=this.stack[this.stack.length-1];t?t.children.push(e):this.roots.push(e)}readName(){var e;let t=this.index;for(;this.index<this.xml.length&&void 0!==(e=this.xml[this.index])&&nn.has(e);)this.index+=1;return this.xml.slice(t,this.index)}readRequiredName(e){let t=this.readName();if(!t)throw Error(e);return t}readAttributeValue(e){let t=this.xml[this.index];if('"'!==t&&"'"!==t)throw Error(`XML attribute "${e}" must use a quoted value.`);this.index+=1;let r=this.index,n=this.xml.indexOf(t,r);if(-1===n)throw Error(`XML attribute "${e}" is not closed.`);return this.index=n+1,nu(this.xml.slice(r,n).trim())}skipDeclaration(){let e={quote:null,bracketDepth:0};for(let t=this.index+2;t<this.xml.length;t+=1)if(function(e,t){var r,n,a;return!(void 0===t||(r=e,n=t,r.quote?(n===r.quote&&(r.quote=null),!0):('"'===n||"'"===n)&&(r.quote=n,!0)))&&(function(e,t){if("["===t){e.bracketDepth+=1;return}"]"===t&&e.bracketDepth>0&&(e.bracketDepth-=1)}(e,t),a=e,">"===t&&0===a.bracketDepth)}(e,this.xml[t])){this.index=t+1;return}throw Error("XML declaration is not closed.")}skipUntil(e,t){let r=this.xml.indexOf(e,this.index+e.length);if(-1===r)throw Error(t);this.index=r+e.length}skipWhitespace(){for(var e;this.index<this.xml.length&&void 0!==(e=this.xml[this.index])&&na.has(e);)this.index+=1}startsWith(e){return this.xml.startsWith(e,this.index)}}function nu(e){return e.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g,(e,t)=>{switch(t){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';case"apos":return"'";default:var r=e,n=t;let a=n.startsWith("#x")?Number.parseInt(n.slice(2),16):Number(n.slice(1));if(!Number.isInteger(a)||a<0||a>1114111)return r;try{return String.fromCodePoint(a)}catch{return r}}})}let nd=new Set(["ProductPaths","DependentProductPaths","TestHostPath","TestBundlePath","UITargetAppPath"]);async function nc(e){var t;let r=await np(e);if(!r||0===r.length)return null;let n=f.dirname(e),a=new Set,i=function(e,t){let r=[],n=new Set,a=[];for(let i of e){if(i.startsWith("__TESTHOST__/")){a.push(i.slice(13));continue}if(!i.startsWith("__TESTROOT__/"))continue;let e=i.slice(13);r.push(f.join(t,e));let o=function(e){let t=/\.app(?:\/|$)/.exec(e);return t&&void 0!==t.index?e.slice(0,t.index+4):null}(e);o&&n.add(f.join(t,o))}return{testRootPaths:r,hostRoots:Array.from(n),hostRelativePaths:a}}(r,n);for(let e of i.testRootPaths){if(!l.existsSync(e))return null;a.add(e)}for(let e of(t=i).hostRelativePaths.map(e=>{let r=t.hostRoots.find(t=>l.existsSync(f.join(t,e)));return r?f.join(r,e):null})){if(!e)return null;a.add(e)}return Array.from(a)}async function np(e){let t=await rE(e);if(t){var r,n,a,i=t;let e=new Set;for(let t of[a=i,...function(e){let t=e.TestConfigurations;if(!Array.isArray(t))return[];let r=[];for(let e of t){if(!nf(e))continue;let t=e.TestTargets;Array.isArray(t)&&r.push(...t.filter(nf))}return r}(a),...Object.values(a).filter(e=>nf(e)&&"TestBundlePath"in e)])for(let r of function(e){let t=new Set;for(let[r,n]of Object.entries(e))if(nd.has(r)){if("string"==typeof n){t.add(n);continue}if(Array.isArray(n))for(let e of n)"string"==typeof e&&t.add(e)}return Array.from(t)}(t))e.add(r);return Array.from(e)}if("darwin"===process.platform)return null;try{let t;return r=l.readFileSync(e,"utf8"),n=no(r),t=new Set,ns(n,(e,r)=>{if(nd.has(e)){if("string"===r.name&&r.text)return void t.add(r.text);if("array"===r.name)for(let e of r.children)"string"===e.name&&e.text&&t.add(e.text)}}),Array.from(t)}catch{return null}}function nf(e){return!!e&&"object"==typeof e}let nm="XCTestDevices",nh=".agent-device-backup",nw=".agent-device-xctestdevices-backup-",ng=f.join(c.homedir(),".agent-device","ios-runner"),ny=".agent-device-runner-cache.json",nv={PreferredScreenCaptureFormat:"screenshots",SystemAttachmentLifetime:"keepNever",UserAttachmentLifetime:"keepNever"},nI=new Map,nb=new Set;function nA(e){return e?.trim()??""}function nS(e=process.env){return nA(e.AGENT_DEVICE_IOS_BUNDLE_ID)||nA(e.AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID)||"com.callstack.agentdevice.runner"}function nx(e=process.env){let t=nA(e.AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID);return t||`${nS(e)}.uitests`}let n_=function(e=process.env){let t=nS(e),r=nx(e);return Array.from(new Set([nA(e.AGENT_DEVICE_IOS_RUNNER_CONTAINER_BUNDLE_ID),`${r}.xctrunner`,t].filter(e=>e.length>0)))}(process.env);function nN(e=c.homedir()){return f.join(e,"Library","Developer","XCTestDevices")}async function nM(e,t={}){if("ios"!==e.platform||"simulator"!==e.kind)return null;let r=Z(e.simulatorSetPath);if(!r)return null;let n=f.resolve(r),a=f.resolve(t.xctestDeviceSetPath??nN()),i=f.resolve(t.backupPath??function(e=nN()){return`${e}${nh}`}(a)),o=f.resolve(t.lockDirPath??function(e=c.homedir()){return f.join(e,".agent-device","xctest-device-set.lock")}()),s=t.ownerStartTime??em(process.pid),u=await nP({lockDirPath:o,owner:{pid:t.ownerPid??process.pid,startTime:s,acquiredAtMs:t.nowMs??Date.now()}});try{if(nk({xctestDeviceSetPath:a,backupPath:i}),function(e,t){if(f.resolve(e)===f.resolve(t))return!0;try{return l.realpathSync.native(e)===l.realpathSync.native(t)}catch{return!1}}(n,a))return await u(),null;l.mkdirSync(n,{recursive:!0}),l.existsSync(a)&&l.renameSync(a,i),function(e){let{requestedSetPath:t,xctestDeviceSetPath:r}=e,n=f.dirname(r),a=f.join(n,`${nm}.agent-device-link-${process.pid}-${Date.now()}`);l.mkdirSync(n,{recursive:!0});try{l.symlinkSync(t,a,"dir"),l.renameSync(a,r)}catch(e){throw l.existsSync(a)&&nD(a),e}}({requestedSetPath:n,xctestDeviceSetPath:a})}catch(e){throw nk({xctestDeviceSetPath:a,backupPath:i}),await u(),new D("COMMAND_FAILED","Failed to redirect XCTest device set path",{requestedSetPath:n,xctestDeviceSetPath:a,backupPath:i,error:String(e)})}let d=!1;return{release:async()=>{if(!d){d=!0;try{nk({xctestDeviceSetPath:a,backupPath:i})}finally{await u()}}}}}function nk(e){let{xctestDeviceSetPath:t,backupPath:r}=e,n=[r,...function(e){let t=f.dirname(e),r=f.basename(e).replace(nh,""),n=r===nm?nw:`${r}${nw}`;try{return l.readdirSync(t).filter(e=>e.startsWith(n)).sort().map(e=>f.join(t,e))}catch{return[]}}(r)],a=n.find(e=>l.existsSync(e)),i=l.existsSync(t)&&l.lstatSync(t).isSymbolicLink();if(a){if(i&&nD(t),l.existsSync(t))if(!i)return void eN({level:"warn",phase:"ios_runner_xctest_device_set_restore_collision",data:{xctestDeviceSetPath:t,activeBackupPath:a}});else a!==r?l.rmSync(a,{recursive:!0,force:!0}):l.rmSync(r,{recursive:!0,force:!0});else l.mkdirSync(f.dirname(t),{recursive:!0}),l.renameSync(a,t);for(let e of n)e!==a&&l.existsSync(e)&&l.rmSync(e,{recursive:!0,force:!0});return}i&&(eN({level:"warn",phase:"ios_runner_xctest_device_set_orphaned_symlink",data:{xctestDeviceSetPath:t}}),nD(t))}function nD(e){!l.existsSync(e)||l.lstatSync(e).isSymbolicLink()&&l.unlinkSync(e)}async function nP(e){let{lockDirPath:t,owner:r}=e,n=f.join(t,"owner.json"),a=Date.now()+3e4;for(l.mkdirSync(f.dirname(t),{recursive:!0});Date.now()<a;)try{l.mkdirSync(t),function(e,t){let r=`${e}.${process.pid}.${Date.now()}.tmp`;l.writeFileSync(r,JSON.stringify(t),"utf8"),l.renameSync(r,e)}(n,r);let e=!1;return async()=>{e||(e=!0,l.rmSync(t,{recursive:!0,force:!0}))}}catch(e){if("EEXIST"!==e.code)throw e;if(function(e,t){let r=null;try{r=l.statSync(e)}catch{return!0}let n=function(e){try{return JSON.parse(l.readFileSync(e,"utf8"))}catch{return null}}(t);if(n){var a;return!(Number.isInteger((a=n).pid)&&!(a.pid<=0)&&eI(a.pid)&&(!a.startTime||em(a.pid)===a.startTime))&&(l.rmSync(e,{recursive:!0,force:!0}),!0)}return!(Date.now()-r.mtimeMs<5e3)&&(l.rmSync(e,{recursive:!0,force:!0}),!0)}(t,n))continue;await e8(100)}throw new D("COMMAND_FAILED","Timed out waiting for XCTest device set lock",{lockDirPath:t})}async function nO(e,t){var r;let n,a=(r=e,(n=process.env.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim())?f.resolve(n):"macos"===r.platform?f.join(ng,"derived","macos"):"simulator"===r.kind?f.join(ng,"derived"):f.join(ng,"derived",r.kind)),i=eW();return await r4(nI,a,async()=>{let r=function(e,t=eW()){var r;let n;return{schemaVersion:1,packageVersion:eH(),runnerSourceFingerprint:function(e){let t=f.join(e,"ios-runner","AgentDeviceRunner"),r=function(e){if(!l.existsSync(e))return[];let t=[],r=[e];for(;r.length>0;){let e=r.pop();for(let i of l.readdirSync(e,{withFileTypes:!0})){var n,a;let o=f.join(e,i.name);if(i.isDirectory()){if("xcuserdata"===i.name)continue;r.push(o);continue}i.isFile()&&(n=i.name,a=o,"project.pbxproj"===n?a.includes(`${f.sep}.xcodeproj${f.sep}`):[".swift",".plist",".entitlements",".xctestplan",".xcconfig",".storyboard",".xib"].includes(f.extname(n)))&&t.push(o)}}return t.sort((e,t)=>e.localeCompare(t))}(t),n=function(e,t){let r=o.createHash("sha256");for(let n of t){let t=f.relative(e,n),a=l.statSync(n);r.update(t),r.update("\0"),r.update(String(a.size)),r.update("\0"),r.update(String(Math.trunc(a.mtimeMs))),r.update("\0")}return r.digest("hex")}(t,r),a=nU.get(t);if(a?.fileStatsFingerprint===n)return a.sourceFingerprint;let i=o.createHash("sha256");for(let e of r){let r=f.relative(t,e);i.update(r),i.update("\0"),i.update(l.readFileSync(e)),i.update("\0")}let s=i.digest("hex");return nU.set(t,{fileStatsFingerprint:n,sourceFingerprint:s}),s}(t),platformName:nJ(e),deviceKind:e.kind,target:e.target??"phone",buildDestinationFamily:"macOS"===(n=nJ(r=e))?`platform=macOS,arch=${nX()}`:"simulator"===r.kind?`generic/platform=${n} Simulator`:`generic/platform=${n}`,runnerBundleBuildSettings:nQ(process.env),runnerSigningBuildSettings:nZ(process.env,"device"===e.kind,e.platform),runnerPerformanceBuildSettings:n0()}}(e,i);V(process.env.AGENT_DEVICE_IOS_CLEAN_DERIVED)&&(n3("clean","forced_clean",{derived:a}),n1(a),nR(a));let n=await n2({derived:a,projectRoot:i,expectedCacheMetadata:r,findXctestrun:t=>nV(t,e),xctestrunReferencesProjectRoot:nq,resolveExistingXctestrunProductPaths:nc});if("reuse_ready"!==n.reason&&n3("rebuild",n.reason,{derived:a,xctestrunPath:n.xctestrunPath}),"reuse_ready"===n.reason)try{return await nt(e,n.productPaths,n.xctestrunPath),n3("reuse","reuse_ready",{derived:a,xctestrunPath:n.xctestrunPath}),nC(a,nT(r,n.xctestrunPath,n.productPaths)),n.xctestrunPath}catch(e){if(!function(e){if(!(e instanceof D))return!1;let t=e.details&&"object"==typeof e.details?e.details.reason:void 0;return"string"==typeof t&&ne.has(t)}(e))throw e;n3("rebuild","repair_failed",{derived:a,xctestrunPath:n.xctestrunPath})}n.xctestrunPath&&(n1(a),nR(a));let s=f.join(i,"ios-runner","AgentDeviceRunner","AgentDeviceRunner.xcodeproj");if(!l.existsSync(s))throw new D("COMMAND_FAILED","iOS runner project not found",{projectPath:s});await nK(e,s,a,t);let u=nV(a,e);if(!u)throw new D("COMMAND_FAILED","Failed to locate .xctestrun after build");let d=await nc(u);if(!d)throw new D("COMMAND_FAILED","Runner build is missing expected products",{xctestrunPath:u});return await nt(e,d,u),nC(a,nT(r,u,d)),n3("build","built_new",{derived:a,xctestrunPath:u}),u})}function nR(e){try{if(!l.existsSync(e))return;if("derived"!==f.basename(e))return void l.rmSync(e,{recursive:!0,force:!0});for(let r of l.readdirSync(e,{withFileTypes:!0})){var t;t=r.name,nE.has(t)&&l.rmSync(f.join(e,r.name),{recursive:!0,force:!0})}}catch{}}let nE=new Set([ny,"Build","BuildCache.noindex","Index.noindex","Logs","ModuleCache.noindex","SDKStatCaches.noindex","SourcePackages","TextBasedInstallAPI","info.plist"]);function nC(e,t){l.mkdirSync(e,{recursive:!0}),l.writeFileSync(f.join(e,ny),`${JSON.stringify(t,null,2)}
5
+ `)}function nL(e){let{artifacts:t,...r}=e;return r}function nT(e,t,r){let n=function(e,t){let r=nF(e);if(null===r||0===t.length)return null;let n=[];for(let e of t){let t=nF(e);if(null===t)return null;n.push({path:e,mtimeMs:t})}return{xctestrunPath:e,xctestrunMtimeMs:r,productPaths:n}}(t,r);return n?{...e,artifacts:n}:e}function n$(e){return!(!e||"object"!=typeof e||Array.isArray(e))&&"string"==typeof e.path&&Number.isInteger(e.mtimeMs)}function nF(e){try{return Math.trunc(l.statSync(e).mtimeMs)}catch{return null}}let nU=new Map;function nV(e,t){if(!l.existsSync(e))return null;let r=[],n=[e];for(;n.length>0;){let e=n.pop();for(let t of l.readdirSync(e,{withFileTypes:!0})){let a=f.join(e,t.name);if(t.isDirectory()){n.push(a);continue}if(t.isFile()&&t.name.endsWith(".xctestrun"))try{let e=l.statSync(a);r.push({path:a,mtimeMs:e.mtimeMs})}catch{}}}return 0===r.length?null:(r.sort((e,r)=>{if(t){let n=nG(r.path,t)-nG(e.path,t);if(0!==n)return n}return r.mtimeMs-e.mtimeMs||e.path.localeCompare(r.path)}),r[0]?.path??null)}function nG(e,t){var r;let n=0,a=e.toLowerCase();f.basename(a).startsWith("agentdevicerunner.env.")&&(n-=1e3),a.includes(`${f.sep}macos${f.sep}`)&&(n-=5e3);let i="macos"===(r=t).platform?{preferred:["macos"],disallowed:["iphoneos","iphonesimulator","appletvos","appletvsimulator"]}:"tv"===r.target?"simulator"===r.kind?{preferred:["appletvsimulator"],disallowed:["appletvos","iphoneos","iphonesimulator","macos"]}:{preferred:["appletvos"],disallowed:["appletvsimulator","iphoneos","iphonesimulator","macos"]}:"simulator"===r.kind?{preferred:["iphonesimulator"],disallowed:["iphoneos","appletvos","appletvsimulator","macos"]}:{preferred:["iphoneos"],disallowed:["iphonesimulator","appletvos","appletvsimulator","macos"]};return i.preferred.length>0&&(i.preferred.some(e=>a.includes(e))?n+=2e3:n-=500),i.disallowed.some(e=>a.includes(e))&&(n-=2500),n}function nq(e,t){try{let r=l.readFileSync(e,"utf8"),n=new Set([t]);try{n.add(l.realpathSync(t))}catch{}for(let e of n)if(r.includes(e))return!0;return!1}catch{return!1}}async function nB(e,t,r){let n=f.dirname(e),a=r.replace(/[^a-zA-Z0-9._-]/g,"_"),i=f.join(n,`AgentDeviceRunner.env.${a}.json`),o=f.join(n,`AgentDeviceRunner.env.${a}.xctestrun`),s=await nj(e);return nW(s,e=>{var r,n;return r=e,n=t,void(r.EnvironmentVariables={...r.EnvironmentVariables??{},...n},r.UITestEnvironmentVariables={...r.UITestEnvironmentVariables??{},...n},r.UITargetAppEnvironmentVariables={...r.UITargetAppEnvironmentVariables??{},...n},r.TestingEnvironmentVariables={...r.TestingEnvironmentVariables??{},...n})}),nW(s,e=>Object.assign(e,nv),{requireTestBundlePath:!0}),await nH(s,i,o),{xctestrunPath:o,jsonPath:i}}async function nj(e){let t=await rO("plutil",["-convert","json","-o","-",e],{allowFailure:!0});if(0!==t.exitCode||!t.stdout.trim())throw new D("COMMAND_FAILED","Failed to read xctestrun plist",{xctestrunPath:e,stderr:t.stderr});try{let e=JSON.parse(t.stdout);if(!e||"object"!=typeof e||Array.isArray(e))throw Error("Root must be an object");return e}catch(t){throw new D("COMMAND_FAILED","Failed to parse xctestrun JSON",{xctestrunPath:e,error:String(t)})}}async function nH(e,t,r){l.writeFileSync(t,JSON.stringify(e,null,2));let n=await rO("plutil",["-convert","xml1","-o",r,t],{allowFailure:!0});if(0!==n.exitCode)throw new D("COMMAND_FAILED","Failed to write xctestrun plist",{tmpXctestrunPath:r,stderr:n.stderr})}function nW(e,t,r={}){let n=e.TestConfigurations;if(Array.isArray(n))for(let e of n)e&&"object"==typeof e&&function(e,t,r){if(Array.isArray(e))for(let n of e){let e=nz(n,r);e&&t(e)}}(e.TestTargets,t,r);for(let r of Object.values(e)){let e=nz(r,{requireTestBundlePath:!0});e&&t(e)}}function nz(e,t){return!e||"object"!=typeof e||Array.isArray(e)||t.requireTestBundlePath&&!e.TestBundlePath?null:e}async function nK(e,t,r,n){let a=nQ(process.env),i=nZ(process.env,"device"===e.kind,e.platform),o="device"===e.kind?["-allowProvisioningUpdates"]:[],s=n0(),l=await nM(e);try{var u;let l;await O("xcodebuild",["build-for-testing","-project",t,"-scheme","AgentDeviceRunner","-parallel-testing-enabled","NO",nY(e),"1","-destination",(u=e,l=nJ(u),"macOS"===l?`platform=macOS,arch=${nX()}`:"simulator"===u.kind?`platform=${l} Simulator,id=${u.id}`:`generic/platform=${l}`),"-derivedDataPath",r,...s,...a,...o,...i],{detached:!0,onSpawn:e=>{nb.add(e),e.on("close",()=>{nb.delete(e)})},onStdoutChunk:e=>{r0(e,n.logPath,n.traceLogPath,n.verbose)},onStderrChunk:e=>{r0(e,n.logPath,n.traceLogPath,n.verbose)}})}catch(i){let e,t,r=i instanceof D?i:new D("COMMAND_FAILED",String(i)),a=(e=r.details?JSON.stringify(r.details):"",((t=`${r.message}
6
+ ${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)??r$);throw new D("COMMAND_FAILED","xcodebuild build-for-testing failed",{error:r.message,details:r.details,logPath:n.logPath,hint:a})}finally{await l?.release()}}function nJ(e){var t;if("ios"!==e.platform&&"macos"!==e.platform)throw new D("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 nX(){return"arm64"===process.arch?"arm64":"x86_64"}function nY(e){return"macos"===e.platform||"device"===e.kind?"-maximum-concurrent-test-device-destinations":"-maximum-concurrent-test-simulator-destinations"}function nZ(e=process.env,t=!1,r="ios"){if("macos"===r)return["CODE_SIGNING_ALLOWED=NO","CODE_SIGNING_REQUIRED=NO","CODE_SIGN_IDENTITY=","DEVELOPMENT_TEAM="];if(!t)return[];let n=e.AGENT_DEVICE_IOS_TEAM_ID?.trim()||"",a=e.AGENT_DEVICE_IOS_SIGNING_IDENTITY?.trim()||"",i=e.AGENT_DEVICE_IOS_PROVISIONING_PROFILE?.trim()||"",o=["CODE_SIGN_STYLE=Automatic"];return n&&o.push(`DEVELOPMENT_TEAM=${n}`),a&&o.push(`CODE_SIGN_IDENTITY=${a}`),i&&o.push(`PROVISIONING_PROFILE_SPECIFIER=${i}`),o}function nQ(e=process.env){let t=nS(e),r=nx(e);return[`AGENT_DEVICE_IOS_RUNNER_APP_BUNDLE_ID=${t}`,`AGENT_DEVICE_IOS_RUNNER_TEST_BUNDLE_ID=${r}`]}function n0(){return["COMPILER_INDEX_STORE_ENABLE=NO","ENABLE_CODE_COVERAGE=NO"]}function n1(e,t=process.env){if(t.AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH?.trim()){var r;let t,n;if(r=e,t=f.resolve(eW(),".tmp"),""===(n=f.relative(t,f.resolve(r)))||n.startsWith("..")||f.isAbsolute(n))throw new D("COMMAND_FAILED","Refusing to clean AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH automatically",{derivedPath:e,hint:`Unset AGENT_DEVICE_IOS_CLEAN_DERIVED, or move AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH under a subdirectory of ${f.join(eW(),".tmp")}.`})}}async function n2(e){var t,r;let n,a=(t=e.derived,r=e.expectedCacheMetadata,(n=function(e){try{let t=JSON.parse(l.readFileSync(f.join(e,ny),"utf8"));if(!t||"object"!=typeof t||Array.isArray(t))return null;return t}catch{return null}}(t))?JSON.stringify(nL(n))!==JSON.stringify(nL(r))?{ok:!1,reason:"cache_metadata_mismatch"}:{ok:!0,metadata:n}:{ok:!1,reason:"cache_metadata_missing"}),i=a.ok?function(e){var t;let r=e?.artifacts;if(!(!(!(t=r)||"object"!=typeof t||Array.isArray(t))&&"string"==typeof t.xctestrunPath&&Number.isInteger(t.xctestrunMtimeMs)&&Array.isArray(t.productPaths)&&t.productPaths.length>0&&t.productPaths.every(n$))||nF(r.xctestrunPath)!==r.xctestrunMtimeMs)return null;let n=[];for(let e of r.productPaths){if(nF(e.path)!==e.mtimeMs)return null;n.push(e.path)}return{xctestrunPath:r.xctestrunPath,productPaths:n}}(a.metadata):null,o=i?.xctestrunPath??e.findXctestrun(e.derived);if(!o)return{reason:"missing_xctestrun",xctestrunPath:null};let s=i?.xctestrunPath===o?i.productPaths:await e.resolveExistingXctestrunProductPaths(o);return s?e.xctestrunReferencesProjectRoot(o,e.projectRoot)?a.ok?{reason:"reuse_ready",xctestrunPath:o,productPaths:s}:{reason:a.reason,xctestrunPath:o,productPaths:s}:{reason:"project_root_mismatch",xctestrunPath:o,productPaths:s}:{reason:"missing_products",xctestrunPath:o,productPaths:[]}}function n3(e,t,r){eN({level:"rebuild"===e?"warn":"info",phase:"runner_xctestrun_cache",data:{action:e,reason:t,...r}})}let n5=new Map,n4=new Map;async function n8(e,t){return await r4(n4,e.id,async()=>{let r,n,a=n5.get(e.id);if(a){if(an(a.child.pid))return eN({level:"debug",phase:"ios_runner_session_reuse",data:{deviceId:e.id,sessionId:a.sessionId,ready:a.ready}}),a;await al({},"stop_stale_session",async()=>{await n7(e.id,a)})}let i={};await al(i,"ensure_booted",async()=>{var t;await ("simulator"!==(t=e).kind?Promise.resolve():t.booted?(eN({level:"debug",phase:"ios_runner_startup_ensure_booted_skipped",data:{deviceId:t.id}}),Promise.resolve()):ai(t))}),t.cleanStaleBundles?await al(i,"cleanup_stale_bundles",async()=>{await n6(e)}):(i.cleanup_stale_bundles=0,eN({level:"debug",phase:"ios_runner_startup_cleanup_stale_bundles_skipped"}));let o=await al(i,"ensure_xctestrun",async()=>await nO(e,t)),s=await al(i,"allocate_port",async()=>await rQ()),{xctestrunPath:l,jsonPath:u}=await al(i,"prepare_xctestrun_env",async()=>await nB(o,{AGENT_DEVICE_RUNNER_PORT:String(s)},`session-${e.id}-${s}`)),d=await al(i,"simulator_set_redirect",async()=>await nM(e));try{({child:r,wait:n}=await al(i,"launch_xcodebuild",()=>{let t;return P("xcodebuild",["test-without-building","-only-testing","AgentDeviceRunnerUITests/RunnerTests/testCommand","-parallel-testing-enabled","NO","-test-timeouts-enabled","NO","-collect-test-diagnostics","never",nY(e),"1","-destination-timeout",String(20),"-xctestrun",l,"-destination",(t=nJ(e),"macOS"===t?`platform=macOS,arch=${nX()}`:"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=>{r0(e,t.logPath,t.traceLogPath,t.verbose)}),r.stderr?.on("data",e=>{r0(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:n,child:r,ready:!1,startupTimings:i,simulatorSetRedirect:d??void 0};return n5.set(e.id,c),c})}async function n6(e){if("simulator"===e.kind)for(let t of n_){let r=await rR(rT(e,["uninstall",e.id,t]),{allowFailure:!0});if(0!==r.exitCode){let e=`${r.stdout}
7
+ ${r.stderr}`.toLowerCase();if(!e.includes("not installed")&&!e.includes("found nothing")&&!e.includes("no such file")&&!e.includes("invalid device")&&!e.includes("could not find"))continue}}}async function n9(e,t){await r4(n4,e.deviceId,async()=>{n5.get(e.deviceId)===e&&(eN({level:"warn",phase:"ios_runner_session_invalidated",data:{deviceId:e.deviceId,sessionId:e.sessionId,reason:t}}),await n7(e.deviceId,e,{graceful:!1,waitTimeoutMs:1e3}))})}async function n7(e,t,r={}){let n=t??n5.get(e);if(n){var a;if(!1!==r.graceful)try{await rH(n.device,n.port,{command:"shutdown"},void 0,15e3)}catch{await aa(n.child.pid,"SIGTERM")}else await aa(n.child.pid,"SIGTERM");try{await Promise.race([n.testPromise,new Promise(e=>setTimeout(e,r.waitTimeoutMs??1e4))])}catch{}(a=n.child.pid)&&(an(a)||ey(a))&&await aa(n.child.pid,"SIGKILL"),r3(n.xctestrunPath),r3(n.jsonPath),await n.simulatorSetRedirect?.release(),n5.get(e)===n&&n5.delete(e)}}async function ae(e){await r4(n4,e,async()=>{await n7(e)})}async function at(){let e=Array.from(n5.values()),t=Array.from(nb);await Promise.allSettled(e.map(async e=>{await aa(e.child.pid,"SIGINT")})),await Promise.allSettled(t.map(async e=>{await aa(e.pid,"SIGINT")})),await Promise.allSettled(e.map(async e=>{await aa(e.child.pid,"SIGTERM")})),await Promise.allSettled(t.map(async e=>{await aa(e.pid,"SIGTERM")})),await Promise.allSettled(e.map(async e=>{await aa(e.child.pid,"SIGKILL")})),await Promise.allSettled(t.map(async e=>{await aa(e.pid,"SIGKILL"),nb.delete(e)})),await Promise.allSettled(e.map(async e=>{await e.simulatorSetRedirect?.release()}))}async function ar(){await at();let e=Array.from(n5.keys());await Promise.allSettled(e.map(async e=>{await ae(e)}));let t=Array.from(nb);await Promise.allSettled(t.map(async e=>{try{await aa(e.pid,"SIGTERM"),await aa(e.pid,"SIGKILL")}finally{nb.delete(e)}}))}function an(e){return!!e&&eI(e)}async function aa(e,t){if(!e||e<=0)return;try{process.kill(-e,t)}catch{}try{process.kill(e,t)}catch{}let r="SIGINT"===t?"INT":"SIGTERM"===t?"TERM":"KILL";try{await rO("pkill",[`-${r}`,"-P",String(e)],{allowFailure:!0})}catch{}}async function ai(e){await rR(rT(e,["bootstatus",e.id,"-b"]),{timeoutMs:45e3})}async function ao(e,t,r,n,a,i){var o,s;if(o=t,s=r.command,o.startupTimingsReported||!o.startupTimings||(o.startupTimingsReported=!0,eN({level:"info",phase:"ios_runner_session_startup_timings",durationMs:Object.values(o.startupTimings).reduce((e,t)=>e+t,0),data:{command:s,sessionId:o.sessionId,ready:o.ready,timings:o.startupTimings}})),rq(r.command)){let o=await e_("ios_runner_command_send",async()=>await rH(e,t.port,r,n,a,t,i),{command:r.command,readOnly:!0,sessionReady:t.ready,timeoutMs:a});return await as(o,t,n)}let l=et.fromTimeoutMs(a);if(function(e,t){if(!e.ready||"tap"!==t.command&&"tapSeries"!==t.command)return!0;let r=e.lastSuccessfulRunnerResponseAtMs;return void 0===r||Date.now()-r>1e4}(t,r)){let a=t.ready?Math.min(5e3,l.remainingMs()):Math.min(45e3,l.remainingMs()),o=await e_("ios_runner_readiness_preflight",async()=>await rH(e,t.port,{command:"uptime"},n,a,t,i),{command:r.command,sessionReady:t.ready,timeoutMs:a});await as(o,t,n)}else eN({level:"debug",phase:"ios_runner_readiness_preflight_skipped",data:{command:r.command,lastSuccessfulRunnerResponseAgeMs:void 0===t.lastSuccessfulRunnerResponseAtMs?void 0:Date.now()-t.lastSuccessfulRunnerResponseAtMs,sessionReady:t.ready}});let u=l.remainingMs();if(u<=0)throw new D("COMMAND_FAILED","Runner command deadline exceeded",{timeoutMs:a});let d=await e_("ios_runner_command_send",async()=>await rW(e,t.port,r,u,i),{command:r.command});return await as(d,t,n)}async function as(e,t,r){let n,a=await e.text();try{let e=JSON.parse(a);n=e&&"object"==typeof e?e:{}}catch{throw new D("COMMAND_FAILED","Invalid runner response",{text:a})}if(!n.ok){let e=n.error?.code;throw new D("string"==typeof e&&e.trim().length>0?N(e):"COMMAND_FAILED",("string"==typeof n.error?.message?n.error.message:void 0)??"Runner error",{runner:n,xcodebuild:{exitCode:1,stdout:"",stderr:""},logPath:r})}return(t.ready=!0,t.lastSuccessfulRunnerResponseAtMs=Date.now(),n.data&&"object"==typeof n.data&&!Array.isArray(n.data))?n.data:{}}async function al(e,t,r){let n=Date.now();try{return await r()}finally{let r=Date.now()-n;e[t]=r,eN({level:"debug",phase:`ios_runner_startup_${t}`,durationMs:r})}}let au=new h;function ad(e,t={}){return void 0!==ac(e,t)}function ac(e,t={}){let r=au.getStore();return r&&r.deviceId===e.id&&(r.requestId?r.requestId===t.requestId:!t.requestId)?r:void 0}async function ap(e,t,r){if(!e)return await r();let n={provider:af(e),deviceId:t.deviceId,requestId:t.requestId};return await au.run(n,r)}function af(e){return"function"==typeof e?{runCommand:e}:e}async function am(e,t,r={}){if("ios"!==e.platform&&"macos"!==e.platform)throw new D("UNSUPPORTED_PLATFORM",`Unsupported platform for iOS runner: ${e.platform}`);if("simulator"!==e.kind&&"device"!==e.kind)throw new D("UNSUPPORTED_OPERATION",`Unsupported iOS device kind for runner: ${e.kind}`);rB(r.requestId);let n=function(e,t,r,n={}){if(r)return af(r);let a=ac(e,n);return a?af(a.provider):af(t)}(e,{runCommand:ah},void 0,{requestId:r.requestId});return rq(t.command)?$(()=>(rB(r.requestId),n.runCommand(e,t,r)),{shouldRetry:e=>(rB(r.requestId),rF(e))}):n.runCommand(e,t,r)}async function ah(e,t,r){let n;rB(r.requestId);let a=rw(r.requestId);try{let i=((n=await n8(e,r)).ready,45e3);return await ao(e,n,t,r.logPath,i,a)}catch(o){let i=o instanceof D?o:new D("COMMAND_FAILED",String(o));if("COMMAND_FAILED"===i.code&&"string"==typeof i.message&&i.message.includes("Runner did not accept connection")&&rU(i)&&n){rB(r.requestId),await n9(n,"runner_connect_failed_before_command_send"),n=await n8(e,{...r,cleanStaleBundles:!0});try{return await ao(e,n,t,r.logPath,45e3,a)}catch(e){throw rF(e instanceof D?e:new D("COMMAND_FAILED",String(e)))&&await n9(n,"transport_error_after_retry_command_send"),e}}throw!n&&i.message.includes("Runner did not accept connection")&&await ae(e.id),n&&rF(i)&&await n9(n,"transport_error_after_command_send"),o}}function aw(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_")}let ag=["platform","device","udid","serial","out","verbose","metroHost","metroPort","bundleUrl","launchUrl","snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw",...e4,"relaunch","saveScript","noRecord","fps","quality","hideTouches","count","intervalMs","delayMs","holdMs","jitterPx","doubleTap","clickButton","pauseMs","pattern"];function ay(e){let t=e.result?.text;if("string"==typeof t&&t.trim().length>0)return t;let r=e.positionals??[];if(0===r.length)return"";let n=r[0];return n?.startsWith("@")?r.length>=3?r.slice(2).join(" ").trim():r.slice(1).join(" ").trim():!(r.length>=3)||Number.isNaN(Number(r[0]))||Number.isNaN(Number(r[1]))?r.slice(1).join(" ").trim():r.slice(2).join(" ").trim()}function av(e){let t=new Set,r=[];for(let n of e)t.has(n)||(t.add(n),r.push(n));return r}let aI=/^-?\d+(\.\d+)?$/,ab=/^[^\s"\\]+$/,aA=new Map([["--count","count"],["--interval-ms","intervalMs"],["--hold-ms","holdMs"],["--jitter-px","jitterPx"]]),aS=new Map([["--count","count"],["--pause-ms","pauseMs"]]),ax=new Map([["--delay-ms","delayMs"]]);function a_(e){return"click"===e||"press"===e}function aN(e){return a_(e)||"longpress"===e}function aM(e){return"type"===e||"fill"===e}function ak(e){return aP(e,aO)}function aD(e){return JSON.stringify(e)}function aP(e,t){return t(e)?e:aD(e)}function aO(e){return aR(e)&&e.startsWith("@")||aI.test(e)}function aR(e){return ab.test(e)}function aE(e,t){let r=t.flags??{};if(a_(t.command)){"number"==typeof r.count&&e.push("--count",String(r.count)),"number"==typeof r.intervalMs&&e.push("--interval-ms",String(r.intervalMs)),"number"==typeof r.holdMs&&e.push("--hold-ms",String(r.holdMs)),"number"==typeof r.jitterPx&&e.push("--jitter-px",String(r.jitterPx)),!0===r.doubleTap&&e.push("--double-tap");let t=r.clickButton;t&&"primary"!==t&&e.push("--button",t);return}if("swipe"===t.command){"number"==typeof r.count&&e.push("--count",String(r.count)),"number"==typeof r.pauseMs&&e.push("--pause-ms",String(r.pauseMs)),("one-way"===r.pattern||"ping-pong"===r.pattern)&&e.push("--pattern",r.pattern);return}aM(t.command)&&"number"==typeof r.delayMs&&e.push("--delay-ms",String(r.delayMs))}function aC(e,t){t&&(("ios"===t.platform||"android"===t.platform)&&e.push("--platform",t.platform),"string"==typeof t.metroHost&&t.metroHost.length>0&&e.push("--metro-host",aP(t.metroHost,aR)),"number"==typeof t.metroPort&&e.push("--metro-port",String(t.metroPort)),"string"==typeof t.bundleUrl&&t.bundleUrl.length>0&&e.push("--bundle-url",aP(t.bundleUrl,aR)),"string"==typeof t.launchUrl&&t.launchUrl.length>0&&e.push("--launch-url",aP(t.launchUrl,aR)))}function aL(e,t){let r=[],n={},a=a_(e)?aA:"swipe"===e?aS:aM(e)?ax:void 0;for(let i=0;i<t.length;i+=1){let o=t[i];if(a_(e)&&"--double-tap"===o){n.doubleTap=!0;continue}let s=t[i+1];if(a_(e)&&"--button"===o&&void 0!==s){("primary"===s||"secondary"===s||"middle"===s)&&(n.clickButton=s),i+=1;continue}let l=a?.get(o);if(l&&void 0!==s){let e=a$(s);if(null!==e){n[l]=e,i+=1;continue}}if("swipe"===e&&"--pattern"===o&&void 0!==s){("one-way"===s||"ping-pong"===s)&&(n.pattern=s),i+=1;continue}r.push(o)}return{positionals:r,flags:n}}function aT(e){let t=[],r={};for(let n=0;n<e.length;n+=1){let a=e[n],i=e[n+1];if("--platform"===a&&void 0!==i){("ios"===i||"android"===i)&&(r.platform=i),n+=1;continue}if("--metro-host"===a&&void 0!==i){r.metroHost=i,n+=1;continue}if("--metro-port"===a&&void 0!==i){let e=a$(i);null!==e&&(r.metroPort=e),n+=1;continue}if("--bundle-url"===a&&void 0!==i){r.bundleUrl=i,n+=1;continue}if("--launch-url"===a&&void 0!==i){r.launchUrl=i,n+=1;continue}t.push(a)}return{positionals:t,flags:r}}function a$(e){if(!e)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}function aF(e,t={}){let r=[e.command];if("snapshot"===e.command)e.flags?.snapshotInteractiveOnly&&r.push("-i"),e.flags?.snapshotCompact&&r.push("-c"),"number"==typeof e.flags?.snapshotDepth&&r.push("-d",String(e.flags.snapshotDepth)),e.flags?.snapshotScope&&r.push("-s",ak(e.flags.snapshotScope)),e.flags?.snapshotRaw&&r.push("--raw");else if("open"===e.command){for(let t of e.positionals??[])r.push(ak(t));e.flags?.relaunch&&r.push("--relaunch"),aC(r,e.runtime)}else if("runtime"===e.command)!function(e,t,r={}){let n=t.positionals??[];for(let t of r.includeAllPositionals?n:n.slice(0,1))e.push(aP(t,aR));aC(e,t.flags)}(r,e,{includeAllPositionals:t.runtimeIncludeAllPositionals});else if("record"===e.command)!function(e,t){let[r,...n]=t.positionals??[];for(let t of(r&&e.push(aP(r,aR)),n))e.push(ak(t));"number"==typeof t.flags?.fps&&e.push("--fps",String(t.flags.fps)),"number"==typeof t.flags?.quality&&e.push("--quality",String(t.flags.quality)),t.flags?.hideTouches&&e.push("--hide-touches")}(r,e);else if("screenshot"===e.command){for(let t of e.positionals??[])r.push(ak(t));eC(r,e.flags)}else{for(let t of e.positionals??[])r.push(ak(t));aE(r,e)}return r.join(" ")}class aU{sessionsDir;constructor(e){this.sessionsDir=e}write(e){let t;try{if(!e.recordSession)return{written:!1};t=this.resolveScriptPath(e);let r=f.dirname(t);l.existsSync(r)||l.mkdirSync(r,{recursive:!0});let n=function(e){var t=e,r=function(e){let t=[];for(let r of e.actions){if("snapshot"===r.command)continue;let n=function(e){let t=function(e){let t=Array.isArray(e.result?.selectorChain)&&e.result.selectorChain.every(e=>"string"==typeof e)?e.result.selectorChain:[];return t.length>0?t.join(" || "):void 0}(e);if(t&&aV(e.command))return a_(e.command)?{...e,positionals:[t]}:"longpress"===e.command?function(e,t){let r="number"==typeof e.result?.durationMs?String(e.result.durationMs):function(e){let t=e.at(-1);if(!(e.length<=1)&&void 0!==t&&""!==t.trim())return Number.isFinite(Number(t))?t:void 0}(e.positionals??[]);return{...e,positionals:r?[t,r]:[t]}}(e,t):"fill"===e.command?function(e,t){let r=ay(e);return r.length>0?{...e,positionals:[t,r]}:void 0}(e,t):function(e,t){let r=e.positionals?.[0];return"text"===r||"attrs"===r?{...e,positionals:[r,t]}:void 0}(e,t)}(r);if(n){t.push(n);continue}let a=function(e,t){if(!aV(t.command))return;let r=t.result?.refLabel;if("string"!=typeof r||0===r.trim().length)return;let n=r.trim();return{ts:t.ts,command:"snapshot",positionals:[],flags:{platform:e.device.platform,snapshotInteractiveOnly:!0,snapshotCompact:!0,snapshotScope:n},result:{scope:n}}}(e,r);a&&t.push(a),t.push(r)}return t}(e);let n=[],a=t.device.kind?` kind=${t.device.kind}`:"";for(let e of(n.push(`context platform=${t.device.platform} device=${aD(t.device.name)}${a} theme=unknown`),r))e.flags?.noRecord||n.push(function(e){var t,r;let n=(t=[e.command],r=e,a_(r.command)?function(e,t){let r=t.positionals?.[0];if(r){if(r.startsWith("@"))return e.push(ak(r)),aG(e,t),aE(e,t),e.join(" ");if(1===t.positionals.length)return e.push(ak(r)),aE(e,t),e.join(" ")}}(t,r):"fill"===r.command?function(e,t){let r=t.positionals?.[0];if(!r?.startsWith("@"))return;e.push(ak(r)),aG(e,t);let n=t.positionals.slice(1).join(" ");return t.positionals.length>1&&e.push(ak(n)),aE(e,t),e.join(" ")}(t,r):"get"===r.command?function(e,t){let r=t.positionals?.[0],n=t.positionals?.[1];if(r&&n)return e.push(ak(r)),e.push(ak(n)),n.startsWith("@")&&aG(e,t),e.join(" ")}(t,r):void 0);return n||aF(e)}(e));return`${n.join("\n")}
8
+ `}(e);return l.writeFileSync(t,n),{written:!0,path:t}}catch(r){return eN({level:"warn",phase:"session_script_write_failed",data:{session:e.name,path:t,error:r instanceof Error?r.message:String(r)}}),{written:!1}}}resolveScriptPath(e){if(e.saveScriptPath)return e6(e.saveScriptPath,{cwd:void 0});l.existsSync(this.sessionsDir)||l.mkdirSync(this.sessionsDir,{recursive:!0});let t=aw(e.name),r=new Date(e.createdAt).toISOString().replace(/[:.]/g,"-");return f.join(this.sessionsDir,`${t}-${r}.ad`)}}function aV(e){return aN(e)||"fill"===e||"get"===e}function aG(e,t){let r=t.result?.refLabel;"string"==typeof r&&r.trim().length>0&&e.push(ak(r))}class aq{sessions=new Map;runtimeHints=new Map;sessionsDir;scriptWriter;constructor(e){this.sessionsDir=e,this.scriptWriter=new aU(e)}get(e){return this.sessions.get(e)}has(e){return this.sessions.has(e)}set(e,t){this.sessions.set(e,t)}delete(e){return this.runtimeHints.delete(e),this.sessions.delete(e)}values(){return this.sessions.values()}toArray(){return Array.from(this.sessions.values())}getRuntimeHints(e){return this.runtimeHints.get(e)}setRuntimeHints(e,t){this.runtimeHints.set(e,t)}clearRuntimeHints(e){return this.runtimeHints.delete(e)}recordAction(e,t){t.flags?.noRecord||(t.flags?.saveScript&&(e.recordSession=!0,"string"==typeof t.flags.saveScript&&(e.saveScriptPath=e6(t.flags.saveScript,{cwd:void 0}))),e.actions.push({ts:Date.now(),command:t.command,positionals:t.positionals,runtime:t.runtime,flags:function(e){if(!e)return{};let t={};for(let r of ag)void 0!==e[r]&&(t[r]=e[r]);return t}(t.flags),result:t.result}),eN({level:"debug",phase:"record_action",data:{command:t.command,session:e.name}}))}writeSessionLog(e){let t=this.scriptWriter.write(e);t.written&&eN({level:"info",phase:"session_script_written",data:{session:e.name,path:t.path}})}defaultTracePath(e){let t=aw(e.name),r=new Date().toISOString().replace(/[:.]/g,"-");return f.join(this.sessionsDir,`${t}-${r}.trace.log`)}resolveAppLogPath(e){return f.join(this.sessionsDir,aw(e),"app.log")}resolveAppLogPidPath(e){return f.join(this.sessionsDir,aw(e),"app-log.pid")}static expandHome(e,t){return e6(e,{cwd:t})}}let aB="app-log.pid";function aj(e){let t=e.trim();if(!t)return null;if(/^\d+$/.test(t))return{pid:Number.parseInt(t,10)};try{let e=JSON.parse(t);if(!Number.isInteger(e.pid)||e.pid<=0)return null;return e}catch{return null}}function aH(e,t){if(!e)return;let r=f.dirname(e);l.existsSync(r)||l.mkdirSync(r,{recursive:!0});let n={pid:t,startTime:em(t)??void 0,command:ew(t)??void 0};l.writeFileSync(e,`${JSON.stringify(n)}
9
+ `)}function aW(e){if(e&&l.existsSync(e))try{l.unlinkSync(e)}catch{}}async function az(e,t=2e3){await Promise.race([e.then(()=>void 0).catch(()=>void 0),new Promise(e=>setTimeout(e,t))])}function aK(e,t){let r=t.includeTokens?.filter(e=>e.length>0)??[],n="",a=n=>{(!(r.length>0)||r.some(e=>n.includes(e)))&&e.write(function(e,t){if(0===t.length)return e;let r=e;for(let e of t)r=r.replace(e,"[REDACTED]");return r}(n,t.redactionPatterns))};return{onChunk:e=>{let t=`${n}${e}`.split("\n");for(let e of(n=t.pop()??"",t))a(`${e}
10
+ `)},flush:()=>{n&&(a(n),n="")}}}function aJ(e,t,r){let n=e.stdout,a=e.stderr;return n&&a?(n.setEncoding("utf8"),a.setEncoding("utf8"),n.on("data",r.writer.onChunk),a.on("data",r.writer.onChunk),t.on("error",()=>{e.killed||e.kill("SIGKILL")}),e.on("error",()=>t.destroy()),new Promise(n=>{e.on("close",e=>{r.writer.flush(),r.endStreamOnClose&&t.end(),n({stdout:"",stderr:"",exitCode:e??1})})})):Promise.resolve({stdout:"",stderr:"missing stdio pipes",exitCode:1})}function aX(e){if(!/^[a-zA-Z0-9._:-]+$/.test(e))throw new D("INVALID_ARGS",`Invalid Android package name for logs: ${e}`)}async function aY(e,t){let r=(await tn(z(e))(["shell","pidof",t],{allowFailure:!0})).stdout.trim().split(/\s+/)[0];return r&&/^\d+$/.test(r)?r:null}async function aZ(e,t){var r,n;let a;aX(t);let i=await aY(e,t),o=tn(z(e)),s=await K(o,{lines:4e3,timeoutMs:3e3}).catch(()=>"");if(0===s.trim().length)return null;let l=function(e,t,r){let n=new Set;for(let a of(r&&n.add(r),e.split("\n")))if(a.includes(t))for(let e of function(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=[RegExp(`\\bStart proc\\s+(\\d+):${r}(?:\\b|/)`,"i"),RegExp(`\\b(\\d+):${r}(?:\\b|/)`,"i"),RegExp(`${r}.*?\\bpid\\s*[=:]?\\s*(\\d+)\\b`,"i"),RegExp(`\\bpid\\s*[=:]?\\s*(\\d+)\\b.*${r}`,"i")],a=[];for(let t of n){let r=t.exec(e),n=r?.[1];n&&/^\d+$/.test(n)&&a.push(n)}return a}(a,t))n.add(e);return[...n]}(s,t,i);if(0===l.length)return null;let u=(r=s,n=t,a=new Set(l),r.split("\n").filter(e=>{var t;let r;if(!e.trim())return!1;if(e.includes(n))return!0;let i=(t=e,r=/\(\s*(\d+)\)\s*:/.exec(t),r?.[1]??null);return!!i&&a.has(i)}).join("\n"));return 0===u.trim().length?null:{pid:i,text:u,recoveredPids:l}}async function aQ(e,t,r,n,a){let i,o,s="recovering",l=!1,u=(async()=>{try{for(;!l;){let u=await aY(e,t);if(!u){s="recovering",await e8(1e3);continue}let d=tt(z(e)),c=G(d,{pid:u});i=c;let p=aK(r,{redactionPatterns:n});if(o=aJ(c,r,{endStreamOnClose:!1,writer:p}),"number"==typeof c.pid&&aH(a,c.pid),s="active",await o,aW(a),i=void 0,o=void 0,l)break;s="recovering",await e8(500)}return{stdout:"",stderr:"",exitCode:0}}finally{r.end(),aW(a)}})();return{backend:"android",getState:()=>s,startedAt:Date.now(),wait:u,stop:async()=>{l=!0,i&&!i.killed&&i.kill("SIGINT"),o&&await az(o),i&&!i.killed&&i.kill("SIGKILL"),await az(u),aW(a)}}}function a0(e,t){let r=a3(e),n=[`subsystem == "${r}"`,`subsystem CONTAINS "${r}"`,`processImagePath ENDSWITH[c] "/${r}"`,`senderImagePath ENDSWITH[c] "/${r}"`];if(t){let e=a3(t);n.push(`process == "${e}"`,`processImagePath ENDSWITH[c] "/${e}"`,`senderImagePath ENDSWITH[c] "/${e}"`,`processImagePath CONTAINS[c] "/${e}.app/"`,`senderImagePath CONTAINS[c] "/${e}.app/"`)}return n.join(" OR ")}async function a1(e){let{deviceId:t,appBundleId:r,executableName:n,startedAt:a,simulatorSetPath:i}=e,o=rL(["spawn",t,"log","show","--style","compact","--info","--predicate",a0(r,n)],{simulatorSetPath:i});"number"==typeof a&&Number.isFinite(a)&&a>0?o.push("--start",`@${Math.floor(a/1e3)}`):o.push("--last","5m");let s=await rR(o,{allowFailure:!0,timeoutMs:4e3});if(0!==s.exitCode||0===s.stdout.trim().length)return null;let l=s.stdout.split("\n").map(e=>e.trimEnd()).filter(e=>{let t=e.trim();return t.length>0&&!t.startsWith("Timestamp Ty Process[PID:TID]")});return 0===l.length?null:{text:`${l.join("\n")}
11
+ `,recoveredLineCount:l.length}}async function a2(e,t,r,n,a,i){let o=await a5({deviceId:e,appBundleId:t,simulatorSetPath:a});return a6({backend:"ios-simulator",cmd:"xcrun",args:function(e){let{deviceId:t,appBundleId:r,executableName:n,simulatorSetPath:a}=e;return rL(["spawn",t,"log","stream","--style","compact","--level","info","--predicate",a0(r,n)],{simulatorSetPath:a})}({deviceId:e,appBundleId:t,executableName:o,simulatorSetPath:a}),stream:r,redactionPatterns:n,pidPath:i})}function a3(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}async function a5(e){let{deviceId:t,appBundleId:r,simulatorSetPath:n}=e,a=await rR(rL(["get_app_container",t,r,"app"],{simulatorSetPath:n}),{allowFailure:!0,timeoutMs:4e3});if(0!==a.exitCode)return;let i=a.stdout.trim();if(!i)return;let o=f.join(i,"Info.plist"),s=await R("plutil",["-extract","CFBundleExecutable","raw","-o","-",o],{allowFailure:!0,timeoutMs:4e3});if(0===s.exitCode)return s.stdout.trim()||void 0}async function a4(e,t,r,n){return a6({backend:"macos",cmd:"log",args:["stream","--style","compact","--predicate",a0(e)],stream:t,redactionPatterns:r,pidPath:n})}async function a8(e,t,r,n){return a6({backend:"ios-device",cmd:"xcrun",args:["devicectl","device","log","stream","--device",e],stream:t,redactionPatterns:r,pidPath:n})}function a6(e){let t="active",r=P(e.cmd,e.args,{allowFailure:!0,captureOutput:!1});r.wait.catch(()=>{});let n=r.child,a=aK(e.stream,{redactionPatterns:e.redactionPatterns});"number"==typeof n.pid&&aH(e.pidPath,n.pid);let i=aJ(n,e.stream,{endStreamOnClose:!0,writer:a}).then(r=>(0!==r.exitCode&&(t="failed"),aW(e.pidPath),r),r=>{throw t="failed",aW(e.pidPath),r});return{backend:e.backend,getState:()=>t,startedAt:Date.now(),wait:i,stop:async()=>{n.killed||n.kill("SIGINT"),await az(i),n.killed||n.kill("SIGKILL"),await az(i),aW(e.pidPath)}}}let a9=RegExp("\\b(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\\b\\s+https?:\\/\\/","i"),a7=/https?:\/\/[^\s"'<>\])]+/i,ie=[/\bstatus(?:Code)?["'=: ]+([1-5]\d{2})\b/i,/\bresponse(?:\s+code)?["'=: ]+([1-5]\d{2})\b/i,/\bHTTP\/[0-9.]+\s+([1-5]\d{2})\b/i];function it(e,t,r=e.limits.maxEntries){let n=[...e.entries],a=new Set(n.map(e=>ia(e)));for(let e of t.entries){let t=ia(e);if(!a.has(t)&&(a.add(t),n.push(e),n.length>=r))break}return{...e,matchedLines:n.length,entries:n}}function ir(e,t){let r=ih(t?.maxEntries,25,1,200),n=t?.backend,a=t?.include??"summary",i=ih(t?.maxPayloadChars,2048,64,16384),o=ih(t?.maxScanLines,4e3,100,2e4),s=e.split("\n"),l=Math.max(0,s.length-o),u=s.slice(l),d=[];for(let e=u.length-1;e>=0&&d.length<r;e-=1){let t=u[e];if(!t?.trim())continue;let r=function(e,t,r,n,a,i){let o=e[t]?.trim();if(!o)return null;let s=function(e){let t=e.indexOf("{");if(t<0)return null;let r=e.lastIndexOf("}");if(r<=t)return null;let n=e.slice(t,r+1);try{let e=JSON.parse(n);return e&&"object"==typeof e?e:null}catch{return null}}(o),l=id(s,["method","httpMethod"]),u=id(s,["url","requestUrl"]),d=function(e,t){if(!e)return null;for(let r of t){let t=e[r];if("number"==typeof t&&Number.isInteger(t))return t;if("string"==typeof t&&/^\d{3}$/.test(t.trim()))return Number.parseInt(t.trim(),10)}return null}(s,["status","statusCode","responseCode"]),c=a9.exec(o),p=/\bmethod["'=: ]+([A-Z]+)\b/i.exec(o),f=(l??p?.[1]??c?.[1])?.toUpperCase(),m=a7.exec(o),h=u??m?.[0];if(!h)return null;let w=d??io(o)??void 0;if(!(l||p?.[1]||c?.[1]||void 0!==w||/\bURL["'=: ]+https?:\/\//i.test(o)||/\bheaders?["'=: ]+/i.test(o)||/\b(?:requestBody|responseBody|payload|request|response)["'=: ]+/i.test(o)))return null;let g={method:f,url:h,status:w,timestamp:is(o),packetId:il(o)??void 0,durationMs:iu(o)??void 0,raw:im(o,i),line:r};if("android"===n&&function(e,t,r){let n=ii(t,r,5),a=e.packetId??n.map(e=>il(e)).find(e=>"string"==typeof e&&e.length>0);a&&(e.packetId=a);let i=a?ii(t,r,12).filter(e=>il(e)===a):n;e.timestamp||(e.timestamp=i.map(e=>is(e)).find(e=>"string"==typeof e&&e.length>0)),void 0===e.status&&(e.status=i.map(e=>io(e)).find(e=>"number"==typeof e)),void 0===e.durationMs&&(e.durationMs=i.map(e=>iu(e)).find(e=>"number"==typeof e))}(g,e,t),"headers"===a||"all"===a){let e=function(e,t){if(t){let e=t.headers??t.requestHeaders??t.responseHeaders;if(void 0!==e)return ip(e)}let r=/\bheaders?["'=: ]+(\{.*\})/i.exec(e);return r?.[1]?.trim()}(o,s);e&&(g.headers=im(e,i))}if("body"===a||"all"===a){let e=ic(o,s,["requestBody","body","payload","request"]),t=ic(o,s,["responseBody","response"]);e&&(g.requestBody=im(e,i)),t&&(g.responseBody=im(t,i))}return g}(u,e,l+e+1,n,a,i);r&&d.push(r)}return{path:t?.path??"<memory>",exists:!0,scannedLines:u.length,matchedLines:d.length,entries:d,include:a,limits:{maxEntries:r,maxPayloadChars:i,maxScanLines:o}}}function ia(e){return`${e.timestamp??""}|${e.method??""}|${e.url}|${e.status??""}|${e.raw}`}function ii(e,t,r){let n=[],a=Math.max(0,t-r),i=Math.min(e.length-1,t+r);for(let t=a;t<=i;t+=1){let r=e[t]?.trim();r&&n.push(r)}return n}function io(e){for(let t of ie){let r=t.exec(e);if(!r)continue;let n=Number.parseInt(r[1]??"",10);if(Number.isInteger(n))return n}return null}function is(e){let t=/\b\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z)?\b/.exec(e);if(t)return t[0];let r=/\b\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+\b/.exec(e);return r?.[0]}function il(e){let t=/\bpacket id (\d+)\b/i.exec(e);return t?.[1]??null}function iu(e){let t=/\b(?:duration|elapsed request\/response time, ms)[:= ]+(\d+)\b/i.exec(e);if(!t)return null;let r=Number.parseInt(t[1]??"",10);return Number.isInteger(r)?r:null}function id(e,t){if(e)for(let r of t){let t=e[r];if("string"==typeof t&&t.trim().length>0)return t.trim()}}function ic(e,t,r){if(t){for(let e of r)if(void 0!==t[e])return ip(t[e])}for(let t of r){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=RegExp(`\\b${r}["'=: ]+(.+)$`,"i").exec(e);if(n?.[1])return n[1].trim()}}function ip(e){if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}}function im(e,t){return e.length<=t?e:`${e.slice(0,t)}...<truncated>`}function ih(e,t,r,n){return void 0!==e&&Number.isInteger(e)?Math.max(r,Math.min(n,e)):t}let iw={start:async e=>await ix(e)},ig=rI(iw,function(e={}){return{...iw,...e}});async function iy(e,t){return await ig.run(e,t)}function iv(e,t){let r=process.env[e];if(!r)return t;let n=Number.parseInt(r,10);return Number.isInteger(n)&&n>0?n:t}function iI(e){let t=f.dirname(e);l.existsSync(t)||l.mkdirSync(t,{recursive:!0}),function(e,t){if(l.existsSync(e)&&!(l.statSync(e).size<t.maxBytes))for(let r=t.maxRotatedFiles;r>=1;r-=1){let t=1===r?e:`${e}.${r-1}`,n=`${e}.${r}`;l.existsSync(t)&&(l.existsSync(n)&&l.unlinkSync(n),l.renameSync(t,n))}}(e,{maxBytes:iv("AGENT_DEVICE_APP_LOG_MAX_BYTES",5242880),maxRotatedFiles:iv("AGENT_DEVICE_APP_LOG_MAX_FILES",1)})}async function ib(e){var t,r,n,a;let i,o,s,u,{device:d,appBundleId:c,appLogState:p,appLogStartedAt:f,appLogPath:m,maxEntries:h,include:w,maxPayloadChars:g,maxScanLines:y}=e,v="macos"===d.platform?"macos":"ios"===d.platform?"device"===d.kind?"ios-device":"ios-simulator":"android",I=(t={backend:v,maxEntries:h,include:w,maxPayloadChars:g,maxScanLines:y},i=ih(t?.maxEntries,25,1,200),o=t?.include??"summary",s=ih(t?.maxPayloadChars,2048,64,16384),u=ih(t?.maxScanLines,4e3,100,2e4),l.existsSync(m)?ir(l.readFileSync(m,"utf8"),{...t,path:m}):{path:m,exists:!1,scannedLines:0,matchedLines:0,entries:[],include:o,limits:{maxEntries:i,maxPayloadChars:s,maxScanLines:u}}),b=[],A=await iA({device:d,appBundleId:c,appLogPath:m,appLogState:p});if(A){let e=await aZ(d.id,c);if(e){let t=ir(e.text,{path:`${m} (adb logcat recovery)`,backend:"android",maxEntries:h,include:w,maxPayloadChars:g,maxScanLines:y});t.entries.length>0&&(I=it(t,I,h),b.push((r=A,n=e.recoveredPids,"stale-active"===r.reason?`Session app log stream was still bound to prior Android PID ${r.trackedPid}. Recovered recent Android HTTP entries from adb logcat for PID set ${n.join(", ")}.`:`Session app log stream was inactive. Recovered recent Android HTTP entries from adb logcat for PID set ${n.join(", ")}.`)))}}if("ios"===d.platform&&"simulator"===d.kind&&c&&0===I.entries.length){let e=await i_({deviceId:d.id,appBundleId:c,startedAt:f,simulatorSetPath:d.simulatorSetPath,appLogPath:m,maxEntries:h,include:w,maxPayloadChars:g,maxScanLines:y});e&&(e.dump.entries.length>0?(I=it(e.dump,I,h),b.push(`Recovered ${e.dump.entries.length} iOS simulator HTTP entr${1===e.dump.entries.length?"y":"ies"} from simctl log show (${e.recoveredLineCount} app log lines scanned).`)):e.recoveredLineCount>0&&b.push(`Recovered ${e.recoveredLineCount} recent iOS simulator app log lines from simctl log show, but none looked like HTTP traffic. This app may not emit request URLs, status, or timing into Unified Logging for this repro window.`))}return void 0===p?b.push("Capture uses the session app log file. For fresh traffic, run logs clear --restart before reproducing requests."):"active"!==p&&0===b.length&&("ios"===d.platform&&"simulator"===d.kind?b.push("Session app log stream is inactive. The iOS simulator recovery path scanned recent simctl log history, but a fresh logs clear --restart window is still the most reliable repro loop."):b.push("Session app log stream is inactive. Run logs clear --restart, reproduce the request window again, then rerun network dump.")),0===I.entries.length&&b.push("ios"===(a=d).platform&&"simulator"===a.kind?"No HTTP(s) entries were found in recent iOS simulator app logs. If the app only emits non-HTTP diagnostics, inspect logs path or add app-side URLSession/network logging for per-request timing and payload details.":"ios"===a.platform?"No HTTP(s) entries were found in recent iOS device app logs. iOS network dump only sees what the app emits into Unified Logging for this process.":"No HTTP(s) entries were found in recent session app logs."),{backend:v,dump:I,notes:b}}async function iA(e){let{device:t,appBundleId:r,appLogPath:n,appLogState:a}=e;if("android"!==t.platform||!r)return null;if(void 0!==a&&"active"!==a)return{reason:"inactive"};if("active"!==a)return null;let i=function(e){let t=function(e){if(!e||!l.existsSync(e))return null;try{return aj(l.readFileSync(e,"utf8"))}catch{return null}}(e)?.command;if(!t)return null;let r=/(?:^|\s)--pid\s+(\d+)(?:\s|$)/.exec(t);return r?.[1]??null}(f.join(f.dirname(n),aB));if(!i)return null;let o=await aY(t.id,r);return o&&o!==i?{reason:"stale-active",trackedPid:i}:null}async function iS(e,t,r,n){return await ig.resolve(void 0).start({device:e,appBundleId:t,outPath:r,pidPath:n})}async function ix({device:e,appBundleId:t,outPath:r,pidPath:n}){iI(r);let a=l.createWriteStream(r,{flags:"a"}),i=function(){let e=process.env.AGENT_DEVICE_APP_LOG_REDACT_PATTERNS;if(!e)return[];let t=e.split(",").map(e=>e.trim()).filter(e=>e.length>0),r=[];for(let e of t)try{r.push(RegExp(e,"gi"))}catch{}return r}();if("ios"===e.platform)return"device"===e.kind?await a8(e.id,a,i,n):await a2(e.id,t,a,i,e.simulatorSetPath,n);if("android"===e.platform)return aX(t),await aQ(e.id,t,a,i,n);if("macos"===e.platform)return await a4(t,a,i,n);throw a.end(),new D("UNSUPPORTED_PLATFORM",`unsupported platform: ${e.platform}`)}async function i_(e){let t=await a1({deviceId:e.deviceId,appBundleId:e.appBundleId,startedAt:e.startedAt,simulatorSetPath:e.simulatorSetPath});return t?{dump:ir(t.text,{path:`${e.appLogPath} (simctl log show recovery)`,backend:"ios-simulator",maxEntries:e.maxEntries,include:e.include,maxPayloadChars:e.maxPayloadChars,maxScanLines:e.maxScanLines}),recoveredLineCount:t.recoveredLineCount}:null}async function iN(e){await e.stop(),await az(e.wait)}async function iM(e,t){let r={},n=[];if(t||n.push("No app bundle is tracked in this session. Run open <app> first for app-scoped logs."),"android"===e.platform){try{let t=await Y(e,["shell","echo","ok"],{allowFailure:!0,timeoutMs:1e3});r.adbAvailable=0===t.exitCode}catch{r.adbAvailable=!1}if(t)try{r.androidPidVisible=(await Y(e,["shell","pidof",t],{allowFailure:!0,timeoutMs:1e3})).stdout.trim().length>0}catch{r.androidPidVisible=!1}}if("ios"===e.platform&&"simulator"===e.kind)try{let e=await rR(["simctl","help"],{allowFailure:!0});r.simctlAvailable=0===e.exitCode}catch{r.simctlAvailable=!1}if("ios"===e.platform&&"device"===e.kind)try{let e=await rR(["devicectl","--version"],{allowFailure:!0});r.devicectlAvailable=0===e.exitCode}catch{r.devicectlAvailable=!1}if("macos"===e.platform)try{let e=await R("log",["help"],{allowFailure:!0});r.logAvailable=0===e.exitCode}catch{r.logAvailable=!1}return{checks:r,notes:n}}function ik(e){let t=f.dirname(e),r=f.basename(e);l.existsSync(t)||l.mkdirSync(t,{recursive:!0}),l.existsSync(e)?l.truncateSync(e,0):l.writeFileSync(e,"","utf8");let n=0;for(let e of l.readdirSync(t)){if(!e.startsWith(`${r}.`))continue;let a=e.slice(r.length+1);if(/^\d+$/.test(a))try{l.unlinkSync(f.join(t,e)),n+=1}catch{}}return{path:e,cleared:!0,removedRotatedFiles:n}}let iD=new Map;function iP(e){let t=o.randomUUID(),r=setTimeout(()=>{iO(t)},9e5);return r.unref(),iD.set(t,{artifactPath:e.artifactPath,tenantId:e.tenantId,fileName:e.fileName,deleteAfterDownload:!1!==e.deleteAfterDownload,timer:r}),t}function iO(e){let t=iD.get(e);if(t&&(clearTimeout(t.timer),iD.delete(e),t.deleteAfterDownload))try{l.rmSync(t.artifactPath,{force:!0})}catch{}}let iR=new Map;function iE(e,t){let r=iR.get(e);if(!r)throw new D("INVALID_ARGS",`Uploaded artifact not found: ${e}`);if(r.tenantId&&r.tenantId!==t)throw new D("UNAUTHORIZED","Uploaded artifact belongs to a different tenant");return clearTimeout(r.timer),r.artifactPath}function iC(e){let t=iR.get(e);t&&(clearTimeout(t.timer),iR.delete(e),l.rmSync(t.tempDir,{recursive:!0,force:!0}))}async function iL(e){let t=await iT(e);await R("tar",["xf",e.archivePath,"-C",e.tempDir]);let r=f.join(e.tempDir,t);if(!l.existsSync(r))throw new D("INVALID_ARGS",`Expected extracted bundle "${t}" not found in archive`);return r}async function iT(e){let t=await R("tar",["-tf",e.archivePath],{allowFailure:!0});if(0!==t.exitCode)throw new D("INVALID_ARGS","Artifact is not a valid tar archive",{archivePath:e.archivePath,stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});let r=t.stdout.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);if(0===r.length)throw new D("INVALID_ARGS","Uploaded app bundle archive is empty");let n=r.map(i$),a=e.expectedRootName??function(e,t){let r=new Set;for(let t of e){let[e]=t.split("/");e&&r.add(e)}let n=[...r];if("ios"===t){let e=n.filter(e=>e.toLowerCase().endsWith(".app")),t=e[0];if(void 0!==t&&1===e.length)return t;if(0===e.length)throw new D("INVALID_ARGS","iOS app bundle archives must contain a single top-level .app directory");throw new D("INVALID_ARGS",`iOS app bundle archives must contain exactly one top-level .app directory, found: ${e.join(", ")}`)}let a=n[0];if(void 0!==a&&1===n.length)return a;throw new D("INVALID_ARGS",`Archive must contain a single top-level bundle, found: ${n.join(", ")}`)}(n,e.platform);if(!n.some(e=>e===a||e.startsWith(`${a}/`)))throw new D("INVALID_ARGS",`Uploaded archive must contain a top-level "${a}" bundle`);for(let e of n){var i=e,o=a;if(i!==o&&!i.startsWith(`${o}/`))throw new D("INVALID_ARGS",`Archive entry must stay inside top-level "${o}" bundle: ${i}`)}for(let t of(await R("tar",["-tvf",e.archivePath])).stdout.split(/\r?\n/).filter(Boolean))if("l"===t[0]||"h"===t[0])throw new D("INVALID_ARGS","Uploaded app bundle archive cannot contain symlinks or hard links");return a}function i$(e){if(e.includes("\0"))throw new D("INVALID_ARGS",`Invalid archive entry: ${e}`);if(f.posix.isAbsolute(e))throw new D("INVALID_ARGS",`Archive entry must be relative: ${e}`);let t=f.posix.normalize(e).replace(/^(\.\/)+/,"");if(!t||"."===t||t.startsWith("../"))throw new D("INVALID_ARGS",`Archive entry escapes bundle root: ${e}`);return t}function iF(e,t){return new Promise((r,n)=>{let a,i=!1,o=0,s=l.createWriteStream(t),u=e=>{if(!i){if(i=!0,a&&clearTimeout(a),e)return void iU(s,t).finally(()=>n(e));r()}},d=()=>{a&&clearTimeout(a),a=setTimeout(()=>{let t=new D("COMMAND_FAILED","Artifact transfer timed out due to inactivity",{timeoutMs:6e4});"destroy"in e&&"function"==typeof e.destroy&&e.destroy(t),c.destroy(t),u(t)},6e4)},c=new I({transform(e,t,r){d();let n=Buffer.isBuffer(e)?e.length:Buffer.byteLength(e,t);(o+=n)>0x80000000?r(new D("INVALID_ARGS","Upload exceeds maximum size of 2147483648 bytes")):r(null,e)}});e.on("aborted",()=>{u(new D("COMMAND_FAILED","Artifact transfer was interrupted"))}),d(),b(e,c,s).then(()=>u(),e=>u(e))})}async function iU(e,t){if(e.destroy(),!e.closed)try{await v(e,"close")}catch{}await l.promises.rm(t,{force:!0}).catch(()=>{})}async function iV(e){let t,r=e.headers["x-artifact-type"],n=e.headers["x-artifact-filename"];if(!r||!n)throw new D("INVALID_ARGS","Missing required headers: x-artifact-type and x-artifact-filename");if("file"!==r&&"app-bundle"!==r)throw new D("INVALID_ARGS",`Invalid x-artifact-type: ${r}. Must be "file" or "app-bundle".`);!function(e){if(void 0===e)return;let t=Number(e);if(Number.isFinite(t)&&t>0x80000000)throw new D("INVALID_ARGS","Upload exceeds maximum size of 2147483648 bytes")}(e.headers["content-length"]);let a=function(e){let t=e.trim(),r=f.basename(t);if(!r||"."===r||".."===r)throw new D("INVALID_ARGS",`Invalid artifact filename: ${e}`);return r}(n),i=(t=function(e){let t=e?.trim();if(!t)return"request";let r=t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");return r.length>0?r.slice(0,48):"request"}("upload"),l.mkdtempSync(f.join(c.tmpdir(),`agent-device-artifact-${t}-`)));try{if("file"===r){let t=f.join(i,a);return await iF(e,t),{artifactPath:t,tempDir:i}}let t=f.join(i,"artifact.tar");await iF(e,t);let n=await iL({archivePath:t,tempDir:i,platform:"ios",expectedRootName:a});return l.rmSync(t,{force:!0}),{artifactPath:n,tempDir:i}}catch(e){throw l.rmSync(i,{recursive:!0,force:!0}),e}}let iG=new h;async function iq(e,t){return await iG.run(e,t)}function iB(e){iG.getStore()?.(e)}let ij=new Set(["agent_device.command","agent-device.command"]),iH=new Set(["agent_device.install_from_source","agent-device.install_from_source"]),iW=new Set(["agent_device.release_materialized_paths","agent-device.release_materialized_paths"]),iz={"agent_device.lease.allocate":"lease_allocate","agent-device.lease.allocate":"lease_allocate","agent_device.lease.heartbeat":"lease_heartbeat","agent-device.lease.heartbeat":"lease_heartbeat","agent_device.lease.release":"lease_release","agent-device.lease.release":"lease_release"},iK=new Set([...ij,...iH,...iW,...Object.keys(iz)]);function iJ(e,t,r,n){return{jsonrpc:"2.0",id:e,error:{code:t,message:r,data:n}}}function iX(e,t,r=200){e.statusCode=r,e.setHeader("content-type","application/json"),e.end(JSON.stringify(t))}function iY(e,t){e.destroyed||(e.write(eT(t)),e.end())}function iZ(e){switch(e){case"INVALID_ARGS":return 400;case"UNAUTHORIZED":return 401;case"SESSION_NOT_FOUND":return 404;default:return 500}}function iQ(e,t){let r="string"==typeof t.authorization?t.authorization:"",n=r.toLowerCase().startsWith("bearer ")?r.slice(7):void 0,a="string"==typeof t["x-agent-device-token"]?t["x-agent-device-token"]:void 0;return("string"==typeof e.token?e.token:void 0)??a??n??""}function i0(e,t){let r=e[t];return"string"==typeof r?r:void 0}function i1(e,t){let r=e[t];return Number.isInteger(r)?Number(r):void 0}function i2(e,t){let r="string"==typeof e[t]?e[t].trim():"";if(!r)throw new D("INVALID_ARGS",`Invalid params: source.${t} is required for github-actions-artifact sources`);return r}function i3(e,t){let r=e[t],n="number"==typeof r?r:"string"==typeof r?Number(r):NaN;if(!Number.isInteger(n))throw new D("INVALID_ARGS",`Invalid params: source.${t} must be an integer`);return n}async function i5(e,t){if(!e)return{ok:!0};let r=await e(t);if(void 0===r||!0===r)return{ok:!0};if(!1===r){let e=k(new D("UNAUTHORIZED","Request rejected by auth hook"));return{ok:!1,statusCode:401,response:iJ(t.rpcRequest.id??null,-32001,e.message,e)}}if(!1===r.ok){let e=k(new D(N(r.code,"UNAUTHORIZED"),r.message??"Request rejected by auth hook",r.details));return{ok:!1,statusCode:401,response:iJ(t.rpcRequest.id??null,-32001,e.message,e)}}if("string"==typeof r.tenantId&&r.tenantId.length>0){let e=eO(r.tenantId);if(!e){let e=k(new D("INVALID_ARGS","Auth hook returned invalid tenantId"));return{ok:!1,statusCode:500,response:iJ(t.rpcRequest.id??null,-32e3,e.message,e)}}return{ok:!0,tenantId:e}}return{ok:!0}}async function i4(){let e,t=process.env.AGENT_DEVICE_HTTP_AUTH_HOOK;if(!t)return null;let r=process.env.AGENT_DEVICE_HTTP_AUTH_EXPORT||"default",n=f.isAbsolute(t)?t:f.resolve(t);try{e=await import(y(n).href)}catch(e){throw new D("COMMAND_FAILED","Failed to load AGENT_DEVICE_HTTP_AUTH_HOOK module",{hookPath:n,error:e instanceof Error?e.message:String(e)})}let a=e[r];if("function"!=typeof a)throw new D("INVALID_ARGS",`Auth hook export ${r} is not a function`,{hookPath:n,exportName:r});return a}async function i8(e){let t=await i4(),{handleRequest:r,token:n}=e;return w.createServer((e,a)=>{if("GET"===e.method&&"/health"===e.url){a.statusCode=200,a.setHeader("content-type","application/json"),a.end(JSON.stringify({ok:!0}));return}if("POST"===e.method&&"/upload"===e.url)return void i6(e,a,t,n);if("GET"===e.method&&e.url?.startsWith("/artifacts/"))return void i9(e,a,t,n);if("POST"!==e.method||"/rpc"!==e.url){a.statusCode=404,a.end("Not found");return}let i="";e.setEncoding("utf8"),e.on("data",t=>{(i+=t).length>1048576&&e.destroy(Error("request too large"))}),e.on("error",()=>{a.headersSent||iX(a,iJ(null,-32700,"Parse error"),400)}),e.on("end",async()=>{let n,o;try{n=JSON.parse(i)}catch{iX(a,iJ(null,-32700,"Parse error"),400);return}if("2.0"!==n.jsonrpc||"string"!=typeof n.method)return void iX(a,iJ(n.id??null,-32600,"Invalid Request"),400);if(!iK.has(n.method))return void iX(a,iJ(n.id??null,-32601,`Method not found: ${n.method}`),404);if(!n.params||"object"!=typeof n.params)return void iX(a,iJ(n.id??null,-32602,"Invalid params"),400);try{var s;let i=n.params,l=function(e,t,r){if(ij.has(e))return{token:iQ(t,r),session:t.session??"default",command:t.command??"",positionals:Array.isArray(t.positionals)?t.positionals:[],flags:t.flags,runtime:t.runtime,meta:t.meta};if(iH.has(e)){let e,n=i0(t,"platform");if("ios"!==n&&"android"!==n)throw new D("INVALID_ARGS",'Invalid params: platform must be "ios" or "android"');return{token:iQ(t,r),session:i0(t,"session")??"default",command:"install_source",positionals:[],flags:{platform:n},meta:{requestId:i0(t,"requestId"),installSource:function(e){let t=e.source;if(!t||"object"!=typeof t)throw new D("INVALID_ARGS","Invalid params: source is required");if("url"===t.kind){let e="string"==typeof t.url?t.url.trim():"";if(!e)throw new D("INVALID_ARGS","Invalid params: source.url is required for url sources");let r=t.headers,n={};if(void 0!==r){if(!r||"object"!=typeof r||Array.isArray(r))throw new D("INVALID_ARGS","Invalid params: source.headers must be a string map");for(let[e,t]of Object.entries(r)){if("string"!=typeof t)throw new D("INVALID_ARGS","Invalid params: source.headers values must be strings");n[e]=t}}return Object.keys(n).length>0?{kind:"url",url:e,headers:n}:{kind:"url",url:e}}if("path"===t.kind){let e="string"==typeof t.path?t.path.trim():"";if(!e)throw new D("INVALID_ARGS","Invalid params: source.path is required for path sources");return{kind:"path",path:e}}if("github-actions-artifact"===t.kind)return function(e){let t,r=i2(e,"owner"),n=i2(e,"repo"),a=void 0!==e.artifactId,i=void 0!==e.runId,o=void 0!==e.artifactName;if(a&&(i||o))throw new D("INVALID_ARGS","Invalid params: source must specify either artifactId or artifactName, not both");if(!a&&i&&!o)throw new D("INVALID_ARGS","Invalid params: source.artifactName is required when source.runId is specified");if(!a&&!o)throw new D("INVALID_ARGS","Invalid params: source must specify artifactId or artifactName");return a?{kind:"github-actions-artifact",owner:r,repo:n,artifactId:i3(e,"artifactId")}:(i&&(t=i3(e,"runId")),{kind:"github-actions-artifact",owner:r,repo:n,...i?{runId:t}:{},artifactName:i2(e,"artifactName")})}(t);throw new D("INVALID_ARGS",'Invalid params: source.kind must be "url", "path", or "github-actions-artifact"')}(t),retainMaterializedPaths:(e=t.retainPaths,"boolean"==typeof e?e:void 0),materializedPathRetentionMs:i1(t,"retentionMs")}}}if(iW.has(e)){let e=i0(t,"materializationId")?.trim();if(!e)throw new D("INVALID_ARGS","Invalid params: materializationId is required");return{token:iQ(t,r),session:i0(t,"session")??"default",command:"release_materialized_paths",positionals:[],meta:{requestId:i0(t,"requestId"),materializationId:e}}}let n=iz[e];if(n)return{token:iQ(t,r),session:i0(t,"session")??"default",command:n,positionals:[],meta:{tenantId:i0(t,"tenantId")??i0(t,"tenant"),runId:i0(t,"runId"),leaseId:i0(t,"leaseId"),leaseTtlMs:i1(t,"ttlMs"),leaseBackend:i0(t,"backend")}};throw new D("INVALID_ARGS",`Method not found: ${e}`)}(n.method,i,e.headers);if(s=n.method,ij.has(s)&&("string"!=typeof l.command||0===l.command.length))return void iX(a,iJ(n.id??null,-32602,"Invalid params: command is required"),400);o=rc(l.meta?.requestId,n.id),l.meta={...l.meta,requestId:o},rp(o);let u=()=>{a.writableFinished||rf(o)};e.on("aborted",u),a.on("close",u);let d=await i5(t,{headers:e.headers,rpcRequest:n,daemonRequest:l});if(!d.ok)return void iX(a,d.response,d.statusCode);if(d.tenantId&&(l.meta={...l.meta,tenantId:d.tenantId,sessionIsolation:l.meta?.sessionIsolation??l.flags?.sessionIsolation??"tenant"}),eU(l)){a.statusCode=200,a.setHeader("content-type","application/x-ndjson");let e=await iq(e=>{!a.destroyed&&a.write(e5(e))},async()=>await r(l)),t=e.ok?{jsonrpc:"2.0",id:n.id??null,result:e}:iJ(n.id??null,-32e3,e.error.message,e.error);iY(a,t);return}let c=await r(l);if(c.ok)return void iX(a,{jsonrpc:"2.0",id:n.id??null,result:c});iX(a,iJ(n.id??null,-32e3,c.error.message,c.error),iZ(c.error.code))}catch(t){let e=k(t);if(a.headersSent)return void iY(a,iJ(n.id??null,-32e3,e.message,e));iX(a,iJ(n.id??null,-32e3,e.message,e),iZ(e.code))}finally{rm(o)}})})}async function i6(e,t,r,n){try{var a;let i,s,l=await i7({req:e,res:t,authHook:r,expectedToken:n,daemonRequest:{command:"upload",positionals:[]}});if(!l)return;let u=await iV(e),d=(a={artifactPath:u.artifactPath,tempDir:u.tempDir,tenantId:l.tenantId},i=o.randomUUID(),(s=setTimeout(()=>{iC(i)},3e5)).unref(),iR.set(i,{artifactPath:a.artifactPath,tempDir:a.tempDir,tenantId:a.tenantId,timer:s}),i);t.statusCode=200,t.setHeader("content-type","application/json"),t.end(JSON.stringify({ok:!0,uploadId:d}))}catch(e){oe(t,k(e))}}async function i9(e,t,r,n){let a=e.url?.slice("/artifacts/".length)??"";if(!a){t.statusCode=400,t.end("Missing artifact id");return}try{let i=await i7({req:e,res:t,authHook:r,expectedToken:n,daemonRequest:{command:"download_artifact",positionals:[a]}});if(!i)return;let o=function(e,t){let r=iD.get(e);if(!r)throw new D("INVALID_ARGS",`Artifact not found: ${e}`);if(r.tenantId&&r.tenantId!==t)throw new D("UNAUTHORIZED","Artifact belongs to a different tenant");if(!l.existsSync(r.artifactPath))throw iO(e),new D("COMMAND_FAILED",`Artifact file is missing: ${r.artifactPath}`);return{artifactPath:r.artifactPath,fileName:r.fileName,deleteAfterDownload:r.deleteAfterDownload}}(a,i.tenantId),s=l.createReadStream(o.artifactPath);t.statusCode=200,t.setHeader("content-type","application/octet-stream"),o.fileName&&t.setHeader("content-disposition",`attachment; filename="${o.fileName.replace(/"/g,"")}"`),s.on("error",e=>{if(t.headersSent)t.destroy(e);else{let r=k(e);t.statusCode=iZ(r.code),t.end(r.message)}}),t.on("close",()=>{t.writableFinished&&iO(a)}),s.pipe(t)}catch(e){oe(t,k(e))}}async function i7(e){var t,r;let{req:n,res:a,authHook:i,expectedToken:o,daemonRequest:s}=e,l=iQ({},n.headers),u=(t=l,(r=o)&&t!==r?k(new D("UNAUTHORIZED","Invalid token")):null);if(u)return oe(a,u),null;let d=await i5(i,{headers:n.headers,rpcRequest:{jsonrpc:"2.0",id:null,method:"agent_device.command"},daemonRequest:{token:l,session:"default",command:s.command,positionals:s.positionals}});return d.ok?{tenantId:d.tenantId}:(a.statusCode=d.statusCode,a.setHeader("content-type","application/json"),a.end(JSON.stringify({ok:!1,error:d.response.error?.data?.message??d.response.error?.message??"Unauthorized"})),null)}function oe(e,t){e.statusCode=iZ(t.code),e.setHeader("content-type","application/json"),e.end(JSON.stringify({ok:!1,error:t.message,code:t.code}))}function ot(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}function or(e){if(!e)return;let t=e.trim();if(t&&/^[a-f0-9]{16,128}$/i.test(t))return t.toLowerCase()}function on(e){let t=(e??"").trim().toLowerCase();if(!t||"ios-simulator"===t)return"ios-simulator";if("ios-instance"===t||"android-instance"===t)return t;throw new D("INVALID_ARGS",`Unsupported lease backend: ${e??""}`)}class oa{leases=new Map;runBindings=new Map;maxActiveSimulatorLeases;defaultLeaseTtlMs;minLeaseTtlMs;maxLeaseTtlMs;now;constructor(e={}){this.maxActiveSimulatorLeases=Number.isInteger(e.maxActiveSimulatorLeases)?Math.max(0,Number(e.maxActiveSimulatorLeases)):0,this.defaultLeaseTtlMs=Number.isInteger(e.defaultLeaseTtlMs)?Math.max(1,Number(e.defaultLeaseTtlMs)):6e4,this.minLeaseTtlMs=Number.isInteger(e.minLeaseTtlMs)?Math.max(1,Number(e.minLeaseTtlMs)):5e3,this.maxLeaseTtlMs=Number.isInteger(e.maxLeaseTtlMs)?Math.max(this.minLeaseTtlMs,Number(e.maxLeaseTtlMs)):6e5,this.now=e.now??(()=>Date.now())}allocateLease(e){let t=on(e.backend),r=eO(e.tenantId);if(!r)throw new D("INVALID_ARGS","Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");let n=ot(e.runId);if(!n)throw new D("INVALID_ARGS","Invalid run id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");this.cleanupExpiredLeases();let a=this.resolveLeaseTtlMs(e.ttlMs),i=this.bindingKey(r,n,t),s=this.runBindings.get(i);if(s){let e=this.leases.get(s);if(e)return this.refreshLease(e,a);this.runBindings.delete(i)}this.enforceCapacity(t);let l=this.now(),u={leaseId:o.randomBytes(16).toString("hex"),tenantId:r,runId:n,backend:t,createdAt:l,heartbeatAt:l,expiresAt:l+a};return this.leases.set(u.leaseId,u),this.runBindings.set(i,u.leaseId),{...u}}heartbeatLease(e){let t=or(e.leaseId);if(!t)throw new D("INVALID_ARGS","Invalid lease id.");this.cleanupExpiredLeases();let r=this.leases.get(t);if(!r)throw new D("UNAUTHORIZED","Lease is not active",{reason:"LEASE_NOT_FOUND"});this.assertOptionalScopeMatch(r,e.tenantId,e.runId);let n=this.resolveLeaseTtlMs(e.ttlMs);return this.refreshLease(r,n)}releaseLease(e){let t=or(e.leaseId);if(!t)throw new D("INVALID_ARGS","Invalid lease id.");this.cleanupExpiredLeases();let r=this.leases.get(t);return r?(this.assertOptionalScopeMatch(r,e.tenantId,e.runId),this.leases.delete(t),this.runBindings.delete(this.bindingKey(r.tenantId,r.runId,r.backend)),{released:!0}):{released:!1}}assertLeaseAdmission(e){let t=on(e.backend),r=eO(e.tenantId);if(!r)throw new D("INVALID_ARGS","tenant isolation requires tenant id.");let n=ot(e.runId);if(!n)throw new D("INVALID_ARGS","tenant isolation requires run id.");let a=or(e.leaseId);if(!a)throw new D("INVALID_ARGS","tenant isolation requires lease id.");this.cleanupExpiredLeases();let i=this.leases.get(a);if(!i)throw new D("UNAUTHORIZED","Lease is not active",{reason:"LEASE_NOT_FOUND"});if(i.backend!==t||i.tenantId!==r||i.runId!==n)throw new D("UNAUTHORIZED","Lease does not match tenant/run scope",{reason:"LEASE_SCOPE_MISMATCH"})}listActiveLeases(){return this.cleanupExpiredLeases(),Array.from(this.leases.values()).map(e=>({...e}))}cleanupExpiredLeases(){let e=this.now();for(let t of this.leases.values())t.expiresAt>e||(this.leases.delete(t.leaseId),this.runBindings.delete(this.bindingKey(t.tenantId,t.runId,t.backend)))}enforceCapacity(e){if("ios-simulator"!==e||this.maxActiveSimulatorLeases<=0)return;let t=Array.from(this.leases.values()).filter(e=>"ios-simulator"===e.backend).length;if(!(t<this.maxActiveSimulatorLeases))throw new D("COMMAND_FAILED","No simulator lease capacity available",{reason:"LEASE_CAPACITY_EXCEEDED",activeLeases:t,maxActiveLeases:this.maxActiveSimulatorLeases,backend:e,hint:"Retry after releasing another simulator lease."})}resolveLeaseTtlMs(e){if(!Number.isInteger(e))return this.defaultLeaseTtlMs;let t=Number(e);if(t<this.minLeaseTtlMs||t>this.maxLeaseTtlMs)throw new D("INVALID_ARGS",`Lease ttlMs must be between ${this.minLeaseTtlMs} and ${this.maxLeaseTtlMs}.`);return t}refreshLease(e,t){let r=this.now(),n={...e,heartbeatAt:r,expiresAt:r+t};return this.leases.set(n.leaseId,n),this.runBindings.set(this.bindingKey(n.tenantId,n.runId,n.backend),n.leaseId),{...n}}bindingKey(e,t,r){return`${e}:${t}:${r}`}assertOptionalScopeMatch(e,t,r){let n=eO(t),a=ot(r);if(t&&!n)throw new D("INVALID_ARGS","Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");if(r&&!a)throw new D("INVALID_ARGS","Invalid run id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");if(n&&e.tenantId!==n||a&&e.runId!==a)throw new D("UNAUTHORIZED","Lease does not match tenant/run scope",{reason:"LEASE_SCOPE_MISMATCH"})}}function oi(){return{platform:"macos",id:"host-macos-local",name:c.hostname(),kind:"device",target:"desktop",booted:!0}}async function oo(){return[oi()]}let os=/^(iphone|ipad|ipod|appletv)/i,ol=/\b(iphone|ipad|ipod)\b/i,ou=/^appletv/i,od=["apple tv","appletv","tvos"],oc=/^==\s*(.+?)\s*==$/,op=/^(?<name>.+?)\s+\[(?<id>[^[\]]+)\]\s*$/;function of(e){return(e??"").trim().toLowerCase()}function om(e){return of(e.hardwareProperties?.platform)}function oh(e){return e.includes("tvos")}function ow(e){let t=of(e);return od.some(e=>t.includes(e))}function og(e){return[e.name??"",e.deviceProperties?.name??"",e.deviceProperties?.deviceType??""]}function oy(e){return e.hardwareProperties?.productType??e.deviceProperties?.productType??""}async function ov(e={}){let t,r,n=Z(e.simulatorSetPath),a=e.target;try{t=await rR(rL(["list","devices","-j"],{simulatorSetPath:n}))}catch{return null}try{r=JSON.parse(t.stdout)}catch{return null}let i=oI(r,n),o=null,s=null,l=null;for(let e of i)a&&e.target!==a||(e.booted&&(o=o??e),"mobile"===e.target&&(s=s??e),l=l??e);return o??s??l}function oI(e,t){let r=[];for(let[n,a]of Object.entries(e.devices))if(function(e){let t=of(e);return t.includes("ios")||t.includes("tvos")}(n))for(let e of a)e.isAvailable&&r.push({platform:"ios",id:e.udid,name:e.name,kind:"simulator",target:oh(of(n))?"tv":"mobile",booted:"Booted"===e.state,...t?{simulatorSetPath:t}:{}});return r}function ob(e,t){let r=new Set(e.map(e=>e.id)),n=[...e];for(let e of t)r.has(e.id)||(r.add(e.id),n.push(e));return n}async function oA(){let e=null;try{e=f.join(c.tmpdir(),`agent-device-devicectl-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);let t=await rR(["devicectl","list","devices","--json-output",e],{allowFailure:!0,timeoutMs:8e3});if(0!==t.exitCode)return[];let r=await d.readFile(e,"utf8");return function(e){let t=[];for(let r of e.result?.devices??[]){if(!function(e){var t;let r=om(e);return!!(r.includes("ios")||r.includes("tvos"))||(t=oy(e),!!os.test(t.trim())||og(e).some(ow))}(r))continue;let e=r.hardwareProperties?.udid??r.identifier??"",n=r.name??r.deviceProperties?.name??e;e&&t.push({platform:"ios",id:e,name:n,kind:"device",target:function(e){var t;return oh(om(e))?"tv":(t=oy(e),ou.test(t.trim())||og(e).some(ow))?"tv":"mobile"}(r),booted:!0})}return t}(JSON.parse(r))}catch{return[]}finally{e&&await d.rm(e,{force:!0}).catch(()=>{})}}async function oS(){try{let e=await rR(["xctrace","list","devices"],{allowFailure:!0});if(0!==e.exitCode)return[];return function(e){let t=[],r=null;for(let n of e.split(/\r?\n/)){let e=n.trim();if(!e)continue;let a=oc.exec(e);if(a){r=a[1]?.trim()??null;continue}if("Devices"!==r)continue;let i=op.exec(e),o=i?.groups?.id?.trim()??"",s=i?.groups?.name?.trim()??"";if(!o||!s)continue;let l=function(e){return ow(e)?"tv":ol.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 ox(e={}){if("darwin"!==process.platform)throw new D("UNSUPPORTED_PLATFORM","Apple tools are only available on macOS");if(!await rD().whichCommand("xcrun"))throw new D("TOOL_MISSING","xcrun not found in PATH");let t=Z(e.simulatorSetPath),r=await rR(rL(["list","devices","-j"],{simulatorSetPath:t})),n=[];try{let e=JSON.parse(r.stdout);n=oI(e,t)}catch(e){throw new D("COMMAND_FAILED","Failed to parse simctl devices JSON",void 0,e)}if(n.push(oi()),e.udid&&n.some(t=>"ios"===t.platform&&t.id===e.udid)||t)return n;let[a,i]=await Promise.all([oA(),oS()]);return n=ob(n,a),ob(n,i)}async function o_(){return"linux"!==process.platform?[]:[{platform:"linux",id:"local",name:p(),kind:"device",target:"desktop",booted:!0}]}let oN=new h,oM=new h;async function ok(e,t,r){var n,a;let i=await oD(e,t,r);if(n=t,a=i,!oP(n)&&(!n.platform||"apple"===n.platform||"ios"===n.platform)&&"desktop"!==n.target&&(!a||"device"===a.kind)){let e=await ov({simulatorSetPath:r.simulatorSetPath,target:t.target});if(e)return e}if(i)return i;throw new D("DEVICE_NOT_FOUND","No devices found",{selector:t})}async function oD(e,t,r){try{return await r7(e,t,r)}catch(e){var n;if(n=e,!oP(t)&&n instanceof D&&"DEVICE_NOT_FOUND"===n.code)return;throw e}}function oP(e){return!!(e.udid||e.serial||e.deviceName)}async function oO(e){let t=e.platform,r=r9({simulatorSetPath:Z(e.iosSimulatorDeviceSet),platform:t,target:e.target}),n=ec(e.androidDeviceAllowlist),a=function(e){let{flags:t,normalizedPlatform:r,iosSimulatorSetPath:n,androidSerialAllowlist:a}=e;return JSON.stringify({platform:r,target:t.target,device:t.device,udid:t.udid,serial:t.serial,iosSimulatorSetPath:n,androidSerialAllowlist:a?Array.from(a).sort():void 0})}({flags:e,normalizedPlatform:t,iosSimulatorSetPath:r,androidSerialAllowlist:n}),i={platform:t,target:e.target,cacheHit:!1};return await e_("resolve_target_device",async()=>{let o=function(e){let t=oN.getStore(),r=t?.get(e);if(r)return{...r}}(a);if(o)return i.cacheHit=!0,o;let s={platform:t,target:e.target,deviceName:e.device,udid:e.udid,serial:e.serial};if(s.target&&!s.platform)throw new D("INVALID_ARGS","Device target selector requires --platform. Use --platform ios|macos|android|linux|apple with --target mobile|tv|desktop.");let l=await oT({...s,iosSimulatorSetPath:r,androidSerialAllowlist:n?Array.from(n).sort():void 0});if(l)return oF(s)?oU(a,await ok(l,s,{simulatorSetPath:r})):oU(a,await r7(l,s,{simulatorSetPath:r}));"android"===s.platform&&await er();let u=await o$({...s,iosSimulatorSetPath:r,androidSerialAllowlist:n?Array.from(n).sort():void 0});return oF(s)?oU(a,await ok(u,s,{simulatorSetPath:r})):oU(a,await r7(u,s,{simulatorSetPath:r}))},i)}async function oR(e){return oN.getStore()?await e():await oN.run(new Map,e)}async function oE(e,t){return e?await oM.run(e,t):await t()}async function oC(e,t){return await oE(e,async()=>await oR(t))}async function oL(e){return await oT(e)??await o$(e)}async function oT(e){let t=oM.getStore();if(!t)return null;let r=await t(e);return null==r?null:r.map(e=>({...e}))}async function o$(e){if("macos"===e.platform||"apple"===e.platform&&"desktop"===e.target)return await oo();if("linux"===e.platform)return await o_();if("android"===e.platform)return await F({serialAllowlist:e.androidSerialAllowlist?new Set(e.androidSerialAllowlist):void 0});if(e.platform)return await ox({simulatorSetPath:e.iosSimulatorSetPath,udid:e.udid});let t=[];try{t.push(...await F({serialAllowlist:e.androidSerialAllowlist?new Set(e.androidSerialAllowlist):void 0}))}catch{}try{t.push(...await ox({simulatorSetPath:e.iosSimulatorSetPath,udid:e.udid}))}catch{}try{t.push(...await o_())}catch{}return t}function oF(e){return!!e.platform&&"android"!==e.platform&&"linux"!==e.platform}function oU(e,t){return oN.getStore()?.set(e,{...t}),t}let oV={runCommand:R,whichCommand:C,desktop:oH(R,C),clipboard:oW(R,C),screenshot:oz(R,C)},oG=rI(oV,function(e={}){let t={...oV,...e};return{...t,desktop:e.desktop??oH(t.runCommand,t.whichCommand),clipboard:e.clipboard??oW(t.runCommand,t.whichCommand),screenshot:e.screenshot??oz(t.runCommand,t.whichCommand)}});function oq(e){return oG.resolve(e)}async function oB(e,t){return await oG.run(e,t)}async function oj(e,t,r){return await oq().runCommand(e,t,r)}function oH(e,t){return{async openTarget(r){if(r.includes("://")||r.startsWith("/"))return void await e("xdg-open",[r]);if(await t(r)){e(r,[],{allowFailure:!0}).catch(e=>{eN({level:"warn",phase:"linux_app_launch",data:{app:r,error:String(e)}})}),await e8(500);return}await e("xdg-open",[r],{allowFailure:!0})},async closeApp(r){await t("wmctrl")?await e("wmctrl",["-c",r],{allowFailure:!0}):await e("pkill",["-x",r],{allowFailure:!0})}}}function oW(e,t){return{async readText(){let r=oX[await oQ(t,oK)];return(await e(r.cmd,r.args,r.options)).stdout},async writeText(r){let n=oY[await oQ(t,oK)](r);await e(n.cmd,n.args,n.options)}}}function oz(e,t){return{async capture(r){let n=oZ[await oQ(t,oJ)](r);await e(n.cmd,n.args,n.options)}}}let oK={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."},oJ={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."},oX={"wl-clipboard":{cmd:"wl-paste",args:["--no-newline"],options:{allowFailure:!0,timeoutMs:5e3}},xclip:{cmd:"xclip",args:["-selection","clipboard","-o"],options:{allowFailure:!0,timeoutMs:5e3}},xsel:{cmd:"xsel",args:["--clipboard","--output"],options:{allowFailure:!0,timeoutMs:5e3}}},oY={"wl-clipboard":e=>({cmd:"wl-copy",args:["--",e],options:{allowFailure:!1,timeoutMs:5e3}}),xclip:e=>({cmd:"xclip",args:["-selection","clipboard"],options:{allowFailure:!1,timeoutMs:5e3,stdin:e}}),xsel:e=>({cmd:"xsel",args:["--clipboard","--input"],options:{allowFailure:!1,timeoutMs:5e3,stdin:e}})},oZ={grim:e=>({cmd:"grim",args:[e]}),scrot:e=>({cmd:"scrot",args:[e]}),import:e=>({cmd:"import",args:["-window","root",e]}),"gnome-screenshot":e=>({cmd:"gnome-screenshot",args:["-f",e]})};async function oQ(e,t){let r=process.env.WAYLAND_DISPLAY||"wayland"===process.env.XDG_SESSION_TYPE?"wayland":"x11";for(let n of t[r])if(await e(n.command))return n.tool;throw new D("TOOL_MISSING","wayland"===r?t.waylandError:t.x11Error)}async function o0(e,t){let r=["devicectl",...e],n=await rR(r,{allowFailure:!0,timeoutMs:2e4});if(0===n.exitCode)return;let a=String(n.stdout??""),i=String(n.stderr??"");throw new D("COMMAND_FAILED",`Failed to ${t.action}`,{cmd:"xcrun",args:r,exitCode:n.exitCode,stdout:a,stderr:i,deviceId:t.deviceId,hint:o4(a,i)??o5})}async function o1(e,t){var r;return r=function(e){let t=e?.result?.apps;if(!Array.isArray(t))return[];let r=[];for(let e of t){if(!e||"object"!=typeof e)continue;let t="string"==typeof e.bundleIdentifier?e.bundleIdentifier.trim():"";if(!t)continue;let n="string"==typeof e.name&&e.name.trim().length>0?e.name.trim():t,a="string"==typeof e.url&&e.url.trim().length>0?e.url.trim():void 0;r.push({bundleId:t,name:n,url:a})}return r}(await o3(e,{jsonPrefix:"agent-device-ios-apps",args:["devicectl","device","info","apps","--device",e.id,"--include-all-apps"],failureMessage:"Failed to list iOS apps",parseFailureMessage:"Failed to parse iOS apps list"})),"user-installed"===t?r.filter(e=>!e.bundleId.startsWith("com.apple.")):r}async function o2(e){return function(e){let t=e?.result?.runningProcesses;if(!Array.isArray(t))return[];let r=[];for(let e of t){if(!e||"object"!=typeof e)continue;let t="string"==typeof e.executable?e.executable.trim():"",n="number"==typeof e.processIdentifier&&Number.isFinite(e.processIdentifier)?e.processIdentifier:NaN;t&&Number.isFinite(n)&&r.push({executable:t,pid:n})}return r}(await o3(e,{jsonPrefix:"agent-device-ios-processes",args:["devicectl","device","info","processes","--device",e.id],failureMessage:"Failed to list iOS processes",parseFailureMessage:"Failed to parse iOS process list"}))}async function o3(e,t){let r=f.join(c.tmpdir(),`${t.jsonPrefix}-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`),n=[...t.args,"--json-output",r],a=await rR(n,{allowFailure:!0,timeoutMs:2e4});try{if(0!==a.exitCode){let r=String(a.stdout??""),i=String(a.stderr??"");throw new D("COMMAND_FAILED",t.failureMessage,{cmd:"xcrun",args:n,exitCode:a.exitCode,stdout:r,stderr:i,deviceId:e.id,hint:o4(r,i)??o5})}return JSON.parse(await d.readFile(r,"utf8"))}catch(r){if(r instanceof D)throw r;throw new D("COMMAND_FAILED",t.parseFailureMessage,{deviceId:e.id,cause:String(r)})}finally{await d.unlink(r).catch(()=>{})}}let o5="Ensure the iOS device is unlocked, trusted, and available in Xcode > Devices, then retry.";function o4(e,t){let r=`${e}
12
+ ${t}`.toLowerCase();return r.includes("device is busy")&&r.includes("connecting")?"iOS device is still connecting. Keep it unlocked and connected by cable until it is fully available in Xcode Devices, then retry.":r.includes("coredeviceservice")&&r.includes("timed out")?"CoreDevice service timed out. Reconnect the device and retry; if it persists restart Xcode and the iOS device.":null}let o8=new Map;async function o6(e){var t;let r,n=(r="simulator"===(t=e).kind?t.simulatorSetPath??"":"",JSON.stringify([t.platform,t.kind,t.id,t.target??"",r])),a=o8.get(n);if(void 0!==a){if(a>Date.now())return;o8.delete(n)}if("ios"===e.platform){if("simulator"===e.kind){let{ensureBootedSimulator:t}=await Promise.resolve(ro);await t(e),o9(n);return}if("device"===e.kind){await o7(e.id),o9(n);return}}if("android"===e.platform){let{waitForAndroidBoot:t}=await import("../1769.js");await t(e.id),o9(n)}}function o9(e){o8.set(e,Date.now()+5e3)}async function o7(e){let t=f.join(c.tmpdir(),`agent-device-ready-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`),r=Math.max(1,Math.ceil(15));try{let n=await rR(["devicectl","device","info","details","--device",e,"--json-output",t,"--timeout",String(r)],{allowFailure:!0,timeoutMs:18e3}),a=String(n.stdout??""),i=String(n.stderr??""),o=await se(t);if(0===n.exitCode){if(!o.parsed)throw new D("COMMAND_FAILED","iOS device readiness probe failed",{kind:"probe_inconclusive",deviceId:e,stdout:a,stderr:i,hint:"CoreDevice returned success but readiness JSON output was missing or invalid. Retry; if it persists restart Xcode and the iOS device."});let t=o?.tunnelState?.toLowerCase();if("connecting"===t)throw new D("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 D("COMMAND_FAILED","iOS device is not ready for automation",{kind:"not_ready",deviceId:e,stdout:a,stderr:i,exitCode:n.exitCode,tunnelState:o?.tunnelState,hint:st(a,i)})}catch(t){if(t instanceof D&&"COMMAND_FAILED"===t.code){if("not_ready"===("string"==typeof t.details?.kind?t.details.kind:""))throw t;let r=t.details??{},n=String(r.stdout??""),a=String(r.stderr??""),i=Number(r.timeoutMs??15e3),o=`CoreDevice did not respond within ${i}ms. Keep the device unlocked and trusted, then retry; if it persists restart Xcode and the iOS device.`;throw new D("COMMAND_FAILED","iOS device readiness probe failed",{deviceId:e,cause:t.message,timeoutMs:i,stdout:n,stderr:a,hint:n||a?st(n,a):o},t)}throw new D("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 d.rm(t,{force:!0}).catch(()=>{})}}async function se(e){try{let t=await d.readFile(e,"utf8"),r=JSON.parse(t),n=function(e){let t=e?.result;if(!t||"object"!=typeof t)return{};let r=t.connectionProperties?.tunnelState,n=t.device?.connectionProperties?.tunnelState,a="string"==typeof r?r:"string"==typeof n?n:void 0;return a?{tunnelState:a}:{}}(r);return{parsed:!0,tunnelState:n.tunnelState}}catch{return{parsed:!1}}}function st(e,t){let r=o4(e,t);return r||(`${e}
13
+ ${t}`.toLowerCase().includes("timed out waiting for all destinations")?"Xcode destination did not become available in time. Keep device unlocked and retry.":o5)}function sr(e){let t=e.direction,r="up"===t||"down"===t?e.referenceHeight:e.referenceWidth,n=function(e){if(void 0===e)return .6;if(!Number.isFinite(e)||e<=0)throw new D("INVALID_ARGS","scroll amount must be a positive number");return e}(e.amount),a=void 0!==e.pixels?function(e){if(!Number.isFinite(e)||e<=0)throw new D("INVALID_ARGS","scroll pixels must be a positive integer");return Math.max(1,Math.round(e))}(e.pixels):Math.round(r*n),i=Math.max(1,Math.round(.05*r)),o=Math.max(1,Math.min(a,Math.max(1,r-2*i))),s=Math.round(o/2),l=Math.round(e.referenceWidth/2),u=Math.round(e.referenceHeight/2),d=(r,n,a,i)=>({direction:t,x1:r,y1:n,x2:a,y2:i,referenceWidth:e.referenceWidth,referenceHeight:e.referenceHeight,amount:e.amount,pixels:o});switch(t){case"up":return d(l,u-s,l,u+s);case"down":return d(l,u+s,l,u-s);case"left":return d(l-s,u,l+s,u);case"right":return d(l+s,u,l-s,u)}}function sn(e){var t;return!!e&&(!!e.password||!!(t=e.text)&&Array.from(t).every(si))}function sa(e){if(!e)return null;let t=sn(e);return{...e,text:t?null:e.text,...t?{textRedacted:!0}:{}}}function si(e){return"•"===e||"*"===e||"●"===e}function so(e){if(0===e.length)return null;let t=[...e].sort((e,t)=>e-t);return t[Math.floor(t.length/2)]??null}function ss(e,t){let r=Math.max(24,Math.round(.2*Math.min(e.size,t.size))),n=Math.max(48,Math.round(.15*Math.min(e.crossSize,t.crossSize)));return Math.abs(e.size-t.size)<=r&&Math.abs(e.crossSize-t.crossSize)<=n}function sl(e,t){return{start:e.y-t.y,size:e.height,crossSize:e.width}}let su=["device offline","device not found","transport error","connection reset","broken pipe","timed out","no such file or directory"];async function sd(e,t={}){let r=tn(e,t.helperAdb),n=await sc(e,t,r),a=n.xml,i=!1!==t.includeHiddenContentHints;if(!t.interactiveOnly){let o=to(a,800,t);return i&&function(e,t){for(let[r,n]of e){let e=t[r];e&&(n.hiddenContentAbove&&(e.hiddenContentAbove=!0),n.hiddenContentBelow&&(e.hiddenContentBelow=!0))}}(await sI(e,o.nodes,r),o.nodes),{...o,androidSnapshot:n.metadata}}let o=tl(a),s=tf(o,800,{...t,interactiveOnly:!1}),l=tf(o,800,t);if(i){let t=await sI(e,s.nodes,r);sN(t,s,l),0===t.size&&sN(tA(tW(s.nodes)),s,l)}let{sourceNodes:u,...d}=l;return{...d,androidSnapshot:n.metadata}}async function sc(e,t,r){let n=await e_("android_snapshot_helper_artifact_resolution",async()=>await sy(t.helperArtifact));return n.artifact?await sp(e,t,r,n.artifact):(eN({level:n.fallbackReason?"warn":"info",phase:"android_snapshot_helper_unavailable",data:{reason:n.fallbackReason??"artifact_not_found"}}),await sv(e,n.fallbackReason,r))}async function sp(e,t,r,n){var a,i,o,s;let l=(a=e,`${a.platform}:${a.id}`);try{let a=await sf(e,t,r,n,l);return i=await sm(t,r,n),o=n,s=a.reason,{xml:i.xml,metadata:{backend:"android-helper",helperVersion:o.manifest.version,helperApiVersion:i.metadata.helperApiVersion,installReason:s,waitForIdleTimeoutMs:i.metadata.waitForIdleTimeoutMs,waitForIdleQuietMs:i.metadata.waitForIdleQuietMs,timeoutMs:i.metadata.timeoutMs,maxDepth:i.metadata.maxDepth,maxNodes:i.metadata.maxNodes,rootPresent:i.metadata.rootPresent,captureMode:i.metadata.captureMode,windowCount:i.metadata.windowCount,nodeCount:i.metadata.nodeCount,helperTruncated:i.metadata.truncated,elapsedMs:i.metadata.elapsedMs}}}catch(t){return await sh({error:t,helperDeviceKey:l,artifact:n,device:e,adb:r})}}async function sf(e,t,r,n,a){let i=await e_("android_snapshot_helper_install",async()=>await ts({adb:r,adbProvider:tt(e,t.helperAdb),artifact:n,deviceKey:a,installPolicy:t.helperInstallPolicy,timeoutMs:3e4}),{packageName:n.manifest.packageName,versionCode:n.manifest.versionCode,installPolicy:t.helperInstallPolicy??"missing-or-outdated"});return eN({phase:"android_snapshot_helper_install_decision",data:{packageName:i.packageName,versionCode:i.versionCode,installedVersionCode:i.installedVersionCode,installed:i.installed,reason:i.reason}}),i}async function sm(e,t,r){return await e_("android_snapshot_helper_capture",async()=>await tu({adb:t,packageName:r.manifest.packageName,instrumentationRunner:r.manifest.instrumentationRunner,waitForIdleTimeoutMs:e.helperWaitForIdleTimeoutMs??500,timeoutMs:5e3,commandTimeoutMs:3e4}),{packageName:r.manifest.packageName,version:r.manifest.version,timeoutMs:5e3,commandTimeoutMs:3e4})}async function sh(e){let t=function(e){var t,r;let n=k(e);if(!function(e,t){if(!e||"object"!=typeof e)return!1;let r="errorType"in e?String(e.errorType):"",n=sg(e)??t;return/TimeoutException/.test(r)||/timed out/i.test(n)}(n.details?.helper,n.message)&&(t=n,!(t.details?.exitCode===137&&/Android snapshot helper (failed before returning parseable output|output could not be parsed)/.test(t.message)))&&(r=n.message,!/Android snapshot helper output could not be parsed/.test(r)))return;let a=sw(e);return new D(N(n.code),`${a}. Stock UIAutomator fallback was skipped because this usually means the Android accessibility tree is busy or stalled.`,{...n.details,hint:"Android accessibility snapshots can be blocked by busy or continuously changing app UI. Use screenshot as visual truth after this timeout and report the busy UI if it persists."},e)}(e.error);if(t)throw t;let r=sw(e.error);return eN({level:"warn",phase:"android_snapshot_helper_fallback",data:{reason:r}}),tp({deviceKey:e.helperDeviceKey,packageName:e.artifact.manifest.packageName,versionCode:e.artifact.manifest.versionCode}),await sv(e.device,r,e.adb)}function sw(e){let t=k(e),r=sg(t.details?.helper);if(r&&r!==t.message)return`${t.message}: ${r}`;if(r)return r;let n=("string"==typeof t.details?.stderr?t.details.stderr.trim():"").split(/\r?\n/).find(e=>e.trim());return n?`${t.message}: ${n}`:t.message}function sg(e){if(!e||"object"!=typeof e||!("message"in e))return;let t=String(e.message).trim();return t&&"null"!==t?t:void 0}async function sy(e){if(e)return{artifact:e};let t=eH(),r=f.join(eW(),"android-snapshot-helper","dist"),n=f.join(r,`agent-device-android-snapshot-helper-${t}.manifest.json`);try{await A.access(n)}catch{return{}}try{let e=td(JSON.parse(await A.readFile(n,"utf8"))),t=f.join(r,e.assetName??`agent-device-android-snapshot-helper-${e.version}.apk`);return await A.access(t),{artifact:{apkPath:t,manifest:e}}}catch(e){return{fallbackReason:k(e).message}}}async function sv(e,t,r){let n;try{n=await e_("android_snapshot_stock_capture",async()=>await sb(e,r),{fallbackReason:t,timeoutMs:8e3})}catch(e){if(t){var a,i;let r;throw a=e,i=t,new D(N((r=k(a)).code),`${r.message} Android snapshot helper failed before stock fallback: ${i}`,{...r.details,androidSnapshotHelperFallbackReason:i,...r.hint?{hint:r.hint}:{}},a)}throw e}return{xml:n,metadata:{backend:"uiautomator-dump",...t?{fallbackReason:t}:{}}}}async function sI(e,t,r){if(!t.some(e=>ti(e.type)))return new Map;let n=await s_(e,r);return n?function(e,t){let r=function(e){let t={className:"root",rect:{x:0,y:0,width:0,height:0},children:[]},r=[{indent:-1,node:t}],n=/^(\s*)([\w.$]+)\{[^}]* (-?\d+),(-?\d+)-(-?\d+),(-?\d+) #/;for(let t of e.split("\n")){let e=n.exec(t);if(!e)continue;let[a,i,o,s,l,u]=e.slice(1);if(void 0===a||void 0===i||void 0===o||void 0===s||void 0===l||void 0===u)continue;let d=a.length,c=Number(o),p=Number(s),f={className:i,rect:{x:c,y:p,width:Math.max(0,Number(l)-c),height:Math.max(0,Number(u)-p)},children:[]};for(;r.length>1&&d<=r[r.length-1].indent;)r.pop();r[r.length-1].node.children.push(f),r.push({indent:d,node:f})}return t.children.length>0?t:null}(t);if(!r)return new Map;let n=function(e){let t=[],r=[e];for(;r.length>0;){let e=r.pop();if(ti(e.className)){let r=function(e){let t=e.children[0];if(!t)return null;let r=Math.max(t.rect.height,...t.children.map(e=>e.rect.y+e.rect.height)),n=t.children.filter(e=>e.rect.height>0).map(t=>sl(t.rect,e.rect)).sort((e,t)=>e.start-t.start);return 0===n.length?null:{rect:e.rect,contentExtent:r,contentBlocks:n}}(e);r&&t.push(r)}r.push(...e.children)}return t}(r);if(0===n.length)return new Map;let a=new Map;for(let t of e){if(!t.rect||!ti(t.type))continue;let r=function(e,t){let r=null,n=1/0;for(let a of t){let t=Math.abs(a.rect.width-e.width)+Math.abs(a.rect.height-e.height);if(t>32)continue;let i=4*t+(Math.abs(a.rect.x-e.x)+Math.abs(a.rect.y-e.y));i<n&&(r=a,n=i)}return r}(t.rect,n);if(!r)continue;let i=function(e,t){let r=function(e,t){let r=t,n=new Set;for(;!n.has(r.index);){var a,i;n.add(r.index);let o=e.filter(e=>e.parentIndex===r.index&&e.rect);if(1!==o.length)return r;let s=o[0];if(a=s.rect,i=t.rect,a.x!==i.x||a.y!==i.y||a.width!==i.width||a.height!==i.height)return r;r=s}return t}(e,t);return e.filter(e=>e.parentIndex===r.index&&e.rect).map(e=>e.rect).filter(e=>e.height>0).sort((e,t)=>e.y-t.y).map(e=>sl(e,t.rect))}(e,t),o=function(e){let{viewportRect:t,visibleBlocks:r,nativeScrollView:n}=e;if(0===r.length||0===n.contentBlocks.length)return null;let a=function(e){if(0===e.contentBlocks.length)return null;let t=e.contentBlocks[0],r=e.contentBlocks[e.contentBlocks.length-1];if(!t||!r)return null;let n=so(e.contentBlocks.map(e=>e.size))??e.rect.height,a=Math.max(48,Math.round(.5*n)),i=Math.max(24,Math.round(.25*n)),o=t.start>=a,s=e.contentExtent-(r.start+r.size)>=i;return o||s?{above:o,below:s}:null}(n),i=function(e,t){let r=new Map;for(let n of e)for(let e of t){if(!ss(n,e))continue;let t=n.start-e.start,a=8*Math.round(t/8),i=r.get(a)??[];i.push(t),r.set(a,i)}let n=null;for(let e of r.values())(!n||e.length>n.length)&&(n=e);if(!n||n.length<2)return null;let a=[...n].sort((e,t)=>e-t);return a[Math.floor(a.length/2)]??null}(n.contentBlocks,r)??function(e){let{nativeBlocks:t,visibleBlocks:r,viewportExtent:n,contentExtent:a}=e,i=[],o=[];for(let e of t)for(let t of r){if(!ss(e,t))continue;let r=e.start-t.start;16>=Math.abs(r)&&i.push(r),16>=Math.abs(r+n-a)&&o.push(r)}return o.length>0?so(o):i.length>0?so(i):null}({nativeBlocks:n.contentBlocks,visibleBlocks:r,viewportExtent:t.height,contentExtent:n.contentExtent});if(null===i)return a;let o=t.height;return{above:(a?.above??!1)||i>16,below:(a?.below??!1)||i+o<n.contentExtent-16}}({viewportRect:t.rect,visibleBlocks:i,nativeScrollView:r});if(!o)continue;let s={};o.above&&(s.hiddenContentAbove=!0),o.below&&(s.hiddenContentBelow=!0),(s.hiddenContentAbove||s.hiddenContentBelow)&&a.set(t.index,s)}return a}(t,n):new Map}async function sb(e,t=tn(e)){try{return await $(()=>sA(t),{shouldRetry:sx})}catch(t){var r,n;let e;if((r=t)instanceof D&&"COMMAND_FAILED"===r.code&&"number"==typeof r.details?.timeoutMs&&r.details?.cmd==="adb"&&(e=Array.isArray(n=r.details?.args)?n.map(String):"string"==typeof n?n.split(/\s+/):[]).includes("uiautomator")&&e.includes("dump")){let e="Android accessibility snapshots can be blocked by busy or continuously changing app UI. Use screenshot as visual truth after this timeout. Stock Android UIAutomator may still time out on app-owned infinite animations.";throw new D("COMMAND_FAILED",`Android UI hierarchy dump timed out while waiting for the UI to become idle. ${e}`,{...t.details??{},hint:e},t)}throw t}}async function sA(e){var t,r;let n,a,i=await e(["exec-out","uiautomator","dump","/dev/tty"],{allowFailure:!0,timeoutMs:8e3}),o=sS(i.stdout,i.stderr);if(o)return o;let s="/sdcard/window_dump.xml",l=await e(["shell","uiautomator","dump",s],{allowFailure:!0,timeoutMs:8e3}),u=(t=l.stdout,r=l.stderr,n=`${t}
14
+ ${r}`,a=/dumped to:\s*(\S+)/i.exec(n),a?.[1]);if(0!==l.exitCode&&!u)throw new D("COMMAND_FAILED","uiautomator dump did not return XML",{stdout:l.stdout,stderr:l.stderr,exitCode:l.exitCode,reason:"missing_fresh_dump"});let d=await e(["shell","cat",u??s]),c=sS(d.stdout,d.stderr);if(!c)throw new D("COMMAND_FAILED","uiautomator dump did not return XML",{stdout:d.stdout,stderr:d.stderr});return c}function sS(e,t){let r=`${e}
15
+ ${t}`,n=r.indexOf("<?xml"),a=n>=0?n:r.indexOf("<hierarchy");if(a<0)return null;let i=r.lastIndexOf("</hierarchy>");if(i<0||i<a)return null;let o=r.slice(a,i+12).trim();return o.length>0?o:null}function sx(e){if(!(e instanceof D)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details?.stderr,r=("string"==typeof t?t:"").toLowerCase();return su.some(e=>r.includes(e))}async function s_(e,t=tn(e)){try{let e=await t(["shell","dumpsys","activity","top"],{allowFailure:!0,timeoutMs:8e3}),r=`${e.stdout}
16
+ ${e.stderr}`.trim();return r.length>0?r:null}catch{return null}}function sN(e,t,r){if(0===e.size)return;let n=new Map;for(let[e,t]of r.sourceNodes.entries()){let a=r.nodes[e];a&&n.set(t,a)}for(let[r,a]of e){let e=t.sourceNodes[r];if(!e)continue;let i=n.get(e);i&&(a.hiddenContentAbove&&(i.hiddenContentAbove=!0),a.hiddenContentBelow&&(i.hiddenContentBelow=!0))}}async function sM(e,t,r,n){let a=null,i=null,o=await sR(e);for(let s of[0,150,350]){s>0&&await e8(s);let l=await sD(e,t,r,n,o);if(a=l,"ime_capture"===l.reason)return l;i=l.ok?l:null}return i??a??{ok:!1,actual:null,reason:"text_mismatch",targetInput:null,actualInput:null}}async function sk(e,t,r){var n,a,i;return n=await sb(e),a=t,i=r,sP(n,a,i).actualInput?.text??null}async function sD(e,t,r,n,a){return function(e,t,r,n,a={}){var i,o;let s,l=sP(e,t,r,a);return!function(e){let{targetInput:t,actualInput:r}=e;return!!t&&!!r&&r!==t&&r.inputMethodOwned&&!t.inputMethodOwned}(l)?function(e,t){let r=e.actualInput;if(!r||!sn(r))return null;let n=r.text??null,a=Array.from(n??"").length,i=Array.from(t).length,o=null!==n&&a>0&&i>0&&a===i;return{ok:o,actual:n,reason:o?void 0:"masked_unverified",masked:!0,targetInput:e.targetInput,actualInput:r}}(l,n)??(i=l,o=n,{ok:function(e,t){if(e===t)return!0;let r=sO(e),n=sO(t);return!!r&&!!n&&!!(r===n||function(e,t){if(e.length!==t.length||0===e.length||e.slice(1)!==t.slice(1))return!1;let r=e[0],n=t[0];return!!r&&!!n&&n.toLowerCase()===n&&r===n.toUpperCase()}(r,n))}(s=i.actualInput?.text??null,o),actual:s,reason:"text_mismatch",targetInput:i.targetInput,actualInput:i.actualInput}):{ok:!1,actual:l.actualInput?.text??null,reason:"ime_capture",targetInput:l.targetInput,actualInput:l.actualInput}}(await sb(e),t,r,n,a)}function sP(e,t,r,n={}){var a;let i,o={focusedEdit:null,editAtPoint:null,anyAtPoint:null};for(let a of tc(e)){let e=function(e,t){if(!e.rect)return null;let r=e.text??"",n=Math.max(1,e.rect.width*e.rect.height);return{text:r||null,className:e.className,resourceId:e.resourceId,packageName:e.packageName,rect:e.rect,focused:e.focused??!1,password:!0===e.password,inputMethodOwned:eu({packageName:e.packageName,resourceId:e.resourceId,activeInputMethodPackage:t.activeInputMethodPackage}),area:n,editText:function(e){let t=e.toLowerCase();return t.includes("edittext")||t.includes("textfield")}(e.className??"")}}(a,n);e&&function(e,t,r,n){var a,i,o;let s=(a=t.rect,i=r,o=n,i>=a.x&&i<=a.x+a.width&&o>=a.y&&o<=a.y+a.height);if(s&&t.editText&&(e.editAtPoint=sE(e.editAtPoint,t)),t.focused&&t.editText){e.focusedEdit=sE(e.focusedEdit,t);return}s&&t.text&&(e.anyAtPoint=sE(e.anyAtPoint,t))}(o,e,t,r)}return{targetInput:i=(a=o).editAtPoint??a.anyAtPoint,actualInput:(a.focusedEdit?.text?a.focusedEdit:null)??i}}function sO(e){return(e??"").replace(/\s+/g," ").trim()}async function sR(e){try{return{activeInputMethodPackage:(await ea(e)).inputMethodPackage}}catch(e){return eN({level:"warn",phase:"android_fill_verification_input_method_probe_failed",data:{error:e instanceof Error?e.message:String(e)}}),{}}}function sE(e,t){return e&&e.area<t.area?e:t}async function sC(e,t,r){await Y(e,["shell","input","tap",String(t),String(r)])}async function sL(e,t,r,n,a,i=250){await Y(e,["shell","input","swipe",String(t),String(r),String(n),String(a),String(i)])}async function sT(e){await Y(e,["shell","input","keyevent","4"])}async function s$(e){await Y(e,["shell","input","keyevent","3"])}async function sF(e){await Y(e,["shell","input","keyevent","ENTER"])}async function sU(e,t){let r=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 D("INVALID_ARGS",`Unsupported Android rotation: ${e}`)}}(t);await Y(e,["shell","settings","put","system","accelerometer_rotation","0"]),await Y(e,["shell","settings","put","system","user_rotation",r])}async function sV(e){await Y(e,["shell","input","keyevent","187"])}async function sG(e,t,r,n=800){await Y(e,["shell","input","swipe",String(t),String(r),String(t),String(r),String(n)])}async function sq(e,t,r=0){let n=te(e);if(n){await n({action:"type",text:t,delayMs:r}),s0("type","provider-native",t);return}(sZ(t),await sz(e,"type"),r>0&&Array.from(t).length>1)?await sX(e,{action:"type",text:t,chunkSize:1,delayMs:r}):await sX(e,{action:"type",text:t,chunkSize:sJ,delayMs:0})}async function sB(e,t,r){await sC(e,t,r)}async function sj(e,t,r,n,a=0){let i=te(e);if(i){await i({action:"fill",target:{x:t,y:r},text:n,delayMs:a}),s0("fill","provider-native",n);let o=await sM(e,t,r,n);if(o.ok)return;sH(n,o)}sZ(n);let o=Array.from(n).length,s=null;for(let i of[{clearPadding:12,minClear:8,maxClear:48,chunkSize:a>0?1:sJ,inputDelayMs:a},{clearPadding:24,minClear:16,maxClear:96,chunkSize:a>0?1:4,inputDelayMs:a>0?a:15}]){var l,u;await sB(e,t,r),await sz(e,"fill");let a=(l=o+i.clearPadding,u=i.minClear,Math.max(u,Math.min(i.maxClear,l)));await s1(e,a),await sX(e,{action:"fill",text:n,chunkSize:i.chunkSize,delayMs:i.inputDelayMs});let d=await sM(e,t,r,n);if(s=d,d.ok)return;"ime_capture"===d.reason&&sH(n,d)}sH(n,s)}function sH(e,t){let r;throw new D("COMMAND_FAILED",t?.reason==="ime_capture"?"Android fill input was captured by the active keyboard instead of the app field":t?.reason==="masked_unverified"?"Android fill verification could not confirm masked text value":"Android fill verification failed",(r=function(e,t){var r;if(!t)return{expected:e,actual:null,failureReason:"text_mismatch",targetInput:null,actualInput:null};let n=!0===(r=t).masked||sn(r.targetInput)||sn(r.actualInput),a={failureReason:t.reason??"text_mismatch",targetInput:sa(t.targetInput),actualInput:sa(t.actualInput)};return n?{...a,expectedLength:Array.from(e).length,actual:null,masked:!0,actualLength:Array.from(t.actual??"").length}:{...a,expected:e,actual:t.actual}}(e,t),t?.reason==="ime_capture"&&(r.hint="The focused input belongs to the Android keyboard/IME, not the app field. Disable handwriting/stylus input or switch to a standard IME, then retry fill."),r))}async function sW(e,t,r){let n=await sK(e),a=sr({direction:t,amount:r?.amount,pixels:r?.pixels,referenceWidth:n.width,referenceHeight:n.height});return await Y(e,["shell","input","swipe",String(a.x1),String(a.y1),String(a.x2),String(a.y2),"300"]),a}async function sz(e,t){let r;try{r=await ea(e)}catch(e){eN({level:"warn",phase:"android_input_ownership_probe_failed",data:{action:t,error:e instanceof Error?e.message:String(e)}});return}if("ime"===r.inputOwner)throw new D("COMMAND_FAILED","KEYBOARD_OVERLAY_BLOCKING: Android text input is blocked because the focused input belongs to the active keyboard/IME.",{failureReason:"ime_capture",action:t,inputOwner:r.inputOwner,inputType:r.inputType,type:r.type,inputMethodPackage:r.inputMethodPackage,focusedPackage:r.focusedPackage,focusedResourceId:r.focusedResourceId,nextAction:"Focused input appears to be owned by the keyboard/IME; dismiss or change the IME before retrying text entry."})}async function sK(e){let t=(await Y(e,["shell","wm","size"])).stdout.match(/Physical size:\s*(\d+)x(\d+)/);if(!t)throw new D("COMMAND_FAILED","Unable to read screen size");return{width:Number(t[1]),height:Number(t[2])}}let sJ=8;async function sX(e,t){let r=t.text.split("\n");for(let[n,a]of r.entries()){let i=function(e,t){let r=Math.max(1,Math.floor(t)),n=[],a=Array.from(e);for(let e=0;e<a.length;e+=r)n.push(a.slice(e,e+r).join(""));return n.length>0?n:[""]}(a,t.chunkSize);for(let[a,o]of i.entries())await sY(e,o),t.delayMs>0&&(a+1<i.length||n+1<r.length)&&await e8(t.delayMs);n+1<r.length&&await Y(e,["shell","input","keyevent","ENTER"])}s0(t.action,"adb-shell",t.text)}async function sY(e,t){if(t)try{await Y(e,["shell","input","text",t.replace(/ /g,"%s")])}catch(e){if(function(e){if(!(e instanceof D)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details?.stderr,r=("string"==typeof t?t:"").toLowerCase();return!!(r.includes("exception occurred while executing 'text'")||r.includes("nullpointerexception")&&r.includes("inputshellcommand.sendtext"))}(e))throw sQ(t,e);throw e}}function sZ(e){if(!function(e){for(let t of e){let e=t.codePointAt(0);if(void 0!==e&&"\n"!==t&&(e<32||e>126))return!1}return!0}(e))throw sQ(e)}function sQ(e,t){return new D("COMMAND_FAILED","Android text input requires provider-native text injection for non-ASCII/control characters; the current adb-shell fallback supports ASCII text only.",{backend:"adb-shell",textLength:Array.from(e).length,textPreview:e.slice(0,32)},t instanceof Error?t:void 0)}function s0(e,t,r){eN({phase:"android_text_injection",data:{action:e,backend:t,textLength:Array.from(r).length}})}async function s1(e,t){let r=Math.max(0,t);await Y(e,["shell","input","keyevent","KEYCODE_MOVE_END"],{allowFailure:!0});for(let t=0;t<r;t+=24){let n=Math.min(24,r-t);await Y(e,["shell","input","keyevent",...Array(n).fill("KEYCODE_DEL")],{allowFailure:!0})}}async function s2(e,t,r){let n="string"==typeof r.action&&r.action.trim()?r.action.trim():`${t}.TEST_PUSH`,a=["shell","am","broadcast","-a",n,"-p",t],i="string"==typeof r.receiver?r.receiver.trim():"";i&&a.push("-n",i);let o=r.extras;if(void 0!==o&&("object"!=typeof o||null===o||Array.isArray(o)))throw new D("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,r){if("string"==typeof r)return e.push("--es",t,r);if("boolean"==typeof r)return e.push("--ez",t,r?"true":"false");if("number"==typeof r&&Number.isFinite(r))return Number.isInteger(r)?e.push("--ei",t,String(r)):e.push("--ef",t,String(r));throw new D("INVALID_ARGS",`Unsupported Android broadcast extra type for "${t}". Use string, boolean, or number.`)}(a,e,t),s+=1);return await Y(e,a),{action:n,extrasCount:s}}let s3="android-multitouch-helper-v1",s5="ANDROID_MULTITOUCH_HELPER_NO_FINAL_RESULT",s4="ANDROID_MULTITOUCH_HELPER_REPORTED_FAILURE";async function s8(e,t){if(!Number.isFinite(t.scale)||t.scale<=0)throw new D("INVALID_ARGS","gesture pinch requires scale > 0");let r=await s7(e,t.x,t.y);return await le(e,{kind:"pinch",x:r.x,y:r.y,scale:t.scale,durationMs:t.durationMs})}async function s6(e,t){if(!Number.isFinite(t.degrees))throw new D("INVALID_ARGS","gesture rotate requires finite degrees");if(void 0!==t.velocity&&(!Number.isFinite(t.velocity)||0===t.velocity))throw new D("INVALID_ARGS","gesture rotate velocity must be a non-zero number");let r=await s7(e,t.x,t.y),n=t.degrees;return await le(e,{kind:"rotate",x:r.x,y:r.y,degrees:n,durationMs:t.durationMs})}async function s9(e,t){if(!Number.isFinite(t.scale)||t.scale<=0)throw new D("INVALID_ARGS","gesture transform requires scale > 0");if(!Number.isFinite(t.degrees))throw new D("INVALID_ARGS","gesture transform requires finite degrees");if(![t.x,t.y,t.dx,t.dy].every(Number.isFinite))throw new D("INVALID_ARGS","gesture transform requires finite x y dx dy");return await le(e,{kind:"transform",x:t.x,y:t.y,dx:t.dx,dy:t.dy,scale:t.scale,degrees:t.degrees,durationMs:t.durationMs})}async function s7(e,t,r){if(void 0!==t&&void 0!==r)return{x:t,y:r};let n=await sK(e);return{x:Math.round(n.width/2),y:Math.round(n.height/2)}}async function le(e,t){let r=tr(e);if(r)return{backend:"provider-native-touch",...await r(t)??{}};let n=tn(e),a=await ln(),i=tt(e),o=await e_("android_multitouch_helper_install",async()=>{var t;return await la({adb:n,adbProvider:i,artifact:a,deviceKey:(t=e,`${t.platform}:${t.id}`)})},{packageName:a.manifest.packageName,versionCode:a.manifest.versionCode});eN({phase:"android_multitouch_helper_install_decision",data:o});let s=await e_("android_multitouch_helper_gesture",async()=>await lt({adb:n,request:function(e){var t;let r=Math.round(void 0!==(t=e).durationMs?t.durationMs:"pinch"===t.kind?300:Math.min(Math.max(300,16*Math.ceil(Math.abs(t.degrees)/3)),2400));switch(e.kind){case"pinch":return{kind:"pinch",x:Math.round(e.x),y:Math.round(e.y),scale:e.scale,radius:160,durationMs:r};case"rotate":return{kind:"rotate",x:Math.round(e.x),y:Math.round(e.y),degrees:e.degrees,radius:160,durationMs:r};case"transform":return{kind:"transform",x:Math.round(e.x),y:Math.round(e.y),dx:Math.round(e.dx),dy:Math.round(e.dy),scale:e.scale,degrees:e.degrees,durationMs:r}}}(t),packageName:a.manifest.packageName,instrumentationRunner:a.manifest.instrumentationRunner}),{packageName:a.manifest.packageName,version:a.manifest.version});return{backend:"android-multitouch-helper",helperVersion:a.manifest.version,installReason:o.reason,...s}}async function lt(e){let t,r=Buffer.from(JSON.stringify({protocol:s3,...e.request})).toString("base64"),n=await e.adb(["shell","am","instrument","-w","-e","payloadBase64",r,e.instrumentationRunner],{allowFailure:!0,timeoutMs:45e3});try{t=function(e){let t=(function(e){let t=[],r=null;for(let n of e.split(/\r?\n/))n.startsWith("INSTRUMENTATION_RESULT: ")?(r??={},function(e,t){let r=e.indexOf("=");r>=0&&(t[e.slice(0,r)]=e.slice(r+1))}(n.slice(24),r)):n.startsWith("INSTRUMENTATION_CODE: ")&&r&&(t.push(r),r=null);return r&&t.push(r),t})(e).find(e=>e.agentDeviceProtocol===s3);if(!t)throw new D(s5,"Android multi-touch helper did not return a final result");if("true"!==t.ok){var r;throw new D(s4,(r=t).message&&"null"!==r.message?r.message:r.errorType||"Android multi-touch helper returned an error",{errorType:t.errorType,helper:t})}return{kind:t.kind,helperApiVersion:t.helperApiVersion,injectedEvents:lr(t.injectedEvents),elapsedMs:lr(t.elapsedMs)}}(`${n.stdout}
17
+ ${n.stderr}`)}catch(e){if(e instanceof D){if(e.code===s4)throw new D("COMMAND_FAILED",e.message,e.details,e);if(e.code!==s5)throw e}throw new D("COMMAND_FAILED",0===n.exitCode?"Android multi-touch helper output could not be parsed":"Android multi-touch helper failed before returning parseable output",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode},e)}if(0!==n.exitCode)throw new D("COMMAND_FAILED","Android multi-touch helper failed",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode,helper:t});return t}function lr(e){if(void 0===e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}async function ln(){let e=eH(),t=f.join(eW(),"android-multitouch-helper","dist"),r=f.join(t,`agent-device-android-multitouch-helper-${e}.manifest.json`);try{let e=function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new D("INVALID_ARGS","Android multi-touch helper manifest must be an object.");return{name:ld(e.name,"name","android-multitouch-helper"),version:lu(e.version,"version"),assetName:lu(e.assetName,"assetName"),sha256:function(e){let t=lu(e,"sha256").trim().toLowerCase();if(64!==t.length||!/^[0-9a-f]+$/.test(t))throw new D("INVALID_ARGS","Android multi-touch helper manifest sha256 must be a 64-character hex string.");return t}(e.sha256),packageName:ld(e.packageName,"packageName","com.callstack.agentdevice.multitouchhelper"),versionCode:function(e,t){if(!Number.isInteger(e))throw new D("INVALID_ARGS",`Android multi-touch helper manifest ${t} must be an integer.`);return e}(e.versionCode,"versionCode"),instrumentationRunner:ld(e.instrumentationRunner,"instrumentationRunner","com.callstack.agentdevice.multitouchhelper/.MultiTouchInstrumentation"),statusProtocol:ld(e.statusProtocol,"statusProtocol",s3)}}(JSON.parse(await A.readFile(r,"utf8"))),n=f.join(t,e.assetName);return await A.access(n),{apkPath:n,manifest:e}}catch(e){throw new D("UNSUPPORTED_OPERATION","gesture pinch/rotate/transform on Android requires the bundled Android multi-touch helper artifact, but it was not found or could not be read",{manifestPath:r,error:k(e).message},e)}}async function la(e){let{adb:t,artifact:r}=e,n=r.manifest.packageName,a=r.manifest.versionCode,i=`${e.deviceKey}\0${n}\0${a}`;if(li.has(i))return{packageName:n,versionCode:a,installed:!1,reason:"current"};let o=await lo(t,n);if(void 0!==o&&o>=a)return li.add(i),{packageName:n,versionCode:a,installedVersionCode:o,installed:!1,reason:"current"};await ls(r);let s=await ta(r.apkPath,{provider:e.adbProvider,replace:!0,allowTestPackages:!0,allowFailure:!0,timeoutMs:3e4});if(0!==s.exitCode)throw new D("COMMAND_FAILED","Failed to install Android multi-touch helper",{packageName:n,versionCode:a,stdout:s.stdout,stderr:s.stderr,exitCode:s.exitCode});return li.add(i),{packageName:n,versionCode:a,installedVersionCode:o,installed:!0,reason:void 0===o?"missing":"outdated"}}let li=new Set;async function lo(e,t){let r=await e(["shell","cmd","package","list","packages","--show-versioncode",t],{allowFailure:!0,timeoutMs:5e3});if(0!==r.exitCode)return;let n=RegExp(`package:${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:\\s|$).*versionCode:(\\d+)`).exec(`${r.stdout}
18
+ ${r.stderr}`);return n?Number(n[1]):void 0}async function ls(e){let t=await ll(e.apkPath);if(t!==e.manifest.sha256)throw new D("COMMAND_FAILED","Android multi-touch helper APK checksum mismatch",{apkPath:e.apkPath,expectedSha256:e.manifest.sha256,actualSha256:t})}async function ll(e){let t=o.createHash("sha256");return t.update(await A.readFile(e)),t.digest("hex")}function lu(e,t){if("string"!=typeof e||0===e.length)throw new D("INVALID_ARGS",`Android multi-touch helper manifest ${t} is required.`);return e}function ld(e,t,r){if(e!==r)throw new D("INVALID_ARGS",`Android multi-touch helper manifest ${t} must be "${r}".`);return r}function lc(e){return e.map(e=>({args:e.args.join(" "),exitCode:e.exitCode,stderr:e.stderr.slice(0,400)}))}let lp=["camera","microphone","photos","contacts","contacts-limited","notifications","calendar","location","location-always","media-library","motion","reminders","siri"];function lf(e){let t=e.trim().toLowerCase();if("grant"===t)return"grant";if("deny"===t)return"deny";if("reset"===t)return"reset";throw new D("INVALID_ARGS",`Invalid permission action: ${e}. Use grant|deny|reset.`)}function lm(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 D("INVALID_ARGS",`permission setting requires a target: ${lp.join("|")}`)}function lh(e){let t=e.trim().toLowerCase();if("light"===t)return"light";if("dark"===t)return"dark";if("toggle"===t)return"toggle";throw new D("INVALID_ARGS",`Invalid appearance state: ${e}. Use light|dark|toggle.`)}function lw(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 D("INVALID_ARGS",`Invalid setting state: ${e}`)}let lg=["window_animation_scale","transition_animation_scale","animator_duration_scale"];async function ly(e,t,r,n,a){switch(t.toLowerCase()){case"wifi":{let t=lw(r);await Y(e,["shell","svc","wifi",t?"enable":"disable"]);return}case"airplane":{let t=lw(r);await Y(e,["shell","settings","put","global","airplane_mode_on",t?"1":"0"]),await Y(e,["shell","am","broadcast","-a","android.intent.action.AIRPLANE_MODE","--ez","state",t?"true":"false"]);return}case"location":{if("set"===r.toLowerCase()){if("emulator"!==e.kind)throw new D("UNSUPPORTED_OPERATION","Android precise location coordinates are supported only on emulators.",{deviceId:e.id,hint:"Use an Android emulator for adb emu geo fix, or configure location through device/provider tooling."});let{latitude:t,longitude:r}=ez(a);return await Y(e,["emu","geo","fix",String(r),String(t)]),{latitude:t,longitude:r}}let t=lw(r);await Y(e,["shell","settings","put","secure","location_mode",t?"3":"0"]);return}case"animations":{let t=lw(r)?"1":"0";for(let r of lg)await Y(e,["shell","settings","put","global",r,t]);return{scale:t,keys:[...lg]}}case"appearance":{let t=await lI(e,r);await Y(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 D("INVALID_ARGS",`Invalid fingerprint state: ${e}. Use match|nonmatch.`)}(r);await lv(e,t);return}case"permission":{if(!n)throw new D("INVALID_ARGS","permission setting requires an active app in session");let t=lf(r),i=function(e,t){let r=lm(e);if(t?.trim())throw new D("INVALID_ARGS",`Permission mode is only supported for photos. Received: ${t}.`);if("camera"===r)return{kind:"pm",value:"android.permission.CAMERA",type:"camera"};if("microphone"===r)return{kind:"pm",value:"android.permission.RECORD_AUDIO",type:"microphone"};if("photos"===r)return{kind:"pm",value:"android.permission.READ_MEDIA_IMAGES",type:"photos"};if("contacts"===r)return{kind:"pm",value:"android.permission.READ_CONTACTS",type:"contacts"};if("notifications"===r)return{kind:"notifications",appOps:"POST_NOTIFICATION",permission:"android.permission.POST_NOTIFICATIONS"};throw new D("INVALID_ARGS",`Unsupported permission target on Android: ${e}. Use camera|microphone|photos|contacts|notifications.`)}(a?.permissionTarget,a?.permissionMode);if("notifications"===i.kind)return void await lA(e,n,t,i);let o="grant"===t?"grant":"revoke";if("photos"===i.type)return void await lb(e,n,o);await Y(e,["shell","pm",o,n,i.value]);return}default:throw new D("INVALID_ARGS",`Unsupported setting: ${t}`)}}async function lv(e,t){var r;let n,a,i=(r=e,a=[["shell","cmd","fingerprint","touch",n="match"===t?"1":"9999"],["shell","cmd","fingerprint","finger",n]],"emulator"===r.kind&&a.push(["emu","finger","touch",n]),a),o=[];for(let t of i){let r=await Y(e,t,{allowFailure:!0});if(0===r.exitCode)return;o.push({args:t,stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode})}let s=lc(o);if(o.length>0&&o.every(e=>{var t,r;let n;return t=e.stdout,r=e.stderr,(n=`${t}
19
+ ${r}`.toLowerCase()).includes("unknown command")||n.includes("can't find service: fingerprint")||n.includes("service fingerprint was not found")||n.includes("fingerprint cmd unavailable")||n.includes("emu command is not supported")||n.includes("emulator console is not running")||n.includes("fingerprint")&&n.includes("not found")}))throw new D("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 D("COMMAND_FAILED","Failed to simulate Android fingerprint.",{deviceId:e.id,action:t,attempts:s})}async function lI(e,t){let r=lh(t);if("toggle"!==r)return r;let n=await Y(e,["shell","cmd","uimode","night"],{allowFailure:!0});if(0!==n.exitCode)throw new D("COMMAND_FAILED","Failed to read current Android appearance",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode});let a=function(e,t){let r=/night mode:\s*(yes|no|auto)\b/i.exec(`${e}
20
+ ${t}`);if(!r)return null;let n=r[1]?.toLowerCase();return"yes"===n?"dark":"no"===n?"light":"auto"===n?"auto":null}(n.stdout,n.stderr);if(!a)throw new D("COMMAND_FAILED","Unable to determine current Android appearance for toggle",{stdout:n.stdout,stderr:n.stderr});return"auto"===a?"dark":"dark"===a?"light":"dark"}async function lb(e,t,r){let n=await lS(e),a=[];for(let i of null!==n&&n>=33?["android.permission.READ_MEDIA_IMAGES","android.permission.READ_EXTERNAL_STORAGE"]:["android.permission.READ_EXTERNAL_STORAGE","android.permission.READ_MEDIA_IMAGES"]){let n=await Y(e,["shell","pm",r,t,i],{allowFailure:!0});if(0===n.exitCode)return;a.push({permission:i,stderr:n.stderr,exitCode:n.exitCode})}throw new D("COMMAND_FAILED",`Failed to ${r} Android photos permission`,{appPackage:t,sdkInt:n,attempts:a})}async function lA(e,t,r,n){"grant"===r?await Y(e,["shell","pm","grant",t,n.permission],{allowFailure:!0}):(await Y(e,["shell","pm","revoke",t,n.permission],{allowFailure:!0}),"reset"===r&&(await Y(e,["shell","pm","clear-permission-flags",t,n.permission,"user-set"],{allowFailure:!0}),await Y(e,["shell","pm","clear-permission-flags",t,n.permission,"user-fixed"],{allowFailure:!0}))),await Y(e,["shell","appops","set",t,n.appOps,"grant"===r?"allow":"deny"===r?"deny":"default"])}async function lS(e){let t=await Y(e,["shell","getprop","ro.build.version.sdk"],{allowFailure:!0});if(0!==t.exitCode)return null;let r=Number.parseInt(t.stdout.trim(),10);return!Number.isFinite(r)||r<=0?null:r}let lx=Buffer.from([137,80,78,71,13,10,26,10]);async function l_(e,t,r={}){if(!1===r.stabilize)return void await lk(e,t);await lN(e);try{await e8(1e3),await lk(e,t)}finally{await lM(e).catch(()=>{})}}async function lN(e){let t=t=>Y(e,["shell",t],{allowFailure:!0});await t("settings put global sysui_demo_allowed 1");let r=e=>t(`am broadcast -a com.android.systemui.demo -e command ${e}`);await r("clock -e hhmm 0941"),await r("notifications -e visible false")}async function lM(e){await Y(e,["shell","am broadcast -a com.android.systemui.demo -e command exit"],{allowFailure:!0})}async function lk(e,t){let r=await Y(e,["exec-out","screencap","-p"],{binaryStdout:!0});if(!r.stdoutBuffer)throw new D("COMMAND_FAILED","Failed to capture screenshot");let n=r.stdoutBuffer.indexOf(lx);if(n<0)throw new D("COMMAND_FAILED","Screenshot data does not contain a valid PNG header");let a=function(e,t){let r=t+lx.length;for(;r+8<=e.length;){let t=e.readUInt32BE(r),n=r+4,a=e.toString("ascii",n,n+4),i=r+12+t;if(i>e.length)break;if("IEND"===a)return i;r=i}return null}(r.stdoutBuffer,n);if(!a)throw new D("COMMAND_FAILED","Screenshot data does not contain a complete PNG payload");await d.writeFile(t,r.stdoutBuffer.subarray(n,a))}let lD="--launch-console is supported only for iOS simulator app launches",lP="--launch-console requires a direct app launch and cannot be used with URL opens";function lO(e){if(!(e instanceof D)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{};if(4!==t.exitCode)return!1;let r=String(t.stderr??"").toLowerCase();return r.includes("fbsopenapplicationserviceerrordomain")&&r.includes("the request to open")}async function lR(e,t){let r=await rR(rT(e,["get_app_container",e.id,t]),{allowFailure:!0});if(0!==r.exitCode)return{installed:!1};let n=r.stdout.trim();if(!n)return{installed:!1};let a=await rO("plutil",["-extract","CFBundleExecutable","raw","-o","-",`${n}/Info.plist`],{allowFailure:!0});if(0!==a.exitCode||!a.stdout.trim())return{installed:!0};let i=a.stdout.trim(),o=`${n}/${i}`,s=await rO("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 lE(e,t){if("simulator"!==e.kind)throw new D("UNSUPPORTED_OPERATION",`${t} is only supported on iOS simulators`)}async function lC(){await rO("open",["-a","Simulator"],{allowFailure:!0,timeoutMs:1e4})}async function lL(e){let t,r;if("simulator"!==e.kind||"Booted"===await l$(e))return;let n=et.fromTimeoutMs(18e4);try{await es(async({deadline:n})=>{if(n?.isExpired())throw new D("COMMAND_FAILED","iOS simulator boot deadline exceeded",{timeoutMs:18e4});let a=Math.max(1e3,n?.remainingMs()??18e4),i=await rR(rT(e,["boot",e.id]),{allowFailure:!0,timeoutMs:a});t={stdout:String(i.stdout??""),stderr:String(i.stderr??""),exitCode:i.exitCode};let o=`${t.stdout}
21
+ ${t.stderr}`.toLowerCase(),s=o.includes("already booted")||o.includes("current state: booted");if(0!==t.exitCode&&!s)throw new D("COMMAND_FAILED","simctl boot failed",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode});let l=await rR(rT(e,["bootstatus",e.id,"-b"]),{allowFailure:!0,timeoutMs:a});if(r={stdout:String(l.stdout??""),stderr:String(l.stderr??""),exitCode:l.exitCode},0!==r.exitCode)throw new D("COMMAND_FAILED","simctl bootstatus failed",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode});let u=await l$(e);if("Booted"!==u)throw new D("COMMAND_FAILED","Simulator is still booting",{state:u})},{maxAttempts:3,baseDelayMs:500,maxDelayMs:2e3,jitter:.2,shouldRetry:e=>{let n=U({error:e,stdout:r?.stdout??t?.stdout,stderr:r?.stderr??t?.stderr,context:{platform:"ios",phase:"boot"}});return"IOS_BOOT_TIMEOUT"!==n&&"CI_RESOURCE_STARVATION_SUSPECTED"!==n}},{deadline:n,phase:"boot",classifyReason:e=>U({error:e,stdout:r?.stdout??t?.stdout,stderr:r?.stderr??t?.stderr,context:{platform:"ios",phase:"boot"}})})}catch(i){let a=U({error:i,stdout:r?.stdout??t?.stdout,stderr:r?.stderr??t?.stderr,context:{platform:"ios",phase:"boot"}});throw new D("COMMAND_FAILED","iOS simulator failed to boot",{platform:"ios",deviceId:e.id,timeoutMs:18e4,elapsedMs:n.elapsedMs(),reason:a,hint:en(a),boot:t,bootstatus:r})}await lC()}async function lT(e){let t=rT(e,["shutdown",e.id]),r=await rR(t,{allowFailure:!0,timeoutMs:15e3});return{success:0===r.exitCode,exitCode:r.exitCode,stdout:String(r.stdout??""),stderr:String(r.stderr??"")}}async function l$(e){let t="string"==typeof e?e:e.id,r="string"==typeof e?rL(["list","devices","-j"]):rT(e,["list","devices","-j"]),n=await rR(r,{allowFailure:!0,timeoutMs:6e4});if(0!==n.exitCode)return null;try{let e=JSON.parse(String(n.stdout??""));for(let r of Object.values(e.devices??{})){let e=r.find(e=>e.udid===t);if(e)return e.state}return null}catch{return null}}async function lF(e,t){try{let r=await rE(e),n=r?.[t];if("string"==typeof n&&n.length>0)return n}catch{}try{let r=await rO("plutil",["-extract",t,"raw","-o","-",e],{allowFailure:!0});if(0===r.exitCode){let e=String(r.stdout??"").trim();if(e.length>0)return e}}catch{}try{var r,n;let a;return r=await d.readFile(e,"utf8"),n=t,ns(no(r),(e,t)=>{void 0===a&&e===n&&"string"===t.name&&(a=t.text??void 0)}),a}catch{return}}async function lU(e,t){let r;if("url"===e.kind&&!tK(e.url))throw new D("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 tz({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||tK(e.url),signal:t?.signal});try{let e=r=await lG(n.installablePath,t),a=await lV(e.installPath);return{archivePath:n.archivePath??(n.installablePath.toLowerCase().endsWith(".ipa")?n.installablePath:void 0),installablePath:e.installPath,bundleId:a.bundleId,appName:a.appName,cleanup:async()=>{await e.cleanup(),await n.cleanup()}}}catch(e){try{await r?.cleanup()}finally{await n.cleanup()}throw e}}async function lV(e){let t=f.join(e,"Info.plist"),[r,n,a]=await Promise.all([lF(t,"CFBundleIdentifier"),lF(t,"CFBundleDisplayName"),lF(t,"CFBundleName")]);return{bundleId:r,appName:n??a}}async function lG(e,t){if(!e.toLowerCase().endsWith(".ipa"))return{installPath:e,cleanup:async()=>{}};let r=await d.mkdtemp(f.join(c.tmpdir(),"agent-device-ios-ipa-")),n=async()=>{await d.rm(r,{recursive:!0,force:!0})};try{await R("unzip",["-q",e,"-d",r]);let a=f.join(r,"Payload"),i=(await d.readdir(a,{withFileTypes:!0}).catch(()=>{throw new D("INVALID_ARGS","Invalid IPA: missing Payload directory")})).filter(e=>e.isDirectory()&&e.name.toLowerCase().endsWith(".app")).map(e=>({installPath:f.join(a,e.name),bundleName:e.name.replace(/\.app$/i,"")})),o=i[0];if(void 0!==o&&1===i.length)return{installPath:o.installPath,cleanup:n};if(0===i.length)throw new D("INVALID_ARGS","Invalid IPA: expected at least one .app under Payload, found 0");await lq(i);let s=t?.appIdentifierHint?.trim();if(s){let e=function(e,t){let r=t.toLowerCase(),n=e.filter(e=>e.bundleName.toLowerCase()===r);if(1===n.length)return n[0];if(n.length>1)throw new D("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()===r);if(1===t.length)return t[0]}}(i,s);if(e)return{installPath:e.installPath,cleanup:n};throw new D("INVALID_ARGS",`Invalid IPA: found ${i.length} .app bundles under Payload and none matched "${s}". Available bundles: ${i.map(lB).join(", ")}`)}throw new D("INVALID_ARGS",`Invalid IPA: found ${i.length} .app bundles under Payload. Pass an app identifier or bundle name matching one of: ${i.map(lB).join(", ")}`)}catch(e){throw await n(),e}}async function lq(e){await Promise.all(e.map(async e=>{if(e.bundleId&&e.appName)return;let t=await lV(e.installPath);e.bundleId=e.bundleId??t.bundleId,e.appName=e.appName??t.appName}))}function lB(e){let t=e.bundleId??e.appName;return t?`${e.bundleName}.app (${t})`:`${e.bundleName}.app`}let lj="agent-device-macos-helper",lH="AGENT_DEVICE_MACOS_HELPER_BIN",lW=f.join(c.homedir(),".agent-device","macos-helper","current"),lz=f.join(lW,"manifest.json"),lK=/^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+$/;function lJ(e){let t=e.trim();if(!lK.test(t))throw new D("INVALID_ARGS","macOS bundle id must use reverse-DNS form like com.example.App",{bundleId:e});return t}function lX(e,t){t.bundleId&&e.push("--bundle-id",lJ(t.bundleId)),t.surface&&e.push("--surface",t.surface)}function lY(){return function(e){let t=f.dirname(e);for(;;){let e=f.join(t,"macos-helper");if(u(f.join(e,"Package.swift")))return e;let r=f.dirname(t);if(r===t)break;t=r}throw new D("COMMAND_FAILED","Unable to locate macOS helper package root",{modulePath:e})}(g(import.meta.url))}async function lZ(e){let t=await d.readdir(e,{withFileTypes:!0});return(await Promise.all(t.map(async t=>{let r=f.join(e,t.name);return t.isDirectory()?".build"===t.name?[]:await lZ(r):t.isFile()&&(t.name.endsWith(".swift")||"Package.swift"===t.name)?[r]:[]}))).flat().sort()}async function lQ(e){let t=await lZ(e),r=s("sha256");for(let n of t)r.update(f.relative(e,n)),r.update("\0"),r.update(await d.readFile(n)),r.update("\0");let n=await rO("swift",["--version"],{allowFailure:!0,cwd:e,timeoutMs:1e4});return r.update("swift-version"),r.update("\0"),r.update(n.stdout||n.stderr||`exit:${n.exitCode}`),r.update("\0"),r.digest("hex")}async function l0(){try{let e=JSON.parse(await d.readFile(lz,"utf8"));return"string"==typeof e.fingerprint?e.fingerprint:null}catch{return null}}async function l1(){let e=await L(process.env[lH],lH);if(e)return e;let t=lY(),r=await lQ(t),n=f.join(lW,lj);try{if(await l0()===r)return await d.access(n),n}catch{}let a=f.join(lY(),".build","release",lj);process.stderr.write("agent-device: building macOS helper (first run or helper update)\n"),await rO("swift",["build","-c","release","--package-path",t],{cwd:t,timeoutMs:12e4}),await d.mkdir(lW,{recursive:!0});let i=`${n}.tmp`;return await d.copyFile(a,i),await d.rename(i,n),await d.chmod(n,493),await d.writeFile(lz,`${JSON.stringify({fingerprint:r},null,2)}
22
+ `,"utf8"),n}async function l2(){let e=process.env[lH]?.trim();if(e){let t=await L(e,lH);if(t)return t}if(rM.hasScope())return lj;if("darwin"!==process.platform)throw new D("UNSUPPORTED_PLATFORM","macOS helper is only available on macOS");return await l1()}async function l3(e){let t={allowFailure:!0,timeoutMs:3e4},r=rD().macosHelper,n=r?lj:await l2(),a=r?await r.run(e,t):await rO(n,e,t),i=a.stdout.trim(),o=null;if(i)try{o=JSON.parse(i)}catch{o=null}if(0===a.exitCode&&o?.ok)return o.data;throw new D("COMMAND_FAILED",o&&!o.ok?o.error?.message??`macOS helper exited with code ${a.exitCode}`:i||a.stderr.trim()||`macOS helper exited with code ${a.exitCode}`,{helperPath:n,args:e,stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode,...o&&!o.ok?o.error?.details:{}})}async function l5(){return await l3(["app","frontmost"])}async function l4(e){return await l3(["app","quit","--bundle-id",lJ(e)])}async function l8(e,t){return await l3(["permission",e,t])}async function l6(e,t={}){let r=["alert",e];return lX(r,t),await l3(r)}async function l9(e,t={}){let r=["snapshot","--surface",e];return lX(r,t),await l3(r)}async function l7(e,t,r={}){let n=["read","--x",String(e),"--y",String(t)];return lX(n,r),await l3(n)}async function ue(e,t,r={}){let n=["press","--x",String(e),"--y",String(t)];return lX(n,r),await l3(n)}async function ut(e,t={}){let r=["screenshot","--out",e];return lX(r,t),t.fullscreen&&r.push("--fullscreen"),await l3(r)}let ur={settings:"com.apple.systempreferences"},un=/^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/,ua={platform:"macos",deviceId:"host",variant:"all"},ui=ep();async function uo(e){let t=e.trim(),r=ur[t.toLowerCase()];if(r)return r;if(un.test(t))return t;let n=ui.get(ua,t);if(n)return n;let a=(await uf("all")).filter(e=>e.name.toLowerCase()===t.toLowerCase()),i=a[0];if(void 0!==i&&1===a.length)return ui.set(ua,t,i.bundleId);if(a.length>1)throw new D("INVALID_ARGS",`Multiple apps matched "${e}"`,{matches:a});throw new D("APP_NOT_INSTALLED",`No app found matching "${e}"`)}async function us(e,t,r){let n=r?.url?.trim();if(n){if(!ef(n))throw new D("INVALID_ARGS","open <app> <url> requires a valid URL target");let e=r?.appBundleId??await uo(t);await um().openBundle(e,n);return}let a=t.trim();if(ef(a))return void await um().openTarget(a);let i=r?.appBundleId??await uo(a);await um().openBundle(i)}async function ul(e,t){let r=await uo(t),n=await l4(r);if(n.running&&!n.terminated&&!n.forceTerminated)throw new D("COMMAND_FAILED",`Failed to close macOS app ${t}`,{bundleId:r,running:n.running,terminated:n.terminated,forceTerminated:n.forceTerminated})}async function uu(){return await um().readClipboard()}async function ud(e){await um().writeClipboard(e)}async function uc(){return await um().readDarkMode()}async function up(e){let t=lh(e),r="toggle"===t?!await uc():"dark"===t;await um().setDarkMode(r)}async function uf(e){return await um().listApps(e)}function um(){let e=rD().macosHost;if(!e)throw new D("UNSUPPORTED_OPERATION","macOS host provider is not available");return e}function uh(e){if(!(e instanceof D))return{reason:e instanceof Error?e.message:String(e)};let t=e.details??{},r=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:r}}let uw=["--time","9:41","--dataNetwork","wifi","--wifiMode","active","--wifiBars","3","--batteryState","charged","--batteryLevel","100"],ug={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"},uy={1:"searching",2:"failed",3:"active"},uv={0:"notSupported",1:"searching",2:"failed",3:"active"};function uI(e,t,r){return rR(rT(e,t),r)}async function ub(e,t){var r,n;let a;await uS(e),t&&await ux(e,(a=[],(r=t).dataNetwork&&a.push("--dataNetwork",r.dataNetwork),r.wifiMode&&a.push("--wifiMode",r.wifiMode),void 0!==r.wifiBars&&("wifi"===r.dataNetwork||r.wifiMode)&&a.push("--wifiBars",r.wifiBars),r.cellularMode&&a.push("--cellularMode",r.cellularMode),void 0!==r.cellularBars&&(r.cellularMode||(n=r.dataNetwork)&&"hide"!==n&&"wifi"!==n||void 0!==r.operatorName)&&a.push("--cellularBars",r.cellularBars),void 0!==r.operatorName&&a.push("--operatorName",r.operatorName),a))}async function uA(e){let t=await uI(e,["status_bar",e.id,"list"],{allowFailure:!0});if(0!==t.exitCode)throw new D("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 r 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(r);if(e){let r=Number(e[1]),n=ug[r];if(!n)throw new D("COMMAND_FAILED",`Unsupported simulator data network type: ${r}`);t.dataNetwork=n;continue}let n=/^WiFi Mode:\s+(\d+),\s+WiFi Bars:\s+(\d+)$/.exec(r);if(n){let e=uy[Number(n[1])];e&&(t.wifiMode=e),t.wifiBars=n[2];continue}let a=/^Cell Mode:\s+(\d+),\s+Cell Bars:\s+(\d+)$/.exec(r);if(a){let e=Number(a[1]),r=uv[e];if(!r)throw new D("COMMAND_FAILED",`Unsupported simulator cellular mode: ${e}`);t.cellularMode=r,t.cellularBars=a[2];continue}let i=/^Operator Name:\s*(.*)$/.exec(r);if(i){t.operatorName=i[1]??"";continue}}return 0===Object.keys(t).length?null:t}(t.stdout)}async function uS(e){await uI(e,["status_bar",e.id,"clear"])}async function ux(e,t){0!==t.length&&await uI(e,["status_bar",e.id,"override",...t])}function u_(e,t,r){eN({level:"warn",phase:`ios_screenshot_status_bar_${t}`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,...uh(r)}})}function uN(e,t,r){return rR(rT(e,t),r)}let uM={ensureBooted:lL,prepareStatusBarForScreenshot:async function e(e){let t=null,r=!1;try{t=await uA(e),r=!0}catch(t){u_(e,"snapshot_failed",t)}try{await uS(e),await ux(e,uw)}catch(t){u_(e,"prepare_failed",t)}return async()=>{await ub(e,r?t:null)}},captureWithRetry:uP,captureWithRunner:uO,shouldFallbackToRunner:u$};async function uk(e,t,r,n,a){if("macos"===e.platform)return void await uO(e,t,r,n,a);if("simulator"===e.kind)return void await uD(e,t,r,n,void 0,a);try{await o0(["device","screenshot","--device",e.id,t],{action:"capture iOS screenshot",deviceId:e.id});return}catch(t){if(!function(e){if(!(e instanceof D)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{},r="string"==typeof t.stdout?t.stdout:"",n="string"==typeof t.stderr?t.stderr:"",a=`${e.message}
23
23
  ${r}
24
- ${n}`.toLowerCase();return a.includes("unknown option '--device'")||a.includes("unknown subcommand")&&a.includes("screenshot")||a.includes("unrecognized subcommand")&&a.includes("screenshot")}(t))throw t;uA(e,"devicectl_screenshot",t)}await uy(e,t,r,n,a)}async function uw(e,t,r,n,a=um,i){if("simulator"!==e.kind)throw new O("UNSUPPORTED_OPERATION","Simulator screenshot fallback flow supports only iOS simulators");let o="object"==typeof n&&null!==n?n:a;await o.ensureBooted(e);let s=async()=>{};try{s=await o.prepareStatusBarForScreenshot(e)}catch(t){uS(e,"prepare_failed",t)}try{try{await o.captureWithRetry(e,t);return}catch(t){if(!o.shouldFallbackToRunner(t))throw t;uA(e,"simctl_screenshot",t)}await o.captureWithRunner(e,t,r,"boolean"==typeof n?n:void 0,i)}finally{await s().catch(t=>uS(e,"restore_failed",t))}}async function ug(e,t){let r=en.fromTimeoutMs(2e4);await el(async({deadline:r})=>{await uf(e,["io",e.id,"screenshot",t],{timeoutMs:Math.max(1e3,r?.remainingMs()??2e4)})},{maxAttempts:5,baseDelayMs:1e3,maxDelayMs:5e3,jitter:.2,shouldRetry:e=>u_(e)},{deadline:r,phase:"ios_simulator_screenshot"})}async function uy(e,t,r,n,a){let i=(await ao(e,{command:"screenshot",appBundleId:r,fullscreen:n},a)).message;if(!i)throw new O("COMMAND_FAILED","Failed to capture iOS screenshot: runner returned no file path");"macos"===e.platform?await d.copyFile(i,t):"simulator"===e.kind?await uI(e,i,t):await uv(e,i,t)}async function uv(e,t,r){let n=en.fromTimeoutMs(2e4),a={exitCode:1,stdout:"",stderr:""};for(let i of ng)if(0===(a=await rM(["devicectl","device","copy","from","--device",e.id,"--source",t,"--destination",r,"--domain-type","appDataContainer","--domain-identifier",i],{allowFailure:!0,timeoutMs:ub(n,2e4,"runner screenshot copy")})).exitCode)return;let i=a.stderr.trim()||a.stdout.trim()||`devicectl exited with code ${a.exitCode}`;throw new O("COMMAND_FAILED",`Failed to capture iOS screenshot: ${i}`)}async function uI(e,t,r){let n=en.fromTimeoutMs(2e4),a="Unable to locate runner container for simulator screenshot";for(let i of ng){let o=await uf(e,["get_app_container",e.id,i,"data"],{allowFailure:!0,timeoutMs:ub(n,2e4,"runner screenshot container lookup")});if(0!==o.exitCode){let e=o.stderr.trim();e&&(a=e);continue}let s=o.stdout.trim();if(!s){a="simctl get_app_container returned empty output";continue}for(let e of function(e,t){let r=f.resolve(e),n=t.trim();if(!n)return[];let a=[],i=new Set,o=e=>{let t=f.normalize(e);i.has(t)||(i.add(t),a.push(t))},s=n.replace(/^\/+/,""),l=s.replace(/\\/g,"/");if(s&&o(f.join(r,s)),f.isAbsolute(n)&&o(f.normalize(n)),l.startsWith("tmp/"))o(f.join(r,l));else{let e=l.lastIndexOf("/tmp/");if(e>=0){let t=l.slice(e+1);o(f.join(r,t))}}let u=f.basename(n);return u&&o(f.join(r,"tmp",u)),a}(s,t))try{await d.copyFile(e,r);return}catch(e){a=e instanceof Error?e.message:String(e)}}throw new O("COMMAND_FAILED",`Failed to capture iOS screenshot: ${a}`)}function ub(e,t,r){let n=e.remainingMs();if(n>0)return n;throw new O("COMMAND_FAILED",`iOS ${r} timed out after ${t}ms`,{timeoutMs:t,step:r})}function uA(e,t,r){let n=ur(r);eM({level:"warn",phase:"ios_screenshot_fallback",data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,from:t,to:"runner",...n}})}function uS(e,t,r){eM({level:"warn",phase:`ios_screenshot_status_bar_${t}`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,...ur(r)}})}function u_(e){if(!(e instanceof O)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{},r="string"==typeof t.stdout?t.stdout:"",n="string"==typeof t.stderr?t.stderr:"",a=Array.isArray(t.args)?t.args.filter(e=>"string"==typeof e).join(" "):"",i=`${e.message}
24
+ ${n}`.toLowerCase();return a.includes("unknown option '--device'")||a.includes("unknown subcommand")&&a.includes("screenshot")||a.includes("unrecognized subcommand")&&a.includes("screenshot")}(t))throw t;uL(e,"devicectl_screenshot",t)}await uO(e,t,r,n,a)}async function uD(e,t,r,n,a=uM,i){if("simulator"!==e.kind)throw new D("UNSUPPORTED_OPERATION","Simulator screenshot fallback flow supports only iOS simulators");let o="object"==typeof n&&null!==n?n:a;await o.ensureBooted(e);let s=async()=>{};try{s=await o.prepareStatusBarForScreenshot(e)}catch(t){uT(e,"prepare_failed",t)}try{try{await o.captureWithRetry(e,t);return}catch(t){if(!o.shouldFallbackToRunner(t))throw t;uL(e,"simctl_screenshot",t)}await o.captureWithRunner(e,t,r,"boolean"==typeof n?n:void 0,i)}finally{await s().catch(t=>uT(e,"restore_failed",t))}}async function uP(e,t){let r=et.fromTimeoutMs(2e4);await es(async({deadline:r})=>{await uN(e,["io",e.id,"screenshot",t],{timeoutMs:Math.max(1e3,r?.remainingMs()??2e4)})},{maxAttempts:5,baseDelayMs:1e3,maxDelayMs:5e3,jitter:.2,shouldRetry:e=>u$(e)},{deadline:r,phase:"ios_simulator_screenshot"})}async function uO(e,t,r,n,a){let i=(await am(e,{command:"screenshot",appBundleId:r,fullscreen:n},a)).message;if(!i)throw new D("COMMAND_FAILED","Failed to capture iOS screenshot: runner returned no file path");"macos"===e.platform?await d.copyFile(i,t):"simulator"===e.kind?await uE(e,i,t):await uR(e,i,t)}async function uR(e,t,r){let n=et.fromTimeoutMs(2e4),a={exitCode:1,stdout:"",stderr:""};for(let i of n_)if(0===(a=await rR(["devicectl","device","copy","from","--device",e.id,"--source",t,"--destination",r,"--domain-type","appDataContainer","--domain-identifier",i],{allowFailure:!0,timeoutMs:uC(n,2e4,"runner screenshot copy")})).exitCode)return;let i=a.stderr.trim()||a.stdout.trim()||`devicectl exited with code ${a.exitCode}`;throw new D("COMMAND_FAILED",`Failed to capture iOS screenshot: ${i}`)}async function uE(e,t,r){let n=et.fromTimeoutMs(2e4),a="Unable to locate runner container for simulator screenshot";for(let i of n_){let o=await uN(e,["get_app_container",e.id,i,"data"],{allowFailure:!0,timeoutMs:uC(n,2e4,"runner screenshot container lookup")});if(0!==o.exitCode){let e=o.stderr.trim();e&&(a=e);continue}let s=o.stdout.trim();if(!s){a="simctl get_app_container returned empty output";continue}for(let e of function(e,t){let r=f.resolve(e),n=t.trim();if(!n)return[];let a=[],i=new Set,o=e=>{let t=f.normalize(e);i.has(t)||(i.add(t),a.push(t))},s=n.replace(/^\/+/,""),l=s.replace(/\\/g,"/");if(s&&o(f.join(r,s)),f.isAbsolute(n)&&o(f.normalize(n)),l.startsWith("tmp/"))o(f.join(r,l));else{let e=l.lastIndexOf("/tmp/");if(e>=0){let t=l.slice(e+1);o(f.join(r,t))}}let u=f.basename(n);return u&&o(f.join(r,"tmp",u)),a}(s,t))try{await d.copyFile(e,r);return}catch(e){a=e instanceof Error?e.message:String(e)}}throw new D("COMMAND_FAILED",`Failed to capture iOS screenshot: ${a}`)}function uC(e,t,r){let n=e.remainingMs();if(n>0)return n;throw new D("COMMAND_FAILED",`iOS ${r} timed out after ${t}ms`,{timeoutMs:t,step:r})}function uL(e,t,r){let n=uh(r);eN({level:"warn",phase:"ios_screenshot_fallback",data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,from:t,to:"runner",...n}})}function uT(e,t,r){eN({level:"warn",phase:`ios_screenshot_status_bar_${t}`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,...uh(r)}})}function u$(e){if(!(e instanceof D)||"COMMAND_FAILED"!==e.code)return!1;let t=e.details??{},r="string"==typeof t.stdout?t.stdout:"",n="string"==typeof t.stderr?t.stderr:"",a=Array.isArray(t.args)?t.args.filter(e=>"string"==typeof e).join(" "):"",i=`${e.message}
25
25
  ${r}
26
26
  ${n}
27
- ${a}`.toLowerCase();return i.includes("timeout waiting for screen surfaces")||i.includes("nsposixerrordomain")&&i.includes("code=60")&&i.includes("screenshot")||i.includes("timed out")&&i.includes("screenshot")}let ux={settings:"com.apple.Preferences"},uN=ef(),uM=null;function uk(e){return{platform:"ios",deviceId:e.id,variant:e.kind}}function uD(e,t,r){return rM(rO(e,t),r)}function uP(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 l3(t);let r=t.trim();if(r.includes("."))return r;let n=ux[r.toLowerCase()];if(n)return n;let a=uk(e),i=uN.get(a,r);if(i)return i;let o=("simulator"===e.kind?await uH(e):await oq(e,"all")).filter(e=>e.name.toLowerCase()===r.toLowerCase()),s=o[0];if(void 0!==s&&1===o.length)return uN.set(a,r,s.bundleId);if(o.length>1)throw new O("INVALID_ARGS",`Multiple apps matched "${t}"`,{matches:o});throw new O("APP_NOT_INSTALLED",`No app found matching "${t}"`)}async function uR(e,t,r){let n=r?.launchConsole?.trim();if(n&&("ios"!==e.platform||"simulator"!==e.kind))throw new O("UNSUPPORTED_OPERATION",lw);if("macos"===e.platform)return void await l5(e,t,r);let a=r?.url?.trim();if(a){if(n)throw new O("INVALID_ARGS",lg);if(!em(a))throw new O("INVALID_ARGS","open <app> <url> requires a valid URL target");if("simulator"===e.kind){await lA(e),await uD(e,["openurl",e.id,a]);return}let i=er(r?.appBundleId??await uO(e,t),a);if(!i)throw new O("INVALID_ARGS","Deep link open on iOS devices requires an active app bundle ID. Open the app first, then open the URL.");await u1(e,i,{payloadUrl:a});return}let i=t.trim();if(em(i)){if(n)throw new O("INVALID_ARGS",lg);if("simulator"===e.kind){await lA(e),await uD(e,["openurl",e.id,i]);return}let t=er(r?.appBundleId,i);if(!t)throw new O("INVALID_ARGS","Deep link open on iOS devices requires an active app bundle ID. Open the app first, then open the URL.");await u1(e,t,{payloadUrl:i});return}let o=r?.appBundleId??await uO(e,t);"simulator"===e.kind?await uZ(e,o,{...n?{launchConsole:n}:{},...r?.launchArgs?{launchArgs:r.launchArgs}:{}}):await u1(e,o)}async function uC(e){"macos"===e.platform||"simulator"!==e.kind||"Booted"!==await l_(e)&&await lA(e)}async function uE(e,t){if("macos"===e.platform)return void await l4(e,t);let r=await uO(e,t);if("simulator"===e.kind){await lA(e);let t=rO(e,["terminate",e.id,r]),n=await rM(t,{allowFailure:!0});if(0!==n.exitCode){if(n.stderr.toLowerCase().includes("found nothing to terminate"))return;throw new O("COMMAND_FAILED",`xcrun exited with code ${n.exitCode}`,{cmd:"xcrun",args:t,stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode})}return}await oG(["device","process","terminate","--device",e.id,r],{action:"terminate iOS app",deviceId:e.id})}async function uL(e,t){if("ios"!==e.platform||"simulator"!==e.kind)throw new O("UNSUPPORTED_OPERATION","Clearing app state is currently supported only on iOS simulators.");let r=await uO(e,t);await lA(e),await uE(e,r);let n=await uD(e,["get_app_container",e.id,r,"data"],{allowFailure:!0});if(0!==n.exitCode)throw new O("COMMAND_FAILED",`simctl get_app_container failed for ${r}`,{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode});let a=n.stdout.trim();if(!a)throw new O("COMMAND_FAILED",`simctl get_app_container returned an empty data container path for ${r}`);let i=await d.readdir(a);return await Promise.all(i.map(e=>d.rm(f.join(a,e),{recursive:!0,force:!0}))),{bundleId:r,containerPath:a}}async function u$(e,t){return await uN.invalidateWhile(uk(e),async()=>{let r=await uO(e,t);if("simulator"!==e.kind){let t=["devicectl","device","uninstall","app","--device",e.id,r],n=await rM(t,{allowFailure:!0,timeoutMs:2e4});if(0!==n.exitCode){let a=String(n.stdout??""),i=String(n.stderr??"");if(!uP(`${a}
28
- ${i}`.toLowerCase()))throw new O("COMMAND_FAILED",`Failed to uninstall iOS app ${r}`,{cmd:"xcrun",args:t,exitCode:n.exitCode,stdout:a,stderr:i,deviceId:e.id,hint:oW(a,i)??oH})}return{bundleId:r}}await lA(e);let n=await uD(e,["uninstall",e.id,r],{allowFailure:!0});if(0!==n.exitCode&&!uP(`${n.stdout}
29
- ${n.stderr}`.toLowerCase()))throw new O("COMMAND_FAILED",`simctl uninstall failed for ${r}`,{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode});return{bundleId:r}})}async function uT(e,t,r){let n=await lN({kind:"path",path:t},r);try{return await uU(e,n.installablePath),{archivePath:n.archivePath,installablePath:n.installablePath,bundleId:n.bundleId,appName:n.appName,launchTarget:n.bundleId}}finally{await n.cleanup()}}async function uF(e,t,r){return await uN.invalidateWhile(uk(e),async()=>{let{bundleId:n}=await u$(e,t);return await uT(e,r,{appIdentifierHint:t}),{bundleId:n}})}async function uU(e,t){await uN.invalidateWhile(uk(e),async()=>{"simulator"!==e.kind?await oG(["device","install","app","--device",e.id,t],{action:"install iOS app",deviceId:e.id}):(await lA(e),await uD(e,["install",e.id,t]))})}async function uV(e){if("macos"===e.platform)return await l8();lI(e,"clipboard"),await lA(e);let t=await uD(e,["pbpaste",e.id],{allowFailure:!0});if(0!==t.exitCode)throw new O("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 l6(t);lI(e,"clipboard"),await lA(e);let r=await uD(e,["pbcopy",e.id],{allowFailure:!0,stdin:t});if(0!==r.exitCode)throw new O("COMMAND_FAILED","Failed to write iOS simulator clipboard",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode})}async function uq(e,t,r){lI(e,"push"),await lA(e);let n=await d.mkdtemp(f.join(c.tmpdir(),"agent-device-ios-push-")),a=f.join(n,"payload.apns");try{await d.writeFile(a,`${JSON.stringify(r)}
30
- `,"utf8"),await uD(e,["push",e.id,t,a])}finally{await d.rm(n,{recursive:!0,force:!0})}}async function uj(e,t,r,n,a){if("macos"===e.platform){let e=t.toLowerCase();if("appearance"===e)return void await l7(r);if("permission"===e){let e=le(r);if("deny"===e)throw new O("INVALID_ARGS",tD("permission"));let t=function(e){let t=e?.trim().toLowerCase();if("accessibility"===t||"screen-recording"===t||"input-monitoring"===t)return t;throw new O("INVALID_ARGS","Unsupported macOS permission target. Use accessibility|screen-recording|input-monitoring.")}(a?.permissionTarget);return await lz(e,t)}throw new O("INVALID_ARGS",tD(t))}lI(e,"settings"),await lA(e);let i=t.toLowerCase();switch(i){case"wifi":{let t=ln(r);await uD(e,["status_bar",e.id,"override","--wifiMode",t?"active":"failed"]);return}case"airplane":return void(ln(r)?await uD(e,["status_bar",e.id,"override","--dataNetwork","hide","--wifiMode","failed","--wifiBars","0","--cellularMode","failed","--cellularBars","0","--operatorName",""]):await uD(e,["status_bar",e.id,"clear"]));case"location":{if("set"===r.toLowerCase()){let{latitude:t,longitude:r}=e$(a);return await uD(e,["location",e.id,"set",`${t},${r}`]),{latitude:t,longitude:r}}let t=ln(r);if(!n)throw new O("INVALID_ARGS","location setting requires an active app in session");await uD(e,["privacy",e.id,t?"grant":"revoke","location",n]);return}case"faceid":case"touchid":{let t=uz[i],n=function(e,t){let r=e.trim().toLowerCase();if("match"===r)return"match";if("nonmatch"===r)return"nonmatch";if("enroll"===r)return"enroll";if("unenroll"===r)return"unenroll";throw new O("INVALID_ARGS",`Invalid ${t} state: ${e}. Use match|nonmatch|enroll|unenroll.`)}(r,i);await uY(e,n,{settingName:i,label:t.label,modalityAliases:t.modalityAliases});return}case"appearance":{let t=await uW(e,r);await uD(e,["ui",e.id,"appearance",t]);return}case"permission":{var o;if(!n)throw new O("INVALID_ARGS","permission setting requires an active app in session");let t="deny"===(o=le(r))?"revoke":o,i=function(e,t){let r=lt(e);if("photos"!==r&&t?.trim())throw new O("INVALID_ARGS",`Permission mode is only supported for photos. Received: ${t}.`);if("camera"===r)return"camera";if("microphone"===r)return"microphone";if("contacts"===r)return"contacts";if("contacts-limited"===r)return"contacts-limited";if("notifications"===r)return"notifications";if("calendar"===r)return"calendar";if("location"===r)return"location";if("location-always"===r)return"location-always";if("media-library"===r)return"media-library";if("motion"===r)return"motion";if("reminders"===r)return"reminders";if("siri"===r)return"siri";if("photos"===r){let e=t?.trim().toLowerCase();if(!e||"full"===e)return"photos";if("limited"===e)return"photos-add";throw new O("INVALID_ARGS",`Invalid photos mode: ${t}. Use full|limited.`)}throw new O("INVALID_ARGS",`Unsupported permission target: ${e}. Use camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri.`)}(a?.permissionTarget,a?.permissionMode);await uK(e,t,i,n);return}default:throw new O("INVALID_ARGS",`Unsupported setting: ${t}`)}}async function uB(e,t){return"macos"===e.platform?await ue(t):"simulator"===e.kind?rw(await uH(e),t):await oq(e,t)}async function uH(e){let t=(await uD(e,["listapps",e.id],{allowFailure:!0})).stdout.trim();if(!t)return[];let r=null;if(t.startsWith("{"))try{r=JSON.parse(t)}catch{r=null}if(!r&&t.startsWith("{"))try{let e=await rN("plutil",["-convert","json","-o","-","-"],{allowFailure:!0,stdin:t});0===e.exitCode&&e.stdout.trim().startsWith("{")&&(r=JSON.parse(e.stdout))}catch{r=null}return r?Object.entries(r).map(([e,t])=>({bundleId:e,name:t.CFBundleDisplayName??t.CFBundleName??e})):[]}async function uW(e,t){let r=lr(t);if("toggle"!==r)return r;let n=await uD(e,["ui",e.id,"appearance"],{allowFailure:!0});if(0!==n.exitCode)throw new O("COMMAND_FAILED","Failed to read current iOS appearance",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode});let a=function(e,t){let r=/\b(light|dark|unsupported|unknown)\b/i.exec(`${e}
31
- ${t}`);if(!r)return null;let n=r[1]?.toLowerCase();return"dark"===n?"dark":"light"===n?"light":null}(n.stdout,n.stderr);if(!a)throw new O("COMMAND_FAILED","Unable to determine current iOS appearance for toggle",{stdout:n.stdout,stderr:n.stderr});return"dark"===a?"light":"dark"}let uz={faceid:{label:"Face ID",modalityAliases:["face"]},touchid:{label:"Touch ID",modalityAliases:["finger","touch"]}};async function uK(e,t,r,n){let a=await uX(e);if(!a.has(r))throw new O("UNSUPPORTED_OPERATION",`iOS simctl privacy does not support service "${r}" on this runtime.`,{deviceId:e.id,appBundleId:n,hint:`Supported services: ${Array.from(a).sort().join(", ")}`});let i=["privacy",e.id,t,r,n],o="notifications"===r;if(!("reset"===t&&o))try{await uD(e,i);return}catch(t){if(!(o&&uJ(t)))throw t;throw new O("UNSUPPORTED_OPERATION","iOS simulator does not support setting notifications permission via simctl privacy on this runtime.",{deviceId:e.id,appBundleId:n,hint:"Use reset notifications for reprompt behavior, or toggle notifications manually in Settings."})}try{await uD(e,i);return}catch(e){if(!uJ(e))throw e}try{await uD(e,["privacy",e.id,"reset","all",n])}catch(t){throw new O("COMMAND_FAILED","iOS simulator blocked direct notifications reset. Fallback reset-all also failed.",{deviceId:e.id,appBundleId:n,hint:"Use reinstall to force a fresh notifications prompt, or reset simulator content and settings."},t instanceof Error?t:void 0)}}function uJ(e){if(!(e instanceof O)||"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 uX(t){let r=ee(t.simulatorSetPath),n=`${process.env.PATH??""}::${r??""}`;if(uM&&e===n)return uM;let a=await uD(t,["privacy","help"],{allowFailure:!0}),i=function(e){let t=new Set,r=!1;for(let n of e.split("\n")){let e=n.trim();if(!e)continue;if("service"===e){r=!0;continue}if(!r)continue;if(e.startsWith("bundle identifier"))break;let a=/^([a-z-]+)\s+-\s+/.exec(e),i=a?.[1];void 0!==i&&t.add(i)}return t}(`${a.stdout}
32
- ${a.stderr}`);if(0===i.size)throw new O("COMMAND_FAILED","Unable to determine supported simctl privacy services",{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode,hint:"Run `xcrun simctl privacy help` manually to verify available services for this runtime."});return uM=i,e=n,i}async function uY(e,t,r){let n=function(e,t,r){let n=r.length>0?r:["face"];switch(t){case"match":return n.flatMap(t=>[["biometric",e,"match",t],["biometric","match",e,t]]);case"nonmatch":return n.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,r.modalityAliases),a=[];for(let t of n){let r=rO(e,t),n=await rM(r,{allowFailure:!0});if(0===n.exitCode)return;a.push({args:r,stderr:n.stderr,stdout:n.stdout,exitCode:n.exitCode})}let i=s9(a);if(a.length>0&&a.every(e=>{var t,r;let n;return t=e.stdout,r=e.stderr,(n=`${t}
33
- ${r}`.toLowerCase()).includes("unrecognized subcommand")||n.includes("unknown subcommand")||n.includes("not supported")||n.includes("unavailable")||n.includes("biometric")&&n.includes("invalid")}))throw new O("UNSUPPORTED_OPERATION",`${r.label} simulation is not supported on this simulator runtime.`,{deviceId:e.id,action:t,setting:r.settingName,attempts:i});throw new O("COMMAND_FAILED",`Failed to simulate ${r.settingName}.`,{deviceId:e.id,action:t,setting:r.settingName,attempts:i})}async function uZ(e,t,r){await lA(e);let n=0,a=en.fromTimeoutMs(6e4);try{await el(async({deadline:n})=>{var a,i,o,s;let l;if(n?.isExpired())throw new O("COMMAND_FAILED","App launch deadline exceeded",{timeoutMs:6e4});let u=(i=e.id,o=t,s=r,l=["launch"],s?.launchConsole&&l.push("--console-pty"),l.push(i,o),s?.launchArgs&&l.push(...s.launchArgs),a=l,rO(e,a)),d=r?.launchConsole?await uQ(u,r.launchConsole):await rM(u,{allowFailure:!0});if(0!==d.exitCode)throw new O("COMMAND_FAILED",`xcrun exited with code ${d.exitCode}`,{cmd:"xcrun",args:u,stdout:d.stdout,stderr:d.stderr,exitCode:d.exitCode})},{maxAttempts:10,baseDelayMs:1e3,maxDelayMs:5e3,jitter:.2,shouldRetry:e=>!!ly(e)&&(n+=1)<3},{deadline:a})}catch(r){if(ly(r)){var i;let n=(i=await lv(e,t)).installed?!1===i.simulatorCompatible?"ARCH_MISMATCH":"PERSISTENT_LAUNCH_FAIL":"APP_NOT_INSTALLED";r.details={...r.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."}}(n)}}throw r}}async function uQ(e,t){await d.mkdir(f.dirname(t),{recursive:!0});try{let r=await rM(e,{allowFailure:!0,timeoutMs:25e3});return await u0(t,r.stdout,r.stderr),r}catch(n){let e=n instanceof O?n:void 0,r=e?.details;if(r?.timeoutMs===25e3){let e="string"==typeof r.stdout?r.stdout:"",n="string"==typeof r.stderr?r.stderr:"";return await u0(t,e,n),eM({level:"warn",phase:"ios_simulator_launch_console_capture_timeout",data:{timeoutMs:25e3,logPath:t,stdoutBytes:Buffer.byteLength(e),stderrBytes:Buffer.byteLength(n)}}),{stdout:e,stderr:n,exitCode:0}}throw n}}async function u0(e,t,r){var n,a;await d.writeFile(e,(n=t,a=r,!n||!a||n.endsWith("\n")||n.endsWith("\r")?`${n}${a}`:`${n}
34
- ${a}`),"utf8")}async function u1(e,t,r){let n=["device","process","launch","--device",e.id,t];r?.payloadUrl&&n.push("--payload-url",r.payloadUrl),await oG(n,{action:"launch iOS app",deviceId:e.id})}function u2(e,t,r){return{command:"remotePress",remoteButton:e,...void 0!==r?{durationMs:r}:{},...void 0!==t?{appBundleId:t}:{}}}async function u3(e,t,r,n,a,i,o){if("tv"===t.target)return u8(await e(t,u2(a,r.appBundleId),n),i);let s=o??await u5(e,t,r,n),l=oQ({direction:a,amount:i?.amount,pixels:i?.pixels,referenceWidth:s.referenceWidth,referenceHeight:s.referenceHeight});return u8(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:r.appBundleId},n),{amount:l.amount,pixels:l.pixels,preferProvidedPixels:!0})}async function u5(e,t,r,n){let a=await e(t,{command:"interactionFrame",appBundleId:r.appBundleId},n),i=u4(a.x),o=u4(a.y),s=u4(a.referenceWidth),l=u4(a.referenceHeight);if(void 0===i||void 0===o||void 0===s||void 0===l)throw new O("COMMAND_FAILED","interactionFrame did not return a usable frame");return{originX:i,originY:o,referenceWidth:s,referenceHeight:l}}function u4(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function u8(e,t){var r;let{x1:n,y1:a,x2:i,y2:o}={x1:u4((r=e).x),y1:u4(r.y),x2:u4(r.x2),y2:u4(r.y2)},s=u4(e.referenceWidth),l=u4(e.referenceHeight),u=void 0!==n&&void 0!==i?Math.round(Math.abs(i-n)):void 0,d=void 0!==a&&void 0!==o?Math.round(Math.abs(o-a)):void 0,c=t?.preferProvidedPixels&&void 0!==t.pixels?t.pixels:u&&u>0?u:d&&d>0?d:void 0;return{...void 0!==n?{x1:n}:{},...void 0!==a?{y1:a}:{},...void 0!==i?{x2:i}:{},...void 0!==o?{y2:o}:{},...void 0!==s?{referenceWidth:s}:{},...void 0!==l?{referenceHeight:l}:{},...t?.amount!==void 0?{amount:t.amount}:{},...void 0!==c?{pixels:c}:{}}}let u6=null;async function u9(){let e=oD();if(u6?.provider===e)return u6;let t=process.env.WAYLAND_DISPLAY||"wayland"===process.env.XDG_SESSION_TYPE?"wayland":"x11";if("wayland"===t){if(await e.whichCommand("ydotool"))return u6={tool:"ydotool",display:t,provider:e};throw new O("TOOL_MISSING","ydotool is required for input synthesis on Wayland (xdotool does not work on Wayland). Install it via your package manager.")}if(await e.whichCommand("xdotool"))return u6={tool:"xdotool",display:t,provider:e};throw new O("TOOL_MISSING","xdotool is required for input synthesis on X11. Install it via your package manager.")}async function u7(...e){await oD().runCommand("xdotool",e,{allowFailure:!1,timeoutMs:1e4})}async function de(...e){await oD().runCommand("ydotool",e,{allowFailure:!1,timeoutMs:1e4})}function dt(){return oD().input}async function dr(e,t){let{tool:r}=await u9();"xdotool"===r?await u7("mousemove","--sync",String(e),String(t)):await de("mousemove","--absolute","-x",String(e),"-y",String(t))}async function dn(e,t){let r=dt();if(r)return void await r.key(e,t);let{tool:n}=await u9();"xdotool"===n?await u7("key","--clearmodifiers",e):await de("key",...t)}async function da(e,t,r,n){await dr(e,t);let{tool:a}=await u9();"xdotool"===a?await u7("click",r):await de("click",n)}async function di(e,t,r,n,a){let i=dt();i?await i.click(e,t,r):await da(e,t,n,a)}async function ds(e,t){await di(e,t,"primary","1","0xC0")}async function dl(e,t){await di(e,t,"secondary","3","0xC1")}async function du(e,t){await di(e,t,"middle","2","0xC2")}async function dd(e,t){let r=dt();if(r)return void await r.doubleClick(e,t);let{tool:n}=await u9();await dr(e,t),"xdotool"===n?await u7("click","--repeat","2","1"):(await de("click","0xC0"),await de("click","0xC0"))}async function dc(e,t,r=800){let n=dt();if(n)return void await n.longPress(e,t,r);let{tool:a}=await u9();await dr(e,t),"xdotool"===a?(await u7("mousedown","1"),await e2(r),await u7("mouseup","1")):(await de("click","--down","0xC0"),await e2(r),await de("click","--up","0xC0"))}async function dp(e,t){await ds(e,t)}async function df(e,t,r,n,a=300){let i=dt();if(i)return void await i.drag(e,t,r,n,a);let{tool:o}=await u9();await dr(e,t),"xdotool"===o?(await u7("mousedown","1"),await u7("mousemove","--sync",String(r),String(n)),await e2(a),await u7("mouseup","1")):(await de("click","--down","0xC0"),await de("mousemove","--absolute","-x",String(r),"-y",String(n)),await e2(a),await de("click","--up","0xC0"))}async function dm(e,t){let r=dt();if(r)return void await r.scroll(e,t);let{tool:n}=await u9(),a=5;if(t?.pixels!=null?a="xdotool"===n?Math.max(1,Math.round(t.pixels/15)):Math.max(1,Math.round(t.pixels/40)):t?.amount!=null&&(a=Math.max(1,Math.round(5*(t.amount/.6)))),"xdotool"===n)await u7("click","--repeat",String(a),"up"===e?"4":"down"===e?"5":"left"===e?"6":"7");else if("up"===e||"down"===e){let t="up"===e?String(-a):String(a);await de("mousemove","--wheel","-y",t)}else{let t="left"===e?String(-a):String(a);await de("mousemove","--wheel","-x",t)}}async function dh(e,t=0){let r=dt();if(r)return void await r.typeText(e,{delayMs:t});let{tool:n}=await u9();if("xdotool"===n){let r=["type"];t>0&&r.push("--delay",String(t)),r.push("--clearmodifiers","--",e),await u7(...r)}else await de("type","--",e)}async function dw(e,t,r,n=0){await ds(e,t),await e2(100),await dn("ctrl+a",["29:1","30:1","30:0","29:0"]),await e2(50),await dh(r,n)}async function dg(e){await oD().desktop.openTarget(e)}async function dy(e){await oD().desktop.closeApp(e)}async function dv(){await dn("alt+Left",["56:1","105:1","105:0","56:0"])}async function dI(){await dn("super+d",["125:1","32:1","32:0","125:0"])}async function db(){return await oD().clipboard.readText()}async function dA(e){await oD().clipboard.writeText(e)}async function dS(e,t){await oD().screenshot.capture(e,t)}let d_={"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"},dx="atspi-dump.py",dN=null;async function dM(e,t={}){let r,n=oD().accessibility;if(n)return await n.captureTree(e,t);if("linux"!==process.platform)throw new O("UNSUPPORTED_PLATFORM","AT-SPI2 bridge is only available on Linux");if(!await oD().whichCommand("python3"))throw new O("TOOL_MISSING","python3 is required for AT-SPI2 accessibility snapshots on Linux.");let a=t.maxNodes??1500,i=t.maxDepth??12,o=t.maxApps??24,s=[function(){if(dN)return dN;let e=f.dirname(y(import.meta.url));for(let t=0;t<5;t++){let r=f.join(e,"src","platforms","linux",dx);if(l.existsSync(r))return dN=r,r;if(0===t){let t=f.join(e,dx);if(l.existsSync(t))return dN=t,t}e=f.dirname(e)}throw new O("TOOL_MISSING",`Cannot find ${dx}. Ensure the agent-device package is installed correctly.`)}(),"--surface",e,"--max-nodes",String(a),"--max-depth",String(i),"--max-apps",String(o)],u=await oO("python3",s,{allowFailure:!0,timeoutMs:3e4});if(0!==u.exitCode){let e=u.stderr.trim();if(e.includes("No module named")||e.includes("gi.require_version"))throw new O("TOOL_MISSING","AT-SPI2 Python bindings not found. Install python3-gi and gir1.2-atspi-2.0.",{cause:e});throw new O("COMMAND_FAILED",`AT-SPI2 snapshot failed (exit ${u.exitCode}): ${e||u.stdout}`)}try{r=JSON.parse(u.stdout)}catch{throw new O("COMMAND_FAILED",`AT-SPI2 snapshot returned invalid JSON: ${u.stdout.slice(0,200)}`)}if(r.error)throw new O("COMMAND_FAILED",`AT-SPI2: ${r.error}`);return{nodes:(r.nodes??[]).map(e=>{let t,r;return{index:e.index,type:(r=d_[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:r.truncated,surface:e}}async function dk(e){let t="desktop"===e?"desktop":"frontmost-app"===e||"app"===e?"frontmost-app":("menubar"===e&&eM({level:"warn",phase:"linux_snapshot",data:{message:"menubar surface is not supported on Linux, falling back to desktop"}}),"desktop"),r=await dM(t);return{nodes:r.nodes,truncated:r.truncated}}async function dD(e,t,r){let{nodes:n}=await dk(r);for(let r of n.filter(r=>{let n=r.rect;return!!n&&e>=n.x&&t>=n.y&&e<=n.x+n.width&&t<=n.y+n.height}).sort((e,t)=>{let r=e.depth??0,n=t.depth??0;return r!==n?n-r:dP(e.rect)-dP(t.rect)})){let e=function(e){for(let t of[e.value,e.label,e.identifier])if("string"==typeof t&&t.length>0)return t;return""}(r);if(e.trim())return e}return""}function dP(e){return(e?.width??0)*(e?.height??0)}let dO=/^[A-Za-z0-9_.:-]{1,64}$/;function dR(e){return e?.clickButton??"primary"}function dC(e){return"primary"===e.button?null:"click"!==e.commandLabel?new O("INVALID_ARGS","--button is supported only for click"):"macos"!==e.platform&&"linux"!==e.platform?new O("UNSUPPORTED_OPERATION",`click --button ${e.button} is supported only on macOS and Linux`):"macos"===e.platform&&"middle"===e.button?new O("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 O("INVALID_ARGS",`click --button ${e.button} does not support repeat or gesture modifier flags`):null}let dE=[[0,0],[1,0],[0,1],[-1,0],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]];async function dL(e,t,r){for(let n=0;n<e;n+=1)await r(n),n<e-1&&t>0&&await e2(t)}async function d$(e,t){let{x:r,y:n}=dj(t,"longpress requires x y [durationMs]",{hint:"Direct platform longpress requires coordinates. In an open daemon session, use agent-device longpress @ref|selector [durationMs]; otherwise run snapshot -i -c, use the target rect center as x y, then retry longpress x y durationMs."}),a=t[2]?Number(t[2]):void 0;return await e.longPress(r,n,a),{x:r,y:n,durationMs:a,...eV(`Long pressed (${r}, ${n})`)}}async function dT(e,t){let{x:r,y:n}=dj(t,"focus requires x y");return await e.focus(r,n),{x:r,y:n,...eV(`Focused (${r}, ${n})`)}}async function dF(e,t,r){let n=tL(t[0]);if(n)throw new O("INVALID_ARGS",`type does not accept a target ref like "${n}"`,{hint:`Use fill ${n} "text" to target that field, or press ${n} then type "text" to append.`});let a=t.join(" ");if(!a)throw new O("INVALID_ARGS","type requires text");let i=tP(r?.delayMs??0,"delay-ms",0,1e4);return await e.type(a,i),{text:a,delayMs:i,...eV(d9("Typed",a))}}async function dU(e,t,r){if(r?.directElementSelector)return await dV(e,r.directElementSelector,t,r);let n=Number(t[0]),a=Number(t[1]),i=t.slice(2).join(" ");if(Number.isNaN(n)||Number.isNaN(a)||!i)throw new O("INVALID_ARGS","fill requires x y text");let o=tP(r?.delayMs??0,"delay-ms",0,1e4);return await e.fill(n,a,i,o),{x:n,y:a,text:i,delayMs:o,...eV(d9("Filled",i))}}async function dV(e,t,r,n){if(!e.fillElementSelector)throw new O("UNSUPPORTED_OPERATION","direct element selector fill is not supported");let a=r.join(" ");if(!a)throw new O("INVALID_ARGS","fill requires text");let i=tP(n.delayMs??0,"delay-ms",0,1e4),o=await e.fillElementSelector(t,a,i);return{selector:t.raw,text:a,delayMs:i,...o??{},...eV(d9("Filled",a))}}async function dG(e,t,r,n){var a,i,o,s;if(n?.directElementSelector&&"ios"===e.platform)return await dq(t,n.directElementSelector);let{x:l,y:u}=dj(r,"press requires x y");if("macos"===e.platform&&n?.surface&&"app"!==n.surface)return await dB(l,u,n);let d=dR(n);if("primary"!==d)return await dH(e,l,u,d,n);let c=(s=n,{count:dz(s?.count,1,"count",1,200),intervalMs:dz(s?.intervalMs,0,"interval-ms",0,1e4),holdMs:dz(s?.holdMs,0,"hold-ms",0,1e4),jitterPx:dz(s?.jitterPx,0,"jitter-px",0,100),doubleTap:!!s?.doubleTap});return(function({doubleTap:e,holdMs:t,jitterPx:r}){if(e&&t>0)throw new O("INVALID_ARGS","double-tap cannot be combined with hold-ms");if(e&&r>0)throw new O("INVALID_ARGS","double-tap cannot be combined with jitter-px")}(c),a=c.count,i=c.holdMs,o=c.jitterPx,r1(e.platform)&&a>1&&0===i&&0===o)?await dK(e,l,u,c,n):await dJ(t,l,u,c)}async function dq(e,t){if(!e.tapElementSelector)throw new O("UNSUPPORTED_OPERATION","direct element selector tap is not supported");let r=await e.tapElementSelector(t);return{selector:t.raw,...r??{},...eV(`Tapped ${t.raw}`)}}function dj(e,t,r){let n=Number(e[0]),a=Number(e[1]);if(Number.isNaN(n)||Number.isNaN(a))throw new O("INVALID_ARGS",t,r);return{x:n,y:a}}async function dB(e,t,r){let n=dR(r);if("primary"!==n)throw new O("UNSUPPORTED_OPERATION",`${n} click is not supported on macOS ${r.surface} sessions.`);return await lY(e,t,{bundleId:r.appBundleId,surface:r.surface}),{x:e,y:t,...eV(d8({x:e,y:t}))}}async function dH(e,t,r,n,a){return(function(e,t,r){let n=dC({commandLabel:"click",platform:e.platform,button:t,count:r?.count,intervalMs:r?.intervalMs,holdMs:r?.holdMs,jitterPx:r?.jitterPx,doubleTap:r?.doubleTap});if(n)throw n}(e,n,a),"linux"===e.platform)?await dW(t,r,n):(await ao(e,{command:"mouseClick",x:t,y:r,button:n,appBundleId:a?.appBundleId},dX(a)),{x:t,y:r,button:n,...eV(d8({x:t,y:r,button:n}))})}async function dW(e,t,r){return"secondary"===r?await dl(e,t):await du(e,t),{x:e,y:t,button:r,...eV(d8({x:e,y:t,button:r}))}}function dz(e,t,r,n,a){return tP(void 0===e?t:e,r,n,a)}async function dK(e,t,r,n,a){let i=await ao(e,{command:"tapSeries",x:t,y:r,count:n.count,intervalMs:n.intervalMs,doubleTap:n.doubleTap,appBundleId:a?.appBundleId},dX(a));return{x:t,y:r,count:n.count,intervalMs:n.intervalMs,holdMs:n.holdMs,jitterPx:n.jitterPx,doubleTap:n.doubleTap,timingMode:"runner-series",...i,...eV(d8({x:t,y:r}))}}async function dJ(e,t,r,n){let a;return await dL(n.count,n.intervalMs,async i=>{let[o,s]=function(e,t){if(t<=0)return[0,0];let[r,n]=dE[e%dE.length];return[r*t,n*t]}(i,n.jitterPx),l=t+o,u=r+s;if(n.doubleTap){a??=await e.doubleTap(l,u)??void 0;return}n.holdMs>0?a??=await e.longPress(l,u,n.holdMs)??void 0:a??=await e.tap(l,u)??void 0}),eH({x:t,y:r,count:n.count,intervalMs:n.intervalMs,holdMs:n.holdMs,jitterPx:n.jitterPx,doubleTap:n.doubleTap,...a},d8({x:t,y:r}))}function dX(e){return{verbose:e?.verbose,logPath:e?.logPath,traceLogPath:e?.traceLogPath,requestId:e?.requestId}}async function dY(e,t,r,n){let a=Number(r[0]),i=Number(r[1]),o=Number(r[2]),s=Number(r[3]);if([a,i,o,s].some(Number.isNaN))throw new O("INVALID_ARGS","swipe requires x1 y1 x2 y2 [durationMs]");let l=tP(r[4]?Number(r[4]):250,"durationMs",16,1e4),u="ios"===e.platform?Math.min(60,Math.max(16,Math.round(l))):l,d=tP(n?.count??1,"count",1,200),c=tP(n?.pauseMs??0,"pause-ms",0,1e4),p=n?.pattern??"one-way";if("one-way"!==p&&"ping-pong"!==p)throw new O("INVALID_ARGS",`Invalid pattern: ${p}`);if(r1(e.platform)&&d>1){let t=await ao(e,{command:"dragSeries",x:a,y:i,x2:o,y2:s,durationMs:u,count:d,pauseMs:c,pattern:p,appBundleId:n?.appBundleId},{verbose:n?.verbose,logPath:n?.logPath,traceLogPath:n?.traceLogPath,requestId:n?.requestId});return{x1:a,y1:i,x2:o,y2:s,durationMs:l,effectiveDurationMs:u,timingMode:"runner-series",count:d,pauseMs:c,pattern:p,...t,...eV(d6(d,p))}}return await dL(d,c,async e=>{"ping-pong"===p&&e%2==1?await t.swipe(o,s,a,i,u):await t.swipe(a,i,o,s,u)}),eH({x1:a,y1:i,x2:o,y2:s,durationMs:l,effectiveDurationMs:u,timingMode:"ios"===e.platform?"safe-normalized":"direct",count:d,pauseMs:c,pattern:p},d6(d,p))}async function dZ(e,t){let r=Number(t[0]),n=Number(t[1]),a=Number(t[2]),i=Number(t[3]);if([r,n,a,i].some(e=>!Number.isFinite(e)))throw new O("INVALID_ARGS","gesture pan requires x y dx dy [durationMs]");let o=tP(t[4]?Number(t[4]):500,"durationMs",16,1e4),s=r+a,l=n+i;return await e.pan(r,n,s,l,o),{x:r,y:n,dx:a,dy:i,x2:s,y2:l,durationMs:o,...eV(`Panned (${r}, ${n}) by (${a}, ${i})`)}}async function dQ(e,t){let r=function(e,t){if("up"===e||"down"===e||"left"===e||"right"===e)return e;throw new O("INVALID_ARGS",`${t} must be up, down, left, or right`)}(t[0],"fling direction"),n=Number(t[1]),a=Number(t[2]);if(![n,a].every(Number.isFinite))throw new O("INVALID_ARGS","gesture fling requires direction x y [distance] [durationMs]");let i=function(e,t){if(!Number.isFinite(e)||e<=0)throw new O("INVALID_ARGS",`${t} must be a positive number`);return e}(t[3]?Number(t[3]):180,"distance"),o=tP(t[4]?Number(t[4]):50,"durationMs",16,1e3),{x2:s,y2:l}=function(e,t,r,n){switch(r){case"up":return{x2:e,y2:t-n};case"down":return{x2:e,y2:t+n};case"left":return{x2:e-n,y2:t};case"right":return{x2:e+n,y2:t}}}(n,a,r,i);return await e.fling(n,a,s,l,o),{direction:r,x:n,y:a,x2:s,y2:l,distance:i,durationMs:o,...eV(`Flung ${r}`)}}async function d0(e,t,r){var n;let a=t[0],i=t[1]?Number(t[1]):void 0,o=r?.pixels;if(!a)throw new O("INVALID_ARGS","scroll requires direction");if(void 0!==i&&!Number.isFinite(i))throw new O("INVALID_ARGS","scroll amount must be a number");if(void 0!==i&&void 0!==o)throw new O("INVALID_ARGS","scroll accepts either a relative amount or --pixels, not both");let s="bottom"===(n=a)?{direction:"down",edge:"bottom"}:"top"===n?{direction:"up",edge:"top"}:{direction:function(e){switch(e){case"up":case"down":case"left":case"right":return e;default:throw new O("INVALID_ARGS",`Unknown direction: ${e}`)}}(n)},l={},u=0;if(s.edge){let t=s.edge,n=await tk({edge:t,captureState:async n=>await d1(e,r,t,n),scroll:async()=>await e.scroll(s.direction,{amount:i,pixels:o})});l=n.result??{},u=n.passes}else l=await e.scroll(s.direction,{amount:i,pixels:o}),u=1;return eH({direction:s.direction,...s.edge?{edge:s.edge,passes:u}:{},...void 0!==i?{amount:i}:{},...void 0!==o?{pixels:o}:{},...l},tg(s.direction,s.edge,u,i,o))}async function d1(e,t,r,n){if("function"!=typeof e.snapshot)throw new O("UNSUPPORTED_OPERATION",`scroll ${r} requires snapshot support to verify hidden content before scrolling`);let a=e.snapshot;return await t_({edge:r,scope:n,captureNodes:async e=>(await a({appBundleId:t?.appBundleId,compact:!0,scope:e})).nodes??[]})}async function d2(e,t,r,n){if("tv"===e.target)throw new O("UNSUPPORTED_OPERATION","gesture pinch is not supported on tvOS");if("macos"===e.platform&&n?.surface&&"app"!==n.surface)throw new O("UNSUPPORTED_OPERATION","gesture pinch is only supported in macOS app sessions. Re-open the target app without --surface desktop|menubar|frontmost-app first.");let a=Number(r[0]),i=r[1]?Number(r[1]):void 0,o=r[2]?Number(r[2]):void 0;if(Number.isNaN(a)||a<=0)throw new O("INVALID_ARGS","gesture pinch requires scale > 0");let s=await t.pinch(a,i,o);return{scale:a,x:i,y:o,...s,...eV(`Pinched to scale ${a}`)}}async function d3(e,t,r){if("tv"===e.target)throw new O("UNSUPPORTED_OPERATION","gesture rotate is not supported on tvOS");if("macos"===e.platform)throw new O("UNSUPPORTED_OPERATION","gesture rotate is not supported on macOS; XCTest rotation gestures are available only for iOS app sessions.");let{degrees:n,x:a,y:i,velocity:o}=function(e){let t=Number(e[0]);if(!Number.isFinite(t))throw new O("INVALID_ARGS","gesture rotate requires degrees [x] [y] [velocity]");let r=function(e,t){if(void 0===e&&void 0===t)return{};if(void 0===e||void 0===t)throw new O("INVALID_ARGS","gesture rotate center requires both x and y");let r=Number(e),n=Number(t);if(!Number.isFinite(r)||!Number.isFinite(n))throw new O("INVALID_ARGS","gesture rotate center requires finite x and y");return{x:r,y:n}}(e[1],e[2]),n=Number(e[3]??(t>=0?1:-1));if(!Number.isFinite(n)||0===n)throw new O("INVALID_ARGS","gesture rotate velocity must be a non-zero number");return{degrees:t,...r,velocity:Math.abs(n)*(t>=0?1:-1)}}(r),s=await t.rotateGesture(n,a,i,o);return{degrees:n,...void 0!==a&&void 0!==i?{x:a,y:i}:{},velocity:o,...s,...eV(`Rotated gesture ${n} degrees`)}}async function d5(e,t,r){if("tv"===e.target)throw new O("UNSUPPORTED_OPERATION","gesture transform is not supported on tvOS");let n="ios"===e.platform&&"simulator"===e.kind;if("android"!==e.platform&&!n)throw new O("UNSUPPORTED_OPERATION","gesture transform is currently supported on Android and iOS simulators");let a=function(e){let t=Number(e[0]),r=Number(e[1]),n=Number(e[2]),a=Number(e[3]),i=Number(e[4]),o=Number(e[5]);if(![t,r,n,a,i,o].every(Number.isFinite))throw new O("INVALID_ARGS","gesture transform requires x y dx dy scale degrees [durationMs]");if(i<=0)throw new O("INVALID_ARGS","gesture transform scale must be > 0");return{x:t,y:r,dx:n,dy:a,scale:i,degrees:o,durationMs:void 0===e[6]?void 0:tP(Number(e[6]),"durationMs",16,1e4)}}(r),i=await t.transformGesture(a);return{...a,...i,...eV(`Requested transform gesture by (${a.dx}, ${a.dy}), scale ${a.scale}, rotate ${a.degrees} degrees`)}}async function d4(e,t,r){let{x:n,y:a}=dj(t,"read requires x y");if("android"===e.platform)return{action:"read",text:await sh(e,n,a)??""};if("linux"===e.platform)return{action:"read",text:await dD(n,a,r?.surface)};if("macos"===e.platform&&r?.surface&&"app"!==r.surface)return{action:"read",text:(await lX(n,a,{bundleId:r.appBundleId,surface:r.surface})).text};let i=await ao(e,{command:"readText",x:n,y:a,appBundleId:r?.appBundleId},{verbose:r?.verbose,logPath:r?.logPath,traceLogPath:r?.traceLogPath,requestId:r?.requestId});return{action:"read",text:"string"==typeof i.text?i.text:"string"==typeof i.message?i.message:""}}function d8(e){return e.button&&"primary"!==e.button?`Clicked ${e.button} (${e.x}, ${e.y})`:`Tapped (${e.x}, ${e.y})`}function d6(e,t){return e<=1?"Swiped":"ping-pong"===t?`Swiped ${e} times (ping-pong)`:`Swiped ${e} times`}function d9(e,t){return`${e} ${Array.from(t).length} chars`}function d7(e,t){let r,n=t?.subject??"Payload",a=e.trim();if(!a)throw new O("INVALID_ARGS",`${n} cannot be empty`);let i=t?.expandPath?t.expandPath(a,t.cwd):a;try{if(!l.statSync(i).isFile())throw new O("INVALID_ARGS",`${n} path is not a file: ${i}`);return{kind:"file",path:i}}catch(t){if(t instanceof O)throw t;let e=t.code;if("EACCES"===e||"EPERM"===e)throw new O("INVALID_ARGS",`${n} file is not readable: ${i}`);if(e&&"ENOENT"!==e)throw new O("COMMAND_FAILED",`Unable to read ${n} file: ${i}`,{cause:String(t)})}if((r=a.trim()).startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))return{kind:"inline",text:a};throw new O("INVALID_ARGS",`${n} file not found: ${i}`)}async function ce(e){let t=d7(e,{subject:"Push payload"}),r="inline"===t.kind?t.text:await ct(t.path);try{let e=JSON.parse(r);if(!e||"object"!=typeof e||Array.isArray(e))throw new O("INVALID_ARGS","push payload must be a JSON object");return e}catch(t){if(t instanceof O)throw t;throw new O("INVALID_ARGS",`Invalid push payload JSON: ${e}`)}}async function ct(e){try{return await d.readFile(e,"utf8")}catch(r){let t=r.code;if("ENOENT"===t)throw new O("INVALID_ARGS",`Push payload file not found: ${e}`);if("EISDIR"===t)throw new O("INVALID_ARGS",`Push payload path is not a file: ${e}`);if("EACCES"===t||"EPERM"===t)throw new O("INVALID_ARGS",`Push payload file is not readable: ${e}`);throw new O("COMMAND_FAILED",`Unable to read push payload file: ${e}`,{cause:String(r)})}}async function cr(e,t,r,n,a){let i={requestId:a?.requestId,appBundleId:a?.appBundleId,verbose:a?.verbose,logPath:a?.logPath,traceLogPath:a?.traceLogPath},o=function(e,t){switch(e.platform){case"android":return{open:(t,r)=>H(e,t,{activity:r?.activity,appBundleId:r?.appBundleId,url:r?.url}),openDevice:()=>K(e),close:t=>W(e,t),tap:(t,r)=>sb(e,t,r),doubleTap:async(t,r)=>{await sb(e,t,r),await sb(e,t,r)},swipe:(t,r,n,a,i)=>sA(e,t,r,n,a,i),pan:(t,r,n,a,i)=>sA(e,t,r,n,a,i),fling:(t,r,n,a,i)=>sA(e,t,r,n,a,i),longPress:(t,r,n)=>sk(e,t,r,n),focus:(t,r)=>sP(e,t,r),type:(t,r)=>sD(e,t,r),fill:(t,r,n,a)=>sO(e,t,r,n,a),scroll:(t,r)=>sC(e,t,r),pinch:(t,r,n)=>sz(e,{scale:t,x:r,y:n}),screenshot:(t,r)=>lp(e,t,r),snapshot:async t=>{let r=await eN("snapshot_capture",async()=>await o6(e,{interactiveOnly:t?.interactiveOnly,compact:t?.compact,depth:t?.depth,scope:t?.scope,raw:t?.raw}),{backend:"android"});return{nodes:r.nodes??[],truncated:r.truncated??!1,backend:"android",analysis:r.analysis,androidSnapshot:r.androidSnapshot}},back:t=>sS(e),home:()=>s_(e),rotate:t=>sN(e,t),rotateGesture:(t,r,n,a)=>sK(e,{degrees:t,x:r,y:n,velocity:a}),transformGesture:t=>sJ(e,t),appSwitcher:()=>sM(e),readClipboard:()=>Y(e),writeClipboard:t=>B(e,t),setSetting:(t,r,n,a)=>li(e,t,r,n,a)};case"linux":return{open:e=>dg(e),openDevice:()=>Promise.resolve(),close:e=>dy(e),tap:(e,t)=>ds(e,t),doubleTap:(e,t)=>dd(e,t),swipe:(e,t,r,n,a)=>df(e,t,r,n,a),pan:(e,t,r,n,a)=>df(e,t,r,n,a),fling:()=>{throw new O("UNSUPPORTED_OPERATION","gesture fling not supported on Linux")},longPress:(e,t,r)=>dc(e,t,r),focus:(e,t)=>dp(e,t),type:(e,t)=>dh(e,t),fill:(e,t,r,n)=>dw(e,t,r,n),scroll:(e,t)=>dm(e,t),pinch:()=>{throw new O("UNSUPPORTED_OPERATION","gesture pinch not supported on Linux")},screenshot:(e,t)=>dS(e,t),snapshot:async e=>{let t=await eN("snapshot_capture",async()=>await dk(e?.surface),{backend:"linux-atspi"});return{nodes:t.nodes??[],truncated:t.truncated??!1,backend:"linux-atspi"}},back:()=>dv(),home:()=>dI(),rotate:()=>{throw new O("UNSUPPORTED_OPERATION","rotate not supported on Linux")},rotateGesture:()=>{throw new O("UNSUPPORTED_OPERATION","gesture rotate not supported on Linux")},transformGesture:()=>{throw new O("UNSUPPORTED_OPERATION","gesture transform not supported on Linux")},appSwitcher:()=>{throw new O("UNSUPPORTED_OPERATION","appSwitcher not yet supported on Linux")},readClipboard:()=>db(),writeClipboard:e=>dA(e),setSetting:()=>{throw new O("UNSUPPORTED_OPERATION","setSetting not supported on Linux")}};case"ios":case"macos":return function(e,t){let r,{overrides:n,runnerOpts:a}={runnerOpts:r={verbose:t.verbose,logPath:t.logPath,traceLogPath:t.traceLogPath,requestId:t.requestId},overrides:{tap:async(n,a)=>await ao(e,{command:"tap",x:n,y:a,appBundleId:t.appBundleId},r),tapElementSelector:async n=>await ao(e,{command:"tap",selectorKey:n.key,selectorValue:n.value,allowNonHittableCoordinateFallback:n.allowNonHittableCoordinateFallback,appBundleId:t.appBundleId},r),doubleTap:async(n,a)=>await ao(e,{command:"tapSeries",x:n,y:a,count:1,intervalMs:0,doubleTap:!0,appBundleId:t.appBundleId},r),swipe:async(n,a,i,o,s)=>await ao(e,{command:"drag",x:n,y:a,x2:i,y2:o,durationMs:s,appBundleId:t.appBundleId},r),pan:async(n,a,i,o,s)=>await ao(e,{command:"drag",x:n,y:a,x2:i,y2:o,durationMs:s??500,appBundleId:t.appBundleId},r),fling:async(n,a,i,o,s)=>await ao(e,{command:"drag",x:n,y:a,x2:i,y2:o,durationMs:s??16,appBundleId:t.appBundleId},r),longPress:async(n,a,i)=>await ao(e,{command:"longPress",x:n,y:a,durationMs:i,appBundleId:t.appBundleId},r),focus:async(n,a)=>await ao(e,{command:"tap",x:n,y:a,appBundleId:t.appBundleId},r),type:async(n,a)=>{await ao(e,{command:"type",text:n,delayMs:a,textEntryMode:"\n"===n?void 0:"append",appBundleId:t.appBundleId},r)},fillElementSelector:async(n,a,i)=>await ao(e,{command:"type",selectorKey:n.key,selectorValue:n.value,allowNonHittableCoordinateFallback:n.allowNonHittableCoordinateFallback,text:a,delayMs:i,textEntryMode:"replace",appBundleId:t.appBundleId},r),fill:async(n,a,i,o)=>await ao(e,{command:"type",x:n,y:a,text:i,delayMs:o,textEntryMode:"replace",appBundleId:t.appBundleId},r),scroll:async(n,a)=>await u3(ao,e,t,r,n,a),pinch:async(n,a,i)=>{await ao(e,{command:"pinch",scale:n,x:a,y:i,appBundleId:t.appBundleId},r)},rotateGesture:async(n,a,i,o)=>{await ao(e,{command:"rotateGesture",degrees:n,x:a,y:i,velocity:o,appBundleId:t.appBundleId},r)},transformGesture:async n=>await ao(e,{command:"transformGesture",x:n.x,y:n.y,dx:n.dx,dy:n.dy,scale:n.scale,degrees:n.degrees,durationMs:n.durationMs,appBundleId:t.appBundleId},r)}};return{open:(t,r)=>uR(e,t,{appBundleId:r?.appBundleId,launchConsole:r?.launchConsole,launchArgs:r?.launchArgs,url:r?.url}),openDevice:()=>uC(e),close:t=>uE(e,t),screenshot:async(t,r)=>{"macos"===e.platform&&r?.surface&&"app"!==r.surface?await lZ(t,{surface:r.surface,fullscreen:r.fullscreen}):await uh(e,t,r?.appBundleId,r?.fullscreen,a)},snapshot:async t=>{var r;let n={nodes:Array.isArray((r=await eN("snapshot_capture",async()=>await ao(e,{command:"snapshot",appBundleId:t?.appBundleId,interactiveOnly:t?.interactiveOnly,compact:t?.compact,depth:t?.depth,scope:t?.scope,raw:t?.raw},a),{backend:"xctest"})).nodes)?r.nodes:void 0,truncated:"boolean"==typeof r.truncated?r.truncated:void 0},i=n.nodes??[];if(0===i.length&&"simulator"===e.kind)throw new O("COMMAND_FAILED","XCTest snapshot returned 0 nodes on iOS simulator.");return{nodes:i,truncated:n.truncated??!1,backend:"xctest"}},back:async r=>{"tv"===e.target?await ao(e,u2("menu",t.appBundleId),a):await ao(e,{command:"system"===r?"backSystem":"backInApp",appBundleId:t.appBundleId},a)},home:async()=>{"tv"===e.target?await ao(e,u2("home",t.appBundleId),a):await ao(e,{command:"home",appBundleId:t.appBundleId},a)},rotate:async r=>{await ao(e,{command:"rotate",orientation:r,appBundleId:t.appBundleId},a)},appSwitcher:async()=>{await ao(e,{command:"appSwitcher",appBundleId:t.appBundleId},a)},readClipboard:()=>uV(e),writeClipboard:t=>uG(e,t),setSetting:(t,r,n,a)=>uj(e,t,r,n,a),...n}}(e,t);default:throw new O("UNSUPPORTED_PLATFORM",`Unsupported platform: ${e.platform}`)}}(e,i);return eM({level:"debug",phase:"platform_command_prepare",data:{command:t,platform:e.platform,kind:e.kind}}),await eN("platform_command",async()=>await cn(e,o,t,r,n,a,i),{command:t,platform:e.platform})}async function cn(e,t,r,n,a,i,o){switch(r){case"open":return await ca(e,t,n,i);case"close":{let e=n[0];if(!e)return{closed:"session",...eV("Closed session")};return await t.close(e),{app:e,...eV(`Closed: ${e}`)}}case"press":return await dG(e,t,n,i);case"swipe":return await dY(e,t,n,i);case"pan":return await dZ(t,n);case"fling":return await dQ(t,n);case"longpress":return await d$(t,n);case"focus":return await dT(t,n);case"type":return await dF(t,n,i);case"fill":return await dU(t,n,i);case"scroll":return await d0(t,n,i);case"pinch":return await d2(e,t,n,i);case"rotate-gesture":return await d3(e,t,n);case"transform-gesture":return await d5(e,t,n);case"trigger-app-event":return await ci(e,t,n,i);case"screenshot":return await co(t,n,a,i);case"back":return await t.back(i?.backMode),{action:"back",mode:i?.backMode??"in-app",...eV("Back")};case"home":return await t.home(),{action:"home",...eV("Home")};case"rotate":{let e=eY(n[0]);return await t.rotate(e),{action:"rotate",orientation:e,...eV(`Rotated to ${e}`)}}case"app-switcher":return await t.appSwitcher(),{action:"app-switcher",...eV("Opened app switcher")};case"clipboard":return await cs(t,n);case"keyboard":return await cl(e,n,i,o);case"settings":return await cc(e,t,n,i);case"push":return await cp(e,n,i);case"snapshot":return await cf(t,i);case"read":return await d4(e,n,i);default:throw new O("INVALID_ARGS",`Unknown command: ${r}`)}}async function ca(e,t,r,n){let a=r[0],i=r[1],o=n?.launchConsole;if(r.length>2)throw new O("INVALID_ARGS","open accepts at most two arguments: <app|url> [url]");if(!a){if(o)throw new O("INVALID_ARGS","--launch-console requires an app target");return await t.openDevice(),{app:null,...eV("Opened device")}}if(o&&("ios"!==e.platform||"simulator"!==e.kind))throw new O("UNSUPPORTED_OPERATION",lw);if(void 0!==i){if(em(a))throw new O("INVALID_ARGS","open <app> <url> requires an app target as the first argument");if(!em(i))throw new O("INVALID_ARGS","open <app> <url> requires a valid URL target");if(o)throw new O("INVALID_ARGS",lg);return await t.open(a,{activity:n?.activity,appBundleId:n?.appBundleId,launchArgs:n?.launchArgs,url:i}),{app:a,url:i,...eV(`Opened: ${a}`)}}if(o&&em(a))throw new O("INVALID_ARGS",lg);if("android"===e.platform&&n?.launchArgs&&n.launchArgs.length>0)throw new O("UNSUPPORTED_OPERATION","Launch arguments are currently supported only on Apple platforms.");if(n?.clearAppState){if(em(a))throw new O("INVALID_ARGS","Clearing app state requires an app target, not a deep link.");if("ios"!==e.platform||"simulator"!==e.kind)throw new O("UNSUPPORTED_OPERATION","Clearing app state is currently supported only on iOS simulators.");await uL(e,a)}return await t.open(a,{activity:n?.activity,appBundleId:n?.appBundleId,launchConsole:o,launchArgs:n?.launchArgs}),{app:a,...o?{launchConsole:o}:{},...eV(`Opened: ${a}`)}}async function ci(e,t,r,n){let{eventName:a,payload:i}=function(e){let t=e[0]?.trim(),r=e[1]?.trim();if(!t)throw new O("INVALID_ARGS","trigger-app-event requires <event> [payloadJson]");if(!dO.test(t))throw new O("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 O("INVALID_ARGS","trigger-app-event accepts at most two arguments: <event> [payloadJson]");let n=function(e,t){if(e)try{let r=JSON.parse(e);if(!r||"object"!=typeof r||Array.isArray(r))throw new O("INVALID_ARGS",`trigger-app-event payload for "${t}" must be a JSON object`);let n=JSON.stringify(r);if(Buffer.byteLength(n,"utf8")>8192)throw new O("INVALID_ARGS",`trigger-app-event payload for "${t}" exceeds 8192 bytes`);return r}catch(t){if(t instanceof O)throw t;throw new O("INVALID_ARGS",`Invalid trigger-app-event payload JSON: ${e}`)}}(r,t);return{eventName:t,payload:n}}(r),o=function(e,t,r){var n;let a,i=(a=("ios"===(n=e)?process.env.AGENT_DEVICE_IOS_APP_EVENT_URL_TEMPLATE:"macos"===n?process.env.AGENT_DEVICE_MACOS_APP_EVENT_URL_TEMPLATE:process.env.AGENT_DEVICE_ANDROID_APP_EVENT_URL_TEMPLATE)??process.env.AGENT_DEVICE_APP_EVENT_URL_TEMPLATE,a?.trim()||void 0);if(!i)throw new O("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=r?JSON.stringify(r):"",s=i.replaceAll("{event}",encodeURIComponent(t)).replaceAll("{payload}",encodeURIComponent(o)).replaceAll("{platform}",encodeURIComponent(e));if(s.length>4096)throw new O("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,a,i);return await t.open(o,{appBundleId:n?.appBundleId}),{event:a,eventUrl:o,transport:"deep-link",...eV(`Triggered app event: ${a}`)}}async function co(e,t,r,n){let a=t[0]??r??`./screenshot-${Date.now()}.png`;await d.mkdir(f.dirname(a),{recursive:!0});let i=eU(n);return await e.screenshot(a,{appBundleId:n?.appBundleId,fullscreen:i.fullscreen,stabilize:i.stabilize,surface:n?.surface}),{path:a,...eV(`Saved screenshot: ${a}`)}}async function cs(e,t){let r=(t[0]??"").toLowerCase();if("read"!==r&&"write"!==r)throw new O("INVALID_ARGS","clipboard requires a subcommand: read or write");if("read"===r){if(1!==t.length)throw new O("INVALID_ARGS","clipboard read does not accept additional arguments");return{action:r,text:await e.readClipboard()}}if(t.length<2)throw new O("INVALID_ARGS",'clipboard write requires text (use "" to clear clipboard)');let n=t.slice(1).join(" ");return await e.writeClipboard(n),{action:r,textLength:Array.from(n).length,...eV("Clipboard updated")}}async function cl(e,t,r,n){let a=(t[0]??"status").toLowerCase();if(!tf(a))throw new O("INVALID_ARGS","keyboard requires a subcommand: status, get, dismiss, enter, or return");if(t.length>1)throw new O("INVALID_ARGS","keyboard accepts at most one subcommand argument");if("android"===e.platform)return await cu(e,a);if("ios"===e.platform)return await cd(e,a,r,n);throw new O("UNSUPPORTED_OPERATION","keyboard is supported only on Android and iOS")}async function cu(e,t){if("enter"===t||"return"===t)return await sx(e),{platform:"android",action:"enter",...eV("Keyboard enter pressed")};if("dismiss"===t){let t=await et(e);return{platform:"android",action:"dismiss",attempts:t.attempts,wasVisible:t.wasVisible,dismissed:t.dismissed,visible:t.visible,inputType:t.inputType,type:t.type,inputMethodPackage:t.inputMethodPackage,focusedPackage:t.focusedPackage,focusedResourceId:t.focusedResourceId,inputOwner:t.inputOwner}}let r=await eo(e);return{platform:"android",action:"status",visible:r.visible,inputType:r.inputType,type:r.type,inputMethodPackage:r.inputMethodPackage,focusedPackage:r.focusedPackage,focusedResourceId:r.focusedResourceId,inputOwner:r.inputOwner}}async function cd(e,t,r,n){if("dismiss"!==t&&"enter"!==t&&"return"!==t)throw new O("UNSUPPORTED_OPERATION","keyboard status/get is currently supported only on Android; use keyboard dismiss or enter on iOS");if("enter"===t||"return"===t){let t=await ao(e,{command:"keyboardReturn",appBundleId:r?.appBundleId},n);return{platform:"ios",action:"enter",visible:t.visible,wasVisible:t.wasVisible,...eV("Keyboard enter pressed")}}let a=await ao(e,{command:"keyboardDismiss",appBundleId:r?.appBundleId},n);return{platform:"ios",action:"dismiss",wasVisible:a.wasVisible,dismissed:a.dismissed,visible:a.visible,...eV(a.dismissed?"Keyboard dismissed":"Keyboard already hidden")}}async function cc(e,t,r,n){var a;let[i,o,s,l]=r;if(!i||!o)throw new O("INVALID_ARGS","settings requires setting state");let u="location"===i&&"set"===o,d=("permission"===i||u?r[4]:r[2])??n?.appBundleId,c="permission"===i?{permissionTarget:s,permissionMode:l}:u?{latitude:eD(s,"latitude"),longitude:eD(l,"longitude")}:void 0;eM({level:"debug",phase:"settings_apply",data:u?{setting:i,state:o,latitude:s,longitude:l,platform:e.platform}:"permission"===i?{setting:i,state:o,permissionTarget:s,permissionMode:l,platform:e.platform}:{setting:i,state:o,appBundleId:d,platform:e.platform}});let p=await t.setSetting(i,o,d,c);return p&&"object"==typeof p?eH({setting:i,state:o,...p},("string"==typeof(a=p).message&&a.message.length>0?a.message:void 0)??`Updated setting: ${i}`):{setting:i,state:o,...eV(`Updated setting: ${i}`)}}async function cp(e,t,r){let n=t[0]?.trim(),a=t[1]?.trim();if(!n||!a)throw new O("INVALID_ARGS","push requires <bundle|package> <payload.json|inline-json>");let i=await ce(a);if("ios"===e.platform)return await uq(e,n,i),{platform:"ios",bundleId:n,...eV(`Pushed notification to ${n}`)};let o=await sj(e,n,i);return{platform:"android",package:n,action:o.action,extrasCount:o.extrasCount,...eV(`Pushed notification to ${n}`)}}async function cf(e,t){return await e.snapshot({appBundleId:t?.appBundleId,interactiveOnly:t?.snapshotInteractiveOnly,compact:t?.snapshotCompact,depth:t?.snapshotDepth,scope:t?.snapshotScope,raw:t?.snapshotRaw,surface:t?.surface})}function cm(e,t,r){return{ok:!1,error:{code:e,message:t,...r?{details:r}:{}}}}function ch(e,t,r){return t||cw(r)?null:cm("INVALID_ARGS",`${e} requires an active session or an explicit device selector (e.g. --platform ios).`)}function cw(e){return!!(e?.platform||e?.target||e?.device||e?.udid||e?.serial)}function cg(e){return"ios"===e.platform&&"simulator"===e.kind}async function cy(e,t){cg(e)&&!(t<=0)&&await new Promise(e=>setTimeout(e,t))}async function cv(e){let t=cw(e.flags)||!e.session?await oy(e.flags??{}):await cI(e.session.device);return!1!==e.ensureReady&&await oK(t),t}async function cI(e){if("ios"!==e.platform||"simulator"!==e.kind||"darwin"!==process.platform)return e;let t={platform:"ios",target:e.target,udid:e.id,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}};try{return await oy(t)}catch(e){if(!(e instanceof O)||"DEVICE_NOT_FOUND"!==e.code)throw e}return await oy({platform:"ios",target:e.target,device:e.name,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}})}function cb(e){let t=e.flags?.device?.trim();return t||(e.resolvedDevice?.platform==="android"&&"emulator"===e.resolvedDevice.kind?e.resolvedDevice.name:e.sessionDevice?.platform==="android"&&"emulator"===e.sessionDevice.kind?e.sessionDevice.name:void 0)}let cA={startIosSimulatorRecording:({device:e,outPath:t})=>R("xcrun",rO(e,["io",e.id,"recordVideo",t]),{allowFailure:!0})},cS=rh(cA,function(e={}){return{...cA,...e}});async function c_(e,t){return await cS.run(e,t)}let cx=[{resolverKey:"androidAdbProvider",resolve(e,t){let r=e.androidAdbProvider;if(!r||"android"!==t.device.platform)return{};let n=r(t),a="function"==typeof n?n:n?.exec;return{androidAdb:{provider:n,executor:a,serial:t.device.id}}},appendWrapper(e,t){cD(t,e.androidAdb,(t,r)=>e5(t,{serial:e.androidAdb?.serial??""},r))}},{resolverKey:"appleRunnerProvider",resolve(e,t){let r=e.appleRunnerProvider;return r&&r1(t.device.platform)?{appleRunner:{provider:r(t),deviceId:t.device.id,requestId:t.req.meta?.requestId}}:{}},appendWrapper(e,t){cD(t,e.appleRunner,(t,r)=>aa(t,{deviceId:e.appleRunner?.deviceId??"",requestId:e.appleRunner?.requestId},r))}},{resolverKey:"appleToolProvider",resolve(e,t){let r=e.appleToolProvider;return r&&r1(t.device.platform)?{appleTool:{provider:r(t)}}:{}},appendWrapper(e,t){cD(t,e.appleTool,rx)}},{resolverKey:"linuxToolProvider",resolve(e,t){let r=e.linuxToolProvider;return r&&"linux"===t.device.platform?{linuxTool:{provider:r(t)}}:{}},appendWrapper(e,t){cD(t,e.linuxTool,oP)}},{resolverKey:"appLogProvider",resolve(e,t){let r=e.appLogProvider;return r?{appLog:{provider:r(t)}}:{}},appendWrapper(e,t){cD(t,e.appLog,iu)}},{resolverKey:"recordingProvider",resolve(e,t){let r=e.recordingProvider;return r?{recording:{provider:r(t)}}:{}},appendWrapper(e,t){cD(t,e.recording,c_)}}];async function cN(e,t){let r=await cM(e),n={androidAdbExecutor:r.androidAdb?.executor},a=function(e){let t=[];for(let r of cx)r.appendWrapper(e,t);return t}(r);return await cP(a,async()=>await t(n))}async function cM(e){var t,r,n;if(t=e.providers,!cx.some(e=>!!t[e.resolverKey]))return{};let a=await ck(e.req,e.existingSession);if(!a)return{};let i=(r=e,n=a,{req:r.req,device:n,session:r.existingSession});return cx.reduce((t,r)=>({...t,...r.resolve(e.providers,i)}),{})}async function ck(e,t){var r;return t?e.command===eP.apps&&cw(e.flags)?await oy(e.flags??{}):t.device:e.command===eP.open||cw(e.flags)||(r=e).command===eP.record&&"start"===(r.positionals?.[0]??"").toLowerCase()?await oy(e.flags??{}):void 0}function cD(e,t,r){let n=t?.provider;n&&e.push(async e=>await r(n,e))}async function cP(e,t){let r=t;for(let t of[...e].reverse()){let e=r;r=async()=>await t(e)}return await r()}let cO=e=>"macos"!==e.platform,cR=e=>"ios"===e.platform&&"simulator"===e.kind&&"tv"!==e.target,cC={device:!0},cE={},cL={apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cC},c$={apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cE,supports:cO},cT={alert:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cE,supports:e=>"android"===e.platform||"macos"===e.platform||"simulator"===e.kind},pinch:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cE,supports:e=>"android"===e.platform||"macos"===e.platform||"simulator"===e.kind&&"tv"!==e.target},"rotate-gesture":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cE,supports:e=>"android"===e.platform||cR(e)},"transform-gesture":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cE,supports:e=>"android"===e.platform||cR(e)},"app-switcher":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cE,supports:cO},open:cL,close:cL,reinstall:c$,install:c$,"install-from-source":c$,apps:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cE},back:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cC},boot:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cE,supports:cO},click:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cC},clipboard:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cC,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:cE,supports:e=>"android"===e.platform||"ios"===e.platform&&"tv"!==e.target},fill:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cC},fling:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cE},snapshot:cL,diff:cL,screenshot:cL,wait:cL,get:cL,find:cL,is:cL,focus:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cC},home:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cC,supports:cO},logs:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cE},network:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cE},longpress:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cC},perf:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cE},pan:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cC},press:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cC},push:{apple:{simulator:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cE,supports:cO},record:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cE},"react-native":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cE},rotate:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cE,supports:e=>"android"===e.platform||"ios"===e.platform&&"tv"!==e.target},scroll:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cC},swipe:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cC},settings:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cE,supports:e=>"android"===e.platform||"macos"===e.platform||"simulator"===e.kind},"trigger-app-event":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cE},type:cL};function cF(e,t){let r=cT[e];if(!r)return!0;let n=r1(t.platform)?r.apple:"linux"===t.platform?r.linux:r.android;return!!n&&(!r.supports||!!r.supports(t))&&!0===n[t.kind??"unknown"]}let cU=[250,400,600];function cV(e,t,r=e.snapshot){if("android"!==e.device.platform)return;let n=r?.comparisonSafe===!0;e.androidSnapshotFreshness={action:t,markedAt:Date.now(),baselineCount:r?.nodes.length??0,baselineSignatures:n?cB(r?.nodes??[]):void 0,routeComparable:n}}function cG(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 cq(e){e&&"android"===e.device.platform&&delete e.androidSnapshotFreshness}function cj(e){return"press"===e||"click"===e||"back"===e||"open"===e}function cB(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 cH(e,t,r,n,a){return{requestId:a??e_().requestId,appBundleId:r,activity:t?.activity,launchConsole:t?.launchConsole,launchArgs:t?.launchArgs,clearAppState:t?.clearAppState,verbose:t?.verbose,logPath:e,traceLogPath:n,snapshotInteractiveOnly:t?.snapshotInteractiveOnly,snapshotCompact:t?.snapshotCompact,snapshotDepth:t?.snapshotDepth,snapshotScope:t?.snapshotScope,snapshotRaw:t?.snapshotRaw,...eW(t),count:t?.count,intervalMs:t?.intervalMs,delayMs:t?.delayMs,holdMs:t?.holdMs,jitterPx:t?.jitterPx,pixels:t?.pixels,doubleTap:t?.doubleTap,clickButton:dR(t),backMode:t?.backMode,pauseMs:t?.pauseMs,pattern:t?.pattern}}function cW(e){e?.postGestureStabilization&&(e.postGestureStabilization=void 0)}async function cz(e){let{session:t,capture:r}=e,n=t?.postGestureStabilization;if(!t||!cK(t.device.platform)||!n)return await r();let a=Date.now(),i=1,o=await r(),s=cJ(o.nodes);for(;Date.now()-a<1500;){await e2(200),i+=1;let e=await r(),l=cJ(e.nodes);if(function(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){let n=e[r],a=t[r];if(!n||!a||n.key!==a.key||Math.abs(n.x-a.x)>1||Math.abs(n.y-a.y)>1||Math.abs(n.width-a.width)>1||Math.abs(n.height-a.height)>1)return!1}return!0}(s,l))return cW(t),eM({level:i>2?"info":"debug",phase:"post_gesture_snapshot_stabilized",data:{action:n.action,attempts:i,durationMs:Date.now()-a}}),e;o=e,s=l}return cW(t),eM({level:"warn",phase:"post_gesture_snapshot_stabilization_timeout",data:{action:n.action,attempts:i,durationMs:Date.now()-a}}),o}function cK(e){return"ios"===e||"android"===e}function cJ(e){let t=new Map,r=[];for(let i of e){var n,a;if(!i.rect||!([(n=i.rect).x,n.y,n.width,n.height].every(e=>Number.isFinite(e))&&n.width>0&&n.height>0)||(a=i,`${a.label??""} ${a.identifier??""}`.toLowerCase().includes("scroll bar")))continue;let e=[i.identifier,i.label,i.value,i.type].map(e=>"string"==typeof e?e.trim():"").join("|");if(!e.replaceAll("|",""))continue;let o=t.get(e)??0;t.set(e,o+1),r.push({key:`${e}|#${o}`,x:i.rect.x,y:i.rect.y,width:i.rect.width,height:i.rect.height})}return r}let cX=["x","y","width","height"];function cY(e,t){let r=e[t]?.depth??0,n=[];for(let a=t+1;a<e.length;a+=1){let t=e[a];if(t){if((t.depth??0)<=r)break;n.push(t)}}return n}function cZ(e,t,r){for(let n of function(e,t){let r=[],n="number"==typeof e.parentIndex?t.get(e.parentIndex):void 0,a=new Set;for(;n&&!a.has(n.index);)a.add(n.index),r.push(n),n="number"==typeof n.parentIndex?t.get(n.parentIndex):void 0;return r}(e,t))if(r(n))return n;return null}function cQ(e,t){let r=t1(e.type??""),n=e.label?.trim();return!!(c0(e)||"other"===r&&!n&&!e.value||("other"===r||"statictext"===r)&&n&&t.includes(n))||"image"===r}function c0(e){return"button"===t1(e.type??"")&&e.label?.trim()==="chevron"&&!1===e.enabled}function c1(e){let t=t1(e??"");return"collectionview"===t||"table"===t||"scrollview"===t||"scrollarea"===t}function c2(e,t,r){e.set(t.index,{...t,...e.get(t.index),...r})}function c3(e,t){return!!e&&!!t&&cX.every(r=>.5>=Math.abs(e[r]-t[r]))}function c5(e){let t;for(let a of e){var r,n;let e=t1(a.type??"");("application"===e||"window"===e)&&(r=a.rect,n=t,r&&(!n||c4(r)>c4(n)))&&(t=a.rect)}return t}function c4(e){return e?e.width*e.height:0}function c8(e){let t=t1(e.type??"");return"scrollview"===t||"scrollarea"===t}function c6(e,t){return!0===e||!!t||void 0}function c9(e,t,r){for(let n of e)(function(e,t){let r=e.label?.trim();if(!r||r!==t)return!1;let n=t1(e.type??"");return"other"===n||"statictext"===n||"link"===n})(n,t)&&r.add(n.index)}function c7(e,t,r,n){for(let a of cY(e,t))a.index!==r&&function(e){let t=t1(e.type??"");return"button"!==t&&("image"===t||"Search"===e.label)}(a)&&n.add(a.index)}function pe(e,t){for(let r=0;r<e.length;r+=1){let n=e[r],a=n?.label?.trim();n&&a&&"other"===t1(n.type??"")&&t(n,a,r)}}function pt(e,t,r,n){for(let a of e)(cQ(a,t)||n&&pn(a,n))&&r.add(a.index)}function pr(e,t,r){if("button"!==t1(e.type??""))return!1;let n=t.identifier?.trim(),a=e.identifier?.trim();return!!n&&!!a&&n===a||e.label?.trim()===r&&c3(e.rect,t.rect)}function pn(e,t){return"button"===t1(e.type??"")&&!e.label?.trim()&&!e.value?.trim()&&c3(e.rect,t.rect)}let pa=[function(e,t){var r,n,a,i;let{suppressedIndexes:o}=t;(function(e,t){let r=c5(e),n=r?r.y+r.height:null;if(null!==n)for(let r=0;r<e.length;r+=1){var a,i;let o=e[r];if(o&&(a=o,i=n,a.rect&&"keyboard"===t1(a.type??"")&&a.rect.y>=i))for(let a of(t.add(o.index),function(e,t,r,n){let a=new Map(t.map(e=>[e.index,e])),i="number"==typeof e.parentIndex?a.get(e.parentIndex):void 0;for(;i?.rect&&i.rect.y>=n;)r.add(i.index),i="number"==typeof i.parentIndex?a.get(i.parentIndex):void 0}(o,e,t,n),cY(e,r)))t.add(a.index)}})(e,o),function(e,t){for(let r of e)!("other"!==t1(r.type??"")||!0===r.hittable||r.label?.trim()||r.value?.trim())&&r.identifier?.trim()&&t.add(r.index)}(e,o);let s=new Map(e.map(e=>[e.index,e]));for(let r of e)(function(e){let t=e.label?.trim();return!!(t&&th(t))})(r)&&function(e,t,r){var n,a,i,o;c1(e.type)||r.suppressedIndexes.add(e.index);let s=tS(e.label?.trim()??"",e.value);if(!s)return;let l=function(e,t,r={}){return(!0===r.includeSelf&&c1(e.type)?e:null)??cZ(e,t,e=>c1(e.type))}(e,t,{includeSelf:!0});l&&(n=r,a=l,i=e,o=s,c2(n.replacements,a,{rect:function(e,t){if(e&&t&&!(t.height<=0)&&!(t.height>=e.height)&&!(t.y<e.y)&&!(t.y>e.y+e.height))return{...e,y:t.y,height:Math.min(t.height,e.y+e.height-t.y)}}(a.rect,i.rect)??a.rect,hiddenContentAbove:c6(a.hiddenContentAbove,o.above),hiddenContentBelow:c6(a.hiddenContentBelow,o.below)}))}(r,s,t);(function(e,t){for(let r=0;r<e.length;r+=1){let n=e[r];if(!n||"searchfield"!==t1(n.type??""))continue;if("Search"===n.label){c7(e,r,null,t);continue}if("Toolbar"!==n.label)continue;let a=cY(e,r).find(e=>"searchfield"===t1(e.type??"")&&"Search"===e.label);a&&(t.add(n.index),function(e,t,r){let n=new Map(t.map(e=>[e.index,e])),a=e;for(;"number"==typeof a.parentIndex;){let e=n.get(a.parentIndex);if(!e||"Toolbar"!==e.label)return;r.add(e.index),a=e}}(n,e,t),c7(e,r,a.index,t))}})(e,o),r=e,n=o,pe(r,(e,t,a)=>{cY(r,a).find(r=>{let n;return("button"===(n=t1(r.type??""))||"link"===n||"switch"===n||"searchfield"===n||"textfield"===n)&&r.label?.trim()===t&&(c3(r.rect,e.rect)||function(e,t){var r,n,a,i,o;let s;if(t.label?.trim()!==e.label?.trim())return!1;let l=t1(t.type??"");return r=e,n=l,s=r.label?.trim(),"button"===n&&("Dismiss"===s||"Back"===s)||"textfield"===l||(a=e,i=l,o=t,"button"===i&&!!a.rect&&!!o.rect&&0===a.rect.x&&0===a.rect.y&&a.rect.width>=300&&a.rect.height>=600&&o.rect.width<a.rect.width)}(e,r))})&&n.add(e.index)}),a=e,i=o,pe(a,(e,t,r)=>{var n;tw(t)&&(n=e.rect)&&n.x<=1&&n.y<=1&&n.width>=300&&n.height>=600&&cY(a,r).some(e=>{var r;return e.label?.trim()===t&&!!(r=e).rect&&r.rect.width>=120&&r.rect.height>=36&&r.rect.height<=180})&&i.add(e.index)}),function(e,t){for(let r=0;r<e.length;r+=1){let n=e[r],a=n?.label?.trim();!(!n||t.has(n.index))&&a&&function(e,t,r,n,a){let i=cY(e,t),o=t1(r.type??"");if("statictext"===o||"link"===o)return c9(i,n,a);if("other"===o){if(function(e,t){return e.some(e=>{let r=t1(e.type??"");return("link"===r||"searchfield"===r||c1(e.type))&&e.label?.trim()===t})}(i,n))return a.add(r.index);c9(i,n,a)}}(e,r,n,a,t)}}(e,o)},function(e,t){let r=new Map(e.map(e=>[e.index,e])),n=c5(r.values());for(let a of e)(function(e,t,r){var n;return!("other"!==t1(e.type??"")||!1===e.enabled||!e.rect||!function(e){let t=e?.trim();return!(!t||/^(toolbar|window|application)$/i.test(t)||t.startsWith("!,")||/debugger|fast refresh/i.test(t))}(e.label)||!cZ(e,t,c8)||!((n=e).rect&&n.rect.height>=44&&n.rect.height<=160&&n.rect.width>=120)||function(e,t,r=.8){let n=c4(e),a=c4(t);return n>0&&a>0&&n/a>=r}(e.rect,r))})(a,r,n)&&c2(t.replacements,a,{type:"Cell"})},function(e,t){for(let r=0;r<e.length;r+=1){let n=e[r],a=n?.label?.trim();n?.rect&&a&&function(e,t,r,n,a){let i=cY(e,t),o=t1(r.type??"");"button"===o?pt(i,n,a.suppressedIndexes,r):"cell"!==o||!function(e,t,r,n){let a=e.find(e=>(function(e,t,r){if("switch"!==t1(e.type??""))return!1;let n=t.identifier?.trim(),a=e.identifier?.trim();return!!n&&!!a&&n===a||e.label?.trim()===r})(e,t,r));if(!a)return!1;let i=e.find(e=>pr(e,t,r)),o=a.identifier?void 0:i?.identifier??t.identifier;return o&&c2(n.replacements,a,{identifier:o}),n.suppressedIndexes.add(t.index),function(e,t,r,n,a){for(let i of e)i.index!==n.index&&(pr(i,t,r)||pn(i,t)||function(e,t){if("switch"!==t1(e.type??"")||e.index===t.index)return!1;let r=e.label?.trim();return r===t.value?.trim()||"0"===r||"1"===r}(i,n)||cQ(i,r))&&a.add(i.index)}(e,t,r,a,n.suppressedIndexes),!0}(i,r,n,a)&&function(e,t,r,n){let a=e.find(e=>pr(e,t,r));if(!a){e.some(c0)&&pt(e,r,n.suppressedIndexes,t);return}!t.identifier&&a.identifier&&c2(n.replacements,t,{identifier:a.identifier}),n.suppressedIndexes.add(a.index),pt(e.filter(e=>e.index!==a.index),r,n.suppressedIndexes,t)}(i,r,n,a)}(e,r,n,a,t)}}];async function pi(e){if(("ios"===e.device.platform||"android"===e.device.platform)&&e.session?.postGestureStabilization)return{snapshot:await cz({session:e.session,capture:async()=>(await pl(e)).snapshot})};let t=cG(e.session);if(t&&"android"===e.device.platform)return await ps(e,t);let r=await po(e);return cq(e.session),{snapshot:pc(r,pu(e)),analysis:r.analysis,androidSnapshot:r.androidSnapshot}}async function po(e){let{device:t,session:r,flags:n,outPath:a,logPath:i,snapshotScope:o}=e;if("linux"===t.platform){let e=await dk(r?.surface);return pp({nodes:e.nodes,truncated:e.truncated,backend:"linux-atspi"},{snapshotDepth:n?.snapshotDepth,snapshotInteractiveOnly:n?.snapshotInteractiveOnly,snapshotScope:o})}return"macos"===t.platform&&r?.surface&&"app"!==r.surface?pp(await lJ(r.surface,{bundleId:"menubar"===r.surface?r.appBundleId:void 0}),{snapshotDepth:n?.snapshotDepth,snapshotInteractiveOnly:n?.snapshotInteractiveOnly,snapshotScope:o}):await cr(t,"snapshot",[],a,{...cH(i,{...n,snapshotScope:o},r?.appBundleId,r?.trace?.outPath)})}async function ps(e,t){let r=await pl(e),n=pd(r,t,e),a=0,i=t.markedAt+1500;for(let o of cU){if(!n)break;let s=i-Date.now();if(s<=0)break;await e2(Math.min(o,s)),r=await pl(e),a+=1,n=pd(r,t,e)}return n||cq(e.session),{snapshot:r.snapshot,analysis:r.data.analysis,androidSnapshot:r.data.androidSnapshot,freshness:a>0||n?{action:t.action,retryCount:a,staleAfterRetries:!!n,reason:n??void 0}:void 0}}async function pl(e){let t=await po(e);return{data:t,snapshot:pc(t,pu(e))}}function pu(e){return void 0===e.snapshotScope?e.flags:{...e.flags,snapshotScope:e.snapshotScope}}function pd(e,t,r){var n,a;let i=r.flags?.snapshotInteractiveOnly===!0,o=e.data.analysis;if(i&&0===e.snapshot.nodes.length&&o&&o.rawNodeCount>=12)return"empty-interactive";if("ref-refresh"===r.androidFreshnessMode)return null;return(n=t.baselineCount,a=e.snapshot.nodes.length,!(n<12)&&a<=Math.floor(.2*n))?e.snapshot.nodes.some(e=>!0===e.hittable||!!e.label?.trim()||!!e.value?.trim()||!!e.identifier?.trim())?null:"sharp-drop":t.routeComparable&&cj(t.action)&&function(e,t){if(!e||0===e.length)return!1;let r=Math.max(e.length,t.length);if(r<12)return!1;let n=cB(t),a=Math.min(e.length,n.length),i=0;for(let t=0;t<a;t+=1)e[t]===n[t]&&(i+=1);let o=Math.max(0,n.length-e.length),s=Math.max(0,e.length-n.length),l=Math.max(3,Math.floor(.15*r));return i>=Math.floor(.9*r)&&o<=l&&s<=l}(t.baselineSignatures,e.snapshot.nodes)?"stuck-route":null}function pc(e,t){var r,n,a,i;let o=e?.nodes??[],s=tx(t?.snapshotRaw?o:t3(o)),l=t?.snapshotScope&&e?.backend!=="macos-helper"?pf(s,t.snapshotScope):s;return{nodes:tG((r=e?.backend,n=t,"xctest"===r&&n?.snapshotInteractiveOnly===!0&&!0!==n.snapshotRaw)?function(e){if(0===e.length)return e;let t=new Map,r=new Set;for(let n of pa)n(e,{replacements:t,suppressedIndexes:r});if(0===r.size&&0===t.size)return e;var n=e.filter(e=>!r.has(e.index)).map(e=>t.get(e.index)??e);let a=new Map(e.map(e=>[e.index,e])),i=new Map;for(let[e,t]of n.entries())i.set(t.index,e);return n.map((e,t)=>{let n="number"==typeof e.parentIndex?i.get(e.parentIndex):void 0;return void 0===n&&"number"==typeof e.parentIndex&&(n=function(e,t,r,n){let a=e,i=new Set;for(;"number"==typeof a&&!i.has(a);){if(i.add(a),!t.has(a))return n.get(a);a=r.get(a)?.parentIndex}}(e.parentIndex,r,a,i)),{...e,index:t,parentIndex:n}})}(l):l),truncated:e?.truncated,createdAt:Date.now(),backend:e?.backend,presentationKey:tU(t$(t)),comparisonSafe:(a=e?.backend,i=t,"android"===a&&i?.snapshotInteractiveOnly!==!0&&i?.snapshotCompact!==!0&&"number"!=typeof i?.snapshotDepth&&!i?.snapshotScope)}}function pp(e,t){var r,n;let a=e.nodes??[];return t.snapshotScope&&(a=pf(a,t.snapshotScope)),t.snapshotInteractiveOnly&&(a=function(e){if(0===e.length)return e;let t=new Map;for(let r of e)t.set(r.index,r);let r=new Set;for(let n of e){if(!function(e){if(e.focused||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")}(n))continue;let e=n;for(;e&&!r.has(e.index);)r.add(e.index),e="number"==typeof e.parentIndex?t.get(e.parentIndex):void 0}return 0===r.size?e:pm(e.filter(e=>r.has(e.index)))}(a)),"number"==typeof t.snapshotDepth&&(r=a,n=t.snapshotDepth,a=pm(r.filter(e=>(e.depth??0)<=n))),{...e,nodes:a}}function pf(e,t){let r=tJ(tG(e),t);if(!r)return[];let n=e.findIndex(e=>e.index===r.index);if(-1===n)return[];let a=e[n]?.depth??0,i=[];for(let t=n;t<e.length;t+=1){let r=e[t];if(!r)continue;let o=r.depth??0;if(t>n&&o<=a)break;i.push(r)}return pm(i,a)}function pm(e,t=0){let r=new Map;for(let[t,n]of e.entries())r.set(n.index,t);return e.map((e,n)=>({...e,index:n,depth:Math.max(0,(e.depth??0)-t),parentIndex:"number"==typeof e.parentIndex?r.get(e.parentIndex):void 0}))}function ph(e,t){e.snapshot=t,e.snapshotScopeSource=void 0}function pw(e){return{get:t=>t===e.sessionName?function(e,t,r={}){if(e)return{name:t,appBundleId:e.appBundleId,appName:e.appName,...!0===r.includeSnapshot?{snapshot:e.snapshot}:{},metadata:{surface:e.surface,...r.metadata??{}}}}(e.getSession(),e.sessionName,e.recordOptions):void 0,set:t=>{t.name!==e.sessionName?eM({level:"warn",phase:"runtime_session_write_skipped",data:{expected:e.sessionName,received:t.name}}):e.setRecord(t)}}}async function pg(e){let{session:t,sessionName:r,outPath:n,outputPlacement:a,dispatchContext:i}=e,o=tM({backend:function(e){let{session:t,outputPlacement:r,dispatchContext:n}=e;return{platform:t.device.platform,captureScreenshot:async(e,a,i)=>{let o={...n,...eW(i),surface:i?.surface};return"out"===r?py(await cr(t.device,"screenshot",[],a,o)):py(await cr(t.device,"screenshot",[a],void 0,o))}}}({session:t,outputPlacement:a,dispatchContext:i}),artifacts:{resolveInput:async()=>{throw new O("UNSUPPORTED_OPERATION","screenshot does not resolve input artifacts")},reserveOutput:async e=>{let t,r;return e?.kind==="path"?r=e.path:(t=await d.mkdtemp(f.join(c.tmpdir(),"agent-device-screenshot-")),r=f.join(t,"screenshot.png")),await d.mkdir(f.dirname(r),{recursive:!0}),{path:r,visibility:"client-visible",publish:async()=>void 0,...t?{cleanup:async()=>{await d.rm(t,{recursive:!0,force:!0})}}:{}}},createTempFile:async e=>{let t=await d.mkdtemp(f.join(c.tmpdir(),`${e.prefix}-`));return{path:f.join(t,`file${e.ext}`),visibility:"internal",cleanup:async()=>{await d.rm(t,{recursive:!0,force:!0})}}}},sessions:pw({sessionName:r,getSession:()=>t,recordOptions:{includeSnapshot:!1},setRecord:()=>{}}),policy:tO()});return await o.capture.screenshot({session:r,requestId:i.requestId,appBundleId:t.appBundleId,...eU(i),surface:t.surface,...n?{out:{kind:"path",path:n}}:{}})}function py(e){if("object"==typeof e&&null!==e)return{..."string"==typeof e.path?{path:e.path}:{},...Array.isArray(e.overlayRefs)?{overlayRefs:e.overlayRefs}:{}}}let pv=/\bis(?:n(?:'|&apos;|&#39;)?t| not)\s+responding\b/i,pI=/^close app$/i,pb="Wait for Android to recover, close the dialog, restart the app, or reboot the emulator, then retry.";async function pA(e){let{session:t}=e;if("android"!==t.device.platform||!t.recording)return"absent";try{let e=await pk(t),r=pP(e);if(!r?.rect)return"absent";let n=await pD(t,r);if(!n.ok)return eM({level:"warn",phase:"android_blocking_dialog_tap_failed",data:{session:t.name,deviceId:t.device.id,exitCode:n.exitCode,stdout:n.stdout.trim(),stderr:n.stderr.trim()}}),"failed";if(!await pO(t))return eM({level:"warn",phase:"android_blocking_dialog_still_present",data:{session:t.name,deviceId:t.device.id}}),"failed";if(t.appBundleId&&(await H(t.device,t.appBundleId),!await pR(t,t.appBundleId)))return eM({level:"warn",phase:"android_blocking_dialog_relaunch_unfocused",data:{session:t.name,deviceId:t.device.id,appBundleId:t.appBundleId}}),"failed";return eM({level:"warn",phase:"android_blocking_dialog_recovered",data:{session:t.name,deviceId:t.device.id,appBundleId:t.appBundleId,x:n.x,y:n.y}}),"recovered"}catch(e){return eM({level:"warn",phase:"android_blocking_dialog_recovery_failed",data:{session:t.name,deviceId:t.device.id,error:e instanceof Error?e.message:String(e)}}),"failed"}}async function pS(e){var t,r;let{session:n,command:a}=e;if("android"!==n.device.platform)return{status:"clear"};let i=await F(n.device);if(!i)return{status:"clear"};if(t=n,r=i,t.appBundleId&&r.package===t.appBundleId){if(await p_(n)){let t=`Recovered Android app ANR before ${a}: closed and relaunched ${n.appBundleId}.`;if("before-command"===e.phase)return{status:"recovered",warning:t};throw pN({session:n,command:a,focus:i,message:`Android app ANR appeared after ${a}; ${n.appBundleId} was closed and relaunched. Retry the command against the fresh app session.`,hint:"Retry the command. If the ANR returns, inspect app logs or restart the emulator."})}throw pN({session:n,command:a,focus:i,message:`Android app ANR blocked ${a}: ${pM(i)}. Automatic recovery failed.`,hint:pb})}throw pN({session:n,command:a,focus:i,message:`Android system dialog is blocking ${a}: ${pM(i)}.`,hint:pb})}async function p_(e){try{return await px(e)}catch(t){return eM({level:"warn",phase:"android_app_anr_recovery_failed",data:{session:e.name,deviceId:e.device.id,appBundleId:e.appBundleId,error:t instanceof Error?t.message:String(t)}}),!1}}async function px(e){if(!e.appBundleId)return!1;let t=pP(await pk(e),{requireDialogSignal:!1});if(!t?.rect)return!1;let r=await pD(e,t);if(!r.ok)return!1;await H(e.device,e.appBundleId);let n=await pR(e,e.appBundleId,{requireNoBlockingDialog:!0});return n&&eM({level:"warn",phase:"android_app_anr_recovered",data:{session:e.name,deviceId:e.device.id,appBundleId:e.appBundleId,x:r.x,y:r.y}}),n}function pN(e){let{session:t,command:r,focus:n,message:a,hint:i}=e;return new O("COMMAND_FAILED",a,{command:r,expectedPackage:t.appBundleId,focusedPackage:n.package,focusedWindow:n.focusedWindow,rawFocus:n.raw,hint:i})}function pM(e){return e.package?`${e.focusedWindow} (package ${e.package})`:e.focusedWindow}async function pk(e){return tG(t3((await o6(e.device,{interactiveOnly:!1,compact:!1})).nodes))}async function pD(e,t){if(!t.rect)return{ok:!1,exitCode:1,stdout:"",stderr:"button has no rect"};let{x:r,y:n}=tV(t.rect),a=await Q(e.device,["shell","input","tap",String(Math.round(r)),String(Math.round(n))],{allowFailure:!0});return 0!==a.exitCode?{ok:!1,exitCode:a.exitCode,stdout:a.stdout.trim(),stderr:a.stderr.trim()}:{ok:!0,x:r,y:n}}function pP(e,t={}){if(!1===t.requireDialogSignal||pL(e))return e.find(e=>pE(e).some(e=>pI.test(e))&&e.rect)}async function pO(e){for(let t=0;t<12;t+=1){if(!pL(await pk(e)))return!0;await e2(500)}return!pL(await pk(e))}async function pR(e,t,r={}){for(let n=0;n<12;n+=1){if(await pC(e,t,r))return!0;await e2(500)}return await pC(e,t,r)}async function pC(e,t,r){return!(r.requireNoBlockingDialog&&await F(e.device))&&(await eu(e.device)).package===t}function pE(e){let t=[e.label,e.identifier];return"string"==typeof e.value&&e.value.trim().length>0&&t.push(e.value),t.filter(e=>"string"==typeof e&&e.trim().length>0).map(e=>e.trim())}function pL(e){return e.some(e=>{let t=pE(e).join(" ").trim();return t.length>0&&pv.test(t)})}function p$(e){return!!(e&&e.width>0&&e.height>0)}function pT(e){return e.width*e.height}function pF(e,t){return t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height}let pU=[255,59,48,255],pV=[255,214,10,255],pG=[0,0,0,255],pq=["scroll","list","recyclerview","edittext","textfield"],pj=["button","link","menu","tab","textfield","searchfield","securetextfield","checkbox","radio","switch","cell"],pB={e:["01110","10000","11110","10000","10000","10001","01110"],0:["01110","10001","10011","10101","11001","10001","01110"],1:["00100","01100","00100","00100","00100","00100","01110"],2:["01110","10001","00001","00010","00100","01000","11111"],3:["11110","00001","00001","01110","00001","00001","11110"],4:["00010","00110","01010","10010","11111","00010","00010"],5:["11111","10000","10000","11110","00001","00001","11110"],6:["01110","10000","10000","11110","10001","10001","01110"],7:["11111","00001","00010","00100","01000","01000","01000"],8:["01110","10001","10001","01110","10001","10001","01110"],9:["01110","10001","10001","01111","00001","00001","01110"]};async function pH(e){let t=tC(await d.readFile(e.screenshotPath),"screenshot"),r=function(e,t,r,n={}){let a=function(e){let t=null;for(let r of e)pz(r)&&p$(r.rect)&&(!t||pT(r.rect)>pT(t))&&(t=r.rect);return t||function(e){let t=1/0,r=1/0,n=-1/0,a=-1/0;for(let i of e)i.rect&&p$(i.rect)&&(t=Math.min(t,i.rect.x),r=Math.min(r,i.rect.y),n=Math.max(n,i.rect.x+i.rect.width),a=Math.max(a,i.rect.y+i.rect.height));return!Number.isFinite(t)||!Number.isFinite(r)||n<=t||a<=r?null:{x:t,y:r,width:n-t,height:a-r}}(e.filter(e=>{var t;return p$(e.rect)&&!("image"===t1((t=e).type??"")&&!pJ(t.label))}))}(e.nodes),i=new Map;for(let n of e.nodes){var o,s;if(!function(e,t,r){let n=[r.label,r.value].some(pX)||pY(r.identifier);return!!function(e,t,r){if("android"!==e.backend||!r.hittable||!p$(r.rect)||pz(r))return!1;let n=t1(r.type??"");return!(pq.some(e=>n.includes(e))||t&&pT(r.rect)>.25*pT(t))}(e,t,r)||(pW(r)?n:n&&function(e){let t=t1(e.type??"");return t.includes("statictext")||t.includes("image")||t.includes("text")||t.includes("other")}(r))}(e,a,n))continue;let l=(o=e.nodes,[function(e){return pW(e)&&!pz(e)}(s=n)?s:null,tZ(o,s,e=>(function(e){return pW(e)&&!pz(e)})(e)),s.hittable?s:null,tZ(o,s,e=>!0===e.hittable)].find(pK)??null);if(!l?.rect||!p$(l.rect))continue;let u=function(e,t,r){let n=pZ(e);if(e.ref!==t.ref&&n)return n;let a=function(e,t){let r=null;for(let n of t){if(n.ref===e.ref||!function(e,t,r){let n=e;for(;void 0!==n.parentIndex;){let e=r[n.parentIndex];if(!e)break;if(e.ref===t.ref)return!0;n=e}return!1}(n,e,t))continue;let a=pZ(n);if(!a)continue;let i=function(e){let t=0;return t1(e.type??"").includes("text")&&(t+=2),pX(e.label)&&(t+=2),pX(e.value)&&(t+=1),t}(n);(!r||i>r.score)&&(r={label:a,score:i})}return r?.label}(t,r);return a||pZ(t)}(n,l,e.nodes),d=function(e,t,r){let n=0;return e.ref===t.ref&&(n+=4),t.hittable&&(n+=3),pW(t)&&(n+=3),pW(e)&&(n+=2),r&&(n+=2),pY(t.identifier)&&(n+=1),pJ(t.value)&&(n+=1),n}(n,l,u),c=function(e,t,r){var n,a;return"android"!==e.backend?t.rect:(n=pW,a=e=>!!pZ(e),(!t.rect||!0!==t.hittable||n(t)||a(t)?null:function(e,t,r){let n=e.rect,a=function(e,t,r){let n=e.rect,a=new Map(t.map(e=>[e.index,e])),i=t.filter(t=>t.ref!==e.ref&&function(e,t,r){let n=e;for(;void 0!==n.parentIndex;){let e=r.get(n.parentIndex);if(!e)break;if(e.ref===t.ref)return!0;n=e}return!1}(t,e,a)&&function(e,t){let r=t1(e.type??"");return r.includes("text")||r.includes("image")&&t(e)}(t,r)&&p$(t.rect)&&pF(n,t.rect)).map(e=>e.rect);return i.length<2?null:function(e){let t=e[0];if(void 0===t)throw Error("unionRects requires at least one rect");let r=t.x,n=t.y,a=t.x+t.width,i=t.y+t.height;for(let t of e.slice(1))r=Math.min(r,t.x),n=Math.min(n,t.y),a=Math.max(a,t.x+t.width),i=Math.max(i,t.y+t.height);return{x:r,y:n,width:a-r,height:i-n}}(i)}(e,t,r);if(!a)return null;let i=a.y-n.y,o=n.y+n.height-(a.y+a.height);if(i<0||o<0||16>Math.abs(o-i))return null;let s=Math.min(i,o),l=Math.round(a.y-s),u=Math.round(a.height+2*s);return u<=0||u>=n.height?null:{x:n.x,y:l,width:n.width,height:u}}(t,r,a))??t.rect)}(e,l,e.nodes),p=function(e,t,r,n,a){if("android"===e.backend||!t)return pQ(function(e){return{x:Math.round(e.x),y:Math.round(e.y),width:Math.round(e.width),height:Math.round(e.height)}}(r),n,a);let i=n/t.width,o=a/t.height;return pQ({x:Math.round((r.x-t.x)*i),y:Math.round((r.y-t.y)*o),width:Math.max(1,Math.round(r.width*i)),height:Math.max(1,Math.round(r.height*o))},n,a)}(e,a,c,t,r);if(!p$(p))continue;let f=i.get(l.ref);(!f||d>f.score)&&i.set(l.ref,{ref:l.ref,label:u,rect:l.rect,overlayRect:p,score:d})}return(function(e){let t=[];for(let r of e.sort((e,t)=>pT(e.overlayRect)-pT(t.overlayRect))){let e=t.findIndex(e=>void 0!==e.label&&e.label===r.label&&(pF(e.overlayRect,r.overlayRect)||pF(r.overlayRect,e.overlayRect)));if(-1===e){t.push(r);continue}pT(r.overlayRect)<pT(t[e].overlayRect)&&(t[e]=r)}return t})([...i.values()]).sort(p4).slice(0,n.maxRefs??24).sort(p5).map(e=>({ref:e.ref,label:e.label,rect:e.rect,overlayRect:e.overlayRect,center:tV(e.overlayRect)}))}(e.snapshot,t.width,t.height,{maxRefs:e.maxRefs});for(let e of r){var n,a;(function(e,t,r){for(let n=0;n<2;n+=1)p1(e,t.x,t.x+t.width-1,t.y+n,r),p1(e,t.x,t.x+t.width-1,t.y+t.height-1-n,r),p2(e,t.x+n,t.y,t.y+t.height-1,r),p2(e,t.x+t.width-1-n,t.y,t.y+t.height-1,r)})(n=t,(a=e).overlayRect,pU),function(e,t,r){let n=6+5*r.length+ +Math.max(0,r.length-1),a=p0(t.x,0,Math.max(0,e.width-n)),i=t.y-11-2,o=i>=0?i:p0(t.y+2,0,Math.max(0,e.height-11));(function(e,t,r,n,a){for(let i=0;i<11;i+=1)for(let o=0;o<n;o+=1)p3(e,t+o,r+i,a)})(e,a,o,n,pV),function(e,t,r,n,a){let i=t;for(let t of n.toLowerCase()){let n=pB[t];if(n)for(let t=0;t<n.length;t+=1)for(let o=0;o<n[t].length;o+=1)"1"===n[t][o]&&p3(e,i+o,r+t,a);i+=6}}(e,a+3,o+2,r,pG)}(n,a.overlayRect,a.ref)}return await d.writeFile(e.screenshotPath,_.sync.write(t)),r}function pW(e){let t=[e.type,e.role,e.subrole].map(e=>t1(e??"")).join(" ");return pj.some(e=>t.includes(e))}function pz(e){let t=[e.type,e.role,e.subrole].map(e=>t1(e??"")).join(" ");return t.includes("application")||t.includes("window")}function pK(e){return!!(e?.rect&&p$(e.rect)&&!pz(e))}function pJ(e){if("string"!=typeof e)return!1;let t=e.trim();return!(!t||/^(true|false)$/i.test(t))}function pX(e){var t;let r;return!!pJ(e)&&(t=e,"toolbar"!==(r=t?.trim().toLowerCase())&&"window"!==r&&"application"!==r&&r?.startsWith("vertical scroll bar")!==!0)}function pY(e){var t;return"string"==typeof e&&!!pX(e)&&(t=e,!/^[a-z0-9_.]+:id\/[a-z0-9_.-]+$/i.test(t.trim()))}function pZ(e){let t=[e.label,e.value].find(pX);return t?t.trim():pY(e.identifier)?e.identifier.trim():void 0}function pQ(e,t,r){let n=p0(e.x,0,Math.max(0,t-1)),a=p0(e.y,0,Math.max(0,r-1)),i=Math.max(1,t-n),o=Math.max(1,r-a);return{x:n,y:a,width:p0(e.width,1,i),height:p0(e.height,1,o)}}function p0(e,t,r){return Number.isFinite(e)?Math.max(t,Math.min(r,e)):t}function p1(e,t,r,n,a){for(let i=t;i<=r;i+=1)p3(e,i,n,a)}function p2(e,t,r,n,a){for(let i=r;i<=n;i+=1)p3(e,t,i,a)}function p3(e,t,r,n){if(t<0||r<0||t>=e.width||r>=e.height)return;let a=(e.width*r+t)*4;e.data[a]=n[0],e.data[a+1]=n[1],e.data[a+2]=n[2],e.data[a+3]=n[3]}function p5(e,t){var r,n;let a=e.overlayRect.y-t.overlayRect.y;if(0!==a)return a;let i=e.overlayRect.x-t.overlayRect.x;return 0!==i?i:(r=e.ref,n=t.ref,Number.parseInt(r.replace(/^\D+/,""),10)-Number.parseInt(n.replace(/^\D+/,""),10))}function p4(e,t){return t.score!==e.score?t.score-e.score:p5(e,t)}function p8(e){return"number"==typeof e.gestureClockOriginAtMs&&"number"==typeof e.gestureClockOriginUptimeMs&&"number"==typeof e.gestureStartUptimeMs?Math.max(0,e.gestureClockOriginAtMs+(e.gestureStartUptimeMs-e.gestureClockOriginUptimeMs)-e.recordingStartedAt):"number"==typeof e.runnerStartedAtUptimeMs&&"number"==typeof e.gestureStartUptimeMs?Math.max(0,e.gestureStartUptimeMs-e.runnerStartedAtUptimeMs):"number"==typeof e.gestureStartUptimeMs&&"number"==typeof e.gestureEndUptimeMs?Math.max(0,e.fallbackFinishedAtMs-(e.gestureEndUptimeMs-e.gestureStartUptimeMs)-e.recordingStartedAt):Math.max(0,e.fallbackStartedAtMs-e.recordingStartedAt)}let p6=new WeakMap;function p9(e){if(!e)return;let t=p6.get(e);if(t)return t;let r=function(e){let t=function(e){let t=e.filter(e=>(function(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("application")||t.includes("window")})(e.type)&&p7(e.rect)).map(e=>e.rect).sort((e,t)=>(t?.width??0)*(t?.height??0)-(e?.width??0)*(e?.height??0))[0];if(t)return t;let r=e.map(e=>e.rect).filter(p7);if(0===r.length)return;let n=Math.max(...r.map(e=>e.x+e.width)),a=Math.max(...r.map(e=>e.y+e.height));if(!(n<=0)&&!(a<=0))return{x:0,y:0,width:n,height:a}}(e);if(t)return{referenceWidth:t.width,referenceHeight:t.height}}(e.nodes??[]);if(r)return p6.set(e,r),r}function p7(e){return!!e&&e.width>0&&e.height>0}let fe={referenceWidth:1e3,referenceHeight:1e3};function ft(e,t,r,n,a={},i=Date.now(),o=Date.now()){var s,l,u,d,c,p,f,m,h;let w,g,y,v=e.recording;if(!v)return;let I={...a,...n??{}},b=fu(I.effectiveDurationMs)??fu(I.durationMs),A={recordingStartedAt:v.startedAt,gestureClockOriginAtMs:v.gestureClockOriginAtMs,gestureClockOriginUptimeMs:v.gestureClockOriginUptimeMs,runnerStartedAtUptimeMs:"ios-device-runner"===v.platform?v.runnerStartedAtUptimeMs:void 0,gestureStartUptimeMs:fu(I.gestureStartUptimeMs),gestureEndUptimeMs:fu(I.gestureEndUptimeMs),fallbackStartedAtMs:i,fallbackFinishedAtMs:o},S="number"==typeof(s={gestureStartUptimeMs:fu(I.gestureStartUptimeMs),gestureEndUptimeMs:fu(I.gestureEndUptimeMs),reportedDurationMs:b,fallbackStartedAtMs:i,fallbackFinishedAtMs:o}).gestureStartUptimeMs&&"number"==typeof s.gestureEndUptimeMs?Math.max(0,s.gestureEndUptimeMs-s.gestureStartUptimeMs):"number"==typeof s.reportedDurationMs?Math.max(0,s.reportedDurationMs):Math.max(0,s.fallbackFinishedAtMs-s.fallbackStartedAtMs),_="ios"===e.device.platform&&void 0===fu(I.gestureStartUptimeMs)&&function(e,t){switch(e){case"click":case"fill":case"focus":return!0;case"press":{let e=fd(fu(t.count),1)??1,r=!0===t.doubleTap,n=fd(fu(t.holdMs),1);return 1===e&&!r&&void 0===n}case"react-native":return"dismiss-overlay"===t.action;default:return!1}}(t,I)?function(e){let t=Math.max(0,e.gestureDurationMs);if(t<600)return p8(e);let r=Math.min(Math.max(.15*t,120),260);return Math.max(0,e.fallbackFinishedAtMs-r-e.recordingStartedAt)}({...A,gestureDurationMs:S}):p8(A),x=(l=e.snapshot,w=fu((u=I).referenceWidth),g=fu(u.referenceHeight),void 0!==w&&w>0&&void 0!==g&&g>0?{referenceWidth:w,referenceHeight:g}:p9(l)),N=(d=t,c=r,p=I,f=_,m=S,h=x,y=fr[d],y?.(c,p,f,m,h)??[]);0!==N.length&&(v.gestureEvents.push(...N),eM({level:"debug",phase:"record_touch_visualization_event",data:{session:e.name,command:t,count:N.length,tMs:_,gestureDurationMs:S,kinds:N.map(e=>e.kind)}}))}let fr={click:(e,t,r,n,a)=>fn(e,t,r,a),press:(e,t,r,n,a)=>fn(e,t,r,a),"react-native":(e,t,r,n,a)=>"dismiss-overlay"===e[0]?fn(e,t,r,a):[],fill:(e,t,r,n,a)=>fa(e,t,r,a),focus:(e,t,r,n,a)=>fa(e,t,r,a),longpress:function(e,t,r,n,a){let i=fc(t,e);if(!i)return[];let{x:o,y:s}=i;return[fs(r,o,s,fm(n,[fu(t.durationMs),fu(e[2])],800),a)]},scroll:function(e,t,r,n,a){let i=fp(t,e),o=fl(t.contentDirection)??fl(t.direction);if(!i||!o)return[];let{x1:s,y1:l,x2:u,y2:d}=i,c=fm(n,[],250),p=fu(t.amount)??fu(e[1]),f=fu(t.pixels);return[{kind:"scroll",tMs:r,x:s,y:l,x2:u,y2:d,...a,durationMs:c,contentDirection:o,...void 0!==p?{amount:p}:{},...void 0!==f?{pixels:f}:{}}]},pan:fi,fling:fi,swipe:fi,pinch:function(e,t,r,n,a){let i=fc(t,e,1),o=fu(t.scale)??fu(e[0]);if(!i||void 0===o||o<=0)return[];let{x:s,y:l}=i;return[{kind:"pinch",tMs:r,x:s,y:l,...a,scale:o,durationMs:fm(n,[],280)}]}};function fn(e,t,r,n){let a=fc(t,e);if(!a)return[];let{x:i,y:o}=a,s=fd(fu(t.count),1)??1,l=fd(fu(t.intervalMs),0)??0,u=!0===t.doubleTap,d=fd(fu(t.holdMs),1),c=[];for(let e=0;e<s;e+=1){let t=r+e*l;if(void 0!==d&&d>0){c.push(fs(t,i,o,d,n));continue}c.push(fo(t,i,o,n)),u&&c.push(fo(t+90,i,o,n))}return c}function fa(e,t,r,n){let a=fc(t,e);if(!a)return[];let{x:i,y:o}=a;return[fo(r,i,o,n)]}function fi(e,t,r,n,a){let i=fp(t,e);if(!i)return[];let{x1:o,y1:s,x2:l,y2:u}=i,d=fm(n,[fu(t.effectiveDurationMs),fu(t.durationMs),fu(e[4])],250),c=fd(fu(t.count),1)??1,p=fd(fu(t.pauseMs),0)??0,f="ping-pong"===t.pattern?"ping-pong":"one-way";return Array.from({length:c},(e,t)=>{var n,i,c,m,h,w,g,y,v,I,b,A,S;let _,{startX:x,startY:N,endX:M,endY:k}=(n=t,i=f,c=o,m=s,h=l,w=u,"ping-pong"===i&&n%2==1?{startX:h,startY:w,endX:c,endY:m}:{startX:c,startY:m,endX:h,endY:w});return g=r+t*(d+p),y=x,v=N,I=M,b=k,A=d,"back-swipe"===(_=function(e,t,r,n,a){if(!a||Math.abs(r-e)<=1.25*Math.abs(n-t))return"swipe";let i=.08*a.referenceWidth;return e<=i&&r>e||e>=a.referenceWidth-i&&r<e?"back-swipe":"swipe"}(y,v,I,b,S=a))?{kind:_,tMs:g,x:y,y:v,x2:I,y2:b,...S,durationMs:A,edge:function(e,t,r){if(r){let t=.08*r.referenceWidth;if(e<=t)return"left";if(e>=r.referenceWidth-t)return"right"}return t>=e?"left":"right"}(y,I,S)}:{kind:_,tMs:g,x:y,y:v,x2:I,y2:b,...S,durationMs:A}})}function fo(e,t,r,n){return{kind:"tap",tMs:e,x:t,y:r,...n}}function fs(e,t,r,n,a){return{kind:"longpress",tMs:e,x:t,y:r,...a,durationMs:n}}function fl(e){if("string"!=typeof e)return;let t=e.trim().toLowerCase();switch(t){case"up":case"down":case"left":case"right":return t;default:return}}function fu(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"!=typeof e||0===e.trim().length)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function fd(e,t){if(void 0===e)return;let r=Math.floor(e);return r>=t?r:void 0}function fc(e,t,r=0){let n=fu(e.x)??fu(t[r]),a=fu(e.y)??fu(t[r+1]);if(void 0!==n&&void 0!==a)return{x:n,y:a}}function fp(e,t){let r=ff(e.x1,e.x,t[0]),n=ff(e.y1,e.y,t[1]),a=ff(e.x2,t[2]),i=ff(e.y2,t[3]);if(void 0!==r&&void 0!==n&&void 0!==a&&void 0!==i)return{x1:r,y1:n,x2:a,y2:i}}function ff(...e){return e.map(fu).find(e=>void 0!==e)}function fm(e,t,r){return fd(e,1)??t.map(e=>fd(e,1)).find(e=>void 0!==e)??r}let fh={pan:"pan",fling:"fling",pinch:"pinch",rotate:"rotate-gesture",transform:"transform-gesture"};async function fw(e){var t,r,n,a,i,o,s,l;let u,d,c,p,f,{req:m,session:h,logPath:w,sessionStore:g,contextFromFlags:y}=e,v=function(e){if("pan"===e.command||"fling"===e.command||"rotate-gesture"===e.command||"transform-gesture"===e.command)return{ok:!1,message:"Use gesture pan, gesture fling, gesture rotate, or gesture transform."};if("gesture"!==e.command)return{ok:!0,platformCommand:e.command,dispatchRequest:e,recordedCommand:e.command};let[t,...r]=e.positionals??[],n=t?fh[t]:void 0;return n?{ok:!0,platformCommand:n,dispatchRequest:{...e,command:n,positionals:r},recordedCommand:e.command}:{ok:!1,message:eB}}(m);if(!v.ok)return{ok:!1,error:{code:"INVALID_ARGS",message:v.message}};let{platformCommand:I,dispatchRequest:b,recordedCommand:A}=v,S=await fy(h,I);if(S)return S;let _=await fg(h,I);if("response"in _)return _.response;let{resolvedPositionals:x,resolvedOut:N,recordedPositionals:M,recordedFlags:k}="screenshot"===(t=b).command?(d=(n=(r=t).positionals??[],a=r.meta?.cwd,(u=n[0])?[aE.expandHome(u,a),...n.slice(1)]:n),p=(c=(i=r.flags?.out,o=r.meta?.cwd,i?aE.expandHome(i,o):i))?{...r.flags??{},out:c}:r.flags??{},{resolvedPositionals:d,resolvedOut:c,recordedPositionals:d,recordedFlags:p}):{resolvedPositionals:f=(s=t).positionals??[],resolvedOut:s.flags?.out,recordedPositionals:f,recordedFlags:s.flags??{}},D=Date.now(),P={...y(m.flags,h.appBundleId,h.trace?.outPath),surface:h.surface},O=await fv({session:h,sessionName:e.sessionName,logPath:w,command:I,request:b,positionals:x,out:N,dispatchContext:P}),R=await fg(h,I,"after-command");if("response"in R)return R.response;"status"in _&&"recovered"===_.status&&(!O||"object"==typeof O)&&((O??={}).warning=_.warning);let C=Date.now(),E=A===I?M:m.positionals??[],L=A===I?k:m.flags??{};return function(e){let{session:t,sessionStore:r,command:n,recordedCommand:a,resolvedPositionals:i,recordedPositionals:o,recordedFlags:s,data:l,actionStartedAt:u,actionFinishedAt:d,flags:c}=e,p=function(e,t,r,n){if("scroll"!==t)return n;let a=p9(e.snapshot),i={...n??{}},o=fl(i.direction)??fl(r[0]);if(!o)return n;let s=fu(i.amount)??fu(r[1]),l=fu(i.pixels),u=fp(i,[]),d=fu(i.referenceWidth),c=fu(i.referenceHeight),p=void 0!==d&&d>0&&void 0!==c&&c>0?{referenceWidth:d,referenceHeight:c}:a??fe;if(u&&(u.x1!==u.x2||u.y1!==u.y2))return{...i,x1:u.x1,y1:u.y1,x2:u.x2,y2:u.y2,contentDirection:o,...void 0!==s?{amount:s}:{},...void 0!==l?{pixels:l}:{},referenceWidth:p.referenceWidth,referenceHeight:p.referenceHeight,durationMs:250};let f=oQ({direction:o,amount:s,pixels:l,referenceWidth:p.referenceWidth,referenceHeight:p.referenceHeight});return{...i,x1:f.x1,y1:f.y1,x2:f.x2,y2:f.y2,contentDirection:o,...void 0!==s?{amount:s}:{},...void 0!==f.pixels?{pixels:f.pixels}:{},referenceWidth:p.referenceWidth,referenceHeight:p.referenceHeight,durationMs:250}}(t,n,i,l);ft(t,n,i,p,c,u,d),r.recordAction(t,{command:a,positionals:o,flags:s,result:l??{}})}({session:h,sessionStore:g,command:I,recordedCommand:A,resolvedPositionals:x,recordedPositionals:E,recordedFlags:L,data:O,actionStartedAt:D,actionFinishedAt:C,flags:m.flags??{}}),cj(I)&&cV(h,I),cK(h.device.platform)&&("swipe"===(l=I)||"scroll"===l)&&(h.postGestureStabilization={action:I,markedAt:Date.now()}),{ok:!0,data:O??{}}}async function fg(e,t,r="before-command"){if("android"!==e.device.platform||!ek.androidBlockingDialogGuardedAction.has(t))return{status:"clear"};try{return await pS({session:e,command:t,phase:r})}catch(e){return{response:{ok:!1,error:P(e)}}}}async function fy(e,t){return cF(t,e.device)?"android"===e.device.platform&&e.recording&&"record"!==t&&await pA({session:e})==="failed"?{ok:!1,error:{code:"COMMAND_FAILED",message:"Android system dialog blocked the recording session"}}:null:{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:`${t} is not supported on this device`}}}async function fv(e){var t;let{session:r,command:n,request:a,positionals:i,out:o,dispatchContext:s}=e;if("screenshot"!==n)return await cr(r.device,n,i,o,{...s});let l=await pg({session:r,sessionName:e.sessionName,outPath:i[0]??o,outputPlacement:"screenshot"!==(t=a).command?"default":(t.positionals??[])[0]?"positional":t.flags?.out?"out":"default",dispatchContext:s});return a.flags?.overlayRefs&&"string"==typeof l?.path&&await fI(r,l,e.logPath),l}async function fI(e,t,r){let n={snapshotInteractiveOnly:!0,snapshotCompact:!0},a=pc(await po({device:e.device,session:e,flags:n,logPath:r,snapshotScope:void 0}),n);ph(e,a);let i=await pH({screenshotPath:t.path,snapshot:a});t.overlayRefs=i}async function fb(e){let{device:t,node:r,flags:n,appBundleId:a,traceOutPath:i,surface:o,contextFromFlags:s}=e,l=tz(r),u=tI(r.rect);if(!u)return l;try{let e=await cr(t,"read",[String(u.x),String(u.y)],void 0,{...s(n,a,i),surface:o}),d=e&&"object"==typeof e?e:void 0,c="string"==typeof d?.text?d.text:"";if(c.trim())return c;return eM({level:"warn",phase:"interaction_read_fallback",data:{reason:"empty_backend_text",nodeRef:r.ref,surface:o,platform:t.platform}}),l}catch(e){return eM({level:"warn",phase:"interaction_read_fallback",data:{reason:"backend_read_failed",nodeRef:r.ref,surface:o,platform:t.platform,error:e instanceof Error?e.message:String(e)}}),l}}async function fA(e,t,r){let n=e.get(t),a=n?.device??await oy(r??{});return n||await oK(a),{session:n,device:a}}async function fS(e,t,r){let n=!e&&"ios"===t.platform;try{return await r()}finally{n&&await n2(t.id)}}function f_(e,t,r,n){t&&e.recordAction(t,{command:r.command,positionals:r.positionals??[],flags:r.flags??{},result:n})}let fx=[["snapshotDepth","--depth"],["snapshotScope","--scope"],["snapshotRaw","--raw"]];function fN(e,t){let r=function(e){if(!e)return[];let t=[];for(let[r,n]of fx)void 0!==e[r]&&t.push(n);return t}(t);return 0===r.length?null:cm("INVALID_ARGS",`${e} @ref does not support ${r.join(", ")}.`)}async function fM(e,t){let r=await fk(e);if(r)throw new O("COMMAND_FAILED",`press ${t} left ${e.appBundleId} and foregrounded ${r.foregroundPackage}. The tap likely escaped the app.`,r)}async function fk(e){var t;if("android"!==e.device.platform||!e.appBundleId)return null;let r=await eu(e.device),n=r.package?.trim();return n&&n!==e.appBundleId&&("com.android.settings"===(t=n)||"com.android.systemui"===t||"com.google.android.permissioncontroller"===t||t.includes("launcher"))?{expectedPackage:e.appBundleId,foregroundPackage:n,activity:r.activity,hint:"com.google.android.permissioncontroller"===n?"Dismiss or allow the permission prompt, then retry the smoke assertion.":"Use screenshot as visual truth, then take a fresh snapshot -i before retrying."}:null}function fD(e,t){let r=Array.isArray(e.selectorChain)?e.selectorChain:void 0,n=fC(e),a=n?.kind==="ref"?fE(n.ref):void 0,i=n?.kind==="selector"?n.selector:void 0,o={...a?{ref:a}:{},...i?{selector:i}:{},...r?{selectorChain:r}:{}};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)}}function fP(e){let t=fC(e);return{...t?.kind==="ref"?{ref:fE(t.ref)}:{},...t?.kind==="selector"?{selector:t.selector}:{},..."string"==typeof e.text?{text:e.text}:{},...e.node&&"object"==typeof e.node?{node:e.node}:{}}}function fO(e){let{selectorChain:t,...r}=e;return r}function fR(e,t,r,n){let a=e.get(t);a&&e.recordAction(a,{command:r.command,positionals:r.positionals??[],flags:r.flags??{},result:n})}function fC(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 fE(e){return e.startsWith("@")?e.slice(1):e}function fL(e,t={}){return{artifacts:function(e,t={}){let r=!0===t.plural?"do":"does";return{resolveInput:async()=>{throw new O("UNSUPPORTED_OPERATION",`${e} ${r} not resolve input artifacts`)},reserveOutput:async()=>{throw new O("UNSUPPORTED_OPERATION",`${e} ${r} not reserve output artifacts`)},createTempFile:async()=>{throw new O("UNSUPPORTED_OPERATION",`${e} ${r} not create temporary files`)}}}(e,t),policy:tO()}}let f$=["application","window","tabbar","scrollbar","image"],fT=new Set(["tab bar"]);async function fF(e,t){var r;if(t.ok||(r=t.error.message,!/^wait timed out for (?:selector|text): /i.test(r)))return t;let n=await fU(e).catch(()=>null);return n?cm(t.error.code,`${t.error.message}. Current surface: ${n.summary}.`,{...t.error.details??{},currentSurface:n.details}):t}async function fU(e){let t=[...(await pi({device:e.device,session:e.session,flags:{...e.req.flags,snapshotInteractiveOnly:!0,snapshotCompact:!0},logPath:e.logPath??""})).snapshot.nodes].sort(fG),r=fV(t,6,{includeIdentifiers:!0});if(0===r.length)return null;let n=fV(t.filter(e=>!fB(e)),4,{includeIdentifiers:!1}),a=fV(t.filter(fH),4,{includeIdentifiers:!0});return{summary:(n.length>0?n:r.slice(0,4)).join(", "),details:{labels:r,...a.length>0?{buttons:a}:{}}}}function fV(e,t,r){let n=new Set,a=[];for(let i of e){let e=fj(i,r);if(!(!e||n.has(e))&&(n.add(e),a.push(e),a.length>=t))break}return a}function fG(e,t){var r,n;return fq(e)-fq(t)||(r=e,n=t,r.rect&&n.rect?r.rect.y-n.rect.y||r.rect.x-n.rect.x:r.rect?-1:n.rect?1:(r.depth??0)-(n.depth??0)||r.index-n.index)}function fq(e){let t=!!fj(e,{includeIdentifiers:!1});return 2*!!fB(e)+ +!t}function fj(e,t){let r=(t.includeIdentifiers?[e.label,e.value,e.identifier]:[e.label,e.value]).map(e=>"string"==typeof e?e.trim():"").find(e=>e.length>0);return r?r.replace(/\s+/g," ").slice(0,80):""}function fB(e){let t=t1(`${e.type??""} ${e.role??""} ${e.subrole??""}`),r=`${e.label??""} ${e.value??""}`.trim().toLowerCase();return f$.some(e=>t.includes(e))||fT.has(r)||r.endsWith(".fill")}function fH(e){return t1(`${e.type??""} ${e.role??""} ${e.subrole??""}`).includes("button")}function fW(e){var t;let{session:r,selectorExpression:n}=e;if(!r||"ios"!==r.device.platform||r.postGestureStabilization)return null;let a=tW(n);if(!a||1!==a.selectors.length)return null;let i=a.selectors[0];if(!i||1!==i.terms.length)return null;let o=i.terms[0];return o&&"string"==typeof o.value&&("id"===(t=o.key)||"label"===t||"text"===t||"value"===t)?{key:o.key,value:o.value,raw:i.raw}:null}function fz(e){let t=D(e);if("COMMAND_FAILED"!==t.code)return!1;let r=t.message.toLowerCase();return r.includes("fetch failed")||r.includes("timed out")||r.includes("timeout")||r.includes("runner did not accept connection")||r.includes("invalid runner response")}async function fK(e){var t;let{req:r}=e;if("find"!==r.command)return null;let n=r.positionals??[];if(0===n.length)return cm("INVALID_ARGS","find requires a locator or text");let a=t8(n);if(!a.query)return cm("INVALID_ARGS","find requires a value");if(r.flags?.findFirst&&r.flags?.findLast)return cm("INVALID_ARGS","find accepts only one of --first or --last");let i=a.action;if("exists"!==(t=i)&&"wait"!==t&&"get_text"!==t&&"get_attrs"!==t)return null;let o=await f8(e,{requireSession:!1,capability:"find"});return o.ok?await f7(async()=>{let t=await o.runtime.selectors.find({session:e.sessionName,requestId:r.meta?.requestId,locator:a.locator,query:a.query,action:i,timeoutMs:a.timeoutMs});return fR(e.sessionStore,e.sessionName,r,function(e,t){if("exists"===t)return{found:!0};if("wait"===t)return{found:!0,waitedMs:e.waitedMs};let r="string"==typeof e.ref?e.ref:void 0;return"get_attrs"===t?{ref:r,action:"get attrs"}:{ref:r,action:"get text",text:"string"==typeof e.text?e.text:""}}(t,i)),"found"===t.kind?{found:!0,..."number"==typeof t.waitedMs?{waitedMs:t.waitedMs}:{}}:{..."string"==typeof t.ref?{ref:t.ref}:{},..."string"==typeof t.text?{text:t.text}:{},...t.node&&"object"==typeof t.node?{node:t.node}:{}}}):o.response}async function fJ(e){let{req:t}=e;if("get"!==t.command)return null;let r=t.positionals?.[0];if("text"!==r&&"attrs"!==r)return cm("INVALID_ARGS","get only supports text or attrs");let n=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 r=e.positionals?.slice(1).join(" ").trim()??"";return r?{ok:!0,target:{kind:"selector",selector:r}}:{ok:!1,response:cm("INVALID_ARGS","get requires @ref or selector expression")}}(t);if(!n.ok)return n.response;if("ref"===n.target.kind){let e=fN("get",t.flags);if(e)return e}if("selector"===n.target.kind){let t=await fZ(e,r,n.target.selector);if(t)return t}let a=await f8(e,{requireSession:!0,capability:"get"});return a.ok?await f7(async()=>{let i=await a.runtime.selectors.get({session:e.sessionName,requestId:t.meta?.requestId,property:r,target:n.target});return fR(e.sessionStore,e.sessionName,t,fD(i,r)),fP(i)}):a.response}async function fX(e){let{req:t}=e;if("is"!==t.command)return null;let r=(t.positionals?.[0]??"").toLowerCase();if(!tR(r))return cm("INVALID_ARGS","is requires predicate: visible|hidden|exists|editable|selected|text");let{split:n}=tK(t.positionals??[]);if(!n)return cm("INVALID_ARGS","is requires a selector expression");let a=n.rest.join(" ").trim();if("text"===r&&!a)return cm("INVALID_ARGS","is text requires expected text value");if("text"!==r&&n.rest.length>0)return cm("INVALID_ARGS",`is ${r} does not accept trailing values`);let i=await fQ(e,r,n.selectorExpression,a);if(i)return i;let o=await f8(e,{requireSession:!0,capability:"is"});if(!o.ok)return o.response;let s=await f7(async()=>{let i=await o.runtime.selectors.is({session:e.sessionName,requestId:t.meta?.requestId,predicate:r,selector:n.selectorExpression,expectedText:a});return fR(e.sessionStore,e.sessionName,t,i),fO(i)});return await me(e,s,`is ${r}`)}async function fY(e){let{req:t,sessionName:r,sessionStore:n}=e,a=eG(t.positionals??[]);if(!a)return cm("INVALID_ARGS","wait requires a duration or text");let{session:i,device:o}=await fA(n,r,t.flags);if("sleep"!==a.kind&&!cF("wait",o))return cm("UNSUPPORTED_OPERATION","wait is not supported on this device");if("selector"===a.kind){let t=await f0({...e,session:i,device:o,selectorExpression:a.selectorExpression,timeoutMs:a.timeoutMs});if(t)return t}let s=async()=>{let s=f4({...e,session:i,device:o}),l=await f7(async()=>{let e=await s.selectors.wait({session:r,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 O("INVALID_ARGS","Ref wait requires an existing snapshot in session.");return{kind:"ref",ref:e.rawRef,timeoutMs:e.timeoutMs}}if(!e.text)throw new O("INVALID_ARGS","wait requires text");return{kind:"text",text:e.text,timeoutMs:e.timeoutMs}}(a,i)});return fR(n,r,t,e),{waitedMs:e.waitedMs,..."string"==typeof e.text?{text:e.text}:{},..."string"==typeof e.selector?{selector:e.selector}:{}}}),u=await fF({req:t,logPath:e.logPath,session:i,device:o},l);return await me(e,u,"wait")};return"sleep"===a.kind?await s():await fS(i,o,s)}async function fZ(e,t,r){let n=await f1(e,r);if(f5(n))return n.response;if(!n)return null;let a=function(e,t,r){if(!r.found||!r.node)return null;let n={target:{kind:"selector",selector:t},node:r.node,selectorChain:[t]};return"attrs"===e?{kind:"attrs",...n}:"string"!=typeof r.text?null:{kind:"text",...n,text:r.text}}(t,n.selector.raw,n.result);return a?(fR(e.sessionStore,e.sessionName,e.req,fD(a,t)),{ok:!0,data:fP(a)}):null}async function fQ(e,t,r,n){var a,i,o,s,l;let u;if("hidden"===t)return null;let d=await f1(e,r);if(f5(d))return d.response;if(!d?.result.found||!d.result.node)return null;let c="exists"===t?{predicate:t,pass:!0,selector:d.selector.raw,matches:1,selectorChain:[d.selector.raw]}:(a=t,i=n,o=d.selector.raw,s=d.session,u=tE({predicate:a,node:l=d.result.node,nodes:[l],expectedText:i,platform:s.device.platform}),{predicate:a,pass:u.pass,selector:o,..."text"===a?{text:u.actualText}:{},selectorChain:[o]});return c?(fR(e.sessionStore,e.sessionName,e.req,c),{ok:!0,data:fO(c)}):null}async function f0(e){let t=fW({session:e.session,selectorExpression:e.selectorExpression});if(!e.session||!t)return null;let r=Date.now(),n=await f3(e,e.session,t);if(f5(n))return n.response;if(!n?.found)return null;let a={kind:"selector",selector:t.raw,waitedMs:Date.now()-r,selectorChain:[t.raw]};return fR(e.sessionStore,e.sessionName,e.req,a),await fF({req:e.req,logPath:e.logPath,session:e.session,device:e.device},{ok:!0,data:a})}async function f1(e,t){let r=e.sessionStore.get(e.sessionName),n=fW({session:r,selectorExpression:t});if(!r||!n)return null;let a=await f3(e,r,n);return f5(a)?a:a?{session:r,selector:n,result:a}:null}async function f2(e,t,r){let n=await ao(t.device,{command:"querySelector",selectorKey:r.key,selectorValue:r.value,appBundleId:t.appBundleId},{verbose:!!e.req.flags?.verbose,logPath:e.logPath,traceLogPath:t.trace?.outPath,requestId:e.req.meta?.requestId}),a=!0===n.found,i=function(e){let t=e.nodes;if(!Array.isArray(t))return;let r=t[0];if(r&&"object"==typeof r)return r}(n);return{found:a,..."string"==typeof n.text?{text:n.text}:{},...i?{node:i}:{}}}async function f3(e,t,r){try{return await f2(e,t,r)}catch(e){if(fz(e))return null;return{kind:"error",response:{ok:!1,error:P(e)}}}}function f5(e){return null!==e&&"kind"in e&&"error"===e.kind}function f4(e){return tM({backend:function(e){let t,{req:r,session:n,device:a,logPath:i,sessionName:o,sessionStore:s}=e,l=0;return{platform:a.platform,captureSnapshot:async(e,u)=>{var d;let c,p={...r.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??r.flags?.snapshotScope,m=Date.now(),h=tU(t$(p)),w="wait"===r.command||"find"===r.command;if(!w&&t&&m-l<750&&!cG(n)&&!n?.postGestureStabilization)return t;if(!w&&n?.snapshot&&m-n.snapshot.createdAt<750&&n.snapshot.presentationKey===h&&!cG(n)&&!n.postGestureStabilization)return l=n.snapshot.createdAt,t={snapshot:n.snapshot};let g=await pi({device:a,session:n,flags:p,outPath:r.flags?.out,logPath:i??"",snapshotScope:f});return n&&(ph(n,g.snapshot),s.set(o,n)),l=m,t={snapshot:g.snapshot}},readText:async(t,o)=>({text:await fb({device:a,node:o,flags:r.flags,appBundleId:n?.appBundleId,traceOutPath:n?.trace?.outPath,surface:n?.surface,contextFromFlags:e.contextFromFlags??((e,t,r)=>cH(i??"",e,t,r))})}),findText:async(t,r)=>({found:await f6(e,r)})}}(e),...fL("selector commands",{plural:!0}),sessions:pw({sessionName:e.sessionName,getSession:()=>e.session,recordOptions:{includeSnapshot:!0},setRecord:t=>{e.session&&t.snapshot&&(ph(e.session,t.snapshot),e.sessionStore.set(e.sessionName,e.session))}})})}async function f8(e,t){let r=e.sessionStore.get(e.sessionName);if(!r&&t.requireSession)return{ok:!1,response:cm("SESSION_NOT_FOUND","No active session. Run open first.")};let n=r?.device??await oy(e.req.flags??{});return(r||await oK(n),cF(t.capability,n))?{ok:!0,runtime:f4({...e,session:r,device:n})}:{ok:!1,response:cm("UNSUPPORTED_OPERATION",`${t.capability} is not supported on this device`)}}async function f6(e,t){let{device:r,session:n,req:a,logPath:i}=e;if("macos"===r.platform&&n?.surface&&"app"!==n.surface)return!!tJ((await f9(e)).nodes,t);if(r1(r.platform)&&n?.appBundleId){let e=await ao(r,{command:"findText",text:t,appBundleId:n?.appBundleId},{verbose:a.flags?.verbose,logPath:i,traceLogPath:n?.trace?.outPath,requestId:a.meta?.requestId});return e?.found===!0}return!!tJ((await f9(e)).nodes,t)}async function f9(e){let t=await pi({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&&(ph(e.session,t.snapshot),e.sessionStore.set(e.sessionName,e.session)),t.snapshot}async function f7(e){try{return{ok:!0,data:await e()}}catch(t){let e=D(t);return cm(e.code,e.message,e.details)}}async function me(e,t,r){var n;let a;if(t.ok)return t;let i=e.sessionStore.get(e.sessionName);if(!i)return t;try{a=await fk(i)}catch{return t}return a?cm(t.error.code,`${r} failed because ${"com.google.android.permissioncontroller"===(n=a).foregroundPackage?`Android permission dialog is blocking ${n.expectedPackage}`:`${n.foregroundPackage} is foreground instead of ${n.expectedPackage}`}.`,{...t.error.details??{},...a,blockedBy:"android_foreground_surface",originalMessage:t.error.message}):t}async function mt(e){var t,r;let{req:n,sessionName:a,logPath:i,sessionStore:o,invoke:s}=e,l=n.command;if("find"!==l)return null;let u=n.positionals??[];if(0===u.length)return cm("INVALID_ARGS","find requires a locator or text");let{locator:d,query:c,action:p,value:f,timeoutMs:m}=t8(u);if(!c)return cm("INVALID_ARGS","find requires a value");if(n.flags?.findFirst&&n.flags?.findLast)return cm("INVALID_ARGS","find accepts only one of --first or --last");let h=await fK({req:n,sessionName:a,logPath:i,sessionStore:o});if(h)return h;let w=o.get(a),g="exists"===(t=p)||"wait"===t||"get_text"===t||"get_attrs"===t;if(!w&&!g)return cm("SESSION_NOT_FOUND","No active session. Run open first.");let y=w?.device??await oy(n.flags??{});w||await oK(y);let v="click"===(r=p)||"focus"===r||"fill"===r||"type"===r,I="role"===d||v?void 0:c,b=0,A=null,S=async()=>{let e=Date.now();if(A&&e-b<750&&!cG(w))return{nodes:A};let{snapshot:t}=await pi({device:y,session:w,flags:{...n.flags,snapshotInteractiveOnly:v,snapshotCompact:v},outPath:n.flags?.out,logPath:i,snapshotScope:I}),r=t.nodes;return b=e,A=r,w&&(ph(w,t),o.set(a,w)),{nodes:r,truncated:t.truncated,backend:t.backend}},_={req:n,sessionName:a,logPath:i,sessionStore:o,invoke:s,session:w,device:y,command:l,locator:d,query:c};if("wait"===p)return ma(_,S,d,c,m);let{nodes:x}=await S(),N=function(e){let{nodes:t,locator:r,query:n,requiresRect:a,flags:i}=e,o=t5(t,r,n,{requireRect:a});if(a&&(o.matches=function(e,t){var r,n;let a=t[0]?.rect;if(!a)return e;let i=e.filter(e=>{if(!e.rect)return!1;let t=tV(e.rect);return t.x>=a.x&&t.x<=a.x+a.width&&t.y>=a.y&&t.y<=a.y+a.height});return r=i.length>0?i:e,n=t,r.length<2?r:r.map((e,t)=>{var r,a;let i;return{node:e,index:t,score:(r=e,"semantic-target"===(i=tN(a=n,r)).reason&&i.node.rect||"same-rect-descendant"===i.reason&&i.node.rect?4:"hittable-ancestor"===i.reason&&i.node.rect&&!mn(i.node,a[0])?2:r.hittable&&r.rect&&!mn(r,a[0])?3:+!!r.rect)}}).sort((e,t)=>t.score!==e.score?t.score-e.score:mr(e.node)-mr(t.node)||e.index-t.index).map(e=>e.node)}(o.matches,t)),a&&o.matches.length>1)if(i?.findFirst)o.matches=[o.matches[0]];else{if(!i?.findLast){var s,l,u;let e;return{ok:!1,response:(s=o.matches,l=r,u=n,e=s.slice(0,8).map(e=>{let t=tH(e)||e.label||e.identifier||e.type||"";return`@${e.ref}${t?`(${t})`:""}`}),cm("AMBIGUOUS_MATCH",`find matched ${s.length} elements for ${l} "${u}". Use a more specific locator or selector.`,{locator:l,query:u,matches:s.length,candidates:e}))}}o.matches=[o.matches[o.matches.length-1]]}let d=o.matches[0]??null;return d?{ok:!0,node:d}:{ok:!1,response:cm("COMMAND_FAILED","find did not match any element")}}({nodes:x,locator:d,query:c,requiresRect:v,flags:n.flags});if(!N.ok)return N.response;let M=N.node,k=v?tb(x,M):M,D=`@${k.ref}`,P={node:M,resolvedNode:k,ref:D,nodes:x,actionFlags:{...n.flags??{},noRecord:!0}},O={exists:()=>mi(_),get_text:()=>mo(_,P),get_attrs:()=>ms(_,P),click:()=>ml(_,P),fill:()=>mu(_,P,f),focus:()=>md(_,P),type:()=>mc(_,P,f)}[p];return O?O():null}function mr(e){return e.rect?e.rect.width*e.rect.height:1/0}function mn(e,t){if(!t?.rect||!e.rect)return!1;let r=e.type?.toLowerCase()??"";return(!!r.includes("application")||!!r.includes("window"))&&e.rect.x===t.rect.x&&e.rect.y===t.rect.y&&e.rect.width===t.rect.width&&e.rect.height===t.rect.height}async function ma(e,t,r,n,a){let{req:i,sessionStore:o,session:s,command:l}=e,u=a??1e4,d=Date.now();for(;Date.now()-d<u;){let{nodes:e}=await t();if(t5(e,r,n,{requireRect:!1}).matches[0])return s&&o.recordAction(s,{command:l,positionals:i.positionals??[],flags:i.flags??{},result:{found:!0,waitedMs:Date.now()-d}}),{ok:!0,data:{found:!0,waitedMs:Date.now()-d}};await e2(300)}return cm("COMMAND_FAILED","find wait timed out")}async function mi(e){let{req:t,sessionStore:r,session:n,command:a}=e;return n&&r.recordAction(n,{command:a,positionals:t.positionals??[],flags:t.flags??{},result:{found:!0}}),{ok:!0,data:{found:!0}}}async function mo(e,t){let{req:r,sessionStore:n,session:a,command:i,device:o,logPath:s}=e,l=await fb({device:o,node:t.node,flags:r.flags,appBundleId:a?.appBundleId,traceOutPath:a?.trace?.outPath,surface:a?.surface,contextFromFlags:(e,t,r)=>cH(s,e,t,r)});return a&&n.recordAction(a,{command:i,positionals:r.positionals??[],flags:r.flags??{},result:{ref:t.ref,action:"get text",text:l}}),{ok:!0,data:{ref:t.ref,text:l,node:t.node}}}async function ms(e,t){let{req:r,sessionStore:n,session:a,command:i}=e;return a&&n.recordAction(a,{command:i,positionals:r.positionals??[],flags:r.flags??{},result:{ref:t.ref,action:"get attrs"}}),{ok:!0,data:{ref:t.ref,node:t.node}}}async function ml(e,t){let{req:r,sessionName:n,sessionStore:a,session:i,invoke:o,command:s,locator:l,query:u}=e,d=await o({token:r.token,session:n,command:"click",positionals:[t.ref],flags:t.actionFlags});if(!d.ok)return d;let c=t.resolvedNode.rect?tV(t.resolvedNode.rect):t.node.rect?tV(t.node.rect):null,p={ref:t.ref,locator:l,query:u};return c&&(p.x=c.x,p.y=c.y),i&&a.recordAction(i,{command:s,positionals:r.positionals??[],flags:r.flags??{},result:{ref:t.ref,action:"click",locator:l,query:u}}),{ok:!0,data:p}}async function mu(e,t,r){let{req:n,sessionName:a,sessionStore:i,session:o,invoke:s,command:l}=e;if(!r)return cm("INVALID_ARGS","find fill requires text");let u=await s({token:n.token,session:a,command:"fill",positionals:[t.ref,r],flags:t.actionFlags});return u.ok&&o&&i.recordAction(o,{command:l,positionals:n.positionals??[],flags:n.flags??{},result:{ref:t.ref,action:"fill"}}),u}async function md(e,t){let r=await mp(e,t);return r.ok&&mf(e,t,"focus"),r}async function mc(e,t,r){let{req:n,device:a,logPath:i,session:o}=e;if(!r)return cm("INVALID_ARGS","find type requires text");let s=await mp(e,t);if(!s.ok)return s;let l=await cr(a,"type",[r],n.flags?.out,{...cH(i,n.flags,o?.appBundleId,o?.trace?.outPath)});return mf(e,t,"type"),{ok:!0,data:l??{ref:t.ref}}}async function mp(e,t){let{req:r,device:n,logPath:a,session:i}=e,o=t.node.rect?tV(t.node.rect):null;return o?{ok:!0,data:await cr(n,"focus",[String(o.x),String(o.y)],r.flags?.out,{...cH(a,r.flags,i?.appBundleId,i?.trace?.outPath)})??{ref:t.ref}}:cm("COMMAND_FAILED","matched element has no bounds")}function mf(e,t,r){let{req:n,sessionStore:a,session:i,command:o}=e;i&&a.recordAction(i,{command:o,positionals:n.positionals??[],flags:n.flags??{},result:{ref:t.ref,action:r}})}function mm(e){var t,r,n;let a,i,o,{data:s,fallbackX:l,fallbackY:u,referenceFrame:d,extra:c}=e,p=(t=c,r=l,n=u,a="string"==typeof t?.ref?t.ref:void 0,i="string"==typeof t?.button?t.button:void 0,o="string"==typeof t?.gesture?t.gesture:void 0,("string"==typeof t?.text?`Filled ${Array.from(t.text).length} chars`:a?"longpress"===o?`Long pressed @${a} (${r}, ${n})`:i&&"primary"!==i?`Clicked ${i} @${a} (${r}, ${n})`:`Tapped @${a} (${r}, ${n})`:void 0)??("string"==typeof s?.message?s.message:void 0));return{x:l,y:u,...d??{},...c??{},...s??{},...eV(p)}}function mh(e){let{session:t,sessionStore:r,command:n,positionals:a,flags:i,result:o,responseData:s,actionStartedAt:l,actionFinishedAt:u,androidFreshnessBaseline:d}=e;return r.recordAction(t,{command:n,positionals:a,flags:i??{},result:o}),cj(n)&&cV(t,n,d??t.snapshot),ft(t,n,a,o,i??{},l,u),{ok:!0,data:s}}async function mw(e){let{session:t,flags:r,sessionStore:n,contextFromFlags:a,captureSnapshotForSession:i}=e;if(!t.recording)return;if(t.recording.touchReferenceFrame)return t.recording.touchReferenceFrame;if("android"===t.device.platform){let e=await sL(t.device),r={referenceWidth:e.width,referenceHeight:e.height};return t.recording&&(t.recording.touchReferenceFrame=r),r}let o=p9(t.snapshot);if(o)return t.recording&&(t.recording.touchReferenceFrame=o),o;if(!t.recording)return;let s=p9(await i(t,r,n,a,{interactiveOnly:!0}));return s&&t.recording&&(t.recording.touchReferenceFrame=s),s}async function mg(e){try{return await mw(e)}catch(t){eM({level:"warn",phase:"touch_reference_frame_resolve_failed",data:{platform:e.session.device.platform,error:t instanceof Error?t.message:String(t)}});return}}function my(e){return p9({nodes:e,createdAt:0})}function mv(e,t){return"macos"!==e.device.platform||"desktop"!==e.surface&&"menubar"!==e.surface||"menubar"===e.surface&&("click"===t||"press"===t)?null:cm("UNSUPPORTED_OPERATION",`${t} is not supported on macOS ${e.surface} sessions yet. Open an app session to act, or use the ${e.surface} surface to inspect.`)}function mI(e){let t=e.sessionStore.get(e.sessionName);if(!t)throw new O("SESSION_NOT_FOUND","No active session. Run open first.");return tM({backend:function(e){let{req:t,session:r}=e;return{platform:r.device.platform,captureSnapshot:async(n,a)=>({snapshot:await e.captureSnapshotForSession(r,t.flags,e.sessionStore,e.contextFromFlags,{interactiveOnly:a?.interactiveOnly===!0})}),tap:async(n,a)=>mb(await cr(r.device,"press",[String(a.x),String(a.y)],t.flags?.out,e.contextFromFlags(t.flags,r.appBundleId,r.trace?.outPath))),fill:async(n,a,i)=>mb(await cr(r.device,"fill",[String(a.x),String(a.y),i],t.flags?.out,e.contextFromFlags(t.flags,r.appBundleId,r.trace?.outPath))),longPress:async(n,a,i)=>mb(await cr(r.device,"longpress",[String(a.x),String(a.y),...i?.durationMs===void 0?[]:[String(i.durationMs)]],t.flags?.out,e.contextFromFlags(t.flags,r.appBundleId,r.trace?.outPath))),typeText:async(n,a)=>mb(await cr(r.device,"type",[a],t.flags?.out,e.contextFromFlags(t.flags,r.appBundleId,r.trace?.outPath)))}}({...e,session:t}),...fL("interaction commands",{plural:!0}),sessions:pw({sessionName:e.sessionName,getSession:()=>t,recordOptions:{includeSnapshot:!0},setRecord:r=>{r.snapshot&&(ph(t,r.snapshot),e.sessionStore.set(e.sessionName,t))}})})}function mb(e){return e&&"object"==typeof e?e:void 0}function mA(e){if(e.length<2)return null;let t=Number(e[0]),r=Number(e[1]);return Number.isFinite(t)&&Number.isFinite(r)?{x:t,y:r}:null}function mS(e,t){let r=mA(e);if(r)return{ok:!0,target:{kind:"point",x:r.x,y:r.y}};let n=e[0]??"";if(n.startsWith("@"))return{ok:!0,target:{kind:"ref",ref:n,fallbackLabel:eR(e).label??""}};let a=e.join(" ").trim();return a?{ok:!0,target:{kind:"selector",selector:a}}:{ok:!1,response:cm("INVALID_ARGS",`${t} requires @ref, selector expression, or x y coordinates`)}}function m_(e){return"ref"===e.kind?{ref:mx(e.target?.kind==="ref"?e.target.ref:void 0),refLabel:e.refLabel,selectorChain:e.selectorChain}:"selector"===e.kind?{selector:e.target?.kind==="selector"?e.target.selector:void 0,selectorChain:e.selectorChain,refLabel:e.refLabel}:{}}function mx(e){return e?.startsWith("@")?e.slice(1):e}async function mN(e){switch(e.req.command){case"press":return await mM(e,"press");case"click":return await mM(e,"click");case"longpress":return await mM(e,"longpress");case"fill":return await mR(e);default:return null}}async function mM(e,t){let r,{req:n,sessionName:a,sessionStore:i}=e,o=i.get(a);if(!o)return cm("SESSION_NOT_FOUND","No active session. Run open first.");let s="click"===t?"click":t,l="longpress"===t?"longpress":"press",u=mv(o,s);if(u)return u;if(!cF(l,o.device))return cm("UNSUPPORTED_OPERATION",`${l} is not supported on this device`);let d=dR(n.flags),c="primary"===d?{}:{button:d};if("longpress"!==t&&"primary"!==d){let e=dC({commandLabel:s,platform:o.device.platform,button:d,count:n.flags?.count,intervalMs:n.flags?.intervalMs,holdMs:n.flags?.holdMs,jitterPx:n.flags?.jitterPx,doubleTap:n.flags?.doubleTap});if(e)return cm(e.code,e.message,e.details)}let p="longpress"===t?function(e){var t,r,n;let a,i=mA(e);if(i){return{ok:!0,target:{kind:"point",x:i.x,y:i.y},...void 0===(t=e[2])?{}:{durationMs:Number(t)}}}let o=(a=(r=e).at(-1),r.length>1&&void 0!==(n=a)&&""!==n.trim()&&Number.isFinite(Number(n))?{targetPositionals:r.slice(0,-1),duration:{durationMs:Number(a)}}:{targetPositionals:r,duration:{}}),s=mS(o.targetPositionals,"longpress");return s.ok?{ok:!0,target:s.target,...o.duration}:s}(n.positionals??[]):mS(n.positionals??[],s);if(!p.ok)return p.response;if("ref"===p.target.kind){let a=e.refSnapshotFlagGuardResponse("longpress"===t?"longpress":"press",n.flags);if(a)return a;r=await mL(e,o)}let f=function(e){var t;let{session:r,commandLabel:n,target:a,flags:i}=e;if("click"!==n||"selector"!==a.kind||(t=i,t?.count!==void 0||t?.intervalMs!==void 0||t?.holdMs!==void 0||t?.jitterPx!==void 0||t?.doubleTap!==void 0||t?.clickButton!==void 0&&"primary"!==t.clickButton))return null;let o=fW({session:r,selectorExpression:a.selector});return o?{...o,...i?.maestro?.allowNonHittableCoordinateFallback?{allowNonHittableCoordinateFallback:!0}:{}}:null}({session:o,commandLabel:s,target:p.target,flags:n.flags});if(f){let t=await mP(e,o,f);if(t)return t}let m="longpress"===t?p.durationMs:void 0;return await mE(e,{androidFreshnessBaseline:r,run:async e=>await mk({runtime:e,command:t,target:p.target,sessionName:a,requestId:n.meta?.requestId,clickButton:d,flags:n.flags,durationMs:m}),afterRun:async e=>{var t;await fM(o,(t=p.target,"point"===t.kind?"coordinate tap":"ref"===e.kind&&e.target?.kind==="ref"?e.target.ref:"selector"===e.kind&&e.target?.kind==="selector"?e.target.selector:"target"))},buildPayloads:async r=>{var n;let a="durationMs"in(n=r)?n.durationMs:void 0,i=await mD({params:e,session:o,result:r,extra:"longpress"===t?{...void 0!==a?{durationMs:a}:{},gesture:"longpress"}:c});return{result:i,responseData:i}}})}async function mk(e){let{runtime:t,command:r,target:n,sessionName:a,requestId:i,flags:o}=e;if("longpress"===r)return await t.interactions.longPress(n,{session:a,requestId:i,durationMs:e.durationMs});let s={session:a,requestId:i,button:e.clickButton,count:o?.count,intervalMs:o?.intervalMs,holdMs:o?.holdMs,jitterPx:o?.jitterPx,doubleTap:o?.doubleTap};return"click"===r?await t.interactions.click(n,s):await t.interactions.press(n,s)}async function mD(e){let{params:t,session:r,result:n,extra:a}=e,i="point"===n.kind?await mg({session:r,flags:t.req.flags,sessionStore:t.sessionStore,contextFromFlags:t.contextFromFlags,captureSnapshotForSession:t.captureSnapshotForSession}):my(r.snapshot?.nodes??[]);return mm({data:n.backendResult,fallbackX:n.point.x,fallbackY:n.point.y,referenceFrame:i,extra:{...m_(n),...a}})}async function mP(e,t,r){return await mO({params:e,session:t,selector:r,command:"press",positionals:[],extra:{selector:r.raw},fallbackPhase:"ios_direct_selector_tap_fallback"})}async function mO(e){let{params:t,session:r,selector:n,command:a,positionals:i,extra:o,fallbackPhase:s}=e,l=Date.now();try{var u,d;let e,s,c=await cr(r.device,a,i,t.req.flags?.out,{...t.contextFromFlags(t.req.flags,r.appBundleId,r.trace?.outPath),directElementSelector:n,surface:r.surface})??{},p=Date.now(),f=(u=c,e="number"==typeof u.x?u.x:void 0,s="number"==typeof u.y?u.y:void 0,void 0!==e&&void 0!==s?{x:e,y:s}:{x:0,y:0}),m=mm({data:c,fallbackX:f.x,fallbackY:f.y,referenceFrame:(d=c,"number"==typeof d.referenceWidth&&"number"==typeof d.referenceHeight?{referenceWidth:d.referenceWidth,referenceHeight:d.referenceHeight}:void 0),extra:{...o,...function(e,t){if(!e.allowNonHittableCoordinateFallback)return{};let r="tapped via non-hittable coordinate fallback"===t.message;return{maestroNonHittableCoordinateFallbackAllowed:!0,maestroNonHittableCoordinateFallbackUsed:r,...r?{maestroFallbackReason:"non-hittable-coordinate"}:{}}}(n,c)}});return mh({session:r,sessionStore:t.sessionStore,command:t.req.command,positionals:t.req.positionals??[],flags:t.req.flags,result:m,responseData:m,actionStartedAt:l,actionFinishedAt:p})}catch(e){if(!fz(e))return{ok:!1,error:P(e)};return eM({level:"debug",phase:s,data:{selector:n.raw,error:e instanceof Error?e.message:String(e)}}),null}}async function mR(e){let{req:t,sessionName:r,sessionStore:n}=e,a=n.get(r);if(a){let e=mv(a,"fill");if(e)return e}if(a&&!cF("fill",a.device))return cm("UNSUPPORTED_OPERATION","fill is not supported on this device");if(!a)return cm("SESSION_NOT_FOUND","No active session. Run open first.");let i=function(e){let t=e[0]??"";if(t.startsWith("@")){var r;let n=eZ(e).text;return n?{ok:!0,target:{kind:"ref",ref:t,fallbackLabel:(r=e).length>=3&&r[1]?.trim()||""},text:n}:{ok:!1,response:cm("INVALID_ARGS","fill requires text after ref")}}let n=mA(e);if(n){let t=e.slice(2).join(" ");return t?{ok:!0,target:{kind:"point",x:n.x,y:n.y},text:t}:{ok:!1,response:cm("INVALID_ARGS","fill requires text after coordinates")}}let a=eZ(e);return"selector"!==a.kind?{ok:!1,response:cm("INVALID_ARGS","fill requires x y text, @ref text, or selector text")}:a.text.trim()?{ok:!0,target:{kind:"selector",selector:a.target.selector},text:a.text}:{ok:!1,response:cm("INVALID_ARGS","fill requires text after selector")}}(t.positionals??[]);if(!i.ok)return i.response;if("ref"===i.target.kind){let r=e.refSnapshotFlagGuardResponse("fill",t.flags);if(r)return r;await mL(e,a)}let o=function(e){let{session:t,target:r,flags:n}=e;if("selector"!==r.kind)return null;let a=fW({session:t,selectorExpression:r.selector});return a?{...a,...n?.maestro?.allowNonHittableCoordinateFallback?{allowNonHittableCoordinateFallback:!0}:{}}:null}({session:a,target:i.target,flags:t.flags});if(o){let t=await mC(e,a,o,i.text);if(t)return t}return await mE(e,{run:async e=>await e.interactions.fill(i.target,i.text,{session:r,requestId:t.meta?.requestId,delayMs:t.flags?.delayMs}),buildPayloads:e=>{let t="point"===e.kind?void 0:my(a.snapshot?.nodes??[]),r=mm({data:e.backendResult,fallbackX:e.point.x,fallbackY:e.point.y,referenceFrame:t,extra:{...m_(e),text:i.text}});e.warning&&(r.warning=e.warning);let n="ref"===e.kind?{...e.backendResult??{ref:mx(e.target?.kind==="ref"?e.target.ref:void 0),x:e.point.x,y:e.point.y}}:r;return e.warning&&(n.warning=e.warning),{result:r,responseData:n}}})}async function mC(e,t,r,n){return await mO({params:e,session:t,selector:r,command:"fill",positionals:[n],extra:{selector:r.raw,text:n},fallbackPhase:"ios_direct_selector_fill_fallback"})}async function mE(e,t){let r=e.sessionStore.get(e.sessionName);if(!r)return cm("SESSION_NOT_FOUND","No active session. Run open first.");let n=mI(e),a=Date.now();try{let i=await pS({session:r,command:e.req.command,phase:"before-command"}),o=await t.run(n);await t.afterRun?.(o),await pS({session:r,command:e.req.command,phase:"after-command"});let s=Date.now(),{result:l,responseData:u}=await t.buildPayloads(o);return"recovered"===i.status&&(l.warning=i.warning,u.warning=i.warning),mh({session:r,sessionStore:e.sessionStore,command:e.req.command,positionals:e.req.positionals??[],flags:e.req.flags,result:l,responseData:u,actionStartedAt:a,actionFinishedAt:s,androidFreshnessBaseline:t.androidFreshnessBaseline})}catch(t){let e=D(t);if("COMMAND_FAILED"===e.code&&"string"==typeof e.details?.expectedPackage&&"string"==typeof e.details?.foregroundPackage)throw e;return{ok:!1,error:P(t)}}}async function mL(e,t){if(!cG(t))return;let r=t.snapshot?.comparisonSafe===!0?t.snapshot:void 0;try{await e.captureSnapshotForSession(t,e.req.flags,e.sessionStore,e.contextFromFlags,{interactiveOnly:!0,androidFreshnessMode:"ref-refresh"})}catch(t){eM({level:"warn",phase:"android_ref_snapshot_refresh_failed",data:{command:e.req.command,error:t instanceof Error?t.message:String(t)}})}return r}async function m$(e,t,r,n,a){let i={...t??{},snapshotInteractiveOnly:a.interactiveOnly,snapshotCompact:a.interactiveOnly},o=n(i,e.appBundleId,e.trace?.outPath),{snapshot:s}=await pi({device:e.device,session:e,flags:i,outPath:i.out,logPath:o.logPath??"",androidFreshnessMode:a.androidFreshnessMode});return ph(e,s),r.set(e.name,e),s}async function mT(e){let t=await mN({...e,captureSnapshotForSession:m$,refSnapshotFlagGuardResponse:fN});if(t)return t;switch(e.req.command){case eP.type:return await mF({...e,captureSnapshotForSession:m$});case"get":return await fJ(e);case"is":return await fX(e);default:return null}}async function mF(e){let{sessionName:t,sessionStore:r}=e,n=r.get(t);if(!n)return cm("SESSION_NOT_FOUND","No active session. Run open first.");if(!cF(eP.type,n.device))return cm("UNSUPPORTED_OPERATION","type is not supported on this device");let a=await mU(n);return a||await mV(e,n)}async function mU(e){return"android"===e.device.platform&&e.recording&&"failed"===await pA({session:e})?cm("COMMAND_FAILED","Android system dialog blocked the recording session"):null}async function mV(e,t){let{req:r,sessionName:n,sessionStore:a}=e,i=(r.positionals??[]).join(" "),o=mI(e),s=Date.now();try{let e=await pS({session:t,command:r.command,phase:"before-command"}),l=await o.interactions.typeText(i,{session:n,requestId:r.meta?.requestId,delayMs:r.flags?.delayMs});await pS({session:t,command:r.command,phase:"after-command"});let u=Date.now(),d={...l.backendResult??{},text:l.text,delayMs:l.delayMs,...eV(l.message??`Typed ${Array.from(l.text).length} chars`)};return"recovered"===e.status&&(d.warning=e.warning),mh({session:t,sessionStore:a,command:r.command,positionals:r.positionals??[],flags:r.flags,result:d,responseData:d,actionStartedAt:s,actionFinishedAt:u})}catch(e){return{ok:!1,error:P(e)}}}function mG(e){return{tenantId:e.meta?.tenantId??e.flags?.tenant,runId:e.meta?.runId??e.flags?.runId,leaseId:e.meta?.leaseId??e.flags?.leaseId,leaseTtlMs:e.meta?.leaseTtlMs,leaseBackend:e.meta?.leaseBackend}}async function mq(e){let{req:t,leaseRegistry:r}=e,n=mG(t);switch(t.command){case"lease_allocate":return{ok:!0,data:{lease:r.allocateLease({tenantId:n.tenantId??"",runId:n.runId??"",backend:n.leaseBackend,ttlMs:n.leaseTtlMs})}};case"lease_heartbeat":return{ok:!0,data:{lease:r.heartbeatLease({leaseId:n.leaseId??"",tenantId:n.tenantId,runId:n.runId,ttlMs:n.leaseTtlMs})}};case"lease_release":return{ok:!0,data:r.releaseLease({leaseId:n.leaseId??"",tenantId:n.tenantId,runId:n.runId})};default:return null}}async function mj(e){var t,r;let{req:n,sessionName:a,sessionStore:i}=e;if(n.command!==eP.reactNative)return null;let o=1===(t=n.positionals??[]).length&&"dismiss-overlay"===t[0]?{ok:!0}:{ok:!1,response:cm("INVALID_ARGS","react-native supports only: dismiss-overlay")};if(!o.ok)return o.response;let s=i.get(a);if(!s)return cm("SESSION_NOT_FOUND","No active session. Run open first.");if(!cF(eP.reactNative,s.device))return cm("UNSUPPORTED_OPERATION","react-native dismiss-overlay is not supported on this device");try{let t=await m$(s,n.flags,i,e.contextFromFlags,{interactiveOnly:!0}),a=tA(t.nodes);if(!a){return r=t,td(r.nodes).detected?cm("COMMAND_FAILED","React Native overlay detected, but no safe dismiss target was found",{hint:"Use screenshot --overlay-refs for visual evidence and report the overlay instead of pressing the warning body."}):{ok:!0,data:{action:"dismiss-overlay",detected:!1,dismissed:!1,...eV("No React Native overlay detected")}}}return await mB(e,s,t,a)}catch(e){return{ok:!1,error:P(e)}}}async function mB(e,t,r,n){let{req:a,sessionStore:i}=e,o=Date.now(),s=await cr(t.device,"press",[String(n.point.x),String(n.point.y)],a.flags?.out,e.contextFromFlags(a.flags,t.appBundleId,t.trace?.outPath))??{},l=Date.now(),u={...my(r.nodes),...s,action:"dismiss-overlay",overlayAction:n.action,x:n.point.x,y:n.point.y,...n.ref?{ref:n.ref}:{},...n.label?{label:n.label}:{},...n.warning?{warning:n.warning}:{},dismissed:!0,verified:!1,verificationRequired:!0,nextCommand:"agent-device snapshot -i -c",...eV("minimize"===n.action?"React Native RedBox minimize action sent; run snapshot -i before continuing":"React Native overlay dismiss action sent; run snapshot -i before continuing")};return mh({session:t,sessionStore:i,command:a.command,positionals:a.positionals??[],flags:a.flags,result:u,responseData:u,actionStartedAt:o,actionFinishedAt:l})}function mH(e=process.env){let t=mK(),r=f.join(t,"home"),n=f.join(t,"module-cache");return l.mkdirSync(r,{recursive:!0}),l.mkdirSync(n,{recursive:!0}),{...e,HOME:r,CLANG_MODULE_CACHE_PATH:n}}async function mW(e){let t=l.statSync(e.sourcePath),r=l.readFileSync(e.sourcePath),n=mZ(e.cacheName??f.basename(e.sourcePath,f.extname(e.sourcePath))),a=mQ(["2",process.platform,process.arch,f.resolve(e.sourcePath),t.size,r]),i=f.join(mK(),"bin",`${n}-${a}`);return await mJ({sourcePath:e.sourcePath,executablePath:i,timeoutMs:e.timeoutMs}),i}async function mz(e){let t=mZ(e.cacheName),r=mQ(["2",process.platform,process.arch,e.source]),n=f.join(mK(),"sources",`${t}-${r}.swift`),a=f.join(mK(),"bin",`${t}-${r}`);return await mJ({sourcePath:n,executablePath:a,sourceText:e.source,timeoutMs:e.timeoutMs}),a}function mK(){let e=process.env.AGENT_DEVICE_SWIFT_CACHE_DIR?.trim();return e?f.resolve(e):f.join(c.tmpdir(),"agent-device-swift-cache")}async function mJ(e){if(mY(e.executablePath))return;let t=f.dirname(e.executablePath);l.mkdirSync(t,{recursive:!0});let r=`${e.executablePath}.lock`;if(!await mX(r,e.executablePath,e.timeoutMs??12e4))return;let n=l.mkdtempSync(f.join(t,`.${f.basename(e.executablePath)}.${process.pid}.`)),a=f.join(n,f.basename(e.executablePath));try{if(mY(e.executablePath))return;void 0===e.sourceText||l.existsSync(e.sourcePath)||(l.mkdirSync(f.dirname(e.sourcePath),{recursive:!0}),l.writeFileSync(e.sourcePath,e.sourceText)),await E("xcrun",["swiftc",e.sourcePath,"-o",a],{timeoutMs:e.timeoutMs??12e4,env:mH()}),l.renameSync(a,e.executablePath)}finally{l.rmSync(n,{recursive:!0,force:!0}),l.rmSync(r,{recursive:!0,force:!0})}}async function mX(e,t,r){let n=Date.now()+r;for(;;){if(mY(t))return!1;try{return l.mkdirSync(e),!0}catch(t){if("EEXIST"!==t.code)throw t;if(function(e,t){try{return Date.now()-l.statSync(e).mtimeMs>=t}catch{return!1}}(e,r)){l.rmSync(e,{recursive:!0,force:!0});continue}if(Date.now()>=n)throw new O("COMMAND_FAILED",`Timed out waiting for Swift cache lock: ${e} (${r}ms)`,{lockDir:e,timeoutMs:r,hint:`Another agent-device process may still be compiling this Swift helper. Retry shortly; if no agent-device process is active, remove "${e}" and retry.`});await x(25)}}}function mY(e){try{return l.accessSync(e,l.constants.X_OK),l.statSync(e).isFile()}catch{return!1}}function mZ(e){return e.replaceAll(/[^A-Za-z0-9._-]/g,"-").replaceAll(/^-+|-+$/g,"")||"swift-helper"}function mQ(e){let t=s("sha256");for(let r of e)t.update(Buffer.isBuffer(r)?r:String(r)),t.update("\0");return t.digest("hex").slice(0,16)}let m0=`
27
+ ${a}`.toLowerCase();return i.includes("timeout waiting for screen surfaces")||i.includes("nsposixerrordomain")&&i.includes("code=60")&&i.includes("screenshot")||i.includes("timed out")&&i.includes("screenshot")}let uF={settings:"com.apple.Preferences"},uU=ep(),uV=null;function uG(e){return{platform:"ios",deviceId:e.id,variant:e.kind}}function uq(e,t,r){return rR(rT(e,t),r)}function uB(e){return e.includes("not installed")||e.includes("not found")||e.includes("no such file")}async function uj(e,t){if("macos"===e.platform)return await uo(t);let r=t.trim();if(r.includes("."))return r;let n=uF[r.toLowerCase()];if(n)return n;let a=uG(e),i=uU.get(a,r);if(i)return i;let o=("simulator"===e.kind?await u5(e):await o1(e,"all")).filter(e=>e.name.toLowerCase()===r.toLowerCase()),s=o[0];if(void 0!==s&&1===o.length)return uU.set(a,r,s.bundleId);if(o.length>1)throw new D("INVALID_ARGS",`Multiple apps matched "${t}"`,{matches:o});throw new D("APP_NOT_INSTALLED",`No app found matching "${t}"`)}async function uH(e,t,r){let n=r?.launchConsole?.trim();if(n&&("ios"!==e.platform||"simulator"!==e.kind))throw new D("UNSUPPORTED_OPERATION",lD);if("macos"===e.platform)return void await us(e,t,r);let a=r?.url?.trim();if(a){if(n)throw new D("INVALID_ARGS",lP);if(!ef(a))throw new D("INVALID_ARGS","open <app> <url> requires a valid URL target");if("simulator"===e.kind){await lL(e),await uq(e,["openurl",e.id,a]);return}let i=ee(r?.appBundleId??await uj(e,t),a);if(!i)throw new D("INVALID_ARGS","Deep link open on iOS devices requires an active app bundle ID. Open the app first, then open the URL.");await da(e,i,{payloadUrl:a});return}let i=t.trim();if(ef(i)){if(n)throw new D("INVALID_ARGS",lP);if("simulator"===e.kind){await lL(e),await uq(e,["openurl",e.id,i]);return}let t=ee(r?.appBundleId,i);if(!t)throw new D("INVALID_ARGS","Deep link open on iOS devices requires an active app bundle ID. Open the app first, then open the URL.");await da(e,t,{payloadUrl:i});return}let o=r?.appBundleId??await uj(e,t);"simulator"===e.kind?await dt(e,o,{...n?{launchConsole:n}:{},...r?.launchArgs?{launchArgs:r.launchArgs}:{}}):await da(e,o)}async function uW(e){"macos"===e.platform||"simulator"!==e.kind||"Booted"!==await l$(e)&&await lL(e)}async function uz(e,t){if("macos"===e.platform)return void await ul(e,t);let r=await uj(e,t);if("simulator"===e.kind){await lL(e);let t=rT(e,["terminate",e.id,r]),n=await rR(t,{allowFailure:!0});if(0!==n.exitCode){if(n.stderr.toLowerCase().includes("found nothing to terminate"))return;throw new D("COMMAND_FAILED",`xcrun exited with code ${n.exitCode}`,{cmd:"xcrun",args:t,stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode})}return}await o0(["device","process","terminate","--device",e.id,r],{action:"terminate iOS app",deviceId:e.id})}async function uK(e,t){if("ios"!==e.platform||"simulator"!==e.kind)throw new D("UNSUPPORTED_OPERATION","Clearing app state is currently supported only on iOS simulators.");let r=await uj(e,t);await lL(e),await uz(e,r);let n=await uq(e,["get_app_container",e.id,r,"data"],{allowFailure:!0});if(0!==n.exitCode)throw new D("COMMAND_FAILED",`simctl get_app_container failed for ${r}`,{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode});let a=n.stdout.trim();if(!a)throw new D("COMMAND_FAILED",`simctl get_app_container returned an empty data container path for ${r}`);let i=await d.readdir(a);return await Promise.all(i.map(e=>d.rm(f.join(a,e),{recursive:!0,force:!0}))),{bundleId:r,containerPath:a}}async function uJ(e,t){return await uU.invalidateWhile(uG(e),async()=>{let r=await uj(e,t);if("simulator"!==e.kind){let t=["devicectl","device","uninstall","app","--device",e.id,r],n=await rR(t,{allowFailure:!0,timeoutMs:2e4});if(0!==n.exitCode){let a=String(n.stdout??""),i=String(n.stderr??"");if(!uB(`${a}
28
+ ${i}`.toLowerCase()))throw new D("COMMAND_FAILED",`Failed to uninstall iOS app ${r}`,{cmd:"xcrun",args:t,exitCode:n.exitCode,stdout:a,stderr:i,deviceId:e.id,hint:o4(a,i)??o5})}return{bundleId:r}}await lL(e);let n=await uq(e,["uninstall",e.id,r],{allowFailure:!0});if(0!==n.exitCode&&!uB(`${n.stdout}
29
+ ${n.stderr}`.toLowerCase()))throw new D("COMMAND_FAILED",`simctl uninstall failed for ${r}`,{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode});return{bundleId:r}})}async function uX(e,t,r){let n=await lU({kind:"path",path:t},r);try{return await uZ(e,n.installablePath),{archivePath:n.archivePath,installablePath:n.installablePath,bundleId:n.bundleId,appName:n.appName,launchTarget:n.bundleId}}finally{await n.cleanup()}}async function uY(e,t,r){return await uU.invalidateWhile(uG(e),async()=>{let{bundleId:n}=await uJ(e,t);return await uX(e,r,{appIdentifierHint:t}),{bundleId:n}})}async function uZ(e,t){await uU.invalidateWhile(uG(e),async()=>{"simulator"!==e.kind?await o0(["device","install","app","--device",e.id,t],{action:"install iOS app",deviceId:e.id}):(await lL(e),await uq(e,["install",e.id,t]))})}async function uQ(e){if("macos"===e.platform)return await uu();lE(e,"clipboard"),await lL(e);let t=await uq(e,["pbpaste",e.id],{allowFailure:!0});if(0!==t.exitCode)throw new D("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 u0(e,t){if("macos"===e.platform)return void await ud(t);lE(e,"clipboard"),await lL(e);let r=await uq(e,["pbcopy",e.id],{allowFailure:!0,stdin:t});if(0!==r.exitCode)throw new D("COMMAND_FAILED","Failed to write iOS simulator clipboard",{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode})}async function u1(e,t,r){lE(e,"push"),await lL(e);let n=await d.mkdtemp(f.join(c.tmpdir(),"agent-device-ios-push-")),a=f.join(n,"payload.apns");try{await d.writeFile(a,`${JSON.stringify(r)}
30
+ `,"utf8"),await uq(e,["push",e.id,t,a])}finally{await d.rm(n,{recursive:!0,force:!0})}}async function u2(e,t,r,n,a){if("macos"===e.platform){let e=t.toLowerCase();if("appearance"===e)return void await up(r);if("permission"===e){let e=lf(r);if("deny"===e)throw new D("INVALID_ARGS",tC("permission"));let t=function(e){let t=e?.trim().toLowerCase();if("accessibility"===t||"screen-recording"===t||"input-monitoring"===t)return t;throw new D("INVALID_ARGS","Unsupported macOS permission target. Use accessibility|screen-recording|input-monitoring.")}(a?.permissionTarget);return await l8(e,t)}throw new D("INVALID_ARGS",tC(t))}lE(e,"settings"),await lL(e);let i=t.toLowerCase();switch(i){case"wifi":{let t=lw(r);await uq(e,["status_bar",e.id,"override","--wifiMode",t?"active":"failed"]);return}case"airplane":return void(lw(r)?await uq(e,["status_bar",e.id,"override","--dataNetwork","hide","--wifiMode","failed","--wifiBars","0","--cellularMode","failed","--cellularBars","0","--operatorName",""]):await uq(e,["status_bar",e.id,"clear"]));case"location":{if("set"===r.toLowerCase()){let{latitude:t,longitude:r}=ez(a);return await uq(e,["location",e.id,"set",`${t},${r}`]),{latitude:t,longitude:r}}let t=lw(r);if(!n)throw new D("INVALID_ARGS","location setting requires an active app in session");await uq(e,["privacy",e.id,t?"grant":"revoke","location",n]);return}case"faceid":case"touchid":{let t=u8[i],n=function(e,t){let r=e.trim().toLowerCase();if("match"===r)return"match";if("nonmatch"===r)return"nonmatch";if("enroll"===r)return"enroll";if("unenroll"===r)return"unenroll";throw new D("INVALID_ARGS",`Invalid ${t} state: ${e}. Use match|nonmatch|enroll|unenroll.`)}(r,i);await de(e,n,{settingName:i,label:t.label,modalityAliases:t.modalityAliases});return}case"appearance":{let t=await u4(e,r);await uq(e,["ui",e.id,"appearance",t]);return}case"permission":{var o;if(!n)throw new D("INVALID_ARGS","permission setting requires an active app in session");let t="deny"===(o=lf(r))?"revoke":o,i=function(e,t){let r=lm(e);if("photos"!==r&&t?.trim())throw new D("INVALID_ARGS",`Permission mode is only supported for photos. Received: ${t}.`);if("camera"===r)return"camera";if("microphone"===r)return"microphone";if("contacts"===r)return"contacts";if("contacts-limited"===r)return"contacts-limited";if("notifications"===r)return"notifications";if("calendar"===r)return"calendar";if("location"===r)return"location";if("location-always"===r)return"location-always";if("media-library"===r)return"media-library";if("motion"===r)return"motion";if("reminders"===r)return"reminders";if("siri"===r)return"siri";if("photos"===r){let e=t?.trim().toLowerCase();if(!e||"full"===e)return"photos";if("limited"===e)return"photos-add";throw new D("INVALID_ARGS",`Invalid photos mode: ${t}. Use full|limited.`)}throw new D("INVALID_ARGS",`Unsupported permission target: ${e}. Use camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri.`)}(a?.permissionTarget,a?.permissionMode);await u6(e,t,i,n);return}default:throw new D("INVALID_ARGS",`Unsupported setting: ${t}`)}}async function u3(e,t){return"macos"===e.platform?await uf(t):"simulator"===e.kind?rb(await u5(e),t):await o1(e,t)}async function u5(e){let t=(await uq(e,["listapps",e.id],{allowFailure:!0})).stdout.trim();if(!t)return[];let r=null;if(t.startsWith("{"))try{r=JSON.parse(t)}catch{r=null}if(!r&&t.startsWith("{"))try{let e=await rO("plutil",["-convert","json","-o","-","-"],{allowFailure:!0,stdin:t});0===e.exitCode&&e.stdout.trim().startsWith("{")&&(r=JSON.parse(e.stdout))}catch{r=null}return r?Object.entries(r).map(([e,t])=>({bundleId:e,name:t.CFBundleDisplayName??t.CFBundleName??e})):[]}async function u4(e,t){let r=lh(t);if("toggle"!==r)return r;let n=await uq(e,["ui",e.id,"appearance"],{allowFailure:!0});if(0!==n.exitCode)throw new D("COMMAND_FAILED","Failed to read current iOS appearance",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode});let a=function(e,t){let r=/\b(light|dark|unsupported|unknown)\b/i.exec(`${e}
31
+ ${t}`);if(!r)return null;let n=r[1]?.toLowerCase();return"dark"===n?"dark":"light"===n?"light":null}(n.stdout,n.stderr);if(!a)throw new D("COMMAND_FAILED","Unable to determine current iOS appearance for toggle",{stdout:n.stdout,stderr:n.stderr});return"dark"===a?"light":"dark"}let u8={faceid:{label:"Face ID",modalityAliases:["face"]},touchid:{label:"Touch ID",modalityAliases:["finger","touch"]}};async function u6(e,t,r,n){let a=await u7(e);if(!a.has(r))throw new D("UNSUPPORTED_OPERATION",`iOS simctl privacy does not support service "${r}" on this runtime.`,{deviceId:e.id,appBundleId:n,hint:`Supported services: ${Array.from(a).sort().join(", ")}`});let i=["privacy",e.id,t,r,n],o="notifications"===r;if(!("reset"===t&&o))try{await uq(e,i);return}catch(t){if(!(o&&u9(t)))throw t;throw new D("UNSUPPORTED_OPERATION","iOS simulator does not support setting notifications permission via simctl privacy on this runtime.",{deviceId:e.id,appBundleId:n,hint:"Use reset notifications for reprompt behavior, or toggle notifications manually in Settings."})}try{await uq(e,i);return}catch(e){if(!u9(e))throw e}try{await uq(e,["privacy",e.id,"reset","all",n])}catch(t){throw new D("COMMAND_FAILED","iOS simulator blocked direct notifications reset. Fallback reset-all also failed.",{deviceId:e.id,appBundleId:n,hint:"Use reinstall to force a fresh notifications prompt, or reset simulator content and settings."},t instanceof Error?t:void 0)}}function u9(e){if(!(e instanceof D)||"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 u7(t){let r=Z(t.simulatorSetPath),n=`${process.env.PATH??""}::${r??""}`;if(uV&&e===n)return uV;let a=await uq(t,["privacy","help"],{allowFailure:!0}),i=function(e){let t=new Set,r=!1;for(let n of e.split("\n")){let e=n.trim();if(!e)continue;if("service"===e){r=!0;continue}if(!r)continue;if(e.startsWith("bundle identifier"))break;let a=/^([a-z-]+)\s+-\s+/.exec(e),i=a?.[1];void 0!==i&&t.add(i)}return t}(`${a.stdout}
32
+ ${a.stderr}`);if(0===i.size)throw new D("COMMAND_FAILED","Unable to determine supported simctl privacy services",{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode,hint:"Run `xcrun simctl privacy help` manually to verify available services for this runtime."});return uV=i,e=n,i}async function de(e,t,r){let n=function(e,t,r){let n=r.length>0?r:["face"];switch(t){case"match":return n.flatMap(t=>[["biometric",e,"match",t],["biometric","match",e,t]]);case"nonmatch":return n.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,r.modalityAliases),a=[];for(let t of n){let r=rT(e,t),n=await rR(r,{allowFailure:!0});if(0===n.exitCode)return;a.push({args:r,stderr:n.stderr,stdout:n.stdout,exitCode:n.exitCode})}let i=lc(a);if(a.length>0&&a.every(e=>{var t,r;let n;return t=e.stdout,r=e.stderr,(n=`${t}
33
+ ${r}`.toLowerCase()).includes("unrecognized subcommand")||n.includes("unknown subcommand")||n.includes("not supported")||n.includes("unavailable")||n.includes("biometric")&&n.includes("invalid")}))throw new D("UNSUPPORTED_OPERATION",`${r.label} simulation is not supported on this simulator runtime.`,{deviceId:e.id,action:t,setting:r.settingName,attempts:i});throw new D("COMMAND_FAILED",`Failed to simulate ${r.settingName}.`,{deviceId:e.id,action:t,setting:r.settingName,attempts:i})}async function dt(e,t,r){await lL(e);let n=0,a=et.fromTimeoutMs(6e4);try{await es(async({deadline:n})=>{var a,i,o,s;let l;if(n?.isExpired())throw new D("COMMAND_FAILED","App launch deadline exceeded",{timeoutMs:6e4});let u=(i=e.id,o=t,s=r,l=["launch"],s?.launchConsole&&l.push("--console-pty"),l.push(i,o),s?.launchArgs&&l.push(...s.launchArgs),a=l,rT(e,a)),d=r?.launchConsole?await dr(u,r.launchConsole):await rR(u,{allowFailure:!0});if(0!==d.exitCode)throw new D("COMMAND_FAILED",`xcrun exited with code ${d.exitCode}`,{cmd:"xcrun",args:u,stdout:d.stdout,stderr:d.stderr,exitCode:d.exitCode})},{maxAttempts:10,baseDelayMs:1e3,maxDelayMs:5e3,jitter:.2,shouldRetry:e=>!!lO(e)&&(n+=1)<3},{deadline:a})}catch(r){if(lO(r)){var i;let n=(i=await lR(e,t)).installed?!1===i.simulatorCompatible?"ARCH_MISMATCH":"PERSISTENT_LAUNCH_FAIL":"APP_NOT_INSTALLED";r.details={...r.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."}}(n)}}throw r}}async function dr(e,t){await d.mkdir(f.dirname(t),{recursive:!0});try{let r=await rR(e,{allowFailure:!0,timeoutMs:25e3});return await dn(t,r.stdout,r.stderr),r}catch(n){let e=n instanceof D?n:void 0,r=e?.details;if(r?.timeoutMs===25e3){let e="string"==typeof r.stdout?r.stdout:"",n="string"==typeof r.stderr?r.stderr:"";return await dn(t,e,n),eN({level:"warn",phase:"ios_simulator_launch_console_capture_timeout",data:{timeoutMs:25e3,logPath:t,stdoutBytes:Buffer.byteLength(e),stderrBytes:Buffer.byteLength(n)}}),{stdout:e,stderr:n,exitCode:0}}throw n}}async function dn(e,t,r){var n,a;await d.writeFile(e,(n=t,a=r,!n||!a||n.endsWith("\n")||n.endsWith("\r")?`${n}${a}`:`${n}
34
+ ${a}`),"utf8")}async function da(e,t,r){let n=["device","process","launch","--device",e.id,t];r?.payloadUrl&&n.push("--payload-url",r.payloadUrl),await o0(n,{action:"launch iOS app",deviceId:e.id})}function di(e,t,r){return{command:"remotePress",remoteButton:e,...void 0!==r?{durationMs:r}:{},...void 0!==t?{appBundleId:t}:{}}}async function ds(e,t,r,n,a,i,o){if("tv"===t.target)return dd(await e(t,di(a,r.appBundleId),n),i);let s=o??await dl(e,t,r,n),l=sr({direction:a,amount:i?.amount,pixels:i?.pixels,referenceWidth:s.referenceWidth,referenceHeight:s.referenceHeight});return dd(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:r.appBundleId},n),{amount:l.amount,pixels:l.pixels,preferProvidedPixels:!0})}async function dl(e,t,r,n){let a=await e(t,{command:"interactionFrame",appBundleId:r.appBundleId},n),i=du(a.x),o=du(a.y),s=du(a.referenceWidth),l=du(a.referenceHeight);if(void 0===i||void 0===o||void 0===s||void 0===l)throw new D("COMMAND_FAILED","interactionFrame did not return a usable frame");return{originX:i,originY:o,referenceWidth:s,referenceHeight:l}}function du(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function dd(e,t){var r;let{x1:n,y1:a,x2:i,y2:o}={x1:du((r=e).x),y1:du(r.y),x2:du(r.x2),y2:du(r.y2)},s=du(e.referenceWidth),l=du(e.referenceHeight),u=void 0!==n&&void 0!==i?Math.round(Math.abs(i-n)):void 0,d=void 0!==a&&void 0!==o?Math.round(Math.abs(o-a)):void 0,c=t?.preferProvidedPixels&&void 0!==t.pixels?t.pixels:u&&u>0?u:d&&d>0?d:void 0;return{...void 0!==n?{x1:n}:{},...void 0!==a?{y1:a}:{},...void 0!==i?{x2:i}:{},...void 0!==o?{y2:o}:{},...void 0!==s?{referenceWidth:s}:{},...void 0!==l?{referenceHeight:l}:{},...t?.amount!==void 0?{amount:t.amount}:{},...void 0!==c?{pixels:c}:{}}}let dc=null;async function dp(){let e=oq();if(dc?.provider===e)return dc;let t=process.env.WAYLAND_DISPLAY||"wayland"===process.env.XDG_SESSION_TYPE?"wayland":"x11";if("wayland"===t){if(await e.whichCommand("ydotool"))return dc={tool:"ydotool",display:t,provider:e};throw new D("TOOL_MISSING","ydotool is required for input synthesis on Wayland (xdotool does not work on Wayland). Install it via your package manager.")}if(await e.whichCommand("xdotool"))return dc={tool:"xdotool",display:t,provider:e};throw new D("TOOL_MISSING","xdotool is required for input synthesis on X11. Install it via your package manager.")}async function df(...e){await oq().runCommand("xdotool",e,{allowFailure:!1,timeoutMs:1e4})}async function dm(...e){await oq().runCommand("ydotool",e,{allowFailure:!1,timeoutMs:1e4})}function dh(){return oq().input}async function dw(e,t){let{tool:r}=await dp();"xdotool"===r?await df("mousemove","--sync",String(e),String(t)):await dm("mousemove","--absolute","-x",String(e),"-y",String(t))}async function dg(e,t){let r=dh();if(r)return void await r.key(e,t);let{tool:n}=await dp();"xdotool"===n?await df("key","--clearmodifiers",e):await dm("key",...t)}async function dy(e,t,r,n){await dw(e,t);let{tool:a}=await dp();"xdotool"===a?await df("click",r):await dm("click",n)}async function dv(e,t,r,n,a){let i=dh();i?await i.click(e,t,r):await dy(e,t,n,a)}async function dI(e,t){await dv(e,t,"primary","1","0xC0")}async function db(e,t){await dv(e,t,"secondary","3","0xC1")}async function dA(e,t){await dv(e,t,"middle","2","0xC2")}async function dS(e,t){let r=dh();if(r)return void await r.doubleClick(e,t);let{tool:n}=await dp();await dw(e,t),"xdotool"===n?await df("click","--repeat","2","1"):(await dm("click","0xC0"),await dm("click","0xC0"))}async function dx(e,t,r=800){let n=dh();if(n)return void await n.longPress(e,t,r);let{tool:a}=await dp();await dw(e,t),"xdotool"===a?(await df("mousedown","1"),await e8(r),await df("mouseup","1")):(await dm("click","--down","0xC0"),await e8(r),await dm("click","--up","0xC0"))}async function d_(e,t){await dI(e,t)}async function dN(e,t,r,n,a=300){let i=dh();if(i)return void await i.drag(e,t,r,n,a);let{tool:o}=await dp();await dw(e,t),"xdotool"===o?(await df("mousedown","1"),await df("mousemove","--sync",String(r),String(n)),await e8(a),await df("mouseup","1")):(await dm("click","--down","0xC0"),await dm("mousemove","--absolute","-x",String(r),"-y",String(n)),await e8(a),await dm("click","--up","0xC0"))}async function dM(e,t){let r=dh();if(r)return void await r.scroll(e,t);let{tool:n}=await dp(),a=5;if(t?.pixels!=null?a="xdotool"===n?Math.max(1,Math.round(t.pixels/15)):Math.max(1,Math.round(t.pixels/40)):t?.amount!=null&&(a=Math.max(1,Math.round(5*(t.amount/.6)))),"xdotool"===n)await df("click","--repeat",String(a),"up"===e?"4":"down"===e?"5":"left"===e?"6":"7");else if("up"===e||"down"===e){let t="up"===e?String(-a):String(a);await dm("mousemove","--wheel","-y",t)}else{let t="left"===e?String(-a):String(a);await dm("mousemove","--wheel","-x",t)}}async function dk(e,t=0){let r=dh();if(r)return void await r.typeText(e,{delayMs:t});let{tool:n}=await dp();if("xdotool"===n){let r=["type"];t>0&&r.push("--delay",String(t)),r.push("--clearmodifiers","--",e),await df(...r)}else await dm("type","--",e)}async function dD(e,t,r,n=0){await dI(e,t),await e8(100),await dg("ctrl+a",["29:1","30:1","30:0","29:0"]),await e8(50),await dk(r,n)}async function dP(e){await oq().desktop.openTarget(e)}async function dO(e){await oq().desktop.closeApp(e)}async function dR(){await dg("alt+Left",["56:1","105:1","105:0","56:0"])}async function dE(){await dg("super+d",["125:1","32:1","32:0","125:0"])}async function dC(){return await oq().clipboard.readText()}async function dL(e){await oq().clipboard.writeText(e)}async function dT(e,t){await oq().screenshot.capture(e,t)}let d$={"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"},dF="atspi-dump.py",dU=null;async function dV(e,t={}){let r,n=oq().accessibility;if(n)return await n.captureTree(e,t);if("linux"!==process.platform)throw new D("UNSUPPORTED_PLATFORM","AT-SPI2 bridge is only available on Linux");if(!await oq().whichCommand("python3"))throw new D("TOOL_MISSING","python3 is required for AT-SPI2 accessibility snapshots on Linux.");let a=t.maxNodes??1500,i=t.maxDepth??12,o=t.maxApps??24,s=[function(){if(dU)return dU;let e=f.dirname(g(import.meta.url));for(let t=0;t<5;t++){let r=f.join(e,"src","platforms","linux",dF);if(l.existsSync(r))return dU=r,r;if(0===t){let t=f.join(e,dF);if(l.existsSync(t))return dU=t,t}e=f.dirname(e)}throw new D("TOOL_MISSING",`Cannot find ${dF}. Ensure the agent-device package is installed correctly.`)}(),"--surface",e,"--max-nodes",String(a),"--max-depth",String(i),"--max-apps",String(o)],u=await oj("python3",s,{allowFailure:!0,timeoutMs:3e4});if(0!==u.exitCode){let e=u.stderr.trim();if(e.includes("No module named")||e.includes("gi.require_version"))throw new D("TOOL_MISSING","AT-SPI2 Python bindings not found. Install python3-gi and gir1.2-atspi-2.0.",{cause:e});throw new D("COMMAND_FAILED",`AT-SPI2 snapshot failed (exit ${u.exitCode}): ${e||u.stdout}`)}try{r=JSON.parse(u.stdout)}catch{throw new D("COMMAND_FAILED",`AT-SPI2 snapshot returned invalid JSON: ${u.stdout.slice(0,200)}`)}if(r.error)throw new D("COMMAND_FAILED",`AT-SPI2: ${r.error}`);return{nodes:(r.nodes??[]).map(e=>{let t,r;return{index:e.index,type:(r=d$[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:r.truncated,surface:e}}async function dG(e){let t="desktop"===e?"desktop":"frontmost-app"===e||"app"===e?"frontmost-app":("menubar"===e&&eN({level:"warn",phase:"linux_snapshot",data:{message:"menubar surface is not supported on Linux, falling back to desktop"}}),"desktop"),r=await dV(t);return{nodes:r.nodes,truncated:r.truncated}}async function dq(e,t,r){let{nodes:n}=await dG(r);for(let r of n.filter(r=>{let n=r.rect;return!!n&&e>=n.x&&t>=n.y&&e<=n.x+n.width&&t<=n.y+n.height}).sort((e,t)=>{let r=e.depth??0,n=t.depth??0;return r!==n?n-r:dB(e.rect)-dB(t.rect)})){let e=function(e){for(let t of[e.value,e.label,e.identifier])if("string"==typeof t&&t.length>0)return t;return""}(r);if(e.trim())return e}return""}function dB(e){return(e?.width??0)*(e?.height??0)}let dj=/^[A-Za-z0-9_.:-]{1,64}$/;function dH(e){return e?.clickButton??"primary"}function dW(e){return"primary"===e.button?null:"click"!==e.commandLabel?new D("INVALID_ARGS","--button is supported only for click"):"macos"!==e.platform&&"linux"!==e.platform?new D("UNSUPPORTED_OPERATION",`click --button ${e.button} is supported only on macOS and Linux`):"macos"===e.platform&&"middle"===e.button?new D("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 D("INVALID_ARGS",`click --button ${e.button} does not support repeat or gesture modifier flags`):null}let dz=[[0,0],[1,0],[0,1],[-1,0],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]];async function dK(e,t,r){for(let n=0;n<e;n+=1)await r(n),n<e-1&&t>0&&await e8(t)}async function dJ(e,t){let{x:r,y:n}=d2(t,"longpress requires x y [durationMs]",{hint:"Direct platform longpress requires coordinates. In an open daemon session, use agent-device longpress @ref|selector [durationMs]; otherwise run snapshot -i -c, use the target rect center as x y, then retry longpress x y durationMs."}),a=t[2]?Number(t[2]):void 0;return await e.longPress(r,n,a),{x:r,y:n,durationMs:a,...eJ(`Long pressed (${r}, ${n})`)}}async function dX(e,t){let{x:r,y:n}=d2(t,"focus requires x y");return await e.focus(r,n),{x:r,y:n,...eJ(`Focused (${r}, ${n})`)}}async function dY(e,t,r){let n=tV(t[0]);if(n)throw new D("INVALID_ARGS",`type does not accept a target ref like "${n}"`,{hint:`Use fill ${n} "text" to target that field, or press ${n} then type "text" to append.`});let a=t.join(" ");if(!a)throw new D("INVALID_ARGS","type requires text");let i=tL(r?.delayMs??0,"delay-ms",0,1e4);return await e.type(a,i),{text:a,delayMs:i,...eJ(cc("Typed",a))}}async function dZ(e,t,r){if(r?.directElementSelector)return await dQ(e,r.directElementSelector,t,r);let n=Number(t[0]),a=Number(t[1]),i=t.slice(2).join(" ");if(Number.isNaN(n)||Number.isNaN(a)||!i)throw new D("INVALID_ARGS","fill requires x y text");let o=tL(r?.delayMs??0,"delay-ms",0,1e4);return await e.fill(n,a,i,o),{x:n,y:a,text:i,delayMs:o,...eJ(cc("Filled",i))}}async function dQ(e,t,r,n){if(!e.fillElementSelector)throw new D("UNSUPPORTED_OPERATION","direct element selector fill is not supported");let a=r.join(" ");if(!a)throw new D("INVALID_ARGS","fill requires text");let i=tL(n.delayMs??0,"delay-ms",0,1e4),o=await e.fillElementSelector(t,a,i);return{selector:t.raw,text:a,delayMs:i,...o??{},...eJ(cc("Filled",a))}}async function d0(e,t,r,n){var a,i,o,s;if(n?.directElementSelector&&"ios"===e.platform)return await d1(t,n.directElementSelector);let{x:l,y:u}=d2(r,"press requires x y");if("macos"===e.platform&&n?.surface&&"app"!==n.surface)return await d3(l,u,n);let d=dH(n);if("primary"!==d)return await d5(e,l,u,d,n);let c=(s=n,{count:d8(s?.count,1,"count",1,200),intervalMs:d8(s?.intervalMs,0,"interval-ms",0,1e4),holdMs:d8(s?.holdMs,0,"hold-ms",0,1e4),jitterPx:d8(s?.jitterPx,0,"jitter-px",0,100),doubleTap:!!s?.doubleTap});return(function({doubleTap:e,holdMs:t,jitterPx:r}){if(e&&t>0)throw new D("INVALID_ARGS","double-tap cannot be combined with hold-ms");if(e&&r>0)throw new D("INVALID_ARGS","double-tap cannot be combined with jitter-px")}(c),a=c.count,i=c.holdMs,o=c.jitterPx,r8(e.platform)&&a>1&&0===i&&0===o)?await d6(e,l,u,c,n):await d9(t,l,u,c)}async function d1(e,t){if(!e.tapElementSelector)throw new D("UNSUPPORTED_OPERATION","direct element selector tap is not supported");let r=await e.tapElementSelector(t);return{selector:t.raw,...r??{},...eJ(`Tapped ${t.raw}`)}}function d2(e,t,r){let n=Number(e[0]),a=Number(e[1]);if(Number.isNaN(n)||Number.isNaN(a))throw new D("INVALID_ARGS",t,r);return{x:n,y:a}}async function d3(e,t,r){let n=dH(r);if("primary"!==n)throw new D("UNSUPPORTED_OPERATION",`${n} click is not supported on macOS ${r.surface} sessions.`);return await ue(e,t,{bundleId:r.appBundleId,surface:r.surface}),{x:e,y:t,...eJ(cu({x:e,y:t}))}}async function d5(e,t,r,n,a){return(function(e,t,r){let n=dW({commandLabel:"click",platform:e.platform,button:t,count:r?.count,intervalMs:r?.intervalMs,holdMs:r?.holdMs,jitterPx:r?.jitterPx,doubleTap:r?.doubleTap});if(n)throw n}(e,n,a),"linux"===e.platform)?await d4(t,r,n):(await am(e,{command:"mouseClick",x:t,y:r,button:n,appBundleId:a?.appBundleId},d7(a)),{x:t,y:r,button:n,...eJ(cu({x:t,y:r,button:n}))})}async function d4(e,t,r){return"secondary"===r?await db(e,t):await dA(e,t),{x:e,y:t,button:r,...eJ(cu({x:e,y:t,button:r}))}}function d8(e,t,r,n,a){return tL(void 0===e?t:e,r,n,a)}async function d6(e,t,r,n,a){let i=await am(e,{command:"tapSeries",x:t,y:r,count:n.count,intervalMs:n.intervalMs,doubleTap:n.doubleTap,appBundleId:a?.appBundleId},d7(a));return{x:t,y:r,count:n.count,intervalMs:n.intervalMs,holdMs:n.holdMs,jitterPx:n.jitterPx,doubleTap:n.doubleTap,timingMode:"runner-series",...i,...eJ(cu({x:t,y:r}))}}async function d9(e,t,r,n){let a;return await dK(n.count,n.intervalMs,async i=>{let[o,s]=function(e,t){if(t<=0)return[0,0];let[r,n]=dz[e%dz.length];return[r*t,n*t]}(i,n.jitterPx),l=t+o,u=r+s;if(n.doubleTap){a??=await e.doubleTap(l,u)??void 0;return}n.holdMs>0?a??=await e.longPress(l,u,n.holdMs)??void 0:a??=await e.tap(l,u)??void 0}),eV({x:t,y:r,count:n.count,intervalMs:n.intervalMs,holdMs:n.holdMs,jitterPx:n.jitterPx,doubleTap:n.doubleTap,...a},cu({x:t,y:r}))}function d7(e){return{verbose:e?.verbose,logPath:e?.logPath,traceLogPath:e?.traceLogPath,requestId:e?.requestId}}async function ce(e,t,r,n){let a=Number(r[0]),i=Number(r[1]),o=Number(r[2]),s=Number(r[3]);if([a,i,o,s].some(Number.isNaN))throw new D("INVALID_ARGS","swipe requires x1 y1 x2 y2 [durationMs]");let l=tL(r[4]?Number(r[4]):250,"durationMs",16,1e4),u="ios"===e.platform?Math.min(60,Math.max(16,Math.round(l))):l,d=tL(n?.count??1,"count",1,200),c=tL(n?.pauseMs??0,"pause-ms",0,1e4),p=n?.pattern??"one-way";if("one-way"!==p&&"ping-pong"!==p)throw new D("INVALID_ARGS",`Invalid pattern: ${p}`);if(r8(e.platform)&&d>1){let t=await am(e,{command:"dragSeries",x:a,y:i,x2:o,y2:s,durationMs:u,count:d,pauseMs:c,pattern:p,appBundleId:n?.appBundleId},{verbose:n?.verbose,logPath:n?.logPath,traceLogPath:n?.traceLogPath,requestId:n?.requestId});return{x1:a,y1:i,x2:o,y2:s,durationMs:l,effectiveDurationMs:u,timingMode:"runner-series",count:d,pauseMs:c,pattern:p,...t,...eJ(cd(d,p))}}return await dK(d,c,async e=>{"ping-pong"===p&&e%2==1?await t.swipe(o,s,a,i,u):await t.swipe(a,i,o,s,u)}),eV({x1:a,y1:i,x2:o,y2:s,durationMs:l,effectiveDurationMs:u,timingMode:"ios"===e.platform?"safe-normalized":"direct",count:d,pauseMs:c,pattern:p},cd(d,p))}async function ct(e,t){let r=Number(t[0]),n=Number(t[1]),a=Number(t[2]),i=Number(t[3]);if([r,n,a,i].some(e=>!Number.isFinite(e)))throw new D("INVALID_ARGS","gesture pan requires x y dx dy [durationMs]");let o=tL(t[4]?Number(t[4]):500,"durationMs",16,1e4),s=r+a,l=n+i;return await e.pan(r,n,s,l,o),{x:r,y:n,dx:a,dy:i,x2:s,y2:l,durationMs:o,...eJ(`Panned (${r}, ${n}) by (${a}, ${i})`)}}async function cr(e,t){let r=function(e,t){if("up"===e||"down"===e||"left"===e||"right"===e)return e;throw new D("INVALID_ARGS",`${t} must be up, down, left, or right`)}(t[0],"fling direction"),n=Number(t[1]),a=Number(t[2]);if(![n,a].every(Number.isFinite))throw new D("INVALID_ARGS","gesture fling requires direction x y [distance] [durationMs]");let i=function(e,t){if(!Number.isFinite(e)||e<=0)throw new D("INVALID_ARGS",`${t} must be a positive number`);return e}(t[3]?Number(t[3]):180,"distance"),o=tL(t[4]?Number(t[4]):50,"durationMs",16,1e3),{x2:s,y2:l}=function(e,t,r,n){switch(r){case"up":return{x2:e,y2:t-n};case"down":return{x2:e,y2:t+n};case"left":return{x2:e-n,y2:t};case"right":return{x2:e+n,y2:t}}}(n,a,r,i);return await e.fling(n,a,s,l,o),{direction:r,x:n,y:a,x2:s,y2:l,distance:i,durationMs:o,...eJ(`Flung ${r}`)}}async function cn(e,t,r){var n;let a=t[0],i=t[1]?Number(t[1]):void 0,o=r?.pixels;if(!a)throw new D("INVALID_ARGS","scroll requires direction");if(void 0!==i&&!Number.isFinite(i))throw new D("INVALID_ARGS","scroll amount must be a number");if(void 0!==i&&void 0!==o)throw new D("INVALID_ARGS","scroll accepts either a relative amount or --pixels, not both");let s="bottom"===(n=a)?{direction:"down",edge:"bottom"}:"top"===n?{direction:"up",edge:"top"}:{direction:function(e){switch(e){case"up":case"down":case"left":case"right":return e;default:throw new D("INVALID_ARGS",`Unknown direction: ${e}`)}}(n)},l={},u=0;if(s.edge){let t=s.edge,n=await tE({edge:t,captureState:async n=>await ca(e,r,t,n),scroll:async()=>await e.scroll(s.direction,{amount:i,pixels:o})});l=n.result??{},u=n.passes}else l=await e.scroll(s.direction,{amount:i,pixels:o}),u=1;return eV({direction:s.direction,...s.edge?{edge:s.edge,passes:u}:{},...void 0!==i?{amount:i}:{},...void 0!==o?{pixels:o}:{},...l},tb(s.direction,s.edge,u,i,o))}async function ca(e,t,r,n){if("function"!=typeof e.snapshot)throw new D("UNSUPPORTED_OPERATION",`scroll ${r} requires snapshot support to verify hidden content before scrolling`);let a=e.snapshot;return await tk({edge:r,scope:n,captureNodes:async e=>(await a({appBundleId:t?.appBundleId,compact:!0,scope:e})).nodes??[]})}async function ci(e,t,r,n){if("tv"===e.target)throw new D("UNSUPPORTED_OPERATION","gesture pinch is not supported on tvOS");if("macos"===e.platform&&n?.surface&&"app"!==n.surface)throw new D("UNSUPPORTED_OPERATION","gesture pinch is only supported in macOS app sessions. Re-open the target app without --surface desktop|menubar|frontmost-app first.");let a=Number(r[0]),i=r[1]?Number(r[1]):void 0,o=r[2]?Number(r[2]):void 0;if(Number.isNaN(a)||a<=0)throw new D("INVALID_ARGS","gesture pinch requires scale > 0");let s=await t.pinch(a,i,o);return{scale:a,x:i,y:o,...s,...eJ(`Pinched to scale ${a}`)}}async function co(e,t,r){if("tv"===e.target)throw new D("UNSUPPORTED_OPERATION","gesture rotate is not supported on tvOS");if("macos"===e.platform)throw new D("UNSUPPORTED_OPERATION","gesture rotate is not supported on macOS; XCTest rotation gestures are available only for iOS app sessions.");let{degrees:n,x:a,y:i,velocity:o}=function(e){let t=Number(e[0]);if(!Number.isFinite(t))throw new D("INVALID_ARGS","gesture rotate requires degrees [x] [y] [velocity]");let r=function(e,t){if(void 0===e&&void 0===t)return{};if(void 0===e||void 0===t)throw new D("INVALID_ARGS","gesture rotate center requires both x and y");let r=Number(e),n=Number(t);if(!Number.isFinite(r)||!Number.isFinite(n))throw new D("INVALID_ARGS","gesture rotate center requires finite x and y");return{x:r,y:n}}(e[1],e[2]),n=Number(e[3]??(t>=0?1:-1));if(!Number.isFinite(n)||0===n)throw new D("INVALID_ARGS","gesture rotate velocity must be a non-zero number");return{degrees:t,...r,velocity:Math.abs(n)*(t>=0?1:-1)}}(r),s=await t.rotateGesture(n,a,i,o);return{degrees:n,...void 0!==a&&void 0!==i?{x:a,y:i}:{},velocity:o,...s,...eJ(`Rotated gesture ${n} degrees`)}}async function cs(e,t,r){if("tv"===e.target)throw new D("UNSUPPORTED_OPERATION","gesture transform is not supported on tvOS");let n="ios"===e.platform&&"simulator"===e.kind;if("android"!==e.platform&&!n)throw new D("UNSUPPORTED_OPERATION","gesture transform is currently supported on Android and iOS simulators");let a=function(e){let t=Number(e[0]),r=Number(e[1]),n=Number(e[2]),a=Number(e[3]),i=Number(e[4]),o=Number(e[5]);if(![t,r,n,a,i,o].every(Number.isFinite))throw new D("INVALID_ARGS","gesture transform requires x y dx dy scale degrees [durationMs]");if(i<=0)throw new D("INVALID_ARGS","gesture transform scale must be > 0");return{x:t,y:r,dx:n,dy:a,scale:i,degrees:o,durationMs:void 0===e[6]?void 0:tL(Number(e[6]),"durationMs",16,1e4)}}(r),i=await t.transformGesture(a);return{...a,...i,...eJ(`Requested transform gesture by (${a.dx}, ${a.dy}), scale ${a.scale}, rotate ${a.degrees} degrees`)}}async function cl(e,t,r){let{x:n,y:a}=d2(t,"read requires x y");if("android"===e.platform)return{action:"read",text:await sk(e,n,a)??""};if("linux"===e.platform)return{action:"read",text:await dq(n,a,r?.surface)};if("macos"===e.platform&&r?.surface&&"app"!==r.surface)return{action:"read",text:(await l7(n,a,{bundleId:r.appBundleId,surface:r.surface})).text};let i=await am(e,{command:"readText",x:n,y:a,appBundleId:r?.appBundleId},{verbose:r?.verbose,logPath:r?.logPath,traceLogPath:r?.traceLogPath,requestId:r?.requestId});return{action:"read",text:"string"==typeof i.text?i.text:"string"==typeof i.message?i.message:""}}function cu(e){return e.button&&"primary"!==e.button?`Clicked ${e.button} (${e.x}, ${e.y})`:`Tapped (${e.x}, ${e.y})`}function cd(e,t){return e<=1?"Swiped":"ping-pong"===t?`Swiped ${e} times (ping-pong)`:`Swiped ${e} times`}function cc(e,t){return`${e} ${Array.from(t).length} chars`}function cp(e,t){let r,n=t?.subject??"Payload",a=e.trim();if(!a)throw new D("INVALID_ARGS",`${n} cannot be empty`);let i=t?.expandPath?t.expandPath(a,t.cwd):a;try{if(!l.statSync(i).isFile())throw new D("INVALID_ARGS",`${n} path is not a file: ${i}`);return{kind:"file",path:i}}catch(t){if(t instanceof D)throw t;let e=t.code;if("EACCES"===e||"EPERM"===e)throw new D("INVALID_ARGS",`${n} file is not readable: ${i}`);if(e&&"ENOENT"!==e)throw new D("COMMAND_FAILED",`Unable to read ${n} file: ${i}`,{cause:String(t)})}if((r=a.trim()).startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))return{kind:"inline",text:a};throw new D("INVALID_ARGS",`${n} file not found: ${i}`)}async function cf(e){let t=cp(e,{subject:"Push payload"}),r="inline"===t.kind?t.text:await cm(t.path);try{let e=JSON.parse(r);if(!e||"object"!=typeof e||Array.isArray(e))throw new D("INVALID_ARGS","push payload must be a JSON object");return e}catch(t){if(t instanceof D)throw t;throw new D("INVALID_ARGS",`Invalid push payload JSON: ${e}`)}}async function cm(e){try{return await d.readFile(e,"utf8")}catch(r){let t=r.code;if("ENOENT"===t)throw new D("INVALID_ARGS",`Push payload file not found: ${e}`);if("EISDIR"===t)throw new D("INVALID_ARGS",`Push payload path is not a file: ${e}`);if("EACCES"===t||"EPERM"===t)throw new D("INVALID_ARGS",`Push payload file is not readable: ${e}`);throw new D("COMMAND_FAILED",`Unable to read push payload file: ${e}`,{cause:String(r)})}}async function ch(e,t,r,n,a){let i={requestId:a?.requestId,appBundleId:a?.appBundleId,verbose:a?.verbose,logPath:a?.logPath,traceLogPath:a?.traceLogPath},o=function(e,t){switch(e.platform){case"android":return{open:(t,r)=>B(e,t,{activity:r?.activity,appBundleId:r?.appBundleId,url:r?.url}),openDevice:()=>W(e),close:t=>j(e,t),tap:(t,r)=>sC(e,t,r),doubleTap:async(t,r)=>{await sC(e,t,r),await sC(e,t,r)},swipe:(t,r,n,a,i)=>sL(e,t,r,n,a,i),pan:(t,r,n,a,i)=>sL(e,t,r,n,a,i),fling:(t,r,n,a,i)=>sL(e,t,r,n,a,i),longPress:(t,r,n)=>sG(e,t,r,n),focus:(t,r)=>sB(e,t,r),type:(t,r)=>sq(e,t,r),fill:(t,r,n,a)=>sj(e,t,r,n,a),scroll:(t,r)=>sW(e,t,r),pinch:(t,r,n)=>s8(e,{scale:t,x:r,y:n}),screenshot:(t,r)=>l_(e,t,r),snapshot:async t=>{let r=await e_("snapshot_capture",async()=>await sd(e,{interactiveOnly:t?.interactiveOnly,compact:t?.compact,depth:t?.depth,scope:t?.scope,raw:t?.raw}),{backend:"android"});return{nodes:r.nodes??[],truncated:r.truncated??!1,backend:"android",analysis:r.analysis,androidSnapshot:r.androidSnapshot}},back:t=>sT(e),home:()=>s$(e),rotate:t=>sU(e,t),rotateGesture:(t,r,n,a)=>s6(e,{degrees:t,x:r,y:n,velocity:a}),transformGesture:t=>s9(e,t),appSwitcher:()=>sV(e),readClipboard:()=>J(e),writeClipboard:t=>q(e,t),setSetting:(t,r,n,a)=>ly(e,t,r,n,a)};case"linux":return{open:e=>dP(e),openDevice:()=>Promise.resolve(),close:e=>dO(e),tap:(e,t)=>dI(e,t),doubleTap:(e,t)=>dS(e,t),swipe:(e,t,r,n,a)=>dN(e,t,r,n,a),pan:(e,t,r,n,a)=>dN(e,t,r,n,a),fling:()=>{throw new D("UNSUPPORTED_OPERATION","gesture fling not supported on Linux")},longPress:(e,t,r)=>dx(e,t,r),focus:(e,t)=>d_(e,t),type:(e,t)=>dk(e,t),fill:(e,t,r,n)=>dD(e,t,r,n),scroll:(e,t)=>dM(e,t),pinch:()=>{throw new D("UNSUPPORTED_OPERATION","gesture pinch not supported on Linux")},screenshot:(e,t)=>dT(e,t),snapshot:async e=>{let t=await e_("snapshot_capture",async()=>await dG(e?.surface),{backend:"linux-atspi"});return{nodes:t.nodes??[],truncated:t.truncated??!1,backend:"linux-atspi"}},back:()=>dR(),home:()=>dE(),rotate:()=>{throw new D("UNSUPPORTED_OPERATION","rotate not supported on Linux")},rotateGesture:()=>{throw new D("UNSUPPORTED_OPERATION","gesture rotate not supported on Linux")},transformGesture:()=>{throw new D("UNSUPPORTED_OPERATION","gesture transform not supported on Linux")},appSwitcher:()=>{throw new D("UNSUPPORTED_OPERATION","appSwitcher not yet supported on Linux")},readClipboard:()=>dC(),writeClipboard:e=>dL(e),setSetting:()=>{throw new D("UNSUPPORTED_OPERATION","setSetting not supported on Linux")}};case"ios":case"macos":return function(e,t){let r,{overrides:n,runnerOpts:a}={runnerOpts:r={verbose:t.verbose,logPath:t.logPath,traceLogPath:t.traceLogPath,requestId:t.requestId},overrides:{tap:async(n,a)=>await am(e,{command:"tap",x:n,y:a,appBundleId:t.appBundleId},r),tapElementSelector:async n=>await am(e,{command:"tap",selectorKey:n.key,selectorValue:n.value,allowNonHittableCoordinateFallback:n.allowNonHittableCoordinateFallback,appBundleId:t.appBundleId},r),doubleTap:async(n,a)=>await am(e,{command:"tapSeries",x:n,y:a,count:1,intervalMs:0,doubleTap:!0,appBundleId:t.appBundleId},r),swipe:async(n,a,i,o,s)=>await am(e,{command:"drag",x:n,y:a,x2:i,y2:o,durationMs:s,appBundleId:t.appBundleId},r),pan:async(n,a,i,o,s)=>await am(e,{command:"drag",x:n,y:a,x2:i,y2:o,durationMs:s??500,appBundleId:t.appBundleId},r),fling:async(n,a,i,o,s)=>await am(e,{command:"drag",x:n,y:a,x2:i,y2:o,durationMs:s??16,appBundleId:t.appBundleId},r),longPress:async(n,a,i)=>await am(e,{command:"longPress",x:n,y:a,durationMs:i,appBundleId:t.appBundleId},r),focus:async(n,a)=>await am(e,{command:"tap",x:n,y:a,appBundleId:t.appBundleId},r),type:async(n,a)=>{await am(e,{command:"type",text:n,delayMs:a,textEntryMode:"\n"===n?void 0:"append",appBundleId:t.appBundleId},r)},fillElementSelector:async(n,a,i)=>await am(e,{command:"type",selectorKey:n.key,selectorValue:n.value,allowNonHittableCoordinateFallback:n.allowNonHittableCoordinateFallback,text:a,delayMs:i,textEntryMode:"replace",appBundleId:t.appBundleId},r),fill:async(n,a,i,o)=>await am(e,{command:"type",x:n,y:a,text:i,delayMs:o,textEntryMode:"replace",appBundleId:t.appBundleId},r),scroll:async(n,a)=>await ds(am,e,t,r,n,a),pinch:async(n,a,i)=>{await am(e,{command:"pinch",scale:n,x:a,y:i,appBundleId:t.appBundleId},r)},rotateGesture:async(n,a,i,o)=>{await am(e,{command:"rotateGesture",degrees:n,x:a,y:i,velocity:o,appBundleId:t.appBundleId},r)},transformGesture:async n=>await am(e,{command:"transformGesture",x:n.x,y:n.y,dx:n.dx,dy:n.dy,scale:n.scale,degrees:n.degrees,durationMs:n.durationMs,appBundleId:t.appBundleId},r)}};return{open:(t,r)=>uH(e,t,{appBundleId:r?.appBundleId,launchConsole:r?.launchConsole,launchArgs:r?.launchArgs,url:r?.url}),openDevice:()=>uW(e),close:t=>uz(e,t),screenshot:async(t,r)=>{"macos"===e.platform&&r?.surface&&"app"!==r.surface?await ut(t,{surface:r.surface,fullscreen:r.fullscreen}):await uk(e,t,r?.appBundleId,r?.fullscreen,a)},snapshot:async t=>{var r;let n={nodes:Array.isArray((r=await e_("snapshot_capture",async()=>await am(e,{command:"snapshot",appBundleId:t?.appBundleId,interactiveOnly:t?.interactiveOnly,compact:t?.compact,depth:t?.depth,scope:t?.scope,raw:t?.raw},a),{backend:"xctest"})).nodes)?r.nodes:void 0,truncated:"boolean"==typeof r.truncated?r.truncated:void 0},i=n.nodes??[];if(0===i.length&&"simulator"===e.kind)throw new D("COMMAND_FAILED","XCTest snapshot returned 0 nodes on iOS simulator.");return{nodes:i,truncated:n.truncated??!1,backend:"xctest"}},back:async r=>{"tv"===e.target?await am(e,di("menu",t.appBundleId),a):await am(e,{command:"system"===r?"backSystem":"backInApp",appBundleId:t.appBundleId},a)},home:async()=>{"tv"===e.target?await am(e,di("home",t.appBundleId),a):await am(e,{command:"home",appBundleId:t.appBundleId},a)},rotate:async r=>{await am(e,{command:"rotate",orientation:r,appBundleId:t.appBundleId},a)},appSwitcher:async()=>{await am(e,{command:"appSwitcher",appBundleId:t.appBundleId},a)},readClipboard:()=>uQ(e),writeClipboard:t=>u0(e,t),setSetting:(t,r,n,a)=>u2(e,t,r,n,a),...n}}(e,t);default:throw new D("UNSUPPORTED_PLATFORM",`Unsupported platform: ${e.platform}`)}}(e,i);return eN({level:"debug",phase:"platform_command_prepare",data:{command:t,platform:e.platform,kind:e.kind}}),await e_("platform_command",async()=>await cw(e,o,t,r,n,a,i),{command:t,platform:e.platform})}async function cw(e,t,r,n,a,i,o){switch(r){case"open":return await cg(e,t,n,i);case"close":{let e=n[0];if(!e)return{closed:"session",...eJ("Closed session")};return await t.close(e),{app:e,...eJ(`Closed: ${e}`)}}case"press":return await d0(e,t,n,i);case"swipe":return await ce(e,t,n,i);case"pan":return await ct(t,n);case"fling":return await cr(t,n);case"longpress":return await dJ(t,n);case"focus":return await dX(t,n);case"type":return await dY(t,n,i);case"fill":return await dZ(t,n,i);case"scroll":return await cn(t,n,i);case"pinch":return await ci(e,t,n,i);case"rotate-gesture":return await co(e,t,n);case"transform-gesture":return await cs(e,t,n);case"trigger-app-event":return await cy(e,t,n,i);case"screenshot":return await cv(t,n,a,i);case"back":return await t.back(i?.backMode),{action:"back",mode:i?.backMode??"in-app",...eJ("Back")};case"home":return await t.home(),{action:"home",...eJ("Home")};case"rotate":{let e=e1(n[0]);return await t.rotate(e),{action:"rotate",orientation:e,...eJ(`Rotated to ${e}`)}}case"app-switcher":return await t.appSwitcher(),{action:"app-switcher",...eJ("Opened app switcher")};case"clipboard":return await cI(t,n);case"keyboard":return await cb(e,n,i,o);case"settings":return await cx(e,t,n,i);case"push":return await c_(e,n,i);case"snapshot":return await cN(t,i);case"read":return await cl(e,n,i);default:throw new D("INVALID_ARGS",`Unknown command: ${r}`)}}async function cg(e,t,r,n){let a=r[0],i=r[1],o=n?.launchConsole;if(r.length>2)throw new D("INVALID_ARGS","open accepts at most two arguments: <app|url> [url]");if(!a){if(o)throw new D("INVALID_ARGS","--launch-console requires an app target");return await t.openDevice(),{app:null,...eJ("Opened device")}}if(o&&("ios"!==e.platform||"simulator"!==e.kind))throw new D("UNSUPPORTED_OPERATION",lD);if(void 0!==i){if(ef(a))throw new D("INVALID_ARGS","open <app> <url> requires an app target as the first argument");if(!ef(i))throw new D("INVALID_ARGS","open <app> <url> requires a valid URL target");if(o)throw new D("INVALID_ARGS",lP);return await t.open(a,{activity:n?.activity,appBundleId:n?.appBundleId,launchArgs:n?.launchArgs,url:i}),{app:a,url:i,...eJ(`Opened: ${a}`)}}if(o&&ef(a))throw new D("INVALID_ARGS",lP);if("android"===e.platform&&n?.launchArgs&&n.launchArgs.length>0)throw new D("UNSUPPORTED_OPERATION","Launch arguments are currently supported only on Apple platforms.");if(n?.clearAppState){if(ef(a))throw new D("INVALID_ARGS","Clearing app state requires an app target, not a deep link.");if("ios"!==e.platform||"simulator"!==e.kind)throw new D("UNSUPPORTED_OPERATION","Clearing app state is currently supported only on iOS simulators.");await uK(e,a)}return await t.open(a,{activity:n?.activity,appBundleId:n?.appBundleId,launchConsole:o,launchArgs:n?.launchArgs}),{app:a,...o?{launchConsole:o}:{},...eJ(`Opened: ${a}`)}}async function cy(e,t,r,n){let{eventName:a,payload:i}=function(e){let t=e[0]?.trim(),r=e[1]?.trim();if(!t)throw new D("INVALID_ARGS","trigger-app-event requires <event> [payloadJson]");if(!dj.test(t))throw new D("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 D("INVALID_ARGS","trigger-app-event accepts at most two arguments: <event> [payloadJson]");let n=function(e,t){if(e)try{let r=JSON.parse(e);if(!r||"object"!=typeof r||Array.isArray(r))throw new D("INVALID_ARGS",`trigger-app-event payload for "${t}" must be a JSON object`);let n=JSON.stringify(r);if(Buffer.byteLength(n,"utf8")>8192)throw new D("INVALID_ARGS",`trigger-app-event payload for "${t}" exceeds 8192 bytes`);return r}catch(t){if(t instanceof D)throw t;throw new D("INVALID_ARGS",`Invalid trigger-app-event payload JSON: ${e}`)}}(r,t);return{eventName:t,payload:n}}(r),o=function(e,t,r){var n;let a,i=(a=("ios"===(n=e)?process.env.AGENT_DEVICE_IOS_APP_EVENT_URL_TEMPLATE:"macos"===n?process.env.AGENT_DEVICE_MACOS_APP_EVENT_URL_TEMPLATE:process.env.AGENT_DEVICE_ANDROID_APP_EVENT_URL_TEMPLATE)??process.env.AGENT_DEVICE_APP_EVENT_URL_TEMPLATE,a?.trim()||void 0);if(!i)throw new D("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=r?JSON.stringify(r):"",s=i.replaceAll("{event}",encodeURIComponent(t)).replaceAll("{payload}",encodeURIComponent(o)).replaceAll("{platform}",encodeURIComponent(e));if(s.length>4096)throw new D("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,a,i);return await t.open(o,{appBundleId:n?.appBundleId}),{event:a,eventUrl:o,transport:"deep-link",...eJ(`Triggered app event: ${a}`)}}async function cv(e,t,r,n){let a=t[0]??r??`./screenshot-${Date.now()}.png`;await d.mkdir(f.dirname(a),{recursive:!0});let i=eX(n);return await e.screenshot(a,{appBundleId:n?.appBundleId,fullscreen:i.fullscreen,stabilize:i.stabilize,surface:n?.surface}),{path:a,...eJ(`Saved screenshot: ${a}`)}}async function cI(e,t){let r=(t[0]??"").toLowerCase();if("read"!==r&&"write"!==r)throw new D("INVALID_ARGS","clipboard requires a subcommand: read or write");if("read"===r){if(1!==t.length)throw new D("INVALID_ARGS","clipboard read does not accept additional arguments");return{action:r,text:await e.readClipboard()}}if(t.length<2)throw new D("INVALID_ARGS",'clipboard write requires text (use "" to clear clipboard)');let n=t.slice(1).join(" ");return await e.writeClipboard(n),{action:r,textLength:Array.from(n).length,...eJ("Clipboard updated")}}async function cb(e,t,r,n){let a=(t[0]??"status").toLowerCase();if(!tg(a))throw new D("INVALID_ARGS","keyboard requires a subcommand: status, get, dismiss, enter, or return");if(t.length>1)throw new D("INVALID_ARGS","keyboard accepts at most one subcommand argument");if("android"===e.platform)return await cA(e,a);if("ios"===e.platform)return await cS(e,a,r,n);throw new D("UNSUPPORTED_OPERATION","keyboard is supported only on Android and iOS")}async function cA(e,t){if("enter"===t||"return"===t)return await sF(e),{platform:"android",action:"enter",...eJ("Keyboard enter pressed")};if("dismiss"===t){let t=await Q(e);return{platform:"android",action:"dismiss",attempts:t.attempts,wasVisible:t.wasVisible,dismissed:t.dismissed,visible:t.visible,inputType:t.inputType,type:t.type,inputMethodPackage:t.inputMethodPackage,focusedPackage:t.focusedPackage,focusedResourceId:t.focusedResourceId,inputOwner:t.inputOwner}}let r=await ea(e);return{platform:"android",action:"status",visible:r.visible,inputType:r.inputType,type:r.type,inputMethodPackage:r.inputMethodPackage,focusedPackage:r.focusedPackage,focusedResourceId:r.focusedResourceId,inputOwner:r.inputOwner}}async function cS(e,t,r,n){if("dismiss"!==t&&"enter"!==t&&"return"!==t)throw new D("UNSUPPORTED_OPERATION","keyboard status/get is currently supported only on Android; use keyboard dismiss or enter on iOS");if("enter"===t||"return"===t){let t=await am(e,{command:"keyboardReturn",appBundleId:r?.appBundleId},n);return{platform:"ios",action:"enter",visible:t.visible,wasVisible:t.wasVisible,...eJ("Keyboard enter pressed")}}let a=await am(e,{command:"keyboardDismiss",appBundleId:r?.appBundleId},n);return{platform:"ios",action:"dismiss",wasVisible:a.wasVisible,dismissed:a.dismissed,visible:a.visible,...eJ(a.dismissed?"Keyboard dismissed":"Keyboard already hidden")}}async function cx(e,t,r,n){var a;let[i,o,s,l]=r;if(!i||!o)throw new D("INVALID_ARGS","settings requires setting state");let u="location"===i&&"set"===o,d=("permission"===i||u?r[4]:r[2])??n?.appBundleId,c="permission"===i?{permissionTarget:s,permissionMode:l}:u?{latitude:eB(s,"latitude"),longitude:eB(l,"longitude")}:void 0;eN({level:"debug",phase:"settings_apply",data:u?{setting:i,state:o,latitude:s,longitude:l,platform:e.platform}:"permission"===i?{setting:i,state:o,permissionTarget:s,permissionMode:l,platform:e.platform}:{setting:i,state:o,appBundleId:d,platform:e.platform}});let p=await t.setSetting(i,o,d,c);return p&&"object"==typeof p?eV({setting:i,state:o,...p},("string"==typeof(a=p).message&&a.message.length>0?a.message:void 0)??`Updated setting: ${i}`):{setting:i,state:o,...eJ(`Updated setting: ${i}`)}}async function c_(e,t,r){let n=t[0]?.trim(),a=t[1]?.trim();if(!n||!a)throw new D("INVALID_ARGS","push requires <bundle|package> <payload.json|inline-json>");let i=await cf(a);if("ios"===e.platform)return await u1(e,n,i),{platform:"ios",bundleId:n,...eJ(`Pushed notification to ${n}`)};let o=await s2(e,n,i);return{platform:"android",package:n,action:o.action,extrasCount:o.extrasCount,...eJ(`Pushed notification to ${n}`)}}async function cN(e,t){return await e.snapshot({appBundleId:t?.appBundleId,interactiveOnly:t?.snapshotInteractiveOnly,compact:t?.snapshotCompact,depth:t?.snapshotDepth,scope:t?.snapshotScope,raw:t?.snapshotRaw,surface:t?.surface})}function cM(e,t,r){return{ok:!1,error:{code:e,message:t,...r?{details:r}:{}}}}function ck(e,t,r){return t||cD(r)?null:cM("INVALID_ARGS",`${e} requires an active session or an explicit device selector (e.g. --platform ios).`)}function cD(e){return!!(e?.platform||e?.target||e?.device||e?.udid||e?.serial)}function cP(e){return"ios"===e.platform&&"simulator"===e.kind}async function cO(e,t){cP(e)&&!(t<=0)&&await new Promise(e=>setTimeout(e,t))}async function cR(e){let t=cD(e.flags)||!e.session?await oO(e.flags??{}):await cE(e.session.device);return!1!==e.ensureReady&&await o6(t),t}async function cE(e){if("ios"!==e.platform||"simulator"!==e.kind||"darwin"!==process.platform)return e;let t={platform:"ios",target:e.target,udid:e.id,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}};try{return await oO(t)}catch(e){if(!(e instanceof D)||"DEVICE_NOT_FOUND"!==e.code)throw e}return await oO({platform:"ios",target:e.target,device:e.name,...e.simulatorSetPath?{iosSimulatorDeviceSet:e.simulatorSetPath}:{}})}function cC(e){let t=e.flags?.device?.trim();return t||(e.resolvedDevice?.platform==="android"&&"emulator"===e.resolvedDevice.kind?e.resolvedDevice.name:e.sessionDevice?.platform==="android"&&"emulator"===e.sessionDevice.kind?e.sessionDevice.name:void 0)}let cL={startIosSimulatorRecording:({device:e,outPath:t})=>P("xcrun",rT(e,["io",e.id,"recordVideo",t]),{allowFailure:!0})},cT=rI(cL,function(e={}){return{...cL,...e}});async function c$(e,t){return await cT.run(e,t)}let cF=[{resolverKey:"androidAdbProvider",resolve(e,t){let r=e.androidAdbProvider;if(!r||"android"!==t.device.platform)return{};let n=r(t),a="function"==typeof n?n:n?.exec;return{androidAdb:{provider:n,executor:a,serial:t.device.id}}},appendWrapper(e,t){cq(t,e.androidAdb,(t,r)=>e9(t,{serial:e.androidAdb?.serial??""},r))}},{resolverKey:"appleRunnerProvider",resolve(e,t){let r=e.appleRunnerProvider;return r&&r8(t.device.platform)?{appleRunner:{provider:r(t),deviceId:t.device.id,requestId:t.req.meta?.requestId}}:{}},appendWrapper(e,t){cq(t,e.appleRunner,(t,r)=>ap(t,{deviceId:e.appleRunner?.deviceId??"",requestId:e.appleRunner?.requestId},r))}},{resolverKey:"appleToolProvider",resolve(e,t){let r=e.appleToolProvider;return r&&r8(t.device.platform)?{appleTool:{provider:r(t)}}:{}},appendWrapper(e,t){cq(t,e.appleTool,rP)}},{resolverKey:"linuxToolProvider",resolve(e,t){let r=e.linuxToolProvider;return r&&"linux"===t.device.platform?{linuxTool:{provider:r(t)}}:{}},appendWrapper(e,t){cq(t,e.linuxTool,oB)}},{resolverKey:"appLogProvider",resolve(e,t){let r=e.appLogProvider;return r?{appLog:{provider:r(t)}}:{}},appendWrapper(e,t){cq(t,e.appLog,iy)}},{resolverKey:"recordingProvider",resolve(e,t){let r=e.recordingProvider;return r?{recording:{provider:r(t)}}:{}},appendWrapper(e,t){cq(t,e.recording,c$)}}];async function cU(e,t){let r=await cV(e),n={androidAdbExecutor:r.androidAdb?.executor},a=function(e){let t=[];for(let r of cF)r.appendWrapper(e,t);return t}(r);return await cB(a,async()=>await t(n))}async function cV(e){var t,r,n;if(t=e.providers,!cF.some(e=>!!t[e.resolverKey]))return{};let a=await cG(e.req,e.existingSession);if(!a)return{};let i=(r=e,n=a,{req:r.req,device:n,session:r.existingSession});return cF.reduce((t,r)=>({...t,...r.resolve(e.providers,i)}),{})}async function cG(e,t){var r;return t?e.command===eD.apps&&cD(e.flags)?await oO(e.flags??{}):t.device:e.command===eD.open||cD(e.flags)||(r=e).command===eD.record&&"start"===(r.positionals?.[0]??"").toLowerCase()?await oO(e.flags??{}):void 0}function cq(e,t,r){let n=t?.provider;n&&e.push(async e=>await r(n,e))}async function cB(e,t){let r=t;for(let t of[...e].reverse()){let e=r;r=async()=>await t(e)}return await r()}let cj=e=>"macos"!==e.platform,cH=e=>"ios"===e.platform&&"simulator"===e.kind&&"tv"!==e.target,cW={device:!0},cz={},cK={apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cW},cJ={apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cz,supports:cj},cX={alert:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cz,supports:e=>"android"===e.platform||"macos"===e.platform||"simulator"===e.kind},pinch:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cz,supports:e=>"android"===e.platform||"macos"===e.platform||"simulator"===e.kind&&"tv"!==e.target},"rotate-gesture":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cz,supports:e=>"android"===e.platform||cH(e)},"transform-gesture":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cz,supports:e=>"android"===e.platform||cH(e)},"app-switcher":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cz,supports:cj},open:cK,close:cK,reinstall:cJ,install:cJ,"install-from-source":cJ,apps:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cz},back:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cW},boot:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cz,supports:cj},click:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cW},clipboard:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cW,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:cz,supports:e=>"android"===e.platform||"ios"===e.platform&&"tv"!==e.target},fill:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cW},fling:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cz},snapshot:cK,diff:cK,screenshot:cK,wait:cK,get:cK,find:cK,is:cK,focus:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cW},home:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cW,supports:cj},logs:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cz},network:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cz},longpress:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cW},perf:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cz},pan:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cW},press:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cW},push:{apple:{simulator:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cz,supports:cj},record:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cz},"react-native":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cz},rotate:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cz,supports:e=>"android"===e.platform||"ios"===e.platform&&"tv"!==e.target},scroll:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cW},swipe:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cW},settings:{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cz,supports:e=>"android"===e.platform||"macos"===e.platform||"simulator"===e.kind},"trigger-app-event":{apple:{simulator:!0,device:!0},android:{emulator:!0,device:!0,unknown:!0},linux:cz},type:cK};function cY(e,t){let r=cX[e];if(!r)return!0;let n=r8(t.platform)?r.apple:"linux"===t.platform?r.linux:r.android;return!!n&&(!r.supports||!!r.supports(t))&&!0===n[t.kind??"unknown"]}let cZ=[250,400,600];function cQ(e,t,r=e.snapshot){if("android"!==e.device.platform)return;let n=r?.comparisonSafe===!0;e.androidSnapshotFreshness={action:t,markedAt:Date.now(),baselineCount:r?.nodes.length??0,baselineSignatures:n?c3(r?.nodes??[]):void 0,routeComparable:n}}function c0(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 c1(e){e&&"android"===e.device.platform&&delete e.androidSnapshotFreshness}function c2(e){return"press"===e||"click"===e||"back"===e||"open"===e}function c3(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 c5(e,t,r,n,a){return{requestId:a??eS().requestId,appBundleId:r,activity:t?.activity,launchConsole:t?.launchConsole,launchArgs:t?.launchArgs,clearAppState:t?.clearAppState,verbose:t?.verbose,logPath:e,traceLogPath:n,snapshotInteractiveOnly:t?.snapshotInteractiveOnly,snapshotCompact:t?.snapshotCompact,snapshotDepth:t?.snapshotDepth,snapshotScope:t?.snapshotScope,snapshotRaw:t?.snapshotRaw,...eZ(t),count:t?.count,intervalMs:t?.intervalMs,delayMs:t?.delayMs,holdMs:t?.holdMs,jitterPx:t?.jitterPx,pixels:t?.pixels,doubleTap:t?.doubleTap,clickButton:dH(t),backMode:t?.backMode,pauseMs:t?.pauseMs,pattern:t?.pattern}}function c4(e){e?.postGestureStabilization&&(e.postGestureStabilization=void 0)}async function c8(e){let{session:t,capture:r}=e,n=t?.postGestureStabilization;if(!t||!c6(t.device.platform)||!n)return await r();let a=Date.now(),i=1,o=await r(),s=c9(o.nodes);for(;Date.now()-a<1500;){await e8(200),i+=1;let e=await r(),l=c9(e.nodes);if(function(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){let n=e[r],a=t[r];if(!n||!a||n.key!==a.key||Math.abs(n.x-a.x)>1||Math.abs(n.y-a.y)>1||Math.abs(n.width-a.width)>1||Math.abs(n.height-a.height)>1)return!1}return!0}(s,l))return c4(t),eN({level:i>2?"info":"debug",phase:"post_gesture_snapshot_stabilized",data:{action:n.action,attempts:i,durationMs:Date.now()-a}}),e;o=e,s=l}return c4(t),eN({level:"warn",phase:"post_gesture_snapshot_stabilization_timeout",data:{action:n.action,attempts:i,durationMs:Date.now()-a}}),o}function c6(e){return"ios"===e||"android"===e}function c9(e){let t=new Map,r=[];for(let i of e){var n,a;if(!i.rect||!([(n=i.rect).x,n.y,n.width,n.height].every(e=>Number.isFinite(e))&&n.width>0&&n.height>0)||(a=i,`${a.label??""} ${a.identifier??""}`.toLowerCase().includes("scroll bar")))continue;let e=[i.identifier,i.label,i.value,i.type].map(e=>"string"==typeof e?e.trim():"").join("|");if(!e.replaceAll("|",""))continue;let o=t.get(e)??0;t.set(e,o+1),r.push({key:`${e}|#${o}`,x:i.rect.x,y:i.rect.y,width:i.rect.width,height:i.rect.height})}return r}let c7=["x","y","width","height"];function pe(e,t){let r=e[t]?.depth??0,n=[];for(let a=t+1;a<e.length;a+=1){let t=e[a];if(t){if((t.depth??0)<=r)break;n.push(t)}}return n}function pt(e,t,r){for(let n of function(e,t){let r=[],n="number"==typeof e.parentIndex?t.get(e.parentIndex):void 0,a=new Set;for(;n&&!a.has(n.index);)a.add(n.index),r.push(n),n="number"==typeof n.parentIndex?t.get(n.parentIndex):void 0;return r}(e,t))if(r(n))return n;return null}function pr(e,t){let r=t8(e.type??""),n=e.label?.trim();return!!(pn(e)||"other"===r&&!n&&!e.value||("other"===r||"statictext"===r)&&n&&t.includes(n))||"image"===r}function pn(e){return"button"===t8(e.type??"")&&e.label?.trim()==="chevron"&&!1===e.enabled}function pa(e){let t=t8(e??"");return"collectionview"===t||"table"===t||"scrollview"===t||"scrollarea"===t}function pi(e,t,r){e.set(t.index,{...t,...e.get(t.index),...r})}function po(e,t){return!!e&&!!t&&c7.every(r=>.5>=Math.abs(e[r]-t[r]))}function ps(e){let t;for(let a of e){var r,n;let e=t8(a.type??"");("application"===e||"window"===e)&&(r=a.rect,n=t,r&&(!n||pl(r)>pl(n)))&&(t=a.rect)}return t}function pl(e){return e?e.width*e.height:0}function pu(e){let t=t8(e.type??"");return"scrollview"===t||"scrollarea"===t}function pd(e,t){return!0===e||!!t||void 0}function pc(e,t,r){for(let n of e)(function(e,t){let r=e.label?.trim();if(!r||r!==t)return!1;let n=t8(e.type??"");return"other"===n||"statictext"===n||"link"===n})(n,t)&&r.add(n.index)}function pp(e,t,r,n){for(let a of pe(e,t))a.index!==r&&function(e){let t=t8(e.type??"");return"button"!==t&&("image"===t||"Search"===e.label)}(a)&&n.add(a.index)}function pf(e,t){for(let r=0;r<e.length;r+=1){let n=e[r],a=n?.label?.trim();n&&a&&"other"===t8(n.type??"")&&t(n,a,r)}}function pm(e,t,r,n){for(let a of e)(pr(a,t)||n&&pw(a,n))&&r.add(a.index)}function ph(e,t,r){if("button"!==t8(e.type??""))return!1;let n=t.identifier?.trim(),a=e.identifier?.trim();return!!n&&!!a&&n===a||e.label?.trim()===r&&po(e.rect,t.rect)}function pw(e,t){return"button"===t8(e.type??"")&&!e.label?.trim()&&!e.value?.trim()&&po(e.rect,t.rect)}let pg=[function(e,t){var r,n,a,i;let{suppressedIndexes:o}=t;(function(e,t){let r=ps(e),n=r?r.y+r.height:null;if(null!==n)for(let r=0;r<e.length;r+=1){var a,i;let o=e[r];if(o&&(a=o,i=n,a.rect&&"keyboard"===t8(a.type??"")&&a.rect.y>=i))for(let a of(t.add(o.index),function(e,t,r,n){let a=new Map(t.map(e=>[e.index,e])),i="number"==typeof e.parentIndex?a.get(e.parentIndex):void 0;for(;i?.rect&&i.rect.y>=n;)r.add(i.index),i="number"==typeof i.parentIndex?a.get(i.parentIndex):void 0}(o,e,t,n),pe(e,r)))t.add(a.index)}})(e,o),function(e,t){for(let r of e)!("other"!==t8(r.type??"")||!0===r.hittable||r.label?.trim()||r.value?.trim())&&r.identifier?.trim()&&t.add(r.index)}(e,o);let s=new Map(e.map(e=>[e.index,e]));for(let r of e)(function(e){let t=e.label?.trim();return!!(t&&tv(t))})(r)&&function(e,t,r){var n,a,i,o;pa(e.type)||r.suppressedIndexes.add(e.index);let s=tM(e.label?.trim()??"",e.value);if(!s)return;let l=function(e,t,r={}){return(!0===r.includeSelf&&pa(e.type)?e:null)??pt(e,t,e=>pa(e.type))}(e,t,{includeSelf:!0});l&&(n=r,a=l,i=e,o=s,pi(n.replacements,a,{rect:function(e,t){if(e&&t&&!(t.height<=0)&&!(t.height>=e.height)&&!(t.y<e.y)&&!(t.y>e.y+e.height))return{...e,y:t.y,height:Math.min(t.height,e.y+e.height-t.y)}}(a.rect,i.rect)??a.rect,hiddenContentAbove:pd(a.hiddenContentAbove,o.above),hiddenContentBelow:pd(a.hiddenContentBelow,o.below)}))}(r,s,t);(function(e,t){for(let r=0;r<e.length;r+=1){let n=e[r];if(!n||"searchfield"!==t8(n.type??""))continue;if("Search"===n.label){pp(e,r,null,t);continue}if("Toolbar"!==n.label)continue;let a=pe(e,r).find(e=>"searchfield"===t8(e.type??"")&&"Search"===e.label);a&&(t.add(n.index),function(e,t,r){let n=new Map(t.map(e=>[e.index,e])),a=e;for(;"number"==typeof a.parentIndex;){let e=n.get(a.parentIndex);if(!e||"Toolbar"!==e.label)return;r.add(e.index),a=e}}(n,e,t),pp(e,r,a.index,t))}})(e,o),r=e,n=o,pf(r,(e,t,a)=>{pe(r,a).find(r=>{let n;return("button"===(n=t8(r.type??""))||"link"===n||"switch"===n||"searchfield"===n||"textfield"===n)&&r.label?.trim()===t&&(po(r.rect,e.rect)||function(e,t){var r,n,a,i,o;let s;if(t.label?.trim()!==e.label?.trim())return!1;let l=t8(t.type??"");return r=e,n=l,s=r.label?.trim(),"button"===n&&("Dismiss"===s||"Back"===s)||"textfield"===l||(a=e,i=l,o=t,"button"===i&&!!a.rect&&!!o.rect&&0===a.rect.x&&0===a.rect.y&&a.rect.width>=300&&a.rect.height>=600&&o.rect.width<a.rect.width)}(e,r))})&&n.add(e.index)}),a=e,i=o,pf(a,(e,t,r)=>{var n;tI(t)&&(n=e.rect)&&n.x<=1&&n.y<=1&&n.width>=300&&n.height>=600&&pe(a,r).some(e=>{var r;return e.label?.trim()===t&&!!(r=e).rect&&r.rect.width>=120&&r.rect.height>=36&&r.rect.height<=180})&&i.add(e.index)}),function(e,t){for(let r=0;r<e.length;r+=1){let n=e[r],a=n?.label?.trim();!(!n||t.has(n.index))&&a&&function(e,t,r,n,a){let i=pe(e,t),o=t8(r.type??"");if("statictext"===o||"link"===o)return pc(i,n,a);if("other"===o){if(function(e,t){return e.some(e=>{let r=t8(e.type??"");return("link"===r||"searchfield"===r||pa(e.type))&&e.label?.trim()===t})}(i,n))return a.add(r.index);pc(i,n,a)}}(e,r,n,a,t)}}(e,o)},function(e,t){let r=new Map(e.map(e=>[e.index,e])),n=ps(r.values());for(let a of e)(function(e,t,r){var n;return!("other"!==t8(e.type??"")||!1===e.enabled||!e.rect||!function(e){let t=e?.trim();return!(!t||/^(toolbar|window|application)$/i.test(t)||t.startsWith("!,")||/debugger|fast refresh/i.test(t))}(e.label)||!pt(e,t,pu)||!((n=e).rect&&n.rect.height>=44&&n.rect.height<=160&&n.rect.width>=120)||function(e,t,r=.8){let n=pl(e),a=pl(t);return n>0&&a>0&&n/a>=r}(e.rect,r))})(a,r,n)&&pi(t.replacements,a,{type:"Cell"})},function(e,t){for(let r=0;r<e.length;r+=1){let n=e[r],a=n?.label?.trim();n?.rect&&a&&function(e,t,r,n,a){let i=pe(e,t),o=t8(r.type??"");"button"===o?pm(i,n,a.suppressedIndexes,r):"cell"!==o||!function(e,t,r,n){let a=e.find(e=>(function(e,t,r){if("switch"!==t8(e.type??""))return!1;let n=t.identifier?.trim(),a=e.identifier?.trim();return!!n&&!!a&&n===a||e.label?.trim()===r})(e,t,r));if(!a)return!1;let i=e.find(e=>ph(e,t,r)),o=a.identifier?void 0:i?.identifier??t.identifier;return o&&pi(n.replacements,a,{identifier:o}),n.suppressedIndexes.add(t.index),function(e,t,r,n,a){for(let i of e)i.index!==n.index&&(ph(i,t,r)||pw(i,t)||function(e,t){if("switch"!==t8(e.type??"")||e.index===t.index)return!1;let r=e.label?.trim();return r===t.value?.trim()||"0"===r||"1"===r}(i,n)||pr(i,r))&&a.add(i.index)}(e,t,r,a,n.suppressedIndexes),!0}(i,r,n,a)&&function(e,t,r,n){let a=e.find(e=>ph(e,t,r));if(!a){e.some(pn)&&pm(e,r,n.suppressedIndexes,t);return}!t.identifier&&a.identifier&&pi(n.replacements,t,{identifier:a.identifier}),n.suppressedIndexes.add(a.index),pm(e.filter(e=>e.index!==a.index),r,n.suppressedIndexes,t)}(i,r,n,a)}(e,r,n,a,t)}}];async function py(e){if(("ios"===e.device.platform||"android"===e.device.platform)&&e.session?.postGestureStabilization)return{snapshot:await c8({session:e.session,capture:async()=>(await pb(e)).snapshot})};let t=c0(e.session);if(t&&"android"===e.device.platform)return await pI(e,t);let r=await pv(e);return c1(e.session),{snapshot:px(r,pA(e)),analysis:r.analysis,androidSnapshot:r.androidSnapshot}}async function pv(e){let{device:t,session:r,flags:n,outPath:a,logPath:i,snapshotScope:o}=e;if("linux"===t.platform){let e=await dG(r?.surface);return p_({nodes:e.nodes,truncated:e.truncated,backend:"linux-atspi"},{snapshotDepth:n?.snapshotDepth,snapshotInteractiveOnly:n?.snapshotInteractiveOnly,snapshotScope:o})}return"macos"===t.platform&&r?.surface&&"app"!==r.surface?p_(await l9(r.surface,{bundleId:"menubar"===r.surface?r.appBundleId:void 0}),{snapshotDepth:n?.snapshotDepth,snapshotInteractiveOnly:n?.snapshotInteractiveOnly,snapshotScope:o}):await ch(t,"snapshot",[],a,{...c5(i,{...n,snapshotScope:o},r?.appBundleId,r?.trace?.outPath)})}async function pI(e,t){let r=await pb(e),n=pS(r,t,e),a=0,i=t.markedAt+1500;for(let o of cZ){if(!n)break;let s=i-Date.now();if(s<=0)break;await e8(Math.min(o,s)),r=await pb(e),a+=1,n=pS(r,t,e)}return n||c1(e.session),{snapshot:r.snapshot,analysis:r.data.analysis,androidSnapshot:r.data.androidSnapshot,freshness:a>0||n?{action:t.action,retryCount:a,staleAfterRetries:!!n,reason:n??void 0}:void 0}}async function pb(e){let t=await pv(e);return{data:t,snapshot:px(t,pA(e))}}function pA(e){return void 0===e.snapshotScope?e.flags:{...e.flags,snapshotScope:e.snapshotScope}}function pS(e,t,r){var n,a;let i=r.flags?.snapshotInteractiveOnly===!0,o=e.data.analysis;if(i&&0===e.snapshot.nodes.length&&o&&o.rawNodeCount>=12)return"empty-interactive";if("ref-refresh"===r.androidFreshnessMode)return null;return(n=t.baselineCount,a=e.snapshot.nodes.length,!(n<12)&&a<=Math.floor(.2*n))?e.snapshot.nodes.some(e=>!0===e.hittable||!!e.label?.trim()||!!e.value?.trim()||!!e.identifier?.trim())?null:"sharp-drop":t.routeComparable&&c2(t.action)&&function(e,t){if(!e||0===e.length)return!1;let r=Math.max(e.length,t.length);if(r<12)return!1;let n=c3(t),a=Math.min(e.length,n.length),i=0;for(let t=0;t<a;t+=1)e[t]===n[t]&&(i+=1);let o=Math.max(0,n.length-e.length),s=Math.max(0,e.length-n.length),l=Math.max(3,Math.floor(.15*r));return i>=Math.floor(.9*r)&&o<=l&&s<=l}(t.baselineSignatures,e.snapshot.nodes)?"stuck-route":null}function px(e,t){var r,n,a,i;let o=e?.nodes??[],s=tD(t?.snapshotRaw?o:t9(o)),l=t?.snapshotScope&&e?.backend!=="macos-helper"?pN(s,t.snapshotScope):s;return{nodes:tW((r=e?.backend,n=t,"xctest"===r&&n?.snapshotInteractiveOnly===!0&&!0!==n.snapshotRaw)?function(e){if(0===e.length)return e;let t=new Map,r=new Set;for(let n of pg)n(e,{replacements:t,suppressedIndexes:r});if(0===r.size&&0===t.size)return e;var n=e.filter(e=>!r.has(e.index)).map(e=>t.get(e.index)??e);let a=new Map(e.map(e=>[e.index,e])),i=new Map;for(let[e,t]of n.entries())i.set(t.index,e);return n.map((e,t)=>{let n="number"==typeof e.parentIndex?i.get(e.parentIndex):void 0;return void 0===n&&"number"==typeof e.parentIndex&&(n=function(e,t,r,n){let a=e,i=new Set;for(;"number"==typeof a&&!i.has(a);){if(i.add(a),!t.has(a))return n.get(a);a=r.get(a)?.parentIndex}}(e.parentIndex,r,a,i)),{...e,index:t,parentIndex:n}})}(l):l),truncated:e?.truncated,createdAt:Date.now(),backend:e?.backend,presentationKey:tj(tG(t)),comparisonSafe:(a=e?.backend,i=t,"android"===a&&i?.snapshotInteractiveOnly!==!0&&i?.snapshotCompact!==!0&&"number"!=typeof i?.snapshotDepth&&!i?.snapshotScope)}}function p_(e,t){var r,n;let a=e.nodes??[];return t.snapshotScope&&(a=pN(a,t.snapshotScope)),t.snapshotInteractiveOnly&&(a=function(e){if(0===e.length)return e;let t=new Map;for(let r of e)t.set(r.index,r);let r=new Set;for(let n of e){if(!function(e){if(e.focused||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")}(n))continue;let e=n;for(;e&&!r.has(e.index);)r.add(e.index),e="number"==typeof e.parentIndex?t.get(e.parentIndex):void 0}return 0===r.size?e:pM(e.filter(e=>r.has(e.index)))}(a)),"number"==typeof t.snapshotDepth&&(r=a,n=t.snapshotDepth,a=pM(r.filter(e=>(e.depth??0)<=n))),{...e,nodes:a}}function pN(e,t){let r=t0(tW(e),t);if(!r)return[];let n=e.findIndex(e=>e.index===r.index);if(-1===n)return[];let a=e[n]?.depth??0,i=[];for(let t=n;t<e.length;t+=1){let r=e[t];if(!r)continue;let o=r.depth??0;if(t>n&&o<=a)break;i.push(r)}return pM(i,a)}function pM(e,t=0){let r=new Map;for(let[t,n]of e.entries())r.set(n.index,t);return e.map((e,n)=>({...e,index:n,depth:Math.max(0,(e.depth??0)-t),parentIndex:"number"==typeof e.parentIndex?r.get(e.parentIndex):void 0}))}function pk(e,t){e.snapshot=t,e.snapshotScopeSource=void 0}function pD(e){return{get:t=>t===e.sessionName?function(e,t,r={}){if(e)return{name:t,appBundleId:e.appBundleId,appName:e.appName,...!0===r.includeSnapshot?{snapshot:e.snapshot}:{},metadata:{surface:e.surface,...r.metadata??{}}}}(e.getSession(),e.sessionName,e.recordOptions):void 0,set:t=>{t.name!==e.sessionName?eN({level:"warn",phase:"runtime_session_write_skipped",data:{expected:e.sessionName,received:t.name}}):e.setRecord(t)}}}async function pP(e){let{session:t,sessionName:r,outPath:n,outputPlacement:a,dispatchContext:i}=e,o=tR({backend:function(e){let{session:t,outputPlacement:r,dispatchContext:n}=e;return{platform:t.device.platform,captureScreenshot:async(e,a,i)=>{let o={...n,...eZ(i),surface:i?.surface};return"out"===r?pO(await ch(t.device,"screenshot",[],a,o)):pO(await ch(t.device,"screenshot",[a],void 0,o))}}}({session:t,outputPlacement:a,dispatchContext:i}),artifacts:{resolveInput:async()=>{throw new D("UNSUPPORTED_OPERATION","screenshot does not resolve input artifacts")},reserveOutput:async e=>{let t,r;return e?.kind==="path"?r=e.path:(t=await d.mkdtemp(f.join(c.tmpdir(),"agent-device-screenshot-")),r=f.join(t,"screenshot.png")),await d.mkdir(f.dirname(r),{recursive:!0}),{path:r,visibility:"client-visible",publish:async()=>void 0,...t?{cleanup:async()=>{await d.rm(t,{recursive:!0,force:!0})}}:{}}},createTempFile:async e=>{let t=await d.mkdtemp(f.join(c.tmpdir(),`${e.prefix}-`));return{path:f.join(t,`file${e.ext}`),visibility:"internal",cleanup:async()=>{await d.rm(t,{recursive:!0,force:!0})}}}},sessions:pD({sessionName:r,getSession:()=>t,recordOptions:{includeSnapshot:!1},setRecord:()=>{}}),policy:tT()});return await o.capture.screenshot({session:r,requestId:i.requestId,appBundleId:t.appBundleId,...eX(i),surface:t.surface,...n?{out:{kind:"path",path:n}}:{}})}function pO(e){if("object"==typeof e&&null!==e)return{..."string"==typeof e.path?{path:e.path}:{},...Array.isArray(e.overlayRefs)?{overlayRefs:e.overlayRefs}:{}}}let pR=/\bis(?:n(?:'|&apos;|&#39;)?t| not)\s+responding\b/i,pE=/^close app$/i,pC="Wait for Android to recover, close the dialog, restart the app, or reboot the emulator, then retry.";async function pL(e){let{session:t}=e;if("android"!==t.device.platform||!t.recording)return"absent";try{let e=await pG(t),r=pB(e);if(!r?.rect)return"absent";let n=await pq(t,r);if(!n.ok)return eN({level:"warn",phase:"android_blocking_dialog_tap_failed",data:{session:t.name,deviceId:t.device.id,exitCode:n.exitCode,stdout:n.stdout.trim(),stderr:n.stderr.trim()}}),"failed";if(!await pj(t))return eN({level:"warn",phase:"android_blocking_dialog_still_present",data:{session:t.name,deviceId:t.device.id}}),"failed";if(t.appBundleId&&(await B(t.device,t.appBundleId),!await pH(t,t.appBundleId)))return eN({level:"warn",phase:"android_blocking_dialog_relaunch_unfocused",data:{session:t.name,deviceId:t.device.id,appBundleId:t.appBundleId}}),"failed";return eN({level:"warn",phase:"android_blocking_dialog_recovered",data:{session:t.name,deviceId:t.device.id,appBundleId:t.appBundleId,x:n.x,y:n.y}}),"recovered"}catch(e){return eN({level:"warn",phase:"android_blocking_dialog_recovery_failed",data:{session:t.name,deviceId:t.device.id,error:e instanceof Error?e.message:String(e)}}),"failed"}}async function pT(e){var t,r;let{session:n,command:a}=e;if("android"!==n.device.platform)return{status:"clear"};let i=await T(n.device);if(!i)return{status:"clear"};if(t=n,r=i,t.appBundleId&&r.package===t.appBundleId){if(await p$(n)){let t=`Recovered Android app ANR before ${a}: closed and relaunched ${n.appBundleId}.`;if("before-command"===e.phase)return{status:"recovered",warning:t};throw pU({session:n,command:a,focus:i,message:`Android app ANR appeared after ${a}; ${n.appBundleId} was closed and relaunched. Retry the command against the fresh app session.`,hint:"Retry the command. If the ANR returns, inspect app logs or restart the emulator."})}throw pU({session:n,command:a,focus:i,message:`Android app ANR blocked ${a}: ${pV(i)}. Automatic recovery failed.`,hint:pC})}throw pU({session:n,command:a,focus:i,message:`Android system dialog is blocking ${a}: ${pV(i)}.`,hint:pC})}async function p$(e){try{return await pF(e)}catch(t){return eN({level:"warn",phase:"android_app_anr_recovery_failed",data:{session:e.name,deviceId:e.device.id,appBundleId:e.appBundleId,error:t instanceof Error?t.message:String(t)}}),!1}}async function pF(e){if(!e.appBundleId)return!1;let t=pB(await pG(e),{requireDialogSignal:!1});if(!t?.rect)return!1;let r=await pq(e,t);if(!r.ok)return!1;await B(e.device,e.appBundleId);let n=await pH(e,e.appBundleId,{requireNoBlockingDialog:!0});return n&&eN({level:"warn",phase:"android_app_anr_recovered",data:{session:e.name,deviceId:e.device.id,appBundleId:e.appBundleId,x:r.x,y:r.y}}),n}function pU(e){let{session:t,command:r,focus:n,message:a,hint:i}=e;return new D("COMMAND_FAILED",a,{command:r,expectedPackage:t.appBundleId,focusedPackage:n.package,focusedWindow:n.focusedWindow,rawFocus:n.raw,hint:i})}function pV(e){return e.package?`${e.focusedWindow} (package ${e.package})`:e.focusedWindow}async function pG(e){return tW(t9((await sd(e.device,{interactiveOnly:!1,compact:!1})).nodes))}async function pq(e,t){if(!t.rect)return{ok:!1,exitCode:1,stdout:"",stderr:"button has no rect"};let{x:r,y:n}=tH(t.rect),a=await Y(e.device,["shell","input","tap",String(Math.round(r)),String(Math.round(n))],{allowFailure:!0});return 0!==a.exitCode?{ok:!1,exitCode:a.exitCode,stdout:a.stdout.trim(),stderr:a.stderr.trim()}:{ok:!0,x:r,y:n}}function pB(e,t={}){if(!1===t.requireDialogSignal||pK(e))return e.find(e=>pz(e).some(e=>pE.test(e))&&e.rect)}async function pj(e){for(let t=0;t<12;t+=1){if(!pK(await pG(e)))return!0;await e8(500)}return!pK(await pG(e))}async function pH(e,t,r={}){for(let n=0;n<12;n+=1){if(await pW(e,t,r))return!0;await e8(500)}return await pW(e,t,r)}async function pW(e,t,r){return!(r.requireNoBlockingDialog&&await T(e.device))&&(await el(e.device)).package===t}function pz(e){let t=[e.label,e.identifier];return"string"==typeof e.value&&e.value.trim().length>0&&t.push(e.value),t.filter(e=>"string"==typeof e&&e.trim().length>0).map(e=>e.trim())}function pK(e){return e.some(e=>{let t=pz(e).join(" ").trim();return t.length>0&&pR.test(t)})}function pJ(e){return!!(e&&e.width>0&&e.height>0)}function pX(e){return e.width*e.height}function pY(e,t){return t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height}let pZ=[255,59,48,255],pQ=[255,214,10,255],p0=[0,0,0,255],p1=["scroll","list","recyclerview","edittext","textfield"],p2=["button","link","menu","tab","textfield","searchfield","securetextfield","checkbox","radio","switch","cell"],p3={e:["01110","10000","11110","10000","10000","10001","01110"],0:["01110","10001","10011","10101","11001","10001","01110"],1:["00100","01100","00100","00100","00100","00100","01110"],2:["01110","10001","00001","00010","00100","01000","11111"],3:["11110","00001","00001","01110","00001","00001","11110"],4:["00010","00110","01010","10010","11111","00010","00010"],5:["11111","10000","10000","11110","00001","00001","11110"],6:["01110","10000","10000","11110","10001","10001","01110"],7:["11111","00001","00010","00100","01000","01000","01000"],8:["01110","10001","10001","01110","10001","10001","01110"],9:["01110","10001","10001","01111","00001","00001","01110"]};async function p5(e){let t=tF(await d.readFile(e.screenshotPath),"screenshot"),r=function(e,t,r,n={}){let a=function(e){let t=null;for(let r of e)p8(r)&&pJ(r.rect)&&(!t||pX(r.rect)>pX(t))&&(t=r.rect);return t||function(e){let t=1/0,r=1/0,n=-1/0,a=-1/0;for(let i of e)i.rect&&pJ(i.rect)&&(t=Math.min(t,i.rect.x),r=Math.min(r,i.rect.y),n=Math.max(n,i.rect.x+i.rect.width),a=Math.max(a,i.rect.y+i.rect.height));return!Number.isFinite(t)||!Number.isFinite(r)||n<=t||a<=r?null:{x:t,y:r,width:n-t,height:a-r}}(e.filter(e=>{var t;return pJ(e.rect)&&!("image"===t8((t=e).type??"")&&!p9(t.label))}))}(e.nodes),i=new Map;for(let n of e.nodes){var o,s;if(!function(e,t,r){let n=[r.label,r.value].some(p7)||fe(r.identifier);return!!function(e,t,r){if("android"!==e.backend||!r.hittable||!pJ(r.rect)||p8(r))return!1;let n=t8(r.type??"");return!(p1.some(e=>n.includes(e))||t&&pX(r.rect)>.25*pX(t))}(e,t,r)||(p4(r)?n:n&&function(e){let t=t8(e.type??"");return t.includes("statictext")||t.includes("image")||t.includes("text")||t.includes("other")}(r))}(e,a,n))continue;let l=(o=e.nodes,[function(e){return p4(e)&&!p8(e)}(s=n)?s:null,t3(o,s,e=>(function(e){return p4(e)&&!p8(e)})(e)),s.hittable?s:null,t3(o,s,e=>!0===e.hittable)].find(p6)??null);if(!l?.rect||!pJ(l.rect))continue;let u=function(e,t,r){let n=ft(e);if(e.ref!==t.ref&&n)return n;let a=function(e,t){let r=null;for(let n of t){if(n.ref===e.ref||!function(e,t,r){let n=e;for(;void 0!==n.parentIndex;){let e=r[n.parentIndex];if(!e)break;if(e.ref===t.ref)return!0;n=e}return!1}(n,e,t))continue;let a=ft(n);if(!a)continue;let i=function(e){let t=0;return t8(e.type??"").includes("text")&&(t+=2),p7(e.label)&&(t+=2),p7(e.value)&&(t+=1),t}(n);(!r||i>r.score)&&(r={label:a,score:i})}return r?.label}(t,r);return a||ft(t)}(n,l,e.nodes),d=function(e,t,r){let n=0;return e.ref===t.ref&&(n+=4),t.hittable&&(n+=3),p4(t)&&(n+=3),p4(e)&&(n+=2),r&&(n+=2),fe(t.identifier)&&(n+=1),p9(t.value)&&(n+=1),n}(n,l,u),c=function(e,t,r){var n,a;return"android"!==e.backend?t.rect:(n=p4,a=e=>!!ft(e),(!t.rect||!0!==t.hittable||n(t)||a(t)?null:function(e,t,r){let n=e.rect,a=function(e,t,r){let n=e.rect,a=new Map(t.map(e=>[e.index,e])),i=t.filter(t=>t.ref!==e.ref&&function(e,t,r){let n=e;for(;void 0!==n.parentIndex;){let e=r.get(n.parentIndex);if(!e)break;if(e.ref===t.ref)return!0;n=e}return!1}(t,e,a)&&function(e,t){let r=t8(e.type??"");return r.includes("text")||r.includes("image")&&t(e)}(t,r)&&pJ(t.rect)&&pY(n,t.rect)).map(e=>e.rect);return i.length<2?null:function(e){let t=e[0];if(void 0===t)throw Error("unionRects requires at least one rect");let r=t.x,n=t.y,a=t.x+t.width,i=t.y+t.height;for(let t of e.slice(1))r=Math.min(r,t.x),n=Math.min(n,t.y),a=Math.max(a,t.x+t.width),i=Math.max(i,t.y+t.height);return{x:r,y:n,width:a-r,height:i-n}}(i)}(e,t,r);if(!a)return null;let i=a.y-n.y,o=n.y+n.height-(a.y+a.height);if(i<0||o<0||16>Math.abs(o-i))return null;let s=Math.min(i,o),l=Math.round(a.y-s),u=Math.round(a.height+2*s);return u<=0||u>=n.height?null:{x:n.x,y:l,width:n.width,height:u}}(t,r,a))??t.rect)}(e,l,e.nodes),p=function(e,t,r,n,a){if("android"===e.backend||!t)return fr(function(e){return{x:Math.round(e.x),y:Math.round(e.y),width:Math.round(e.width),height:Math.round(e.height)}}(r),n,a);let i=n/t.width,o=a/t.height;return fr({x:Math.round((r.x-t.x)*i),y:Math.round((r.y-t.y)*o),width:Math.max(1,Math.round(r.width*i)),height:Math.max(1,Math.round(r.height*o))},n,a)}(e,a,c,t,r);if(!pJ(p))continue;let f=i.get(l.ref);(!f||d>f.score)&&i.set(l.ref,{ref:l.ref,label:u,rect:l.rect,overlayRect:p,score:d})}return(function(e){let t=[];for(let r of e.sort((e,t)=>pX(e.overlayRect)-pX(t.overlayRect))){let e=t.findIndex(e=>void 0!==e.label&&e.label===r.label&&(pY(e.overlayRect,r.overlayRect)||pY(r.overlayRect,e.overlayRect)));if(-1===e){t.push(r);continue}pX(r.overlayRect)<pX(t[e].overlayRect)&&(t[e]=r)}return t})([...i.values()]).sort(fl).slice(0,n.maxRefs??24).sort(fs).map(e=>({ref:e.ref,label:e.label,rect:e.rect,overlayRect:e.overlayRect,center:tH(e.overlayRect)}))}(e.snapshot,t.width,t.height,{maxRefs:e.maxRefs});for(let e of r){var n,a;(function(e,t,r){for(let n=0;n<2;n+=1)fa(e,t.x,t.x+t.width-1,t.y+n,r),fa(e,t.x,t.x+t.width-1,t.y+t.height-1-n,r),fi(e,t.x+n,t.y,t.y+t.height-1,r),fi(e,t.x+t.width-1-n,t.y,t.y+t.height-1,r)})(n=t,(a=e).overlayRect,pZ),function(e,t,r){let n=6+5*r.length+ +Math.max(0,r.length-1),a=fn(t.x,0,Math.max(0,e.width-n)),i=t.y-11-2,o=i>=0?i:fn(t.y+2,0,Math.max(0,e.height-11));(function(e,t,r,n,a){for(let i=0;i<11;i+=1)for(let o=0;o<n;o+=1)fo(e,t+o,r+i,a)})(e,a,o,n,pQ),function(e,t,r,n,a){let i=t;for(let t of n.toLowerCase()){let n=p3[t];if(n)for(let t=0;t<n.length;t+=1)for(let o=0;o<n[t].length;o+=1)"1"===n[t][o]&&fo(e,i+o,r+t,a);i+=6}}(e,a+3,o+2,r,p0)}(n,a.overlayRect,a.ref)}return await d.writeFile(e.screenshotPath,tO.sync.write(t)),r}function p4(e){let t=[e.type,e.role,e.subrole].map(e=>t8(e??"")).join(" ");return p2.some(e=>t.includes(e))}function p8(e){let t=[e.type,e.role,e.subrole].map(e=>t8(e??"")).join(" ");return t.includes("application")||t.includes("window")}function p6(e){return!!(e?.rect&&pJ(e.rect)&&!p8(e))}function p9(e){if("string"!=typeof e)return!1;let t=e.trim();return!(!t||/^(true|false)$/i.test(t))}function p7(e){var t;let r;return!!p9(e)&&(t=e,"toolbar"!==(r=t?.trim().toLowerCase())&&"window"!==r&&"application"!==r&&r?.startsWith("vertical scroll bar")!==!0)}function fe(e){var t;return"string"==typeof e&&!!p7(e)&&(t=e,!/^[a-z0-9_.]+:id\/[a-z0-9_.-]+$/i.test(t.trim()))}function ft(e){let t=[e.label,e.value].find(p7);return t?t.trim():fe(e.identifier)?e.identifier.trim():void 0}function fr(e,t,r){let n=fn(e.x,0,Math.max(0,t-1)),a=fn(e.y,0,Math.max(0,r-1)),i=Math.max(1,t-n),o=Math.max(1,r-a);return{x:n,y:a,width:fn(e.width,1,i),height:fn(e.height,1,o)}}function fn(e,t,r){return Number.isFinite(e)?Math.max(t,Math.min(r,e)):t}function fa(e,t,r,n,a){for(let i=t;i<=r;i+=1)fo(e,i,n,a)}function fi(e,t,r,n,a){for(let i=r;i<=n;i+=1)fo(e,t,i,a)}function fo(e,t,r,n){if(t<0||r<0||t>=e.width||r>=e.height)return;let a=(e.width*r+t)*4;e.data[a]=n[0],e.data[a+1]=n[1],e.data[a+2]=n[2],e.data[a+3]=n[3]}function fs(e,t){var r,n;let a=e.overlayRect.y-t.overlayRect.y;if(0!==a)return a;let i=e.overlayRect.x-t.overlayRect.x;return 0!==i?i:(r=e.ref,n=t.ref,Number.parseInt(r.replace(/^\D+/,""),10)-Number.parseInt(n.replace(/^\D+/,""),10))}function fl(e,t){return t.score!==e.score?t.score-e.score:fs(e,t)}function fu(e){return"number"==typeof e.gestureClockOriginAtMs&&"number"==typeof e.gestureClockOriginUptimeMs&&"number"==typeof e.gestureStartUptimeMs?Math.max(0,e.gestureClockOriginAtMs+(e.gestureStartUptimeMs-e.gestureClockOriginUptimeMs)-e.recordingStartedAt):"number"==typeof e.runnerStartedAtUptimeMs&&"number"==typeof e.gestureStartUptimeMs?Math.max(0,e.gestureStartUptimeMs-e.runnerStartedAtUptimeMs):"number"==typeof e.gestureStartUptimeMs&&"number"==typeof e.gestureEndUptimeMs?Math.max(0,e.fallbackFinishedAtMs-(e.gestureEndUptimeMs-e.gestureStartUptimeMs)-e.recordingStartedAt):Math.max(0,e.fallbackStartedAtMs-e.recordingStartedAt)}let fd=new WeakMap;function fc(e){if(!e)return;let t=fd.get(e);if(t)return t;let r=function(e){let t=function(e){let t=e.filter(e=>(function(e){if(!e)return!1;let t=e.toLowerCase();return t.includes("application")||t.includes("window")})(e.type)&&fp(e.rect)).map(e=>e.rect).sort((e,t)=>(t?.width??0)*(t?.height??0)-(e?.width??0)*(e?.height??0))[0];if(t)return t;let r=e.map(e=>e.rect).filter(fp);if(0===r.length)return;let n=Math.max(...r.map(e=>e.x+e.width)),a=Math.max(...r.map(e=>e.y+e.height));if(!(n<=0)&&!(a<=0))return{x:0,y:0,width:n,height:a}}(e);if(t)return{referenceWidth:t.width,referenceHeight:t.height}}(e.nodes??[]);if(r)return fd.set(e,r),r}function fp(e){return!!e&&e.width>0&&e.height>0}let ff={referenceWidth:1e3,referenceHeight:1e3};function fm(e,t,r,n,a={},i=Date.now(),o=Date.now()){var s,l,u,d,c,p,f,m,h;let w,g,y,v=e.recording;if(!v)return;let I={...a,...n??{}},b=fA(I.effectiveDurationMs)??fA(I.durationMs),A={recordingStartedAt:v.startedAt,gestureClockOriginAtMs:v.gestureClockOriginAtMs,gestureClockOriginUptimeMs:v.gestureClockOriginUptimeMs,runnerStartedAtUptimeMs:"ios-device-runner"===v.platform?v.runnerStartedAtUptimeMs:void 0,gestureStartUptimeMs:fA(I.gestureStartUptimeMs),gestureEndUptimeMs:fA(I.gestureEndUptimeMs),fallbackStartedAtMs:i,fallbackFinishedAtMs:o},S="number"==typeof(s={gestureStartUptimeMs:fA(I.gestureStartUptimeMs),gestureEndUptimeMs:fA(I.gestureEndUptimeMs),reportedDurationMs:b,fallbackStartedAtMs:i,fallbackFinishedAtMs:o}).gestureStartUptimeMs&&"number"==typeof s.gestureEndUptimeMs?Math.max(0,s.gestureEndUptimeMs-s.gestureStartUptimeMs):"number"==typeof s.reportedDurationMs?Math.max(0,s.reportedDurationMs):Math.max(0,s.fallbackFinishedAtMs-s.fallbackStartedAtMs),x="ios"===e.device.platform&&void 0===fA(I.gestureStartUptimeMs)&&function(e,t){switch(e){case"click":case"fill":case"focus":return!0;case"press":{let e=fS(fA(t.count),1)??1,r=!0===t.doubleTap,n=fS(fA(t.holdMs),1);return 1===e&&!r&&void 0===n}case"react-native":return"dismiss-overlay"===t.action;default:return!1}}(t,I)?function(e){let t=Math.max(0,e.gestureDurationMs);if(t<600)return fu(e);let r=Math.min(Math.max(.15*t,120),260);return Math.max(0,e.fallbackFinishedAtMs-r-e.recordingStartedAt)}({...A,gestureDurationMs:S}):fu(A),_=(l=e.snapshot,w=fA((u=I).referenceWidth),g=fA(u.referenceHeight),void 0!==w&&w>0&&void 0!==g&&g>0?{referenceWidth:w,referenceHeight:g}:fc(l)),N=(d=t,c=r,p=I,f=x,m=S,h=_,y=fh[d],y?.(c,p,f,m,h)??[]);0!==N.length&&(v.gestureEvents.push(...N),eN({level:"debug",phase:"record_touch_visualization_event",data:{session:e.name,command:t,count:N.length,tMs:x,gestureDurationMs:S,kinds:N.map(e=>e.kind)}}))}let fh={click:(e,t,r,n,a)=>fw(e,t,r,a),press:(e,t,r,n,a)=>fw(e,t,r,a),"react-native":(e,t,r,n,a)=>"dismiss-overlay"===e[0]?fw(e,t,r,a):[],fill:(e,t,r,n,a)=>fg(e,t,r,a),focus:(e,t,r,n,a)=>fg(e,t,r,a),longpress:function(e,t,r,n,a){let i=fx(t,e);if(!i)return[];let{x:o,y:s}=i;return[fI(r,o,s,fM(n,[fA(t.durationMs),fA(e[2])],800),a)]},scroll:function(e,t,r,n,a){let i=f_(t,e),o=fb(t.contentDirection)??fb(t.direction);if(!i||!o)return[];let{x1:s,y1:l,x2:u,y2:d}=i,c=fM(n,[],250),p=fA(t.amount)??fA(e[1]),f=fA(t.pixels);return[{kind:"scroll",tMs:r,x:s,y:l,x2:u,y2:d,...a,durationMs:c,contentDirection:o,...void 0!==p?{amount:p}:{},...void 0!==f?{pixels:f}:{}}]},pan:fy,fling:fy,swipe:fy,pinch:function(e,t,r,n,a){let i=fx(t,e,1),o=fA(t.scale)??fA(e[0]);if(!i||void 0===o||o<=0)return[];let{x:s,y:l}=i;return[{kind:"pinch",tMs:r,x:s,y:l,...a,scale:o,durationMs:fM(n,[],280)}]}};function fw(e,t,r,n){let a=fx(t,e);if(!a)return[];let{x:i,y:o}=a,s=fS(fA(t.count),1)??1,l=fS(fA(t.intervalMs),0)??0,u=!0===t.doubleTap,d=fS(fA(t.holdMs),1),c=[];for(let e=0;e<s;e+=1){let t=r+e*l;if(void 0!==d&&d>0){c.push(fI(t,i,o,d,n));continue}c.push(fv(t,i,o,n)),u&&c.push(fv(t+90,i,o,n))}return c}function fg(e,t,r,n){let a=fx(t,e);if(!a)return[];let{x:i,y:o}=a;return[fv(r,i,o,n)]}function fy(e,t,r,n,a){let i=f_(t,e);if(!i)return[];let{x1:o,y1:s,x2:l,y2:u}=i,d=fM(n,[fA(t.effectiveDurationMs),fA(t.durationMs),fA(e[4])],250),c=fS(fA(t.count),1)??1,p=fS(fA(t.pauseMs),0)??0,f="ping-pong"===t.pattern?"ping-pong":"one-way";return Array.from({length:c},(e,t)=>{var n,i,c,m,h,w,g,y,v,I,b,A,S;let x,{startX:_,startY:N,endX:M,endY:k}=(n=t,i=f,c=o,m=s,h=l,w=u,"ping-pong"===i&&n%2==1?{startX:h,startY:w,endX:c,endY:m}:{startX:c,startY:m,endX:h,endY:w});return g=r+t*(d+p),y=_,v=N,I=M,b=k,A=d,"back-swipe"===(x=function(e,t,r,n,a){if(!a||Math.abs(r-e)<=1.25*Math.abs(n-t))return"swipe";let i=.08*a.referenceWidth;return e<=i&&r>e||e>=a.referenceWidth-i&&r<e?"back-swipe":"swipe"}(y,v,I,b,S=a))?{kind:x,tMs:g,x:y,y:v,x2:I,y2:b,...S,durationMs:A,edge:function(e,t,r){if(r){let t=.08*r.referenceWidth;if(e<=t)return"left";if(e>=r.referenceWidth-t)return"right"}return t>=e?"left":"right"}(y,I,S)}:{kind:x,tMs:g,x:y,y:v,x2:I,y2:b,...S,durationMs:A}})}function fv(e,t,r,n){return{kind:"tap",tMs:e,x:t,y:r,...n}}function fI(e,t,r,n,a){return{kind:"longpress",tMs:e,x:t,y:r,...a,durationMs:n}}function fb(e){if("string"!=typeof e)return;let t=e.trim().toLowerCase();switch(t){case"up":case"down":case"left":case"right":return t;default:return}}function fA(e){if("number"==typeof e&&Number.isFinite(e))return e;if("string"!=typeof e||0===e.trim().length)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function fS(e,t){if(void 0===e)return;let r=Math.floor(e);return r>=t?r:void 0}function fx(e,t,r=0){let n=fA(e.x)??fA(t[r]),a=fA(e.y)??fA(t[r+1]);if(void 0!==n&&void 0!==a)return{x:n,y:a}}function f_(e,t){let r=fN(e.x1,e.x,t[0]),n=fN(e.y1,e.y,t[1]),a=fN(e.x2,t[2]),i=fN(e.y2,t[3]);if(void 0!==r&&void 0!==n&&void 0!==a&&void 0!==i)return{x1:r,y1:n,x2:a,y2:i}}function fN(...e){return e.map(fA).find(e=>void 0!==e)}function fM(e,t,r){return fS(e,1)??t.map(e=>fS(e,1)).find(e=>void 0!==e)??r}let fk={pan:"pan",fling:"fling",pinch:"pinch",rotate:"rotate-gesture",transform:"transform-gesture"};async function fD(e){var t,r,n,a,i,o,s,l;let u,d,c,p,f,{req:m,session:h,logPath:w,sessionStore:g,contextFromFlags:y}=e,v=function(e){if("pan"===e.command||"fling"===e.command||"rotate-gesture"===e.command||"transform-gesture"===e.command)return{ok:!1,message:"Use gesture pan, gesture fling, gesture rotate, or gesture transform."};if("gesture"!==e.command)return{ok:!0,platformCommand:e.command,dispatchRequest:e,recordedCommand:e.command};let[t,...r]=e.positionals??[],n=t?fk[t]:void 0;return n?{ok:!0,platformCommand:n,dispatchRequest:{...e,command:n,positionals:r},recordedCommand:e.command}:{ok:!1,message:e$}}(m);if(!v.ok)return{ok:!1,error:{code:"INVALID_ARGS",message:v.message}};let{platformCommand:I,dispatchRequest:b,recordedCommand:A}=v,S=await fO(h,I);if(S)return S;let x=await fP(h,I);if("response"in x)return x.response;let{resolvedPositionals:_,resolvedOut:N,recordedPositionals:M,recordedFlags:k}="screenshot"===(t=b).command?(d=(n=(r=t).positionals??[],a=r.meta?.cwd,(u=n[0])?[aq.expandHome(u,a),...n.slice(1)]:n),p=(c=(i=r.flags?.out,o=r.meta?.cwd,i?aq.expandHome(i,o):i))?{...r.flags??{},out:c}:r.flags??{},{resolvedPositionals:d,resolvedOut:c,recordedPositionals:d,recordedFlags:p}):{resolvedPositionals:f=(s=t).positionals??[],resolvedOut:s.flags?.out,recordedPositionals:f,recordedFlags:s.flags??{}},D=Date.now(),P={...y(m.flags,h.appBundleId,h.trace?.outPath),surface:h.surface},O=await fR({session:h,sessionName:e.sessionName,logPath:w,command:I,request:b,positionals:_,out:N,dispatchContext:P}),R=await fP(h,I,"after-command");if("response"in R)return R.response;"status"in x&&"recovered"===x.status&&(!O||"object"==typeof O)&&((O??={}).warning=x.warning);let E=Date.now(),C=A===I?M:m.positionals??[],L=A===I?k:m.flags??{};return function(e){let{session:t,sessionStore:r,command:n,recordedCommand:a,resolvedPositionals:i,recordedPositionals:o,recordedFlags:s,data:l,actionStartedAt:u,actionFinishedAt:d,flags:c}=e,p=function(e,t,r,n){if("scroll"!==t)return n;let a=fc(e.snapshot),i={...n??{}},o=fb(i.direction)??fb(r[0]);if(!o)return n;let s=fA(i.amount)??fA(r[1]),l=fA(i.pixels),u=f_(i,[]),d=fA(i.referenceWidth),c=fA(i.referenceHeight),p=void 0!==d&&d>0&&void 0!==c&&c>0?{referenceWidth:d,referenceHeight:c}:a??ff;if(u&&(u.x1!==u.x2||u.y1!==u.y2))return{...i,x1:u.x1,y1:u.y1,x2:u.x2,y2:u.y2,contentDirection:o,...void 0!==s?{amount:s}:{},...void 0!==l?{pixels:l}:{},referenceWidth:p.referenceWidth,referenceHeight:p.referenceHeight,durationMs:250};let f=sr({direction:o,amount:s,pixels:l,referenceWidth:p.referenceWidth,referenceHeight:p.referenceHeight});return{...i,x1:f.x1,y1:f.y1,x2:f.x2,y2:f.y2,contentDirection:o,...void 0!==s?{amount:s}:{},...void 0!==f.pixels?{pixels:f.pixels}:{},referenceWidth:p.referenceWidth,referenceHeight:p.referenceHeight,durationMs:250}}(t,n,i,l);fm(t,n,i,p,c,u,d),r.recordAction(t,{command:a,positionals:o,flags:s,result:l??{}})}({session:h,sessionStore:g,command:I,recordedCommand:A,resolvedPositionals:_,recordedPositionals:C,recordedFlags:L,data:O,actionStartedAt:D,actionFinishedAt:E,flags:m.flags??{}}),c2(I)&&cQ(h,I),c6(h.device.platform)&&("swipe"===(l=I)||"scroll"===l)&&(h.postGestureStabilization={action:I,markedAt:Date.now()}),{ok:!0,data:O??{}}}async function fP(e,t,r="before-command"){if("android"!==e.device.platform||!ek.androidBlockingDialogGuardedAction.has(t))return{status:"clear"};try{return await pT({session:e,command:t,phase:r})}catch(e){return{response:{ok:!1,error:k(e)}}}}async function fO(e,t){return cY(t,e.device)?"android"===e.device.platform&&e.recording&&"record"!==t&&await pL({session:e})==="failed"?{ok:!1,error:{code:"COMMAND_FAILED",message:"Android system dialog blocked the recording session"}}:null:{ok:!1,error:{code:"UNSUPPORTED_OPERATION",message:`${t} is not supported on this device`}}}async function fR(e){var t;let{session:r,command:n,request:a,positionals:i,out:o,dispatchContext:s}=e;if("screenshot"!==n)return await ch(r.device,n,i,o,{...s});let l=await pP({session:r,sessionName:e.sessionName,outPath:i[0]??o,outputPlacement:"screenshot"!==(t=a).command?"default":(t.positionals??[])[0]?"positional":t.flags?.out?"out":"default",dispatchContext:s});return a.flags?.overlayRefs&&"string"==typeof l?.path&&await fE(r,l,e.logPath),l}async function fE(e,t,r){let n={snapshotInteractiveOnly:!0,snapshotCompact:!0},a=px(await pv({device:e.device,session:e,flags:n,logPath:r,snapshotScope:void 0}),n);pk(e,a);let i=await p5({screenshotPath:t.path,snapshot:a});t.overlayRefs=i}async function fC(e){let{device:t,node:r,flags:n,appBundleId:a,traceOutPath:i,surface:o,contextFromFlags:s}=e,l=tZ(r),u=tx(r.rect);if(!u)return l;try{let e=await ch(t,"read",[String(u.x),String(u.y)],void 0,{...s(n,a,i),surface:o}),d=e&&"object"==typeof e?e:void 0,c="string"==typeof d?.text?d.text:"";if(c.trim())return c;return eN({level:"warn",phase:"interaction_read_fallback",data:{reason:"empty_backend_text",nodeRef:r.ref,surface:o,platform:t.platform}}),l}catch(e){return eN({level:"warn",phase:"interaction_read_fallback",data:{reason:"backend_read_failed",nodeRef:r.ref,surface:o,platform:t.platform,error:e instanceof Error?e.message:String(e)}}),l}}async function fL(e,t,r){let n=e.get(t),a=n?.device??await oO(r??{});return n||await o6(a),{session:n,device:a}}async function fT(e,t,r){let n=!e&&"ios"===t.platform;try{return await r()}finally{n&&await ae(t.id)}}function f$(e,t,r,n){t&&e.recordAction(t,{command:r.command,positionals:r.positionals??[],flags:r.flags??{},result:n})}let fF=[["snapshotDepth","--depth"],["snapshotScope","--scope"],["snapshotRaw","--raw"]];function fU(e,t){let r=function(e){if(!e)return[];let t=[];for(let[r,n]of fF)void 0!==e[r]&&t.push(n);return t}(t);return 0===r.length?null:cM("INVALID_ARGS",`${e} @ref does not support ${r.join(", ")}.`)}async function fV(e,t){let r=await fG(e);if(r)throw new D("COMMAND_FAILED",`press ${t} left ${e.appBundleId} and foregrounded ${r.foregroundPackage}. The tap likely escaped the app.`,r)}async function fG(e){var t;if("android"!==e.device.platform||!e.appBundleId)return null;let r=await el(e.device),n=r.package?.trim();return n&&n!==e.appBundleId&&("com.android.settings"===(t=n)||"com.android.systemui"===t||"com.google.android.permissioncontroller"===t||t.includes("launcher"))?{expectedPackage:e.appBundleId,foregroundPackage:n,activity:r.activity,hint:"com.google.android.permissioncontroller"===n?"Dismiss or allow the permission prompt, then retry the smoke assertion.":"Use screenshot as visual truth, then take a fresh snapshot -i before retrying."}:null}function fq(e,t){let r=Array.isArray(e.selectorChain)?e.selectorChain:void 0,n=fW(e),a=n?.kind==="ref"?fz(n.ref):void 0,i=n?.kind==="selector"?n.selector:void 0,o={...a?{ref:a}:{},...i?{selector:i}:{},...r?{selectorChain:r}:{}};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)}}function fB(e){let t=fW(e);return{...t?.kind==="ref"?{ref:fz(t.ref)}:{},...t?.kind==="selector"?{selector:t.selector}:{},..."string"==typeof e.text?{text:e.text}:{},...e.node&&"object"==typeof e.node?{node:e.node}:{}}}function fj(e){let{selectorChain:t,...r}=e;return r}function fH(e,t,r,n){let a=e.get(t);a&&e.recordAction(a,{command:r.command,positionals:r.positionals??[],flags:r.flags??{},result:n})}function fW(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 fz(e){return e.startsWith("@")?e.slice(1):e}function fK(e,t={}){return{artifacts:function(e,t={}){let r=!0===t.plural?"do":"does";return{resolveInput:async()=>{throw new D("UNSUPPORTED_OPERATION",`${e} ${r} not resolve input artifacts`)},reserveOutput:async()=>{throw new D("UNSUPPORTED_OPERATION",`${e} ${r} not reserve output artifacts`)},createTempFile:async()=>{throw new D("UNSUPPORTED_OPERATION",`${e} ${r} not create temporary files`)}}}(e,t),policy:tT()}}let fJ=["application","window","tabbar","scrollbar","image"],fX=new Set(["tab bar"]);async function fY(e,t){var r;if(t.ok||(r=t.error.message,!/^wait timed out for (?:selector|text): /i.test(r)))return t;let n=await fZ(e).catch(()=>null);return n?cM(t.error.code,`${t.error.message}. Current surface: ${n.summary}.`,{...t.error.details??{},currentSurface:n.details}):t}async function fZ(e){let t=[...(await py({device:e.device,session:e.session,flags:{...e.req.flags,snapshotInteractiveOnly:!0,snapshotCompact:!0},logPath:e.logPath??""})).snapshot.nodes].sort(f0),r=fQ(t,6,{includeIdentifiers:!0});if(0===r.length)return null;let n=fQ(t.filter(e=>!f3(e)),4,{includeIdentifiers:!1}),a=fQ(t.filter(f5),4,{includeIdentifiers:!0});return{summary:(n.length>0?n:r.slice(0,4)).join(", "),details:{labels:r,...a.length>0?{buttons:a}:{}}}}function fQ(e,t,r){let n=new Set,a=[];for(let i of e){let e=f2(i,r);if(!(!e||n.has(e))&&(n.add(e),a.push(e),a.length>=t))break}return a}function f0(e,t){var r,n;return f1(e)-f1(t)||(r=e,n=t,r.rect&&n.rect?r.rect.y-n.rect.y||r.rect.x-n.rect.x:r.rect?-1:n.rect?1:(r.depth??0)-(n.depth??0)||r.index-n.index)}function f1(e){let t=!!f2(e,{includeIdentifiers:!1});return 2*!!f3(e)+ +!t}function f2(e,t){let r=(t.includeIdentifiers?[e.label,e.value,e.identifier]:[e.label,e.value]).map(e=>"string"==typeof e?e.trim():"").find(e=>e.length>0);return r?r.replace(/\s+/g," ").slice(0,80):""}function f3(e){let t=t8(`${e.type??""} ${e.role??""} ${e.subrole??""}`),r=`${e.label??""} ${e.value??""}`.trim().toLowerCase();return fJ.some(e=>t.includes(e))||fX.has(r)||r.endsWith(".fill")}function f5(e){return t8(`${e.type??""} ${e.role??""} ${e.subrole??""}`).includes("button")}function f4(e){var t;let{session:r,selectorExpression:n}=e;if(!r||"ios"!==r.device.platform||r.postGestureStabilization)return null;let a=tY(n);if(!a||1!==a.selectors.length)return null;let i=a.selectors[0];if(!i||1!==i.terms.length)return null;let o=i.terms[0];return o&&"string"==typeof o.value&&("id"===(t=o.key)||"label"===t||"text"===t||"value"===t)?{key:o.key,value:o.value,raw:i.raw}:null}function f8(e){let t=M(e);if("COMMAND_FAILED"!==t.code)return!1;let r=t.message.toLowerCase();return r.includes("fetch failed")||r.includes("timed out")||r.includes("timeout")||r.includes("runner did not accept connection")||r.includes("invalid runner response")}async function f6(e){var t;let{req:r}=e;if("find"!==r.command)return null;let n=r.positionals??[];if(0===n.length)return cM("INVALID_ARGS","find requires a locator or text");let a=rt(n);if(!a.query)return cM("INVALID_ARGS","find requires a value");if(r.flags?.findFirst&&r.flags?.findLast)return cM("INVALID_ARGS","find accepts only one of --first or --last");let i=a.action;if("exists"!==(t=i)&&"wait"!==t&&"get_text"!==t&&"get_attrs"!==t)return null;let o=await mu(e,{requireSession:!1,capability:"find"});return o.ok?await mp(async()=>{let t=await o.runtime.selectors.find({session:e.sessionName,requestId:r.meta?.requestId,locator:a.locator,query:a.query,action:i,timeoutMs:a.timeoutMs});return fH(e.sessionStore,e.sessionName,r,function(e,t){if("exists"===t)return{found:!0};if("wait"===t)return{found:!0,waitedMs:e.waitedMs};let r="string"==typeof e.ref?e.ref:void 0;return"get_attrs"===t?{ref:r,action:"get attrs"}:{ref:r,action:"get text",text:"string"==typeof e.text?e.text:""}}(t,i)),"found"===t.kind?{found:!0,..."number"==typeof t.waitedMs?{waitedMs:t.waitedMs}:{}}:{..."string"==typeof t.ref?{ref:t.ref}:{},..."string"==typeof t.text?{text:t.text}:{},...t.node&&"object"==typeof t.node?{node:t.node}:{}}}):o.response}async function f9(e){let{req:t}=e;if("get"!==t.command)return null;let r=t.positionals?.[0];if("text"!==r&&"attrs"!==r)return cM("INVALID_ARGS","get only supports text or attrs");let n=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 r=e.positionals?.slice(1).join(" ").trim()??"";return r?{ok:!0,target:{kind:"selector",selector:r}}:{ok:!1,response:cM("INVALID_ARGS","get requires @ref or selector expression")}}(t);if(!n.ok)return n.response;if("ref"===n.target.kind){let e=fU("get",t.flags);if(e)return e}if("selector"===n.target.kind){let t=await mt(e,r,n.target.selector);if(t)return t}let a=await mu(e,{requireSession:!0,capability:"get"});return a.ok?await mp(async()=>{let i=await a.runtime.selectors.get({session:e.sessionName,requestId:t.meta?.requestId,property:r,target:n.target});return fH(e.sessionStore,e.sessionName,t,fq(i,r)),fB(i)}):a.response}async function f7(e){let{req:t}=e;if("is"!==t.command)return null;let r=(t.positionals?.[0]??"").toLowerCase();if(!t$(r))return cM("INVALID_ARGS","is requires predicate: visible|hidden|exists|editable|selected|text");let{split:n}=tQ(t.positionals??[]);if(!n)return cM("INVALID_ARGS","is requires a selector expression");let a=n.rest.join(" ").trim();if("text"===r&&!a)return cM("INVALID_ARGS","is text requires expected text value");if("text"!==r&&n.rest.length>0)return cM("INVALID_ARGS",`is ${r} does not accept trailing values`);let i=await mr(e,r,n.selectorExpression,a);if(i)return i;let o=await mu(e,{requireSession:!0,capability:"is"});if(!o.ok)return o.response;let s=await mp(async()=>{let i=await o.runtime.selectors.is({session:e.sessionName,requestId:t.meta?.requestId,predicate:r,selector:n.selectorExpression,expectedText:a});return fH(e.sessionStore,e.sessionName,t,i),fj(i)});return await mf(e,s,`is ${r}`)}async function me(e){let{req:t,sessionName:r,sessionStore:n}=e,a=eY(t.positionals??[]);if(!a)return cM("INVALID_ARGS","wait requires a duration or text");let{session:i,device:o}=await fL(n,r,t.flags);if("sleep"!==a.kind&&!cY("wait",o))return cM("UNSUPPORTED_OPERATION","wait is not supported on this device");if("selector"===a.kind){let t=await mn({...e,session:i,device:o,selectorExpression:a.selectorExpression,timeoutMs:a.timeoutMs});if(t)return t}let s=async()=>{let s=ml({...e,session:i,device:o}),l=await mp(async()=>{let e=await s.selectors.wait({session:r,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 D("INVALID_ARGS","Ref wait requires an existing snapshot in session.");return{kind:"ref",ref:e.rawRef,timeoutMs:e.timeoutMs}}if(!e.text)throw new D("INVALID_ARGS","wait requires text");return{kind:"text",text:e.text,timeoutMs:e.timeoutMs}}(a,i)});return fH(n,r,t,e),{waitedMs:e.waitedMs,..."string"==typeof e.text?{text:e.text}:{},..."string"==typeof e.selector?{selector:e.selector}:{}}}),u=await fY({req:t,logPath:e.logPath,session:i,device:o},l);return await mf(e,u,"wait")};return"sleep"===a.kind?await s():await fT(i,o,s)}async function mt(e,t,r){let n=await ma(e,r);if(ms(n))return n.response;if(!n)return null;let a=function(e,t,r){if(!r.found||!r.node)return null;let n={target:{kind:"selector",selector:t},node:r.node,selectorChain:[t]};return"attrs"===e?{kind:"attrs",...n}:"string"!=typeof r.text?null:{kind:"text",...n,text:r.text}}(t,n.selector.raw,n.result);return a?(fH(e.sessionStore,e.sessionName,e.req,fq(a,t)),{ok:!0,data:fB(a)}):null}async function mr(e,t,r,n){var a,i,o,s,l;let u;if("hidden"===t)return null;let d=await ma(e,r);if(ms(d))return d.response;if(!d?.result.found||!d.result.node)return null;let c="exists"===t?{predicate:t,pass:!0,selector:d.selector.raw,matches:1,selectorChain:[d.selector.raw]}:(a=t,i=n,o=d.selector.raw,s=d.session,u=tU({predicate:a,node:l=d.result.node,nodes:[l],expectedText:i,platform:s.device.platform}),{predicate:a,pass:u.pass,selector:o,..."text"===a?{text:u.actualText}:{},selectorChain:[o]});return c?(fH(e.sessionStore,e.sessionName,e.req,c),{ok:!0,data:fj(c)}):null}async function mn(e){let t=f4({session:e.session,selectorExpression:e.selectorExpression});if(!e.session||!t)return null;let r=Date.now(),n=await mo(e,e.session,t);if(ms(n))return n.response;if(!n?.found)return null;let a={kind:"selector",selector:t.raw,waitedMs:Date.now()-r,selectorChain:[t.raw]};return fH(e.sessionStore,e.sessionName,e.req,a),await fY({req:e.req,logPath:e.logPath,session:e.session,device:e.device},{ok:!0,data:a})}async function ma(e,t){let r=e.sessionStore.get(e.sessionName),n=f4({session:r,selectorExpression:t});if(!r||!n)return null;let a=await mo(e,r,n);return ms(a)?a:a?{session:r,selector:n,result:a}:null}async function mi(e,t,r){let n=await am(t.device,{command:"querySelector",selectorKey:r.key,selectorValue:r.value,appBundleId:t.appBundleId},{verbose:!!e.req.flags?.verbose,logPath:e.logPath,traceLogPath:t.trace?.outPath,requestId:e.req.meta?.requestId}),a=!0===n.found,i=function(e){let t=e.nodes;if(!Array.isArray(t))return;let r=t[0];if(r&&"object"==typeof r)return r}(n);return{found:a,..."string"==typeof n.text?{text:n.text}:{},...i?{node:i}:{}}}async function mo(e,t,r){try{return await mi(e,t,r)}catch(e){if(f8(e))return null;return{kind:"error",response:{ok:!1,error:k(e)}}}}function ms(e){return null!==e&&"kind"in e&&"error"===e.kind}function ml(e){return tR({backend:function(e){let t,{req:r,session:n,device:a,logPath:i,sessionName:o,sessionStore:s}=e,l=0;return{platform:a.platform,captureSnapshot:async(e,u)=>{var d;let c,p={...r.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??r.flags?.snapshotScope,m=Date.now(),h=tj(tG(p)),w="wait"===r.command||"find"===r.command;if(!w&&t&&m-l<750&&!c0(n)&&!n?.postGestureStabilization)return t;if(!w&&n?.snapshot&&m-n.snapshot.createdAt<750&&n.snapshot.presentationKey===h&&!c0(n)&&!n.postGestureStabilization)return l=n.snapshot.createdAt,t={snapshot:n.snapshot};let g=await py({device:a,session:n,flags:p,outPath:r.flags?.out,logPath:i??"",snapshotScope:f});return n&&(pk(n,g.snapshot),s.set(o,n)),l=m,t={snapshot:g.snapshot}},readText:async(t,o)=>({text:await fC({device:a,node:o,flags:r.flags,appBundleId:n?.appBundleId,traceOutPath:n?.trace?.outPath,surface:n?.surface,contextFromFlags:e.contextFromFlags??((e,t,r)=>c5(i??"",e,t,r))})}),findText:async(t,r)=>({found:await md(e,r)})}}(e),...fK("selector commands",{plural:!0}),sessions:pD({sessionName:e.sessionName,getSession:()=>e.session,recordOptions:{includeSnapshot:!0},setRecord:t=>{e.session&&t.snapshot&&(pk(e.session,t.snapshot),e.sessionStore.set(e.sessionName,e.session))}})})}async function mu(e,t){let r=e.sessionStore.get(e.sessionName);if(!r&&t.requireSession)return{ok:!1,response:cM("SESSION_NOT_FOUND","No active session. Run open first.")};let n=r?.device??await oO(e.req.flags??{});return(r||await o6(n),cY(t.capability,n))?{ok:!0,runtime:ml({...e,session:r,device:n})}:{ok:!1,response:cM("UNSUPPORTED_OPERATION",`${t.capability} is not supported on this device`)}}async function md(e,t){let{device:r,session:n,req:a,logPath:i}=e;if("macos"===r.platform&&n?.surface&&"app"!==n.surface)return!!t0((await mc(e)).nodes,t);if(r8(r.platform)&&n?.appBundleId){let e=await am(r,{command:"findText",text:t,appBundleId:n?.appBundleId},{verbose:a.flags?.verbose,logPath:i,traceLogPath:n?.trace?.outPath,requestId:a.meta?.requestId});return e?.found===!0}return!!t0((await mc(e)).nodes,t)}async function mc(e){let t=await py({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&&(pk(e.session,t.snapshot),e.sessionStore.set(e.sessionName,e.session)),t.snapshot}async function mp(e){try{return{ok:!0,data:await e()}}catch(t){let e=M(t);return cM(e.code,e.message,e.details)}}async function mf(e,t,r){var n;let a;if(t.ok)return t;let i=e.sessionStore.get(e.sessionName);if(!i)return t;try{a=await fG(i)}catch{return t}return a?cM(t.error.code,`${r} failed because ${"com.google.android.permissioncontroller"===(n=a).foregroundPackage?`Android permission dialog is blocking ${n.expectedPackage}`:`${n.foregroundPackage} is foreground instead of ${n.expectedPackage}`}.`,{...t.error.details??{},...a,blockedBy:"android_foreground_surface",originalMessage:t.error.message}):t}async function mm(e){var t,r;let{req:n,sessionName:a,logPath:i,sessionStore:o,invoke:s}=e,l=n.command;if("find"!==l)return null;let u=n.positionals??[];if(0===u.length)return cM("INVALID_ARGS","find requires a locator or text");let{locator:d,query:c,action:p,value:f,timeoutMs:m}=rt(u);if(!c)return cM("INVALID_ARGS","find requires a value");if(n.flags?.findFirst&&n.flags?.findLast)return cM("INVALID_ARGS","find accepts only one of --first or --last");let h=await f6({req:n,sessionName:a,logPath:i,sessionStore:o});if(h)return h;let w=o.get(a),g="exists"===(t=p)||"wait"===t||"get_text"===t||"get_attrs"===t;if(!w&&!g)return cM("SESSION_NOT_FOUND","No active session. Run open first.");let y=w?.device??await oO(n.flags??{});w||await o6(y);let v="click"===(r=p)||"focus"===r||"fill"===r||"type"===r,I="role"===d||v?void 0:c,b=0,A=null,S=async()=>{let e=Date.now();if(A&&e-b<750&&!c0(w))return{nodes:A};let{snapshot:t}=await py({device:y,session:w,flags:{...n.flags,snapshotInteractiveOnly:v,snapshotCompact:v},outPath:n.flags?.out,logPath:i,snapshotScope:I}),r=t.nodes;return b=e,A=r,w&&(pk(w,t),o.set(a,w)),{nodes:r,truncated:t.truncated,backend:t.backend}},x={req:n,sessionName:a,logPath:i,sessionStore:o,invoke:s,session:w,device:y,command:l,locator:d,query:c};if("wait"===p)return mg(x,S,d,c,m);let{nodes:_}=await S(),N=function(e){let{nodes:t,locator:r,query:n,requiresRect:a,flags:i}=e,o=t7(t,r,n,{requireRect:a});if(a&&(o.matches=function(e,t){var r,n;let a=t[0]?.rect;if(!a)return e;let i=e.filter(e=>{if(!e.rect)return!1;let t=tH(e.rect);return t.x>=a.x&&t.x<=a.x+a.width&&t.y>=a.y&&t.y<=a.y+a.height});return r=i.length>0?i:e,n=t,r.length<2?r:r.map((e,t)=>{var r,a;let i;return{node:e,index:t,score:(r=e,"semantic-target"===(i=tP(a=n,r)).reason&&i.node.rect||"same-rect-descendant"===i.reason&&i.node.rect?4:"hittable-ancestor"===i.reason&&i.node.rect&&!mw(i.node,a[0])?2:r.hittable&&r.rect&&!mw(r,a[0])?3:+!!r.rect)}}).sort((e,t)=>t.score!==e.score?t.score-e.score:mh(e.node)-mh(t.node)||e.index-t.index).map(e=>e.node)}(o.matches,t)),a&&o.matches.length>1)if(i?.findFirst)o.matches=[o.matches[0]];else{if(!i?.findLast){var s,l,u;let e;return{ok:!1,response:(s=o.matches,l=r,u=n,e=s.slice(0,8).map(e=>{let t=tX(e)||e.label||e.identifier||e.type||"";return`@${e.ref}${t?`(${t})`:""}`}),cM("AMBIGUOUS_MATCH",`find matched ${s.length} elements for ${l} "${u}". Use a more specific locator or selector.`,{locator:l,query:u,matches:s.length,candidates:e}))}}o.matches=[o.matches[o.matches.length-1]]}let d=o.matches[0]??null;return d?{ok:!0,node:d}:{ok:!1,response:cM("COMMAND_FAILED","find did not match any element")}}({nodes:_,locator:d,query:c,requiresRect:v,flags:n.flags});if(!N.ok)return N.response;let M=N.node,k=v?t_(_,M):M,D=`@${k.ref}`,P={node:M,resolvedNode:k,ref:D,nodes:_,actionFlags:{...n.flags??{},noRecord:!0}},O={exists:()=>my(x),get_text:()=>mv(x,P),get_attrs:()=>mI(x,P),click:()=>mb(x,P),fill:()=>mA(x,P,f),focus:()=>mS(x,P),type:()=>mx(x,P,f)}[p];return O?O():null}function mh(e){return e.rect?e.rect.width*e.rect.height:1/0}function mw(e,t){if(!t?.rect||!e.rect)return!1;let r=e.type?.toLowerCase()??"";return(!!r.includes("application")||!!r.includes("window"))&&e.rect.x===t.rect.x&&e.rect.y===t.rect.y&&e.rect.width===t.rect.width&&e.rect.height===t.rect.height}async function mg(e,t,r,n,a){let{req:i,sessionStore:o,session:s,command:l}=e,u=a??1e4,d=Date.now();for(;Date.now()-d<u;){let{nodes:e}=await t();if(t7(e,r,n,{requireRect:!1}).matches[0])return s&&o.recordAction(s,{command:l,positionals:i.positionals??[],flags:i.flags??{},result:{found:!0,waitedMs:Date.now()-d}}),{ok:!0,data:{found:!0,waitedMs:Date.now()-d}};await e8(300)}return cM("COMMAND_FAILED","find wait timed out")}async function my(e){let{req:t,sessionStore:r,session:n,command:a}=e;return n&&r.recordAction(n,{command:a,positionals:t.positionals??[],flags:t.flags??{},result:{found:!0}}),{ok:!0,data:{found:!0}}}async function mv(e,t){let{req:r,sessionStore:n,session:a,command:i,device:o,logPath:s}=e,l=await fC({device:o,node:t.node,flags:r.flags,appBundleId:a?.appBundleId,traceOutPath:a?.trace?.outPath,surface:a?.surface,contextFromFlags:(e,t,r)=>c5(s,e,t,r)});return a&&n.recordAction(a,{command:i,positionals:r.positionals??[],flags:r.flags??{},result:{ref:t.ref,action:"get text",text:l}}),{ok:!0,data:{ref:t.ref,text:l,node:t.node}}}async function mI(e,t){let{req:r,sessionStore:n,session:a,command:i}=e;return a&&n.recordAction(a,{command:i,positionals:r.positionals??[],flags:r.flags??{},result:{ref:t.ref,action:"get attrs"}}),{ok:!0,data:{ref:t.ref,node:t.node}}}async function mb(e,t){let{req:r,sessionName:n,sessionStore:a,session:i,invoke:o,command:s,locator:l,query:u}=e,d=await o({token:r.token,session:n,command:"click",positionals:[t.ref],flags:t.actionFlags});if(!d.ok)return d;let c=t.resolvedNode.rect?tH(t.resolvedNode.rect):t.node.rect?tH(t.node.rect):null,p={ref:t.ref,locator:l,query:u};return c&&(p.x=c.x,p.y=c.y),i&&a.recordAction(i,{command:s,positionals:r.positionals??[],flags:r.flags??{},result:{ref:t.ref,action:"click",locator:l,query:u}}),{ok:!0,data:p}}async function mA(e,t,r){let{req:n,sessionName:a,sessionStore:i,session:o,invoke:s,command:l}=e;if(!r)return cM("INVALID_ARGS","find fill requires text");let u=await s({token:n.token,session:a,command:"fill",positionals:[t.ref,r],flags:t.actionFlags});return u.ok&&o&&i.recordAction(o,{command:l,positionals:n.positionals??[],flags:n.flags??{},result:{ref:t.ref,action:"fill"}}),u}async function mS(e,t){let r=await m_(e,t);return r.ok&&mN(e,t,"focus"),r}async function mx(e,t,r){let{req:n,device:a,logPath:i,session:o}=e;if(!r)return cM("INVALID_ARGS","find type requires text");let s=await m_(e,t);if(!s.ok)return s;let l=await ch(a,"type",[r],n.flags?.out,{...c5(i,n.flags,o?.appBundleId,o?.trace?.outPath)});return mN(e,t,"type"),{ok:!0,data:l??{ref:t.ref}}}async function m_(e,t){let{req:r,device:n,logPath:a,session:i}=e,o=t.node.rect?tH(t.node.rect):null;return o?{ok:!0,data:await ch(n,"focus",[String(o.x),String(o.y)],r.flags?.out,{...c5(a,r.flags,i?.appBundleId,i?.trace?.outPath)})??{ref:t.ref}}:cM("COMMAND_FAILED","matched element has no bounds")}function mN(e,t,r){let{req:n,sessionStore:a,session:i,command:o}=e;i&&a.recordAction(i,{command:o,positionals:n.positionals??[],flags:n.flags??{},result:{ref:t.ref,action:r}})}function mM(e){var t,r,n;let a,i,o,{data:s,fallbackX:l,fallbackY:u,referenceFrame:d,extra:c}=e,p=(t=c,r=l,n=u,a="string"==typeof t?.ref?t.ref:void 0,i="string"==typeof t?.button?t.button:void 0,o="string"==typeof t?.gesture?t.gesture:void 0,("string"==typeof t?.text?`Filled ${Array.from(t.text).length} chars`:a?"longpress"===o?`Long pressed @${a} (${r}, ${n})`:i&&"primary"!==i?`Clicked ${i} @${a} (${r}, ${n})`:`Tapped @${a} (${r}, ${n})`:void 0)??("string"==typeof s?.message?s.message:void 0));return{x:l,y:u,...d??{},...c??{},...s??{},...eJ(p)}}function mk(e){let{session:t,sessionStore:r,command:n,positionals:a,flags:i,result:o,responseData:s,actionStartedAt:l,actionFinishedAt:u,androidFreshnessBaseline:d}=e;return r.recordAction(t,{command:n,positionals:a,flags:i??{},result:o}),c2(n)&&cQ(t,n,d??t.snapshot),fm(t,n,a,o,i??{},l,u),{ok:!0,data:s}}async function mD(e){let{session:t,flags:r,sessionStore:n,contextFromFlags:a,captureSnapshotForSession:i}=e;if(!t.recording)return;if(t.recording.touchReferenceFrame)return t.recording.touchReferenceFrame;if("android"===t.device.platform){let e=await sK(t.device),r={referenceWidth:e.width,referenceHeight:e.height};return t.recording&&(t.recording.touchReferenceFrame=r),r}let o=fc(t.snapshot);if(o)return t.recording&&(t.recording.touchReferenceFrame=o),o;if(!t.recording)return;let s=fc(await i(t,r,n,a,{interactiveOnly:!0}));return s&&t.recording&&(t.recording.touchReferenceFrame=s),s}async function mP(e){try{return await mD(e)}catch(t){eN({level:"warn",phase:"touch_reference_frame_resolve_failed",data:{platform:e.session.device.platform,error:t instanceof Error?t.message:String(t)}});return}}function mO(e){return fc({nodes:e,createdAt:0})}function mR(e,t){return"macos"!==e.device.platform||"desktop"!==e.surface&&"menubar"!==e.surface||"menubar"===e.surface&&("click"===t||"press"===t)?null:cM("UNSUPPORTED_OPERATION",`${t} is not supported on macOS ${e.surface} sessions yet. Open an app session to act, or use the ${e.surface} surface to inspect.`)}function mE(e){let t=e.sessionStore.get(e.sessionName);if(!t)throw new D("SESSION_NOT_FOUND","No active session. Run open first.");return tR({backend:function(e){let{req:t,session:r}=e;return{platform:r.device.platform,captureSnapshot:async(n,a)=>({snapshot:await e.captureSnapshotForSession(r,t.flags,e.sessionStore,e.contextFromFlags,{interactiveOnly:a?.interactiveOnly===!0})}),tap:async(n,a)=>mC(await ch(r.device,"press",[String(a.x),String(a.y)],t.flags?.out,e.contextFromFlags(t.flags,r.appBundleId,r.trace?.outPath))),fill:async(n,a,i)=>mC(await ch(r.device,"fill",[String(a.x),String(a.y),i],t.flags?.out,e.contextFromFlags(t.flags,r.appBundleId,r.trace?.outPath))),longPress:async(n,a,i)=>mC(await ch(r.device,"longpress",[String(a.x),String(a.y),...i?.durationMs===void 0?[]:[String(i.durationMs)]],t.flags?.out,e.contextFromFlags(t.flags,r.appBundleId,r.trace?.outPath))),typeText:async(n,a)=>mC(await ch(r.device,"type",[a],t.flags?.out,e.contextFromFlags(t.flags,r.appBundleId,r.trace?.outPath)))}}({...e,session:t}),...fK("interaction commands",{plural:!0}),sessions:pD({sessionName:e.sessionName,getSession:()=>t,recordOptions:{includeSnapshot:!0},setRecord:r=>{r.snapshot&&(pk(t,r.snapshot),e.sessionStore.set(e.sessionName,t))}})})}function mC(e){return e&&"object"==typeof e?e:void 0}function mL(e){if(e.length<2)return null;let t=Number(e[0]),r=Number(e[1]);return Number.isFinite(t)&&Number.isFinite(r)?{x:t,y:r}:null}function mT(e,t){let r=mL(e);if(r)return{ok:!0,target:{kind:"point",x:r.x,y:r.y}};let n=e[0]??"";if(n.startsWith("@"))return{ok:!0,target:{kind:"ref",ref:n,fallbackLabel:eP(e).label??""}};let a=e.join(" ").trim();return a?{ok:!0,target:{kind:"selector",selector:a}}:{ok:!1,response:cM("INVALID_ARGS",`${t} requires @ref, selector expression, or x y coordinates`)}}function m$(e){return"ref"===e.kind?{ref:mF(e.target?.kind==="ref"?e.target.ref:void 0),refLabel:e.refLabel,selectorChain:e.selectorChain}:"selector"===e.kind?{selector:e.target?.kind==="selector"?e.target.selector:void 0,selectorChain:e.selectorChain,refLabel:e.refLabel}:{}}function mF(e){return e?.startsWith("@")?e.slice(1):e}async function mU(e){switch(e.req.command){case"press":return await mV(e,"press");case"click":return await mV(e,"click");case"longpress":return await mV(e,"longpress");case"fill":return await mH(e);default:return null}}async function mV(e,t){let r,{req:n,sessionName:a,sessionStore:i}=e,o=i.get(a);if(!o)return cM("SESSION_NOT_FOUND","No active session. Run open first.");let s="click"===t?"click":t,l="longpress"===t?"longpress":"press",u=mR(o,s);if(u)return u;if(!cY(l,o.device))return cM("UNSUPPORTED_OPERATION",`${l} is not supported on this device`);let d=dH(n.flags),c="primary"===d?{}:{button:d};if("longpress"!==t&&"primary"!==d){let e=dW({commandLabel:s,platform:o.device.platform,button:d,count:n.flags?.count,intervalMs:n.flags?.intervalMs,holdMs:n.flags?.holdMs,jitterPx:n.flags?.jitterPx,doubleTap:n.flags?.doubleTap});if(e)return cM(e.code,e.message,e.details)}let p="longpress"===t?function(e){var t,r,n;let a,i=mL(e);if(i){return{ok:!0,target:{kind:"point",x:i.x,y:i.y},...void 0===(t=e[2])?{}:{durationMs:Number(t)}}}let o=(a=(r=e).at(-1),r.length>1&&void 0!==(n=a)&&""!==n.trim()&&Number.isFinite(Number(n))?{targetPositionals:r.slice(0,-1),duration:{durationMs:Number(a)}}:{targetPositionals:r,duration:{}}),s=mT(o.targetPositionals,"longpress");return s.ok?{ok:!0,target:s.target,...o.duration}:s}(n.positionals??[]):mT(n.positionals??[],s);if(!p.ok)return p.response;if("ref"===p.target.kind){let a=e.refSnapshotFlagGuardResponse("longpress"===t?"longpress":"press",n.flags);if(a)return a;r=await mK(e,o)}let f=function(e){var t;let{session:r,commandLabel:n,target:a,flags:i}=e;if("click"!==n||"selector"!==a.kind||(t=i,t?.count!==void 0||t?.intervalMs!==void 0||t?.holdMs!==void 0||t?.jitterPx!==void 0||t?.doubleTap!==void 0||t?.clickButton!==void 0&&"primary"!==t.clickButton))return null;let o=f4({session:r,selectorExpression:a.selector});return o?{...o,...i?.maestro?.allowNonHittableCoordinateFallback?{allowNonHittableCoordinateFallback:!0}:{}}:null}({session:o,commandLabel:s,target:p.target,flags:n.flags});if(f){let t=await mB(e,o,f);if(t)return t}let m="longpress"===t?p.durationMs:void 0;return await mz(e,{androidFreshnessBaseline:r,run:async e=>await mG({runtime:e,command:t,target:p.target,sessionName:a,requestId:n.meta?.requestId,clickButton:d,flags:n.flags,durationMs:m}),afterRun:async e=>{var t;await fV(o,(t=p.target,"point"===t.kind?"coordinate tap":"ref"===e.kind&&e.target?.kind==="ref"?e.target.ref:"selector"===e.kind&&e.target?.kind==="selector"?e.target.selector:"target"))},buildPayloads:async r=>{var n;let a="durationMs"in(n=r)?n.durationMs:void 0,i=await mq({params:e,session:o,result:r,extra:"longpress"===t?{...void 0!==a?{durationMs:a}:{},gesture:"longpress"}:c});return{result:i,responseData:i}}})}async function mG(e){let{runtime:t,command:r,target:n,sessionName:a,requestId:i,flags:o}=e;if("longpress"===r)return await t.interactions.longPress(n,{session:a,requestId:i,durationMs:e.durationMs});let s={session:a,requestId:i,button:e.clickButton,count:o?.count,intervalMs:o?.intervalMs,holdMs:o?.holdMs,jitterPx:o?.jitterPx,doubleTap:o?.doubleTap};return"click"===r?await t.interactions.click(n,s):await t.interactions.press(n,s)}async function mq(e){let{params:t,session:r,result:n,extra:a}=e,i="point"===n.kind?await mP({session:r,flags:t.req.flags,sessionStore:t.sessionStore,contextFromFlags:t.contextFromFlags,captureSnapshotForSession:t.captureSnapshotForSession}):mO(r.snapshot?.nodes??[]);return mM({data:n.backendResult,fallbackX:n.point.x,fallbackY:n.point.y,referenceFrame:i,extra:{...m$(n),...a}})}async function mB(e,t,r){return await mj({params:e,session:t,selector:r,command:"press",positionals:[],extra:{selector:r.raw},fallbackPhase:"ios_direct_selector_tap_fallback"})}async function mj(e){let{params:t,session:r,selector:n,command:a,positionals:i,extra:o,fallbackPhase:s}=e,l=Date.now();try{var u,d;let e,s,c=await ch(r.device,a,i,t.req.flags?.out,{...t.contextFromFlags(t.req.flags,r.appBundleId,r.trace?.outPath),directElementSelector:n,surface:r.surface})??{},p=Date.now(),f=(u=c,e="number"==typeof u.x?u.x:void 0,s="number"==typeof u.y?u.y:void 0,void 0!==e&&void 0!==s?{x:e,y:s}:{x:0,y:0}),m=mM({data:c,fallbackX:f.x,fallbackY:f.y,referenceFrame:(d=c,"number"==typeof d.referenceWidth&&"number"==typeof d.referenceHeight?{referenceWidth:d.referenceWidth,referenceHeight:d.referenceHeight}:void 0),extra:{...o,...function(e,t){if(!e.allowNonHittableCoordinateFallback)return{};let r="tapped via non-hittable coordinate fallback"===t.message;return{maestroNonHittableCoordinateFallbackAllowed:!0,maestroNonHittableCoordinateFallbackUsed:r,...r?{maestroFallbackReason:"non-hittable-coordinate"}:{}}}(n,c)}});return mk({session:r,sessionStore:t.sessionStore,command:t.req.command,positionals:t.req.positionals??[],flags:t.req.flags,result:m,responseData:m,actionStartedAt:l,actionFinishedAt:p})}catch(e){if(!f8(e))return{ok:!1,error:k(e)};return eN({level:"debug",phase:s,data:{selector:n.raw,error:e instanceof Error?e.message:String(e)}}),null}}async function mH(e){let{req:t,sessionName:r,sessionStore:n}=e,a=n.get(r);if(a){let e=mR(a,"fill");if(e)return e}if(a&&!cY("fill",a.device))return cM("UNSUPPORTED_OPERATION","fill is not supported on this device");if(!a)return cM("SESSION_NOT_FOUND","No active session. Run open first.");let i=function(e){let t=e[0]??"";if(t.startsWith("@")){var r;let n=e2(e).text;return n?{ok:!0,target:{kind:"ref",ref:t,fallbackLabel:(r=e).length>=3&&r[1]?.trim()||""},text:n}:{ok:!1,response:cM("INVALID_ARGS","fill requires text after ref")}}let n=mL(e);if(n){let t=e.slice(2).join(" ");return t?{ok:!0,target:{kind:"point",x:n.x,y:n.y},text:t}:{ok:!1,response:cM("INVALID_ARGS","fill requires text after coordinates")}}let a=e2(e);return"selector"!==a.kind?{ok:!1,response:cM("INVALID_ARGS","fill requires x y text, @ref text, or selector text")}:a.text.trim()?{ok:!0,target:{kind:"selector",selector:a.target.selector},text:a.text}:{ok:!1,response:cM("INVALID_ARGS","fill requires text after selector")}}(t.positionals??[]);if(!i.ok)return i.response;if("ref"===i.target.kind){let r=e.refSnapshotFlagGuardResponse("fill",t.flags);if(r)return r;await mK(e,a)}let o=function(e){let{session:t,target:r,flags:n}=e;if("selector"!==r.kind)return null;let a=f4({session:t,selectorExpression:r.selector});return a?{...a,...n?.maestro?.allowNonHittableCoordinateFallback?{allowNonHittableCoordinateFallback:!0}:{}}:null}({session:a,target:i.target,flags:t.flags});if(o){let t=await mW(e,a,o,i.text);if(t)return t}return await mz(e,{run:async e=>await e.interactions.fill(i.target,i.text,{session:r,requestId:t.meta?.requestId,delayMs:t.flags?.delayMs}),buildPayloads:e=>{let t="point"===e.kind?void 0:mO(a.snapshot?.nodes??[]),r=mM({data:e.backendResult,fallbackX:e.point.x,fallbackY:e.point.y,referenceFrame:t,extra:{...m$(e),text:i.text}});e.warning&&(r.warning=e.warning);let n="ref"===e.kind?{...e.backendResult??{ref:mF(e.target?.kind==="ref"?e.target.ref:void 0),x:e.point.x,y:e.point.y}}:r;return e.warning&&(n.warning=e.warning),{result:r,responseData:n}}})}async function mW(e,t,r,n){return await mj({params:e,session:t,selector:r,command:"fill",positionals:[n],extra:{selector:r.raw,text:n},fallbackPhase:"ios_direct_selector_fill_fallback"})}async function mz(e,t){let r=e.sessionStore.get(e.sessionName);if(!r)return cM("SESSION_NOT_FOUND","No active session. Run open first.");let n=mE(e),a=Date.now();try{let i=await pT({session:r,command:e.req.command,phase:"before-command"}),o=await t.run(n);await t.afterRun?.(o),await pT({session:r,command:e.req.command,phase:"after-command"});let s=Date.now(),{result:l,responseData:u}=await t.buildPayloads(o);return"recovered"===i.status&&(l.warning=i.warning,u.warning=i.warning),mk({session:r,sessionStore:e.sessionStore,command:e.req.command,positionals:e.req.positionals??[],flags:e.req.flags,result:l,responseData:u,actionStartedAt:a,actionFinishedAt:s,androidFreshnessBaseline:t.androidFreshnessBaseline})}catch(t){let e=M(t);if("COMMAND_FAILED"===e.code&&"string"==typeof e.details?.expectedPackage&&"string"==typeof e.details?.foregroundPackage)throw e;return{ok:!1,error:k(t)}}}async function mK(e,t){if(!c0(t))return;let r=t.snapshot?.comparisonSafe===!0?t.snapshot:void 0;try{await e.captureSnapshotForSession(t,e.req.flags,e.sessionStore,e.contextFromFlags,{interactiveOnly:!0,androidFreshnessMode:"ref-refresh"})}catch(t){eN({level:"warn",phase:"android_ref_snapshot_refresh_failed",data:{command:e.req.command,error:t instanceof Error?t.message:String(t)}})}return r}async function mJ(e,t,r,n,a){let i={...t??{},snapshotInteractiveOnly:a.interactiveOnly,snapshotCompact:a.interactiveOnly},o=n(i,e.appBundleId,e.trace?.outPath),{snapshot:s}=await py({device:e.device,session:e,flags:i,outPath:i.out,logPath:o.logPath??"",androidFreshnessMode:a.androidFreshnessMode});return pk(e,s),r.set(e.name,e),s}async function mX(e){let t=await mU({...e,captureSnapshotForSession:mJ,refSnapshotFlagGuardResponse:fU});if(t)return t;switch(e.req.command){case eD.type:return await mY({...e,captureSnapshotForSession:mJ});case"get":return await f9(e);case"is":return await f7(e);default:return null}}async function mY(e){let{sessionName:t,sessionStore:r}=e,n=r.get(t);if(!n)return cM("SESSION_NOT_FOUND","No active session. Run open first.");if(!cY(eD.type,n.device))return cM("UNSUPPORTED_OPERATION","type is not supported on this device");let a=await mZ(n);return a||await mQ(e,n)}async function mZ(e){return"android"===e.device.platform&&e.recording&&"failed"===await pL({session:e})?cM("COMMAND_FAILED","Android system dialog blocked the recording session"):null}async function mQ(e,t){let{req:r,sessionName:n,sessionStore:a}=e,i=(r.positionals??[]).join(" "),o=mE(e),s=Date.now();try{let e=await pT({session:t,command:r.command,phase:"before-command"}),l=await o.interactions.typeText(i,{session:n,requestId:r.meta?.requestId,delayMs:r.flags?.delayMs});await pT({session:t,command:r.command,phase:"after-command"});let u=Date.now(),d={...l.backendResult??{},text:l.text,delayMs:l.delayMs,...eJ(l.message??`Typed ${Array.from(l.text).length} chars`)};return"recovered"===e.status&&(d.warning=e.warning),mk({session:t,sessionStore:a,command:r.command,positionals:r.positionals??[],flags:r.flags,result:d,responseData:d,actionStartedAt:s,actionFinishedAt:u})}catch(e){return{ok:!1,error:k(e)}}}function m0(e){return{tenantId:e.meta?.tenantId??e.flags?.tenant,runId:e.meta?.runId??e.flags?.runId,leaseId:e.meta?.leaseId??e.flags?.leaseId,leaseTtlMs:e.meta?.leaseTtlMs,leaseBackend:e.meta?.leaseBackend}}async function m1(e){let{req:t,leaseRegistry:r}=e,n=m0(t);switch(t.command){case"lease_allocate":return{ok:!0,data:{lease:r.allocateLease({tenantId:n.tenantId??"",runId:n.runId??"",backend:n.leaseBackend,ttlMs:n.leaseTtlMs})}};case"lease_heartbeat":return{ok:!0,data:{lease:r.heartbeatLease({leaseId:n.leaseId??"",tenantId:n.tenantId,runId:n.runId,ttlMs:n.leaseTtlMs})}};case"lease_release":return{ok:!0,data:r.releaseLease({leaseId:n.leaseId??"",tenantId:n.tenantId,runId:n.runId})};default:return null}}async function m2(e){var t,r;let{req:n,sessionName:a,sessionStore:i}=e;if(n.command!==eD.reactNative)return null;let o=1===(t=n.positionals??[]).length&&"dismiss-overlay"===t[0]?{ok:!0}:{ok:!1,response:cM("INVALID_ARGS","react-native supports only: dismiss-overlay")};if(!o.ok)return o.response;let s=i.get(a);if(!s)return cM("SESSION_NOT_FOUND","No active session. Run open first.");if(!cY(eD.reactNative,s.device))return cM("UNSUPPORTED_OPERATION","react-native dismiss-overlay is not supported on this device");try{let t=await mJ(s,n.flags,i,e.contextFromFlags,{interactiveOnly:!0}),a=tN(t.nodes);if(!a){return r=t,tm(r.nodes).detected?cM("COMMAND_FAILED","React Native overlay detected, but no safe dismiss target was found",{hint:"Use screenshot --overlay-refs for visual evidence and report the overlay instead of pressing the warning body."}):{ok:!0,data:{action:"dismiss-overlay",detected:!1,dismissed:!1,...eJ("No React Native overlay detected")}}}return await m3(e,s,t,a)}catch(e){return{ok:!1,error:k(e)}}}async function m3(e,t,r,n){let{req:a,sessionStore:i}=e,o=Date.now(),s=await ch(t.device,"press",[String(n.point.x),String(n.point.y)],a.flags?.out,e.contextFromFlags(a.flags,t.appBundleId,t.trace?.outPath))??{},l=Date.now(),u={...mO(r.nodes),...s,action:"dismiss-overlay",overlayAction:n.action,x:n.point.x,y:n.point.y,...n.ref?{ref:n.ref}:{},...n.label?{label:n.label}:{},...n.warning?{warning:n.warning}:{},dismissed:!0,verified:!1,verificationRequired:!0,nextCommand:"agent-device snapshot -i -c",...eJ("minimize"===n.action?"React Native RedBox minimize action sent; run snapshot -i before continuing":"React Native overlay dismiss action sent; run snapshot -i before continuing")};return mk({session:t,sessionStore:i,command:a.command,positionals:a.positionals??[],flags:a.flags,result:u,responseData:u,actionStartedAt:o,actionFinishedAt:l})}function m5(e=process.env){let t=m6(),r=f.join(t,"home"),n=f.join(t,"module-cache");return l.mkdirSync(r,{recursive:!0}),l.mkdirSync(n,{recursive:!0}),{...e,HOME:r,CLANG_MODULE_CACHE_PATH:n}}async function m4(e){let t=l.statSync(e.sourcePath),r=l.readFileSync(e.sourcePath),n=ht(e.cacheName??f.basename(e.sourcePath,f.extname(e.sourcePath))),a=hr(["2",process.platform,process.arch,f.resolve(e.sourcePath),t.size,r]),i=f.join(m6(),"bin",`${n}-${a}`);return await m9({sourcePath:e.sourcePath,executablePath:i,timeoutMs:e.timeoutMs}),i}async function m8(e){let t=ht(e.cacheName),r=hr(["2",process.platform,process.arch,e.source]),n=f.join(m6(),"sources",`${t}-${r}.swift`),a=f.join(m6(),"bin",`${t}-${r}`);return await m9({sourcePath:n,executablePath:a,sourceText:e.source,timeoutMs:e.timeoutMs}),a}function m6(){let e=process.env.AGENT_DEVICE_SWIFT_CACHE_DIR?.trim();return e?f.resolve(e):f.join(c.tmpdir(),"agent-device-swift-cache")}async function m9(e){if(he(e.executablePath))return;let t=f.dirname(e.executablePath);l.mkdirSync(t,{recursive:!0});let r=`${e.executablePath}.lock`;if(!await m7(r,e.executablePath,e.timeoutMs??12e4))return;let n=l.mkdtempSync(f.join(t,`.${f.basename(e.executablePath)}.${process.pid}.`)),a=f.join(n,f.basename(e.executablePath));try{if(he(e.executablePath))return;void 0===e.sourceText||l.existsSync(e.sourcePath)||(l.mkdirSync(f.dirname(e.sourcePath),{recursive:!0}),l.writeFileSync(e.sourcePath,e.sourceText)),await R("xcrun",["swiftc",e.sourcePath,"-o",a],{timeoutMs:e.timeoutMs??12e4,env:m5()}),l.renameSync(a,e.executablePath)}finally{l.rmSync(n,{recursive:!0,force:!0}),l.rmSync(r,{recursive:!0,force:!0})}}async function m7(e,t,r){let n=Date.now()+r;for(;;){if(he(t))return!1;try{return l.mkdirSync(e),!0}catch(t){if("EEXIST"!==t.code)throw t;if(function(e,t){try{return Date.now()-l.statSync(e).mtimeMs>=t}catch{return!1}}(e,r)){l.rmSync(e,{recursive:!0,force:!0});continue}if(Date.now()>=n)throw new D("COMMAND_FAILED",`Timed out waiting for Swift cache lock: ${e} (${r}ms)`,{lockDir:e,timeoutMs:r,hint:`Another agent-device process may still be compiling this Swift helper. Retry shortly; if no agent-device process is active, remove "${e}" and retry.`});await S(25)}}}function he(e){try{return l.accessSync(e,l.constants.X_OK),l.statSync(e).isFile()}catch{return!1}}function ht(e){return e.replaceAll(/[^A-Za-z0-9._-]/g,"-").replaceAll(/^-+|-+$/g,"")||"swift-helper"}function hr(e){let t=s("sha256");for(let r of e)t.update(Buffer.isBuffer(r)?r:String(r)),t.update("\0");return t.digest("hex").slice(0,16)}let hn=`
35
35
  import Foundation
36
36
  import AVFoundation
37
37
 
@@ -55,15 +55,16 @@ Task {
55
55
 
56
56
  semaphore.wait()
57
57
  exit(exitCode)
58
- `.trim();async function m1(e,t={}){let r,n=t.pollMs??150,a=t.attempts??12,i=0;for(let t=0;t<a;t+=1){let t=0;try{t=l.statSync(e).size}catch{t=0}if(t>0&&t===r){if((i+=1)>=2)return}else i=0;r=t,await e2(n)}}async function m2(e){try{let t=await m3(),r=await E(t,[e],{allowFailure:!0,timeoutMs:1e4,env:mH()});if(0===r.exitCode)return!0;if(m4(r.stderr,r.stdout))return m8(e);return!1}catch(r){var t;if((t=r)instanceof O&&("TOOL_MISSING"===t.code||m4(String(t.details?.stderr??""),String(t.details?.stdout??""))))return m8(e);throw r}}async function m3(){t??=mz({source:m0,cacheName:"video-validator",timeoutMs:3e4});try{return await t}catch(e){throw t=void 0,e}}async function m5(e,t={}){let r=t.pollMs??150,n=t.attempts??12;for(let t=0;t<n;t+=1){if(await m2(e))return;await e2(r)}}function m4(e,t){let r=`${e}
59
- ${t}`;return/\b(no such module ['"]AVFoundation['"]|unable to find utility ["']swiftc?["']|xcrun: error: unable to find utility ["']swiftc?["'])\b/i.test(r)}function m8(e){try{let t=l.statSync(e);if(!t.isFile()||t.size<=0)return!1}catch{return!1}let t=function(e){try{let t=l.openSync(e,"r");try{let e=l.fstatSync(t).size,r=0,n=[];for(;r+8<=e&&n.length<16;){let e=Buffer.alloc(8);if(8>l.readSync(t,e,0,8,r))break;let a=e.readUInt32BE(0),i=e.toString("latin1",4,8);if(n.push(i),1===a){let e=Buffer.alloc(8);if(8>l.readSync(t,e,0,8,r+8))break;a=Number(e.readBigUInt64BE(0))}if(!Number.isFinite(a)||a<=0)break;r+=a}return n}finally{l.closeSync(t)}}catch{return[]}}(e);return t.includes("ftyp")&&t.includes("moov")}function m6(e){let t=f.parse(e);return f.join(t.dir,`${t.name}.gesture-telemetry.json`)}function m9(e){return[...e].sort((e,t)=>e.tMs-t.tMs)}function m7(e){let t=f.dirname(y(import.meta.url)),r=[y(new URL(`./${e}`,import.meta.url)),f.resolve(t,`../../ios-runner/AgentDeviceRunner/RecordingScripts/${e}`),f.resolve(t,`../../../ios-runner/AgentDeviceRunner/RecordingScripts/${e}`),f.resolve(process.cwd(),`ios-runner/AgentDeviceRunner/RecordingScripts/${e}`)];for(let e of r)if(l.existsSync(e))return e;throw new O("COMMAND_FAILED",`Missing recording helper script: ${e}`,{hint:"Ensure ios-runner/AgentDeviceRunner/RecordingScripts is present in this checkout or bundled with the package.",scriptName:e,searchedPaths:r})}async function he(e){var t;let r,n,{videoPath:a,scriptPath:i,scriptArgs:o,commandDescription:s}=e;await m1(a),await m5(a);let u=(t=a,r=f.parse(t),n=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`,f.join(r.dir,`.${r.name}.agent-device-${n}${r.ext||".mp4"}`));try{let e=await mW({sourcePath:i});await E(e,["--input",a,"--output",u,...o],{timeoutMs:12e4,env:mH()}),await m5(u),l.renameSync(u,a)}catch(t){let e=t instanceof O?t:new O("COMMAND_FAILED",String(t),void 0,t instanceof Error?t:void 0);throw new O("COMMAND_FAILED",s,{...e.details,videoPath:a,script:i},e)}finally{l.rmSync(u,{force:!0})}}async function ht(e){let{videoPath:t,trimStartMs:r}=e;r>0&&await he({videoPath:t,scriptPath:n??=m7("recording-trim.swift"),scriptArgs:["--trim-start-ms",String(r)],commandDescription:"Failed to trim the start of the iOS recording"})}async function hr(e){let{videoPath:t,telemetryPath:n,targetLabel:a="recording"}=e;await he({videoPath:t,scriptPath:r??=m7("recording-overlay.swift"),scriptArgs:["--events",n],commandDescription:`Failed to add touch overlays to the ${a}`})}async function hn(e){let{videoPath:t,quality:r,targetLabel:n="recording"}=e;await he({videoPath:t,scriptPath:a??=m7("recording-resize.swift"),scriptArgs:["--quality",String(r)],commandDescription:`Failed to resize the ${n}`})}function ha(e){return e instanceof Error?e.message:String(e)}function hi(e,t){return e.stderr.trim()||e.stdout.trim()||`${t} exited with code ${e.exitCode}`}async function ho(e){let{recording:t,deps:r,trimStartMs:n,targetLabel:a}=e,i=function(e){var t,r,n;let a,i,{recording:o,trimStartMs:s}=e,u=(a=m6((t={videoPath:o.outPath,events:o.gestureEvents,trimStartMs:s}).videoPath),i={version:1,generatedAt:new Date().toISOString(),events:(r=t.events,(n=t.trimStartMs??0)>0?m9(r.flatMap(e=>{let t=e.tMs-n,r="durationMs"in e?e.durationMs:void 0;return("number"==typeof r?t+r:t)<=0?[]:[{...e,tMs:Math.max(0,t)}]})):m9(r))},l.writeFileSync(a,JSON.stringify(i,null,2)),a);return o.telemetryPath=u,u}({recording:t,trimStartMs:n});if(!t.showTouches)return void eM({level:"debug",phase:"record_stop_overlay_skipped",data:{reason:"hide_touches"}});if(0===t.gestureEvents.length)return void eM({level:"debug",phase:"record_stop_overlay_skipped",data:{reason:"no_gesture_events"}});let o=function(e=process.platform){if("darwin"!==e)return"touch overlay burn-in is only available on macOS hosts; returning raw video plus gesture telemetry"}();if(o){t.overlayWarning??=o;return}try{await eN("record_stop_overlay_export",()=>r.overlayRecordingTouches({videoPath:t.outPath,telemetryPath:i,targetLabel:a}),{targetLabel:a,gestureEventCount:t.gestureEvents.length})}catch(e){t.overlayWarning??=`failed to overlay recording touches: ${ha(e)}`}}async function hs(e,t,r){return await Q(J(e),t,r)}async function hl(e,t){let r=await hs(e,["shell","ps","-o","pid=","-p",t],{allowFailure:!0});return 0===r.exitCode&&r.stdout.split(/\s+/).map(e=>e.trim()).includes(t)}async function hu(e,t){for(let r=0;r<40;r+=1){if(!await hl(e,t))return!0;await e2(250)}return!await hl(e,t)}async function hd(e,t){let r,n=0;for(let a=0;a<20;a+=1){let a=await hs(e,["shell","stat","-c","%s",t],{allowFailure:!0}),i=0===a.exitCode?a.stdout.trim():"";if(i.length>0&&i===r){if((n+=1)>=4)return}else n=0;r=i,await e2(250)}}async function hc(e,t,r){for(let n=0;n<8;n+=1){let a=await hs(e,["shell","stat","-c","%s",t],{allowFailure:!0}),i=0===a.exitCode?Number(a.stdout.trim()):NaN;if(Number.isFinite(i)&&i>0)return!0;if(!await hl(e,r))break;if(n+1>=2)return!0;await e2(250)}return!1}async function hp(e){let t,{deps:r,deviceId:n,remotePath:a,outPath:i}=e;for(let e=0;e<2;e+=1){try{l.rmSync(i,{force:!0})}catch{}let o=J(n),s=await e4(a,i,{allowFailure:!0,device:o});if(0!==s.exitCode)t=hi(s,"adb pull");else{await r.waitForStableFile(i,{pollMs:250,attempts:20});let t=await r.isPlayableVideo(i);if(eM({level:"debug",phase:"record_stop_android_pull_validation",data:{deviceId:n,remotePath:a,outPath:i,attempt:e+1,fileSize:(()=>{try{return l.statSync(i).size}catch{return 0}})(),playable:t}}),t)return;eM({level:"warn",phase:"record_stop_android_invalid_video_retry",data:{deviceId:n,remotePath:a,outPath:i,attempt:e+1}})}e<1&&await e2(750)}return t?`failed to copy recording from device: ${t}`:"failed to copy recording from device: pulled file is not a playable MP4"}async function hf(e){let{deviceId:t,quality:r}=e;if(void 0===r||r>=10)return;let n=await hs(t,["shell","wm","size"],{allowFailure:!0}),a=n.stdout.match(/Override size:\s*(\d+)x(\d+)/)??n.stdout.match(/Physical size:\s*(\d+)x(\d+)/);if(0!==n.exitCode||!a)throw Error(`failed to resolve Android screen size for recording quality: ${hi(n,"adb shell wm size")}`);return{width:hm(Number(a[1]),r),height:hm(Number(a[2]),r)}}function hm(e,t){return Math.max(2,2*Math.round(e*t/10/2))}async function hh(e,t){await hs(e,["shell","rm","-f",t],{allowFailure:!0})}async function hw(e,t){let r=await hs(e,["shell","kill","-9",t],{allowFailure:!0});return eM({level:"warn",phase:"record_stop_android_force_signal",data:{deviceId:e,remotePid:t,exitCode:r.exitCode,stdout:r.stdout.trim(),stderr:r.stderr.trim()}}),!(0!==r.exitCode&&await hl(e,t))&&await hu(e,t)}async function hg(e){var t;let r,n,{device:a,recordingBase:i}=e,o="failed to start recording: Android screenrecord did not begin producing frames";try{r=await hf({deviceId:a.id,quality:i.quality})}catch(e){return cm("COMMAND_FAILED",e instanceof Error?e.message:String(e))}for(let e of(t=Date.now(),n=`agent-device-recording-${t}.mp4`,[`/sdcard/${n}`,`/data/local/tmp/${n}`])){let t=await hs(a.id,["shell",function(e,t){let r=["screenrecord"];return t&&r.push("--size",`${t.width}x${t.height}`),r.push(e),`${r.join(" ")} >/dev/null 2>&1 & echo $!`}(e,r)],{allowFailure:!0});if(0!==t.exitCode){o=`failed to start recording: ${hi(t,"adb shell screenrecord")}`;continue}let n=t.stdout.split(/\r?\n/).map(e=>e.trim()).filter(e=>/^\d+$/.test(e)).at(-1);if(!n){o="failed to start recording: adb did not return a valid Android screenrecord pid",await hh(a.id,e);continue}if(eM({level:"debug",phase:"record_start_android_started",data:{deviceId:a.id,remotePath:e,remotePid:n}}),await hc(a.id,e,n))return{platform:"android",remotePath:e,remotePid:n,...i,startedAt:Date.now()};o="failed to start recording: Android screenrecord did not begin producing frames",await hw(a.id,n),await hh(a.id,e)}return cm("COMMAND_FAILED",o)}async function hy(e){let t,r,{deps:n,device:a,recording:i}=e;eM({level:"debug",phase:"record_stop_android_enter",data:{deviceId:a.id,remotePath:i.remotePath,remotePid:i.remotePid}});let o=await hs(a.id,["shell","kill","-2",i.remotePid],{allowFailure:!0});if(eM({level:"debug",phase:"record_stop_android_signal",data:{deviceId:a.id,remotePath:i.remotePath,remotePid:i.remotePid,exitCode:o.exitCode,stdout:o.stdout.trim(),stderr:o.stderr.trim()}}),0!==o.exitCode?await hl(a.id,i.remotePid)&&!await hw(a.id,i.remotePid)&&(t=`failed to stop recording: ${hi(o,"adb shell kill")}`):await hu(a.id,i.remotePid)||await hw(a.id,i.remotePid)||(t=`failed to stop recording: Android screenrecord pid ${i.remotePid} did not exit`),!t){await hd(a.id,i.remotePath);let e=await hp({deps:n,deviceId:a.id,remotePath:i.remotePath,outPath:i.outPath});if(e)return await s(),cm("COMMAND_FAILED",e);await ho({recording:i,deps:n,targetLabel:"Android recording"})}if(await s(),t)return cm("COMMAND_FAILED",t);if(r)return cm("COMMAND_FAILED",r);return null;async function s(){let e=await hs(a.id,["shell","rm","-f",i.remotePath],{allowFailure:!0});eM({level:"debug",phase:"record_stop_android_cleanup",data:{deviceId:a.id,remotePath:i.remotePath,exitCode:e.exitCode,stdout:e.stdout.trim(),stderr:e.stderr.trim()}}),0===e.exitCode||t||(r=`failed to clean up remote recording: ${hi(e,"adb shell rm")}`)}}function hv(e){let t=e.appBundleId?.trim();return t&&t.length>0?t:void 0}function hI(e,t,r){return{verbose:e.flags?.verbose,logPath:t,traceLogPath:r.trace?.outPath,requestId:e.meta?.requestId}}async function hb(e){let{req:t,activeSession:r,device:n,logPath:a,deps:i}=e,o=hv(r);try{await i.runIosRunnerCommand(n,{command:"recordStop",appBundleId:o},hI(t,a,r))}catch(e){eM({level:"warn",phase:"record_stop_runner_failed",data:{platform:n.platform,kind:n.kind,deviceId:n.id,session:r.name,error:ha(e)}})}}async function hA(e){let{req:t,activeSession:r,device:n,logPath:a,deps:i}=e,o=hv(r);if(o)try{await i.runIosRunnerCommand(n,{command:"snapshot",appBundleId:o,interactiveOnly:!0,compact:!0,depth:1},hI(t,a,r))}catch(e){eM({level:"warn",phase:"record_start_simulator_runner_warm_failed",data:{deviceId:n.id,session:r.name,appBundleId:o,error:ha(e)}})}}async function hS(e){let t,r,{req:n,activeSession:a,sessionStore:i,device:o,logPath:s,deps:l,fpsFlag:u,recordingBase:d,appBundleId:c}=e,p=`agent-device-recording-${Date.now()}.mp4`,f=`tmp/${p}`,m=hI(n,s,a),h=async()=>l.runIosRunnerCommand(o,{command:"recordStart",outPath:p,fps:u,quality:d.quality,appBundleId:c},m);try{let e=await h();t="number"==typeof e.recorderStartUptimeMs?e.recorderStartUptimeMs:void 0,r="number"==typeof e.targetAppReadyUptimeMs?e.targetAppReadyUptimeMs:void 0}catch(n){var w,g;if(!ha(n).toLowerCase().includes("recording already in progress"))return cm("COMMAND_FAILED",`failed to start recording: ${ha(n)}`);eM({level:"warn",phase:"record_start_runner_desynced",data:{platform:o.platform,kind:o.kind,deviceId:o.id,session:a.name,error:ha(n)}});let e=(w=o.id,g=a.name,i.toArray().find(e=>e.name!==g&&"ios"===e.device.platform&&"device"===e.device.kind&&e.device.id===w&&e.recording?.platform==="ios-device-runner"));if(e)return cm("COMMAND_FAILED",`failed to start recording: recording already in progress in session '${e.name}'`);try{await l.runIosRunnerCommand(o,{command:"recordStop",appBundleId:c},m)}catch{}try{let e=await h();t="number"==typeof e.recorderStartUptimeMs?e.recorderStartUptimeMs:void 0,r="number"==typeof e.targetAppReadyUptimeMs?e.targetAppReadyUptimeMs:void 0}catch(e){return cm("COMMAND_FAILED",`failed to start recording: ${ha(e)}`)}}return{platform:"ios-device-runner",remotePath:f,runnerStartedAtUptimeMs:t,targetAppReadyUptimeMs:r,...d}}async function h_(e){let{req:t,activeSession:r,device:n,logPath:a,deps:i,fpsFlag:o,recordingBase:s,appBundleId:l}=e;try{await i.runIosRunnerCommand(n,{command:"recordStart",outPath:s.outPath,fps:o,quality:s.quality,appBundleId:l},hI(t,a,r))}catch(e){return cm("COMMAND_FAILED",`failed to start recording: ${ha(e)}`)}return{platform:"macos-runner",...s}}async function hx(e){let{req:t,activeSession:r,device:n,logPath:a,deps:i,recording:o}=e;await hb({req:t,activeSession:r,device:n,logPath:a,deps:i});let s={stdout:"",stderr:"",exitCode:1};for(let e of ng)if(0===(s=await i.runCmd("xcrun",["devicectl","device","copy","from","--device",n.id,"--source",o.remotePath,"--destination",o.outPath,"--domain-type","appDataContainer","--domain-identifier",e],{allowFailure:!0})).exitCode)break;if(0!==s.exitCode){let e=s.stderr.trim()||s.stdout.trim()||`devicectl exited with code ${s.exitCode}`;return cm("COMMAND_FAILED",`failed to copy recording from device: ${e}`)}let l="number"!=typeof o.runnerStartedAtUptimeMs||"number"!=typeof o.targetAppReadyUptimeMs?0:Math.max(0,o.targetAppReadyUptimeMs-o.runnerStartedAtUptimeMs);return l>0&&await i.trimRecordingStart({videoPath:o.outPath,trimStartMs:l}),await ho({recording:o,deps:i,trimStartMs:l,targetLabel:"iOS recording"}),null}async function hN(e){let{req:t,activeSession:r,device:n,logPath:a,deps:i,recording:o}=e;return await hb({req:t,activeSession:r,device:n,logPath:a,deps:i}),await ho({recording:o,deps:i,targetLabel:"macOS recording"}),null}async function hM(e){let{deps:t,recording:r}=e;r.child.kill("SIGINT");let n=await hk(r.wait,5e3);return n||(await hD(t,r,"SIGINT"),(n=await hk(r.wait,2e3))||(r.child.kill("SIGTERM"),await hD(t,r,"SIGTERM"),n=await hk(r.wait,2e3)))?n:(r.child.kill("SIGKILL"),await hD(t,r,"SIGKILL"),await hk(r.wait,2e3))}async function hk(e,t){return await Promise.race([e,e2(t).then(()=>null)])}async function hD(e,t,r){await hO(e,t,r)||await hP(e,t.outPath,r)}async function hP(e,t,r){let n,a=`simctl.*recordVideo.*${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`;try{n=await e.runCmd("pgrep",["-f",a],{allowFailure:!0})}catch(e){eM({level:"warn",phase:"record_stop_ios_simulator_pgrep_failed",data:{outPath:t,signal:r,error:ha(e)}});return}let i=hC(hL(n.stdout)),o=hE(i,r);eM({level:o>0?"warn":"debug",phase:"record_stop_ios_simulator_signal_recorders",data:{outPath:t,signal:r,matchedPidCount:i.length,signaled:o,pgrepExitCode:n.exitCode}})}async function hO(e,t,r){let n=t.recorderPid??t.child.pid;if("number"!=typeof n||!Number.isInteger(n)||n<=0)return eM({level:"debug",phase:"record_stop_ios_simulator_owned_recorder_unavailable",data:{outPath:t.outPath,signal:r,reason:"missing_recorder_pid"}}),!1;let a=await hR(e,n,t.outPath,r),i=hC([n,...a.pids]),o=hE(i,r);return eM({level:o>0?"warn":"debug",phase:"record_stop_ios_simulator_signal_owned_recorder",data:{outPath:t.outPath,signal:r,recorderPid:n,childPidCount:a.pids.length,matchedPidCount:i.length,signaled:o,pgrepExitCode:a.exitCode}}),o>0}async function hR(e,t,r,n){let a;try{a=await e.runCmd("pgrep",["-P",String(t)],{allowFailure:!0})}catch(e){return eM({level:"warn",phase:"record_stop_ios_simulator_owned_pgrep_failed",data:{outPath:r,signal:n,parentPid:t,error:ha(e)}}),{pids:[]}}return{pids:hL(a.stdout),exitCode:a.exitCode}}function hC(e){return Array.from(new Set(e)).filter(e=>Number.isInteger(e)&&e>0&&e!==process.pid)}function hE(e,t){let r=0;for(let n of e)try{process.kill(n,t),r+=1}catch{}return r}function hL(e){return e.split(/\s+/).map(e=>Number(e)).filter(e=>Number.isInteger(e)&&e>0)}async function h$(e){"ios"!==e.platform||0!==e.gestureEvents.length&&await e2(350)}async function hT(e){for(let t=0;t<2;t+=1){try{if(l.statSync(e).size>0)return Date.now()}catch{}if(t+1>=2)break;await e2(250)}return Date.now()}async function hF(e){let t,r,{req:n,activeSession:a,device:i,logPath:o,deps:s,recordingBase:l,resolvedOut:u}=e;l.showTouches&&await hA({req:n,activeSession:a,device:i,logPath:o,deps:s});let{child:d,wait:c}=s.startIosSimulatorRecording({device:i,outPath:u}),p=await hT(u);if(l.showTouches)try{let e=Date.now(),l=await s.runIosRunnerCommand(i,{command:"uptime",appBundleId:hv(a)},hI(n,o,a)),u=Date.now();t=Math.round((e+u)/2),r="number"==typeof l.currentUptimeMs?l.currentUptimeMs:void 0}catch{}return{platform:"ios",child:d,wait:c,...l,recorderPid:d.pid,startedAt:p,gestureClockOriginAtMs:void 0===r?void 0:t,gestureClockOriginUptimeMs:r}}async function hU(e){let t,{req:r,sessionName:n,sessionStore:a,activeSession:i,device:o,logPath:s,deps:u}=e;if(i.recording)return cm("INVALID_ARGS","recording already in progress");let d=r.flags?.fps,c=r.flags?.quality;if(void 0!==d&&(!Number.isInteger(d)||d<1||d>120))return cm("INVALID_ARGS","fps must be an integer between 1 and 120");if(void 0!==c&&(!Number.isInteger(c)||c<5||c>10))return cm("INVALID_ARGS","quality must be an integer between 5 and 10");if(!cF("record",o))return cm("UNSUPPORTED_OPERATION","record is not supported on this device");let p=r.positionals?.[1]??`./recording-${Date.now()}.mp4`,m=aE.expandHome(p,r.meta?.cwd),h={outPath:m,clientOutPath:r.meta?.clientArtifactPaths?.outPath,startedAt:Date.now(),quality:r.flags?.quality,showTouches:r.flags?.hideTouches!==!0,gestureEvents:[]};if(l.mkdirSync(f.dirname(m),{recursive:!0}),l.rmSync(m,{force:!0}),"ios"===o.platform&&"device"===o.kind){let e=hv(i);if(!e)return cm("INVALID_ARGS","record on physical iOS devices requires an active app session; run open <app> first");t=await hS({req:r,activeSession:i,sessionStore:a,device:o,logPath:s,deps:u,fpsFlag:d,recordingBase:h,appBundleId:e})}else if("macos"===o.platform){let e=hv(i);if(!e)return cm("INVALID_ARGS","record on macOS requires an active app session; run open <app> first");t=await h_({req:r,activeSession:i,device:o,logPath:s,deps:u,fpsFlag:d,recordingBase:h,appBundleId:e})}else t="ios"===o.platform?await hF({req:r,activeSession:i,device:o,logPath:s,deps:u,recordingBase:h,resolvedOut:m}):await hg({device:o,recordingBase:h});return"ok"in t?t:(i.recording=t,a.set(n,i),a.recordAction(i,{command:r.command,positionals:r.positionals??[],flags:r.flags??{},result:{action:"start",showTouches:t.showTouches}}),{ok:!0,data:{recording:"started",outPath:t.clientOutPath??p,showTouches:t.showTouches}})}async function hV(e){let{deps:t,device:r,recording:n}=e;if("android"===n.platform)return await hy({deps:t,device:r,recording:n});await eN("record_stop_tail_settle",()=>t.waitForRecordingTail(n),{platform:n.platform,gestureEventCount:n.gestureEvents.length});let a=await eN("record_stop_ios_simulator_process",()=>hM({deps:t,recording:n}),{outPath:n.outPath});if(!a)return cm("COMMAND_FAILED","failed to stop recording: simctl recordVideo did not exit after 5000ms and forced cleanup");if(0!==a.exitCode)return cm("COMMAND_FAILED",`failed to stop recording: ${hi(a,"simctl recordVideo")}`);if(await eN("record_stop_video_stable",()=>t.waitForStableFile(n.outPath,{pollMs:150,attempts:12}),{outPath:n.outPath}),!await eN("record_stop_video_playable_check",()=>t.isPlayableVideo(n.outPath),{outPath:n.outPath}))return cm("COMMAND_FAILED",`failed to stop recording: ${n.outPath} was not finalized into a playable video`);if(void 0!==n.quality&&n.quality<10){let e=n.quality;try{await eN("record_stop_resize",()=>t.resizeRecording({videoPath:n.outPath,quality:e,targetLabel:"iOS recording"}),{outPath:n.outPath,quality:e})}catch(e){n.overlayWarning=`failed to resize recording: ${ha(e)}`}}return await eN("record_stop_finalize_overlay",()=>ho({recording:n,deps:t,targetLabel:"iOS recording"}),{outPath:n.outPath,showTouches:n.showTouches,gestureEventCount:n.gestureEvents.length}),null}async function hG(e){var t;let r,{req:n,activeSession:a,device:i,logPath:o,deps:s}=e;if(!a.recording)return cm("INVALID_ARGS","no active recording");let l=a.recording,u=l.invalidatedReason;a.recording=void 0;let d="ios-device-runner"===l.platform?await hx({req:n,activeSession:a,device:i,logPath:o,deps:s,recording:l}):"macos-runner"===l.platform?await hN({req:n,activeSession:a,device:i,logPath:o,deps:s,recording:l}):await hV({deps:s,device:i,recording:l});if(d)return d;if(u&&"ios"===l.platform&&l.showTouches)l.overlayWarning??=`overlay unavailable: ${u}`;else if(u)return cm("COMMAND_FAILED",u);return r=[{field:"outPath",path:(t=l).outPath,localPath:t.clientOutPath,fileName:f.basename(t.clientOutPath??t.outPath)}],t.telemetryPath&&r.push({field:"telemetryPath",path:t.telemetryPath,localPath:function(e){if(e.clientOutPath)return m6(e.clientOutPath)}(t),fileName:f.basename(t.telemetryPath)}),{ok:!0,data:{recording:"stopped",outPath:t.outPath,telemetryPath:t.telemetryPath,artifacts:r,showTouches:t.showTouches,overlayWarning:t.overlayWarning}}}async function hq(e){let{req:t,sessionName:r,sessionStore:n,logPath:a}=e,i={runCmd:async(e,t,r)=>"xcrun"===e?await rM(t,r):await E(e,t,r),startIosSimulatorRecording:e=>cS.resolve(void 0).startIosSimulatorRecording(e),runIosRunnerCommand:ao,waitForRecordingTail:h$,waitForStableFile:m1,isPlayableVideo:m2,trimRecordingStart:ht,resizeRecording:hn,overlayRecordingTouches:hr},o=n.get(r),s=o?.device??await oy(t.flags??{});o||await oK(s);let l=o??{name:r,device:s,createdAt:Date.now(),actions:[]},u=(t.positionals?.[0]??"").toLowerCase();if(!["start","stop"].includes(u))return cm("INVALID_ARGS","record requires start|stop");if("start"===u)return hU({req:t,sessionName:r,sessionStore:n,activeSession:l,device:s,logPath:a,deps:i});let d=await hG({req:t,activeSession:l,device:s,logPath:a,deps:i});return d.ok&&n.recordAction(l,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{action:"stop",outPath:d.data?.outPath,showTouches:d.data?.showTouches}}),d}async function hj(e){let{req:t,sessionName:r,sessionStore:n,logPath:a}=e,i=t.command;if("record"===i)return hq({req:t,sessionName:r,sessionStore:n,logPath:a});if("trace"===i){let e=(t.positionals?.[0]??"").toLowerCase();if(!["start","stop"].includes(e))return cm("INVALID_ARGS","trace requires start|stop");let a=n.get(r);if(!a)return cm("SESSION_NOT_FOUND","No active session");if("start"===e){if(a.trace)return cm("INVALID_ARGS","trace already in progress");let e=t.positionals?.[1]??n.defaultTracePath(a),r=aE.expandHome(e);return l.mkdirSync(f.dirname(r),{recursive:!0}),l.appendFileSync(r,""),a.trace={outPath:r,startedAt:Date.now()},n.recordAction(a,{command:i,positionals:t.positionals??[],flags:t.flags??{},result:{action:"start",outPath:r}}),{ok:!0,data:{trace:"started",outPath:r}}}if(!a.trace)return cm("INVALID_ARGS","no active trace");let o=a.trace.outPath;if(t.positionals?.[1]){let e=aE.expandHome(t.positionals[1]);l.mkdirSync(f.dirname(e),{recursive:!0}),l.existsSync(o)?l.renameSync(o,e):l.appendFileSync(e,""),o=e}return a.trace=void 0,n.recordAction(a,{command:i,positionals:t.positionals??[],flags:t.flags??{},result:{action:"stop",outPath:o}}),{ok:!0,data:{trace:"stopped",outPath:o}}}return null}let hB=new Map;async function hH(e){let t=await S.mkdtemp(f.join(c.tmpdir(),"agent-device-materialized-"));try{let r=await hK(e.installablePath,f.join(t,"installable")),n=e.archivePath?await hK(e.archivePath,f.join(t,"archive")):void 0,a=o.randomUUID(),i=e.ttlMs??9e5,s=Date.now()+i,l=setTimeout(()=>{hW(a)},i);return hB.set(a,{rootPath:t,installablePath:r,archivePath:n,tenantId:e.tenantId,sessionName:e.sessionName,expiresAt:s,timer:l}),{materializationId:a,installablePath:r,...n?{archivePath:n}:{},expiresAt:new Date(s).toISOString()}}catch(e){throw await S.rm(t,{recursive:!0,force:!0}),e}}async function hW(e,t){let r=hB.get(e);if(!r)throw new O("INVALID_ARGS",`Materialized paths not found: ${e}`);if(r.tenantId&&r.tenantId!==t)throw new O("UNAUTHORIZED","Materialized paths belong to a different tenant");clearTimeout(r.timer),hB.delete(e),await S.rm(r.rootPath,{recursive:!0,force:!0})}async function hz(e){let t=Array.from(hB.entries()).filter(([,t])=>t.sessionName===e).map(([e])=>e);await Promise.all(t.map(async e=>{await hW(e)}))}async function hK(e,t){let r=await S.stat(e);await S.mkdir(t,{recursive:!0});let n=f.join(t,f.basename(e));return r.isDirectory()?await S.cp(e,n,{recursive:!0}):await S.copyFile(e,n),n}async function hJ(e){var t;let r="ios"===(t=e.flags?.platform)||"android"===t?t:void 0;if(e.session){if(r&&e.session.device.platform!==r)throw new O("INVALID_ARGS",`install_from_source requested platform ${r}, but session is bound to ${e.session.device.platform}`);return await oK(e.session.device),e.session.device}if(!r)throw new O("INVALID_ARGS",'install_from_source requires platform "ios" or "android" when no session is provided');let n=await oy(e.flags??{});return await oK(n),n}async function hX(e){let{prepared:t,retention:r,req:n,session:a,sessionName:i}=e;if(r.enabled)return await hH({archivePath:t.archivePath,installablePath:t.installablePath,tenantId:n.meta?.tenantId,sessionName:a?i:void 0,ttlMs:r.ttlMs})}function hY(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function hZ(e){let{req:t,sessionName:r,sessionStore:n}=e,a=n.get(r);try{let e,i,o=(e=function(e){let t=e.meta?.installSource;if(!t)throw new O("INVALID_ARGS","install_from_source requires a source payload");switch(t.kind){case"url":if(!t.url||0===t.url.trim().length)throw new O("INVALID_ARGS","install_from_source url source requires a non-empty url");return t;case"path":if(!t.path||0===t.path.trim().length)throw new O("INVALID_ARGS","install_from_source path source requires a non-empty path");return t;case"github-actions-artifact":throw new O("UNSUPPORTED_OPERATION","install_from_source github-actions-artifact sources require a compatible remote daemon");default:throw new O("UNSUPPORTED_OPERATION",`install_from_source ${String(t.kind)} sources require a compatible remote daemon`)}}(t),(i=t.meta?.uploadedArtifactId)&&"path"===e.kind?{source:{kind:"path",path:ix(i,t.meta?.tenantId)},cleanup:()=>{iN(i)}}:{source:e,cleanup:()=>{}}),s=function(e){let t=e.meta?.retainMaterializedPaths===!0,r=e.meta?.materializedPathRetentionMs;if(!t)return{enabled:!1};if(void 0!==r&&r<=0)throw new O("INVALID_ARGS","install_from_source retentionMs must be a positive integer");return{enabled:!0,ttlMs:r}}(t),l=await hJ({session:a,flags:t.flags});if(!cF("install",l))return cm("UNSUPPORTED_OPERATION","install_from_source is not supported on this device");let u=rc(t.meta?.requestId),d=async(e,i)=>{let l;try{var u;l=await hX({prepared:e,retention:s,req:t,session:a,sessionName:r});let o=await i(l),d=eH(o,(u=o,`Installed: ${eQ(u)}`));return!function(e){let{session:t,sessionStore:r,req:n,data:a}=e;t&&r.recordAction(t,{command:"install_source",positionals:[],flags:n.flags??{},result:a})}({session:a,sessionStore:n,req:t,data:d}),{ok:!0,data:d}}catch(e){throw l&&await hW(l.materializationId,t.meta?.tenantId).catch(()=>{}),e}finally{await e.cleanup(),o.cleanup()}};if("ios"===l.platform){let{installIosInstallablePath:e}=await Promise.resolve(t7),{prepareIosInstallArtifact:t}=await Promise.resolve(re),r=await t(o.source,{signal:u});return await d(r,async t=>{if(await e(l,r.installablePath),!r.bundleId)throw new O("COMMAND_FAILED","Installed iOS app identity could not be resolved from the artifact");return{...hY(t),bundleId:r.bundleId,...r.appName?{appName:r.appName}:{},launchTarget:r.bundleId}})}let{prepareAndroidInstallArtifact:c}=await import("../1769.js"),{installAndroidInstallablePathAndResolvePackageName:p}=await import("../1769.js"),f=await c(o.source,{signal:u});return await d(f,async e=>{let t=await p(l,f.installablePath,f.packageName);if(!t)throw new O("COMMAND_FAILED","Installed Android app identity could not be resolved from the artifact or device state");let{inferAndroidAppName:r}=await import("../1769.js"),n=r(t);return{...hY(e),packageName:t,...n?{appName:n}:{},launchTarget:t}})}catch(e){return{ok:!1,error:P(e)}}}async function hQ(e){let{req:t}=e;try{let e=t.meta?.materializationId?.trim();if(!e)throw new O("INVALID_ARGS","release_materialized_paths requires a materializationId");return await hW(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:P(e)}}}let h0="shared_prefs/ReactNativeDevPrefs.xml",h1="debug_http_host",h2="dev_server_https",h3="RCT_jsLocation",h5="RCT_packager_scheme",h4="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.",h8='<?xml version="1.0" encoding="utf-8" standalone="yes" ?>\n<map>\n</map>\n';function h6(e){return void 0!==ey(e)}async function h9(e){let{device:t,appId:r,runtime:n}=e;if(!r)return;let a=ey(n);if(a){if("android"===t.platform)return void await we(t,r,a);"ios"===t.platform&&"simulator"===t.kind&&await wa(t,r,a)}}async function h7(e){let{device:t,appId:r}=e;if(r){if("android"===t.platform)return void await wt(t,r);"ios"===t.platform&&"simulator"===t.kind&&await wi(t,r)}}async function we(e,t,r){var n,a,i,o,s,l;let u,d;wu(t);let c=(n=await wr(e,t),a=h1,i=`${r.host}:${r.port}`,u=` <string name="${wd(a)}">${wd(i)}</string>`,ws(wl(n,a),u));o=c,s=h2,l="https"===r.scheme,d=` <boolean name="${wd(s)}" value="${l?"true":"false"}" />`,c=ws(wl(o,s),d),await wn(e,t,c)}async function wt(e,t){wu(t);let r=await wr(e,t),n=wl(r,h1),a=wl(n,h2);a!==r&&await wn(e,t,a)}async function wr(e,t){let r=await Q(e,["shell","run-as",t,"cat",h0],{allowFailure:!0});return 0!==r.exitCode?h8:wo(r.stdout)}async function wn(e,t,r){let n=["shell","run-as",t,"id"],a=await Q(e,n,{allowFailure:!0});if(0!==a.exitCode){let e=wc(a.stdout,a.stderr);throw new O("COMMAND_FAILED",e?`Failed to access Android app sandbox for ${t}`:`Failed to probe Android app sandbox for ${t}`,{package:t,cmd:"adb",args:n,stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode,hint:e?h4:"adb shell run-as probe failed. Check adb connectivity and that the device is reachable. Inspect stderr/details for more information."})}try{await Q(e,["shell","run-as",t,"mkdir","-p","shared_prefs"]),await Q(e,["shell","run-as",t,"tee",h0],{stdin:r.trimEnd()})}catch(n){let e=D(n);if("TOOL_MISSING"===e.code)throw e;let r=wc("string"==typeof e.details?.stdout?e.details.stdout:"","string"==typeof e.details?.stderr?e.details.stderr:"");throw new O("COMMAND_FAILED",r?`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:r?h4:"adb run-as succeeded, but writing ReactNativeDevPrefs.xml failed. Inspect stderr/details for the failing shell command."},e)}}async function wa(e,t,r){await rM(rO(e,["spawn",e.id,"defaults","write",t,h3,"-string",`${r.host}:${r.port}`])),await rM(rO(e,["spawn",e.id,"defaults","write",t,h5,"-string",r.scheme]))}async function wi(e,t){await rM(rO(e,["spawn",e.id,"defaults","delete",t,h3]),{allowFailure:!0}),await rM(rO(e,["spawn",e.id,"defaults","delete",t,h5]),{allowFailure:!0})}function wo(e){let t=e.trim();return t.includes("<map")&&t.includes("</map>")?`${t}
60
- `:h8}function ws(e,t){return wo(e).replace("</map>",`${t}
61
- </map>`)}function wl(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return wo(e).replace(RegExp(`^\\s*<string name="${r}">[\\s\\S]*?<\\/string>\\n?`,"m"),"").replace(RegExp(`^\\s*<boolean name="${r}" value="(?:true|false)"\\s*\\/?>\\n?`,"m"),"")}function wu(e){if("binary"!==ed(e))return;let t=Z(e);throw new O("INVALID_ARGS",t,{package:e,hint:t})}function wd(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function wc(e,t){let r=`${e}
62
- ${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=>r.includes(e))}let wp=["platform","metroHost","metroPort","bundleUrl","launchUrl"];function wf(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>void 0!==e&&""!==e).length:0}function wm(e,t){if(void 0!==e){if("string"!=typeof e)throw new O("INVALID_ARGS",`Invalid open runtime ${t}: expected string.`);return ew(e)}}function wh(e){if(void 0!==e){if(!Number.isInteger(e)||e<1||e>65535)throw new O("INVALID_ARGS",`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function ww(e){if("ios"===e||"android"===e)return e}async function wg(e){let{replacedStoredRuntime:t,previousRuntime:r,runtime:n,session:a}=e;!t||!a?.appBundleId||!h6(r)||h6(n)||await h7({device:a.device,appId:a.appBundleId})}async function wy(e){var t,r;let{req:n,sessionName:a,sessionStore:i}=e,o=(n.positionals?.[0]??"show").toLowerCase(),s=i.get(a),l=i.getRuntimeHints(a);if(!["set","show","clear"].includes(o))return cm("INVALID_ARGS","runtime requires set, show, or clear");if("clear"===o){h6(l)&&s?.appBundleId&&await h7({device:s.device,appId:s.appBundleId});let e=i.clearRuntimeHints(a);return{ok:!0,data:{session:a,cleared:e}}}if("show"===o)return{ok:!0,data:{session:a,configured:!!l,runtime:l}};let u=ww(n.flags?.platform??l?.platform??s?.device.platform);if(!u)return cm("INVALID_ARGS","runtime set only supports iOS and Android sessions. Pass --platform ios|android or open an iOS/Android session first.");if(s&&s.device.platform!==u)return cm("INVALID_ARGS",`runtime set targets ${u}, but session "${a}" is already bound to ${s.device.platform}.`);let d={platform:(t=n.flags,r={platform:u,metroHost:ew(t?.metroHost),metroPort:wh(t?.metroPort),bundleUrl:ew(t?.bundleUrl),launchUrl:ew(t?.launchUrl)}).platform??l?.platform,metroHost:r.metroHost??l?.metroHost,metroPort:r.metroPort??l?.metroPort,bundleUrl:r.bundleUrl??l?.bundleUrl,launchUrl:r.launchUrl??l?.launchUrl};return 0===wf(d)?cm("INVALID_ARGS","runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url."):(i.setRuntimeHints(a,d),{ok:!0,data:{session:a,configured:!0,runtime:d}})}let wv="open-command-roundtrip",wI="Not implemented for this platform in this release.",wb=new Set(["app","desktop","frontmost-app"]);async function wA(e){if("app"===e||"desktop"===e||"menubar"===e)return{};let t=await lH();return{appBundleId:t.bundleId,appName:t.appName}}function wS(e){let t=e.replaceAll(",","").match(/^-?\d+(?:\.\d+)?/);if(!t)return null;let r=Number(t[0]);return Number.isFinite(r)?r:null}function w_(e){return Math.round(10*e)/10}function wx(e){return Math.round(10*e)/10}let wN="adb-shell-dumpsys-gfxinfo-framestats";function wM(e,t,r){let n=t.get(r);if(void 0===n)return null;let a=Number(e[n]);return Number.isFinite(a)?a:null}function wk(e){return 0===e.length?{}:{firstFrameNs:Math.min(...e.map(e=>e.intendedVsyncNs)),lastFrameNs:Math.max(...e.map(e=>e.frameCompletedNs))}}function wD(e,t){if(void 0!==e&&void 0!==t)return Math.max(0,Math.round((t-e)/1e6))}function wP(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=e.match(RegExp(`^\\s*${r}:\\s*([0-9][0-9,]*)`,"im"));if(!n)return;let a=n[1];return void 0===a?void 0:wS(a)??void 0}async function wO(e,t,r={}){var n,a,i,o,s,l,u,d;let c=e7(e,r.adb);try{let u,d,p,f,m,h,w,g,y,v,I,b=(n=(await c(["shell","dumpsys","gfxinfo",t,"framestats"],{timeoutMs:15e3})).stdout,a=new Date().toISOString(),function(e,t){if(/no process found for:/i.test(e))throw new O("COMMAND_FAILED",`Android gfxinfo did not find a running process for ${t}`,{metric:"fps",package:t,hint:"Run open <app> for this session again to ensure the Android app is active, then retry perf after the interaction you want to inspect."})}(n,t),p=function(e){let t=e.split(/\nProfile data in ms:\n/i)[0]??"",r=wP(t,"Total frames rendered"),n=t.match(/^\s*Janky frames:\s*([0-9][0-9,]*)\s*\(([0-9.]+)%\)/im);if(void 0===r||!n)return;let a=n[1],i=n[2];if(void 0===a||void 0===i)return;let o=wS(a)??void 0,s=Number(i);if(void 0===o||!Number.isFinite(s)||r<0)return;let l=wP(t,"Uptime"),u=wP(t,"Stats since");return{droppedFramePercent:w_(s),droppedFrameCount:o,totalFrameCount:r,sampleWindowMs:function(e){let{uptimeMs:t,statsSinceNs:r}=e;if(void 0===t||void 0===r)return;let n=t-Math.round(r/1e6);return n>=0?n:void 0}({uptimeMs:l,statsSinceNs:u}),uptimeMs:l,statsSinceNs:u}}(n),f=function(e){let t=[],r=null;for(let a of e.split("\n")){var n;let e=a.trim();if(0===e.length||"---PROFILEDATA---"===e)continue;let i=e.split(",").map(e=>e.trim());if((n=i).includes("IntendedVsync")&&n.includes("FrameCompleted")){r=new Map(i.map((e,t)=>[e,t]));continue}let o=function(e,t){if(!t||e.length<t.size)return;let r=wM(e,t,"Flags"),n=wM(e,t,"IntendedVsync"),a=wM(e,t,"FrameCompleted");if(0===r&&null!==n&&null!==a&&!(n<=0)&&!(a<=n))return{intendedVsyncNs:n,frameCompletedNs:a,durationNs:a-n}}(i,r);o&&t.push(o)}return t.sort((e,t)=>e.intendedVsyncNs-t.intendedVsyncNs)}(n),m=function(e,t,r){let n=function(e){var t;let r=(t=e.map(e=>e.intendedVsyncNs),[...new Set(t.filter(e=>Number.isFinite(e)))].sort((e,t)=>e-t)),n=[];for(let e=1;e<r.length;e+=1){let t=r[e]-r[e-1];t>=4e6&&t<=5e7&&n.push(t)}if(0!==n.length){let e,t;return e=[...n].sort((e,t)=>e-t),t=Math.floor(e.length/2),e.length%2==1?e[t]:(e[t-1]+e[t])/2}}(e);if(t||0!==e.length||function(e){throw new O("COMMAND_FAILED",`Failed to parse Android framestats output for ${e}`,{metric:"fps",package:e,hint:"Retry perf after exercising the app screen. If the problem persists, capture adb shell dumpsys gfxinfo <package> framestats output for debugging."})}(r),t||void 0!==n)return n;throw new O("COMMAND_FAILED",`Failed to infer Android frame deadline from framestats output for ${r}`,{metric:"fps",package:r,hint:"Retry perf after a longer interaction window so consecutive Android frame timestamps are available."})}(f,p,t),h=Date.parse(a),w=function(e){let{frames:t,measuredAtMs:r,summary:n}=e,a=wk(t),i=n?.statsSinceNs,o=i??a.firstFrameNs,s=wD(o,a.lastFrameNs),l=n?.sampleWindowMs??s;if(!Number.isFinite(r)||n?.uptimeMs===void 0||void 0===o)return{sampleWindowMs:l,windowStartNs:o};let u=r-n.uptimeMs;return{sampleWindowMs:l,windowStartNs:o,windowStartedAt:new Date(u+o/1e6).toISOString(),windowEndedAt:function(e){let{deviceBootWallClockMs:t,measuredAtMs:r,summaryStartNs:n,lastFrameNs:a}=e;return void 0!==n?new Date(r).toISOString():void 0===a?void 0:new Date(t+a/1e6).toISOString()}({deviceBootWallClockMs:u,measuredAtMs:r,summaryStartNs:i,lastFrameNs:a.lastFrameNs}),timestampSource:"estimated-from-device-uptime"}}({frames:f,measuredAtMs:h,summary:p}),g=function(e){let{frames:t,frameDeadlineNs:r,summaryDroppedFrameCount:n}=e;return void 0!==n?n<=0?[]:[...t].sort((e,t)=>t.durationNs-e.durationNs).slice(0,n).sort((e,t)=>e.intendedVsyncNs-t.intendedVsyncNs):void 0===r?[]:t.filter(e=>e.durationNs>r)}({frames:f,frameDeadlineNs:m,summaryDroppedFrameCount:p?.droppedFrameCount}),y=p?.sampleWindowMs??w.sampleWindowMs??function(e){if(0===e.length)return;let t=wk(e);return wD(t.firstFrameNs,t.lastFrameNs)}(f),i=p,o=f,s=g,u=i?.totalFrameCount??o.length,d=i?.droppedFrameCount??s.length,v={totalFrameCount:u,droppedFrameCount:d,droppedFramePercent:i?.droppedFramePercent??(u>0?w_(d/u*100):0)},I=function(e){let{droppedFrames:t,timing:r,measuredAtMs:n,summary:a}=e;if(0===t.length)return;let i=function(e){let{frames:t,windowStartNs:r,measuredAtMs:n,uptimeMs:a}=e;if(0===t.length||void 0===r)return[];let i=[],o=[];for(let e of t){let t=o.at(-1);if(!t||e.intendedVsyncNs-t.frameCompletedNs<=5e8){o.push(e);continue}i.push(o),o=[e]}return o.length>0&&i.push(o),i.map(e=>(function(e){let{frames:t,windowStartNs:r,measuredAtMs:n,uptimeMs:a}=e,i=Math.min(...t.map(e=>e.intendedVsyncNs)),o=Math.max(...t.map(e=>e.frameCompletedNs)),s=Math.max(0,Math.round((i-r)/1e6)),l=Math.max(s,Math.round((o-r)/1e6)),u=void 0!==a&&Number.isFinite(n)?n-a:void 0;return{startOffsetMs:s,endOffsetMs:l,startAt:void 0===u?void 0:new Date(u+i/1e6).toISOString(),endAt:void 0===u?void 0:new Date(u+o/1e6).toISOString(),missedDeadlineFrameCount:t.length,worstFrameMs:wx(Math.max(...t.map(e=>e.durationNs))/1e6)}})({frames:e,windowStartNs:r,measuredAtMs:n,uptimeMs:a})).sort((e,t)=>t.missedDeadlineFrameCount-e.missedDeadlineFrameCount||t.worstFrameMs-e.worstFrameMs).slice(0,3).sort((e,t)=>e.startOffsetMs-t.startOffsetMs)}({frames:t,windowStartNs:r.windowStartNs,measuredAtMs:n,uptimeMs:a?.uptimeMs});return i.length>0?i:void 0}({droppedFrames:g,timing:w,measuredAtMs:h,summary:p}),{...v,sampleWindowMs:y,...(l=m,{frameDeadlineMs:void 0===l?void 0:wx(l/1e6),refreshRateHz:void 0===l?void 0:wx(1e9/l)}),windowStartedAt:w.windowStartedAt,windowEndedAt:w.windowEndedAt,timestampSource:w.timestampSource,measuredAt:a,method:wN,source:p?"android-gfxinfo-summary":"framestats-rows",worstWindows:I&&I.length>0?I:void 0});return await wR(e,t,r),b}catch(e){throw u=t,(d=e)instanceof O?new O(d.code,d.message,{...d.details??{},metric:"fps",package:u},d):new O("COMMAND_FAILED",`Failed to sample Android fps for ${u}`,{metric:"fps",package:u},d)}}async function wR(e,t,r={}){let n=e7(e,r.adb);try{await n(["shell","dumpsys","gfxinfo",t,"reset"],{allowFailure:!0,timeoutMs:3e3})}catch{}}let wC="adb-shell-dumpsys-cpuinfo",wE="adb-shell-dumpsys-meminfo";async function wL(e,t,r={}){let n=e7(e,r.adb);try{let e=await n(["shell","dumpsys","cpuinfo"],{timeoutMs:15e3});return function(e,t,r){let n=new Set,a=0;for(let r of eK(e)){var i,o;let e=r.match(/^([0-9]+(?:\.[0-9]+)?)%\s+\d+\/([^\s]+):\s/);if(!e)continue;let s=e[1],l=e[2];if(void 0===s||void 0===l)continue;let u=Number(s);Number.isFinite(u)&&(i=l,o=t,i===o||i.startsWith(`${o}:`))&&(a+=u,n.add(l))}return{usagePercent:w_(a),measuredAt:r,method:wC,matchedProcesses:[...n]}}(e.stdout,t,new Date().toISOString())}catch(e){throw wT("cpu",t,e)}}async function w$(e,t,r={}){let n=e7(e,r.adb);try{let e=await n(["shell","dumpsys","meminfo",t],{timeoutMs:15e3});return function(e,t,r){if(/no process found for:/i.test(e))throw new O("COMMAND_FAILED",`Android meminfo did not find a running process for ${t}`,{metric:"memory",package:t,hint:"Run open <app> for this session again to ensure the Android app is active, then retry perf."});let n=wF(e,"TOTAL PSS")??function(e){for(let t of e.split("\n")){let e=t.trim();if(!/^TOTAL\b(?!\s+PSS:)/.test(e))continue;let r=e.split(/\s+/).slice(1).find(e=>null!==wS(e));if(!r)break;return wS(r)??void 0}}(e);if(void 0===n)throw new O("COMMAND_FAILED",`Failed to parse Android meminfo output for ${t}`,{metric:"memory",package:t,hint:"Retry perf after reopening the app session. If the problem persists, capture adb shell dumpsys meminfo output for debugging."});return{totalPssKb:n,totalRssKb:wF(e,"TOTAL RSS"),measuredAt:r,method:wE}}(e.stdout,t,new Date().toISOString())}catch(e){throw wT("memory",t,e)}}function wT(e,t,r){return r instanceof O?new O(r.code,r.message,{...r.details??{},metric:e,package:t},r):new O("COMMAND_FAILED",`Failed to sample Android ${e} for ${t}`,{metric:e,package:t},r)}function wF(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=e.match(RegExp(`${r}:\\s*([0-9][0-9,]*)`,"i"));if(!n)return;let a=n[1];return void 0===a?void 0:wS(a)??void 0}async function wU(e,t,r){if(("ios"===e.platform||"macos"===e.platform)&&t)return em(t)?"macos"===e.platform?void 0:"device"===e.kind?er(r,t):void 0:await wV(e,t)}async function wV(e,t){try{let{resolveIosApp:r}=await Promise.resolve(t7);return await r(e,t)}catch{return}}async function wG(e,t){if(!("android"!==e.platform||!t||em(t)))try{let{resolveAndroidApp:r}=await import("../1769.js"),n=await r(e,t);return"package"===n.type?n.value:void 0}catch{return}}async function wq(e,t,r){if(r||"android"!==e.platform||!t||!em(t))return r;try{let{getAndroidAppState:t}=await import("../1769.js"),n=await t(e);return n.package?.trim()||r}catch{return r}}async function wj(e,t,r,n){return await wU(e,t,r)??await n(e,t)??("android"===e.platform&&t&&em(t)?r:void 0)}function wB(e){return cm("INVALID_ARGS",e)}function wH(e,t,r,n){try{return function(e){let{device:t,surfaceFlag:r,openTarget:n,existingSurface:a}=e;if(("macos"===t.platform||"linux"===t.platform)&&!r)return a??"app";if("linux"===t.platform){if(!r)return"app";let e=tc(r);if(!wb.has(e))throw new O("INVALID_ARGS",`Linux supports --surface app, desktop, and frontmost-app (got "${r}")`);if("app"!==e&&n)throw new O("INVALID_ARGS",`open --surface ${e} does not accept an app target`);return e}if("macos"!==t.platform){if(r)throw new O("INVALID_ARGS","surface is only supported on macOS and Linux");return"app"}let i=r?tc(r):"app";if("app"!==i&&"menubar"!==i&&n)throw new O("INVALID_ARGS",`open --surface ${i} does not accept an app target`);return i}({device:e,surfaceFlag:t,openTarget:r,existingSurface:n})}catch(e){return cm(e instanceof O?e.code:"INVALID_ARGS",String(e.message))}}function wW(e){let{shouldRelaunch:t,openTarget:r,surface:n,device:a}=e;return t?r&&em(r)?wB("open --relaunch does not support URL targets."):"app"!==n?wB("open --relaunch is supported only for app surfaces."):"android"===a.platform&&r&&"binary"===ed(r)?wB(Z(r)):null:null}async function wz(e){let{req:t,sessionName:r,sessionStore:n,device:a,surface:i,openTarget:o,existingSession:s}=e;await oK(a);let{appBundleId:l,appName:u}=await wK({device:a,surface:i,openTarget:o,existingAppBundleId:s?.appBundleId}),d=function(e){try{return{ok:!0,data:function(e){let{req:t,sessionStore:r,sessionName:n,device:a}=e,i=r.getRuntimeHints(n),o=function(e){let{runtime:t,sessionName:r,platform:n}=e;if(void 0===t)return;if(!t||"object"!=typeof t||Array.isArray(t))throw new O("INVALID_ARGS","open runtime must be an object.");let a=Object.keys(t).find(e=>!wp.includes(e));if(a)throw new O("INVALID_ARGS",`Invalid open runtime field: ${a}. Supported fields are ${wp.join(", ")}.`);return{platform:function(e,t,r){if(void 0===e)return r;if("ios"!==e&&"android"!==e)throw new O("INVALID_ARGS",`Invalid open runtime platform: ${String(e)}. Use "ios" or "android".`);if(r&&e!==r)throw new O("INVALID_ARGS",`open runtime targets ${e}, but session "${t}" is bound to ${r}.`);return e}(t.platform,r,n),metroHost:wm(t.metroHost,"metroHost"),metroPort:function(e){if(void 0!==e){if("number"!=typeof e)throw new O("INVALID_ARGS","Invalid open runtime metroPort: expected integer.");return wh(e)}}(t.metroPort),bundleUrl:wm(t.bundleUrl,"bundleUrl"),launchUrl:wm(t.launchUrl,"launchUrl")}}({runtime:t.runtime,sessionName:n,platform:ww(a.platform)});return void 0===t.runtime?{runtime:function(e,t,r){let n=e.getRuntimeHints(t);if(!n)return;let a=r?.platform,i=ww(a);if(n.platform&&r&&!i)throw new O("INVALID_ARGS",`Session runtime hints are only supported on iOS and Android sessions, but session "${t}" is bound to ${a}.`);if(n.platform&&i&&n.platform!==i)throw new O("INVALID_ARGS",`Session runtime hints target ${n.platform}, but session "${t}" is bound to ${a}. Clear the runtime hints or use a different session.`);return i&&n.platform!==i?{...n,platform:i}:n}(r,n,a),previousRuntime:i,replacedStoredRuntime:!1}:{runtime:o&&wf(o)>0?o:void 0,previousRuntime:i,replacedStoredRuntime:!0}}(e)}}catch(t){let e=D(t);return cm(e.code,e.message,e.details)}}({req:t,sessionStore:n,sessionName:r,device:a});if(!d.ok)return{type:"response",response:d};if(s){let{runtime:e,previousRuntime:t,replacedStoredRuntime:r}=d.data;await wg({replacedStoredRuntime:r,previousRuntime:t,runtime:e,session:s})}return{type:"details",details:{appBundleId:l,appName:u,runtime:d.data.runtime}}}async function wK(e){let{device:t,surface:r,openTarget:n,existingAppBundleId:a}=e,i=await wA(r);return{appBundleId:i.appBundleId??await wj(t,n,a,wG),appName:i.appName??n}}let wJ=new Map;async function wX(e){let{device:t,closeTarget:r,outFlag:n,context:a}=e;"android"!==t.platform&&await n2(t.id),await cr(t,"close",[r],n,a),await cy(t,300)}async function wY(e){var t,r;let n,{runtime:a,device:i,req:o,logPath:s,appBundleId:l,traceLogPath:u,openPositionals:d}=e,c=a?.launchUrl;if(!c||0===d.length||d.length>1)return;let p=d[0]?.trim();!p||em(p)||await cr(i,"open",[c],o.flags?.out,{...(t=s,r=o.flags,n=cH(t,r,l,u),delete n.launchConsole,n)})}async function wZ(e){var t,r,n,a;let i,{req:o,sessionName:s,sessionStore:l,logPath:u,device:d,openTarget:c,openPositionals:p,appName:f,surface:m,appBundleId:h,runtime:w,existingSession:g}=e,y=o.flags?.relaunch===!0,v=g?.trace?.outPath,I=h,b=Date.now(),A={};if(y&&c){let e=I??c,t=Date.now();await wX({device:d,closeTarget:e,outFlag:o.flags?.out,context:{...cH(u,o.flags,I??g?.appBundleId,v)}}),A.relaunchCloseDurationMs=Math.max(0,Date.now()-t)}let S=Date.now();await h9({device:d,appId:I,runtime:w}),A.runtimeHintsDurationMs=Math.max(0,Date.now()-S);let _="ios"===d.platform&&"app"===m&&p.length>0,x={verbose:o.flags?.verbose,logPath:u,traceLogPath:v,requestId:o.meta?.requestId};_&&I?(A.runnerPrewarmKind="session",A.runnerPrewarmScheduled=!0,i=function(e,t={}){return"ios"!==e.platform?void 0:ar(e,{requestId:t.requestId})?void eM({level:"debug",phase:"ios_runner_session_prewarm_skipped_scoped_provider",data:{deviceId:e.id}}):nZ(e,t).then(()=>{}).catch(t=>{eM({level:"warn",phase:"ios_runner_session_prewarm_failed",data:{deviceId:e.id,error:t instanceof Error?t.message:String(t)}})})}(d,x)):_&&(A.runnerPrewarmKind="xctestrun",A.runnerPrewarmScheduled=!0,i=function(e,t={}){return"ios"!==e.platform?void 0:ar(e,{requestId:t.requestId})?void eM({level:"debug",phase:"ios_runner_xctestrun_prewarm_skipped_scoped_provider",data:{deviceId:e.id}}):nS(e,t).then(()=>{}).catch(t=>{eM({level:"warn",phase:"ios_runner_xctestrun_prewarm_failed",data:{deviceId:e.id,error:t instanceof Error?t.message:String(t)}})})}(d,x));let N=Date.now();await cr(d,"open",p,o.flags?.out,{...cH(u,o.flags,I)}),A.openDispatchDurationMs=Math.max(0,Date.now()-N);let M=Date.now();if(await wY({runtime:w,device:d,req:o,logPath:u,appBundleId:I,traceLogPath:v,openPositionals:p}),A.launchUrlDurationMs=Math.max(0,Date.now()-M),y&&i){let e=Date.now();await i,A.runnerPrewarmWaited=!0,A.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}else i&&(A.runnerPrewarmWaited=!1);I=await wq(d,c,I),"android"===d.platform&&I&&await wR(d,I);let k=c?(t=I,{durationMs:Math.max(0,Date.now()-N),measuredAt:new Date().toISOString(),method:wv,appTarget:c,appBundleId:t}):void 0,D=Date.now();if(await cy(d,300),A.postOpenSettleDurationMs=Math.max(0,Date.now()-D),rd(o.meta?.requestId)){let e=rp();return cm(e.code,e.message,e.details)}g&&cV(g,"open",g.snapshot);let P=function(e){let{existingSession:t,sessionName:r,device:n,surface:a,appBundleId:i,appName:o,saveScript:s}=e;return t?{...t,device:n,surface:a,appBundleId:i,appName:o,recordSession:t.recordSession||s,snapshot:void 0}:{name:r,device:n,createdAt:Date.now(),surface:a,appBundleId:i,appName:o,recordSession:s,actions:[]}}({existingSession:g,sessionName:s,device:d,surface:m,appBundleId:I,appName:f,saveScript:!!o.flags?.saveScript});void 0!==o.runtime&&(r=l,n=s,(a=w)&&(0===wf(a)?r.clearRuntimeHints(n):r.setRuntimeHints(n,a))),A.totalDurationMs=Math.max(0,Date.now()-b);let O=function(e){let{sessionName:t,appName:r,appBundleId:n,surface:a,startup:i,timing:o,device:s,runtime:l,runtimeHintCount:u}=e,d={session:t,surface:a};return r&&(d.appName=r),n&&(d.appBundleId=n),i&&(d.startup=i),o&&(d.timing=o),l&&u(l)>0&&(d.runtime=l),s&&(d.platform=s.platform,d.target=s.target??"mobile",d.device=s.name,d.id=s.id,d.kind=s.kind,"android"===s.platform&&(d.serial=s.id)),s?.platform==="ios"&&(d.device_udid=s.id,d.ios_simulator_device_set=s.simulatorSetPath??null),{...d,...eV(`Opened: ${r??n??t}`)}}({sessionName:s,appName:f,appBundleId:I,surface:m,startup:k,timing:A,device:d,runtime:w,runtimeHintCount:wf});return l.recordAction(P,{command:"open",positionals:p,flags:o.flags??{},runtime:void 0!==o.runtime?w:void 0,result:O}),l.set(s,P),{ok:!0,data:O}}async function wQ(e){let{req:t,sessionName:r,logPath:n,sessionStore:a}=e;if(a.has(r)){let e=a.get(r);if(!e)return cm("SESSION_NOT_FOUND",`Session "${r}" not found.`);let i=t.flags?.relaunch===!0,o=t.positionals?.[0],s=o??(i?e.appName:void 0),l=wH(e.device,t.flags?.surface,s,e.surface);if("string"!=typeof l)return l;if(!s&&"app"===l)return i?wB("open --relaunch requires an app name or an active session app."):wB("Session already active. Close it first or pass a new --session name.");let u=wW({shouldRelaunch:i,openTarget:s,surface:l,device:e.device});if(u)return u;let d=await cI(e.device),c=await wz({req:t,sessionName:r,sessionStore:a,device:d,surface:l,openTarget:s,existingSession:e});return"response"===c.type?c.response:await wZ({req:t,sessionName:r,sessionStore:a,logPath:n,device:d,openTarget:s,openPositionals:o?t.positionals??[]:s?[s]:[],appBundleId:c.details.appBundleId,appName:c.details.appName,runtime:c.details.runtime,surface:l,existingSession:e})}let i=t.flags?.relaunch===!0,o=t.positionals?.[0];if(i&&!o)return wB("open --relaunch requires an app argument.");let s=function(e){let{shouldRelaunch:t,openTarget:r,platform:n}=e;return t?r&&em(r)?wB("open --relaunch does not support URL targets."):"android"===n&&r&&"binary"===ed(r)?wB(Z(r)):null:null}({shouldRelaunch:i,openTarget:o,platform:t.flags?.platform==="android"?"android":void 0});if(s)return s;let l=await oy(t.flags??{}),u=wH(l,t.flags?.surface,o);if("string"!=typeof u)return u;let d=wW({shouldRelaunch:i,openTarget:o,surface:u,device:l});return d||await r0(wJ,l.id,async()=>{let e=a.toArray().find(e=>e.device.id===l.id);if(e)return cm("DEVICE_IN_USE",`Device is already in use by session "${e.name}".`,{session:e.name,deviceId:l.id,deviceName:l.name,hint:`Run agent-device session list and reuse --session ${e.name}, or close that session before opening a new one on this device.`});let i=await wz({req:t,sessionName:r,sessionStore:a,device:l,surface:u,openTarget:o});return"response"===i.type?i.response:await wZ({req:t,sessionName:r,sessionStore:a,logPath:n,device:l,openTarget:o,openPositionals:t.positionals??[],appBundleId:i.details.appBundleId,appName:i.details.appName,runtime:i.details.runtime,surface:u})})}async function w0(e){let t=await Q(e,["emu","kill"],{allowFailure:!0,timeoutMs:15e3});return{success:0===t.exitCode,exitCode:t.exitCode,stdout:String(t.stdout??""),stderr:String(t.stderr??"")}}async function w1(e){let{device:t,shutdownRequested:r}=e;if(r&&(cg(t)||"android"===t.platform&&"emulator"===t.kind))try{return cg(t)?await lS(t):await w0(t)}catch(t){let e=P(t);return{success:!1,exitCode:-1,stdout:"",stderr:e.message,error:e}}}async function w2(e){if(await n2(e.device.id),"macos"!==e.device.platform)return;let t="frontmost-app"===e.surface?{surface:"frontmost-app"}:e.appBundleId?{bundleId:e.appBundleId}:{};await lK("dismiss",t).catch(t=>{eM({level:"debug",phase:"macos_close_alert_dismiss_failed",data:{session:e.name,error:t instanceof Error?t.message:String(t)}})})}async function w3(e,t){e.appLog&&await iy(e.appLog),r1(e.device.platform)&&await w2(e),await hz(t).catch(()=>{})}async function w5(e){let t,{req:r,sessionName:n,logPath:a,sessionStore:i}=e,o=i.get(n);if(!o)return await w4(r,a);o.appLog&&await iy(o.appLog),r.positionals&&r.positionals.length>0&&(r1(o.device.platform)&&await w2(o),await cr(o.device,"close",r.positionals,r.flags?.out,{...cH(a,r.flags,o.appBundleId,o.trace?.outPath)}),await cy(o.device,300)),r1(o.device.platform)&&(t=(r.positionals?.length??0)>0,!cg(o.device)||t||r.flags?.shutdown||o.recording)?await w2(o):r1(o.device.platform)&&eM({level:"debug",phase:"ios_runner_retained_after_close",data:{session:o.name,deviceId:o.device.id}}),h6(i.getRuntimeHints(n))&&o.appBundleId&&await h7({device:o.device,appId:o.appBundleId}).catch(()=>{}),i.recordAction(o,{command:"close",positionals:r.positionals??[],flags:r.flags??{},result:{session:n,...eV(`Closed: ${n}`)}}),r.flags?.saveScript&&(o.recordSession=!0),i.writeSessionLog(o),await hz(n).catch(()=>{}),i.delete(n);let s=await w1({device:o.device,shutdownRequested:r.flags?.shutdown});return s?{ok:!0,data:eH({session:n,shutdown:s},`Closed: ${n}`)}:{ok:!0,data:{session:n,...eV(`Closed: ${n}`)}}}async function w4(e,t){if(!e.positionals||0===e.positionals.length)return cm("SESSION_NOT_FOUND","No active session");let r=await cv({session:void 0,flags:e.flags,ensureReady:!0});return await cr(r,"close",e.positionals,e.flags?.out,{...cH(t,e.flags)}),await cy(r,300),{ok:!0,data:{app:e.positionals[0],...eV(`Closed: ${e.positionals[0]}`)}}}let w8={ios:async(e,t,r)=>{let{reinstallIosApp:n}=await Promise.resolve(t7);return await n(e,t,r)},android:async(e,t,r)=>{let{reinstallAndroidApp:n}=await import("../1769.js");return await n(e,t,r)}},w6={ios:async(e,t,r)=>{let{installIosApp:n}=await Promise.resolve(t7),a=await n(e,r,{appIdentifierHint:t});return{bundleId:a.bundleId,appName:a.appName,launchTarget:a.launchTarget}},android:async(e,t,r)=>{let{installAndroidApp:n}=await import("../1769.js"),a=await n(e,r);return{package:a.packageName,appName:a.appName,launchTarget:a.launchTarget}}};async function w9(e){let{req:t,command:r,sessionName:n,sessionStore:a,deployOps:i}=e,o=a.get(n),s=t.flags??{},u=ch(r,o,s);if(u)return u;let d=t.positionals?.[0]?.trim(),c=t.positionals?.[1]?.trim();if(!d||!c)return cm("INVALID_ARGS",`${r} requires: ${r} <app> <path-to-app-binary>`);let p=t.meta?.uploadedArtifactId;try{var f;let e,n=p?ix(p,t.meta?.tenantId):aE.expandHome(c);if(!l.existsSync(n))return cm("INVALID_ARGS",`App binary not found: ${n}`);let u=await cv({session:o,flags:s,ensureReady:!1});if(!cF(r,u))return cm("UNSUPPORTED_OPERATION",`${r} is not supported on this device`);if("ios"===u.platform){let t=await i.ios(u,d,n),r=t.bundleId;e=r?{app:d,appPath:n,platform:"ios",appId:r,bundleId:r,appName:t.appName,launchTarget:t.launchTarget}:{app:d,appPath:n,platform:"ios",appName:t.appName,launchTarget:t.launchTarget}}else{let t=await i.android(u,d,n),r=t.package;e=r?{app:d,appPath:n,platform:"android",appId:r,package:r,packageName:r,appName:t.appName,launchTarget:t.launchTarget}:{app:d,appPath:n,platform:"android",appName:t.appName,launchTarget:t.launchTarget}}let m=eH(e,(f=e,`Installed: ${f.appName??eq(f)}`));return o&&a.recordAction(o,{command:r,positionals:t.positionals??[],flags:t.flags??{},result:m??{}}),{ok:!0,data:m}}finally{p&&iN(p)}}async function w7(e,t,r){return await t6(e,t,r)}async function ge(e){let{req:t,sessionName:r,sessionStore:n}=e;if("session_list"===t.command)return{ok:!0,data:{sessions:n.toArray().map(e=>({name:e.name,platform:e.device.platform,target:e.device.target??"mobile",surface:e.surface??"app",device:e.device.name,id:e.device.id,device_id:e.device.id,createdAt:e.createdAt,..."ios"===e.device.platform&&{device_udid:e.device.id,ios_simulator_device_set:e.device.simulatorSetPath??null}}))}};if("devices"===t.command)try{let e=ep(t.flags?.androidDeviceAllowlist),r=t.flags?.platform,n=r3({simulatorSetPath:ee(t.flags?.iosSimulatorDeviceSet),platform:r,target:t.flags?.target}),a=await oA({platform:r,target:t.flags?.target,deviceName:t.flags?.device,udid:t.flags?.udid,serial:t.flags?.serial,iosSimulatorSetPath:n,androidSerialAllowlist:e?Array.from(e).sort():void 0}),i=r?a.filter(e=>{var t,n;return t=e,!(n=r)||("apple"===n?r1(t.platform):t.platform===n)}):a,o=(t.flags?.target?i.filter(e=>(e.target??"mobile")===t.flags?.target):i).map(({simulatorSetPath:e,...t})=>t);return{ok:!0,data:{devices:o}}}catch(t){let e=D(t);return cm(e.code,e.message,e.details)}if("apps"===t.command){let e=n.get(r),a=t.flags??{},i=ch(t.command,e,a);if(i)return i;let o=await cv({session:e,flags:a,ensureReady:!0});if(!cF("apps",o))return cm("UNSUPPORTED_OPERATION","apps is not supported on this device");let s=eS(t.flags?.appsFilter);return r1(o.platform)?{ok:!0,data:{apps:(await uB(o,s)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}:{ok:!0,data:{apps:(await z(o,s)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}return null}async function gt(e){let{ensureAndroidEmulatorBooted:t}=await import("../1769.js");return await t(e)}let gr='iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).',gn='macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").';async function ga(e){let{req:t,sessionName:r,sessionStore:n}=e,a=n.get(r),i=t.flags??{},o=i.platform;if(!a&&"string"==typeof i?.session&&i.session.trim().length>0)return cm("SESSION_NOT_FOUND","ios"===o?`No active session "${r}". Run open with --session ${r} first.`:`No active session "${r}". Run open with --session ${r} first, or omit --session to query by device selector.`);let s=ch("appstate",a,i);if(s)return s;let l=r1(a?.device.platform)&&function(e,t){if(!t)return!1;if(!cw(e))return!0;let r=e?.platform;return!(r&&!r2(t.device.platform,r)||e?.target&&e.target!==(t.device.target??"mobile")||e?.udid&&e.udid!==t.device.id||e?.serial&&e.serial!==t.device.id)&&(!e?.device||e.device.trim().toLowerCase()===t.device.name.trim().toLowerCase())}(i,a);if("ios"===o&&!l)return cm("SESSION_NOT_FOUND",gr);if("macos"===o&&!l)return cm("SESSION_NOT_FOUND",gn);if(l&&a){let e=a.appName??a.appBundleId;if(!a.appName&&!a.appBundleId){if("macos"===a.device.platform&&a.surface&&"app"!==a.surface&&"frontmost-app"!==a.surface)return{ok:!0,data:{platform:a.device.platform,appName:a.surface,appBundleId:a.appBundleId,source:"session",surface:a.surface}};let e="macos"===a.device.platform?"macOS":"iOS";return cm("COMMAND_FAILED",`No foreground app is tracked for this ${e} session. Open an app in the session, then retry appstate.`)}return{ok:!0,data:{platform:a.device.platform,appName:e??"unknown",appBundleId:a.appBundleId,source:"session",surface:a.surface??"app",..."ios"===a.device.platform?{device_udid:a.device.id,ios_simulator_device_set:a.device.simulatorSetPath??null}:{}}}}let u=await cv({session:a,flags:i,ensureReady:!0});if("ios"===u.platform)return cm("SESSION_NOT_FOUND",gr);if("macos"===u.platform)return cm("SESSION_NOT_FOUND",gn);let{getAndroidAppState:d}=await import("../1769.js"),c=await d(u);return{ok:!0,data:{platform:"android",package:c.package,activity:c.activity}}}async function gi(e){let{req:t,sessionName:r,sessionStore:n}=e;if("boot"===t.command){let e,a=n.get(r),i=t.flags??{},o=ch(t.command,a,i);if(o)return o;let s="android"===(i.platform??a?.device.platform),l=!0===i.headless;if(l&&!s)return cm("INVALID_ARGS","boot --headless is supported only for Android emulators.");let u=cb({flags:i,sessionDevice:a?.device}),d=s&&!!u,c=!1;try{e=await cv({session:a,flags:i,ensureReady:!1})}catch(r){let t=D(r);if(s&&l&&!u&&"DEVICE_NOT_FOUND"===t.code)return cm("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");if(!d||"DEVICE_NOT_FOUND"!==t.code||!u)throw r;e=await gt({avdName:u,serial:i.serial,headless:l}),c=!0}if(i.target&&(e.target??"mobile")!==i.target)return cm("DEVICE_NOT_FOUND",`No ${e.platform} device found matching --target ${i.target}.`);if(s&&l){if("android"!==e.platform||"emulator"!==e.kind)return cm("INVALID_ARGS","boot --headless is supported only for Android emulators.");if(!c){let t=cb({flags:i,sessionDevice:a?.device,resolvedDevice:e});if(!t)return cm("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");e=await gt({avdName:t,serial:i.serial,headless:!0})}await oK(e)}else("android"!==e.platform||!0!==e.booted)&&await oK(e);return cF("boot",e)?{ok:!0,data:{platform:e.platform,target:e.target??"mobile",device:e.name,id:e.id,kind:e.kind,booted:!0}}:cm("UNSUPPORTED_OPERATION","boot is not supported on this device")}return"appstate"===t.command?await ga({req:t,sessionName:r,sessionStore:n}):null}function go(e,t){for(let r of e){if(t(r))return r;let e=go(r.children,t);if(e)return e}}function gs(e,t){let r=[];for(let n of e)t(n)&&r.push(n),r.push(...gs(n.children,t));return r}function gl(e,t){let r=go(e,e=>"schema"===e.name&&e.attributes.name===t);return r?r.children.filter(e=>"col"===e.name).map(e=>{let t;return t=e.children.find(e=>"mnemonic"===e.name),t?.text??null??""}):[]}function gu(e){if(!e||e.children.some(e=>"sentinel"===e.name)||!e.text)return null;let t=Number(e.text);return Number.isFinite(t)?t:null}function gd(e,t){return e?e.attributes.ref?t.get(e.attributes.ref)?.numberValue??null:gu(e):null}let gc="xctrace-animation-hitches";function gp(e,t){let r=r7(e),n=gl(r,t);return{rows:0===n.length?[]:gs(r,e=>"row"===e.name),schema:n}}function gf(e,t){for(let r of e)gf(r.children,t),r.attributes.id&&t.set(r.attributes.id,{numberValue:gu(r),process:gm(r)})}function gm(e){if(!e||e.children.some(e=>"sentinel"===e.name))return null;let t=gu(go(e.children,e=>"pid"===e.name)),r=(e.attributes.fmt??"").replace(/\s+\(\d+\)$/,"").trim();return null===t&&0===r.length?null:{pid:t??void 0,name:r.length>0?r:void 0}}let gh="ps-process-snapshot",gw="ps-process-snapshot",gg="xctrace-activity-monitor",gy="xctrace-activity-monitor";async function gv(e,t){if("ios"===e.platform&&"device"===e.kind)return await gD(e,t);let r=await gk(e,t),n=await gL(e,r);if(0===n.length)throw new O("COMMAND_FAILED",`No running process found for ${t}`,{appBundleId:t,hint:"Run open <app> for this session again to ensure the Apple app is active, then retry perf."});let a=new Date().toISOString();return g$({usagePercent:n.reduce((e,t)=>e+t.cpuPercent,0),residentMemoryKb:n.reduce((e,t)=>e+t.rssKb,0),measuredAt:a,matchedProcesses:[r.executableName],cpuMethod:gh,memoryMethod:gw})}async function gI(e,t){var r;let n,a,i,o,s,l;if("ios"!==e.platform||"device"!==e.kind)throw new O("COMMAND_FAILED","Apple frame-health sampling is currently available only on connected iOS devices.",{metric:"fps",platform:e.platform,deviceKind:e.kind});let u=await gP(e,t),d=await gb(e,t,u);return n=gp((r={hitchesXml:d.hitchesXml,frameLifetimesXml:d.frameLifetimesXml,displayInfoXml:d.displayInfoXml,processIds:u.map(e=>e.pid),processNames:ac(u.map(e=>f.basename(y(e.executable)))),windowStartedAt:d.windowStartedAt,windowEndedAt:d.windowEndedAt,measuredAt:d.windowEndedAt}).frameLifetimesXml,"hitches-frame-lifetimes").rows.length,a=function(e){if(!e)return;let{rows:t,schema:r}=gp(e,"device-display-info"),n=r.indexOf("max-refresh-rate");if(n<0)return;let a=new Map;for(let e of t){gf(e.children,a);let t=gd(e.children[n],a);if(null!==t&&t>0)return t}}(r.displayInfoXml),o=(i=(function(e){let t,r,n=r7(e),a=Object.values(r={start:(t=gl(n,"hitches")).indexOf("start"),duration:t.indexOf("duration"),process:t.indexOf("process"),isSystem:t.indexOf("is-system")}).every(e=>e>=0)?r:null;if(!a)return[];let i=new Map;return gs(n,e=>"row"===e.name).map(e=>(function(e,t,r){var n,a,i;let o;if(gf(e.children,r),!0===(n=e.children[t.isSystem],null===(o=gd(n,r))?null:0!==o))return null;let s=gd(e.children[t.start],r),l=gd(e.children[t.duration],r);if(null===s||null===l)return null;let u=(a=e.children[t.process],i=r,a?a.attributes.ref?i.get(a.attributes.ref)?.process??null:gm(a):null);return{startNs:s,durationNs:l,pid:u?.pid,processName:u?.name}})(e,a,i)).filter(e=>!!e)})(r.hitchesXml).filter(e=>{var t,n,a;return t=e,n=r.processIds,a=r.processNames,!!(void 0!==t.pid&&n.includes(t.pid))||!!t.processName&&a.includes(t.processName)})).length,s=Math.max(0,Math.round(Date.parse(r.windowEndedAt)-Date.parse(r.windowStartedAt))),l=function(e,t){if(0===e.length)return[];let r=[...e].sort((e,t)=>e.startNs-t.startNs),n=[],a=[];for(let e of r){let t=a.at(-1);if(!t||e.startNs-(t.startNs+t.durationNs)<=5e8){a.push(e);continue}n.push(a),a=[e]}return a.length>0&&n.push(a),n.map(e=>{var r,n;let a,i,o,s;return r=e,n=t,a=Math.min(...r.map(e=>e.startNs)),i=Math.max(...r.map(e=>e.startNs+e.durationNs)),s=Math.max(o=Math.max(0,Math.round(a/1e6)),Math.round(i/1e6)),{startOffsetMs:o,endOffsetMs:s,startAt:new Date(n+o).toISOString(),endAt:new Date(n+s).toISOString(),missedDeadlineFrameCount:r.length,worstFrameMs:w_(Math.max(...r.map(e=>e.durationNs))/1e6)}}).sort((e,t)=>t.missedDeadlineFrameCount-e.missedDeadlineFrameCount||t.worstFrameMs-e.worstFrameMs).slice(0,3).sort((e,t)=>e.startOffsetMs-t.startOffsetMs)}(i,Date.parse(r.windowStartedAt)),{droppedFramePercent:n>0?w_(o/n*100):0,droppedFrameCount:o,totalFrameCount:n,sampleWindowMs:s,windowStartedAt:r.windowStartedAt,windowEndedAt:r.windowEndedAt,measuredAt:r.measuredAt,method:gc,matchedProcesses:[...new Set(i.map(e=>e.processName).filter(e=>"string"==typeof e&&e.length>0))],frameDeadlineMs:void 0===a?void 0:w_(1e3/a),refreshRateHz:a,worstWindows:l.length>0?l:void 0}}async function gb(e,t,r){let n=await d.mkdtemp(f.join(c.tmpdir(),"agent-device-ios-frame-perf-")),a=f.join(n,"animation-hitches.trace"),i=f.join(n,"hitches.xml"),o=f.join(n,"frame-lifetimes.xml"),s=f.join(n,"display-info.xml");try{let n=await gA({device:e,appBundleId:t,tracePath:a,template:"Animation Hitches",duration:"2s",targetPids:r.map(e=>e.pid),validateTraceOutput:!0,failureMessage:`Failed to record iOS frame-health sample for ${t}`});await gx(e,t,a,"hitches",i),await gx(e,t,a,"hitches-frame-lifetimes",o);let l=await gN(e,t,a,"device-display-info",s);return{windowStartedAt:n.startedAt,windowEndedAt:n.endedAt,hitchesXml:await d.readFile(i,"utf8"),frameLifetimesXml:await d.readFile(o,"utf8"),displayInfoXml:l?await d.readFile(s,"utf8"):void 0}}finally{await d.rm(n,{recursive:!0,force:!0}).catch(()=>{})}}async function gA(e){let{device:t,appBundleId:r,tracePath:n,template:a,duration:i}=e,o=e.allProcesses?["--all-processes"]:(e.targetPids??[]).flatMap(e=>["--attach",String(e)]),s=["xctrace","record","--template",a,"--device",t.id,...o,"--time-limit",i,"--output",n,"--quiet","--no-prompt"],l=await gS(s,e.tracePath);if(0===l.result.exitCode)return e.validateTraceOutput&&await g_(e,l.result.stdout,l.result.stderr),{startedAt:l.startedAt,endedAt:l.endedAt,capturedAtMs:l.capturedAtMs};throw new O("COMMAND_FAILED",e.failureMessage,{cmd:"xcrun",args:s,exitCode:l.result.exitCode,stdout:l.result.stdout,stderr:l.result.stderr,appBundleId:r,deviceId:t.id,hint:gF(l.result.stdout,l.result.stderr)})}async function gS(e,t){let r;for(let n=1;n<=3;n+=1){n>1&&(await d.rm(t,{recursive:!0,force:!0}).catch(()=>{}),await new Promise(e=>setTimeout(e,1500)));let a=new Date().toISOString(),i=await rM(e,{allowFailure:!0,timeoutMs:6e4});if(r={result:i,startedAt:a,endedAt:new Date().toISOString(),capturedAtMs:Date.now()},0===i.exitCode||!function(e){let t=`${e.stdout}
63
- ${e.stderr}`.toLowerCase();return t.includes("_lockkperf")||t.includes("could not lock kperf")||t.includes("likely another session just started")}(i))break}return r}async function g_(e,t,r){let n=await d.stat(e.tracePath).catch(()=>null);if(!(n?.isDirectory()===!0?(await d.readdir(e.tracePath).catch(()=>[])).length>0:(n?.size??0)>0))throw new O("COMMAND_FAILED",`${e.failureMessage}: xctrace produced no trace data`,{tracePath:e.tracePath,appBundleId:e.appBundleId,deviceId:e.device.id,stdout:t,stderr:r,hint:"Keep the iOS device unlocked and connected by cable, keep the app active, then retry perf."})}async function gx(e,t,r,n,a){let i=["xctrace","export","--input",r,"--xpath",`/trace-toc/run/data/table[@schema="${n}"]`,"--output",a],o=await rM(i,{allowFailure:!0,timeoutMs:15e3});if(0!==o.exitCode)throw new O("COMMAND_FAILED",`Failed to export iOS device ${n} data`,{cmd:"xcrun",args:i,exitCode:o.exitCode,stdout:o.stdout,stderr:o.stderr,appBundleId:t,deviceId:e.id,hint:gF(o.stdout,o.stderr)})}async function gN(e,t,r,n,a){try{return await gx(e,t,r,n,a),!0}catch{return!1}}async function gM(e){let t=r7(e),r=gl(t,"activity-monitor-process-live");if(0===r.length)throw new O("COMMAND_FAILED","Failed to parse xctrace activity-monitor-process-live schema");let n=r.indexOf("pid"),a=r.indexOf("process"),i=r.indexOf("cpu-total"),o=r.indexOf("memory-real");if(n<0||a<0||i<0||o<0)throw new O("COMMAND_FAILED","xctrace activity-monitor-process-live export is missing expected columns");let s=gs(t,e=>"row"===e.name),l=[],u=new Map;for(let e of s){var d,c;let t=e.children;if(0===t.length)continue;for(let e of t){let t=go(e.children,e=>"pid"===e.name&&"string"==typeof e.attributes.id);if(t?.attributes.id){let e=Number(t.text);u.set(t.attributes.id,{numberValue:Number.isFinite(e)?e:null})}e.attributes.id&&u.set(e.attributes.id,{numberValue:gu(e),processName:gT(e)})}let r=gd(t[n],u),s=(d=t[a],c=u,d?d.attributes.ref?c.get(d.attributes.ref)?.processName??null:gT(d):null);null!==r&&Number.isFinite(r)&&s&&l.push({pid:r,processName:s,cpuTimeNs:gd(t[i],u),residentMemoryBytes:gd(t[o],u)})}return l}async function gk(e,t){let r="macos"===e.platform?await gC(t):await gE(e,t),n="macos"===e.platform?f.join(r,"Contents","Info.plist"):f.join(r,"Info.plist"),a=await lx(n,"CFBundleExecutable");if(!a)throw new O("COMMAND_FAILED",`Failed to resolve executable for ${t}`,{appBundleId:t,appPath:r});return{executableName:a,executablePath:"macos"===e.platform?f.join(r,"Contents","MacOS",a):f.join(r,a)}}async function gD(e,t){let r=await gP(e,t),n=await gO(e,t),a=await gO(e,t),i=gR(await gM(n.xml),r,t,e),o=gR(await gM(a.xml),r,t,e),s=a.capturedAtMs-n.capturedAtMs;if(s<=0)throw new O("COMMAND_FAILED",`Invalid Activity Monitor sample window for ${t}`,{appBundleId:t,deviceId:e.id});if(null===i.cpuTimeNs||null===o.cpuTimeNs||null===o.residentMemoryBytes)throw new O("COMMAND_FAILED",`Incomplete Activity Monitor sample for ${t}`,{appBundleId:t,deviceId:e.id,hint:"Keep the app running in the foreground while perf samples the device, then retry."});return g$({usagePercent:Math.max(0,o.cpuTimeNs-i.cpuTimeNs)/(1e6*s)*100,residentMemoryKb:o.residentMemoryBytes/1024,measuredAt:new Date(a.capturedAtMs).toISOString(),matchedProcesses:o.matchedProcesses,cpuMethod:gg,memoryMethod:gy})}async function gP(e,t){let r=(await oq(e,"all")).find(e=>e.bundleId===t);if(!r)throw new O("APP_NOT_INSTALLED",`No iOS device app found for ${t}`,{appBundleId:t,deviceId:e.id});if(!r.url)throw new O("COMMAND_FAILED",`Missing app bundle URL for ${t}`,{appBundleId:t,deviceId:e.id});let n=r.url.replace(/\/$/,""),a=y(n),i=(await oj(e)).filter(e=>e.executable.startsWith(`${n}/`));if(0===i.length)throw new O("COMMAND_FAILED",`No running process found for ${t}`,{appBundleId:t,deviceId:e.id,appBundlePath:a,hint:"Run open <app> for this session again to ensure the iOS app is active, then retry perf."});return i}async function gO(e,t){let r=await d.mkdtemp(f.join(c.tmpdir(),"agent-device-ios-perf-")),n=f.join(r,"sample.trace"),a=f.join(r,"activity-monitor-process-live.xml");try{let r=await gA({device:e,appBundleId:t,tracePath:n,template:"Activity Monitor",duration:"1s",allProcesses:!0,failureMessage:`Failed to record iOS device Activity Monitor sample for ${t}`});return await gx(e,t,n,"activity-monitor-process-live",a),{capturedAtMs:r.capturedAtMs,xml:await d.readFile(a,"utf8")}}finally{await d.rm(r,{recursive:!0,force:!0}).catch(()=>{})}}function gR(e,t,r,n){let a=new Set(t.map(e=>e.pid)),i=new Set(t.map(e=>f.basename(y(e.executable)))),o=e.filter(e=>a.has(e.pid)||i.has(e.processName));if(0===o.length)throw new O("COMMAND_FAILED",`No Activity Monitor sample found for ${r}`,{appBundleId:r,deviceId:n.id,hint:"Keep the app running in the foreground while perf samples the device, then retry."});let s=new Map;for(let e of o){let t=s.get(e.pid);if(!t){s.set(e.pid,e);continue}s.set(e.pid,{pid:e.pid,processName:e.processName||t.processName,cpuTimeNs:gU(t.cpuTimeNs,e.cpuTimeNs),residentMemoryBytes:gU(t.residentMemoryBytes,e.residentMemoryBytes)})}let l=[...s.values()],u=l.map(e=>e.cpuTimeNs).filter(e=>null!==e),d=l.map(e=>e.residentMemoryBytes).filter(e=>null!==e);return{cpuTimeNs:u.length>0?u.reduce((e,t)=>e+t,0):null,residentMemoryBytes:d.length>0?d.reduce((e,t)=>e+t,0):null,matchedProcesses:ac(l.map(e=>e.processName))}}async function gC(e){let t=`kMDItemCFBundleIdentifier == "${e.replaceAll('"','\\"')}"`,r=await rN("mdfind",[t],{allowFailure:!0,timeoutMs:15e3});if(0!==r.exitCode)throw new O("COMMAND_FAILED",`Failed to resolve macOS app bundle for ${e}`,{appBundleId:e,stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode});let n=r.stdout.split("\n").map(e=>e.trim()).find(e=>e.endsWith(".app"));if(!n)throw new O("APP_NOT_INSTALLED",`No macOS app found for ${e}`,{appBundleId:e});return n}async function gE(e,t){let r=rO(e,["get_app_container",e.id,t,"app"]),n=await rM(r,{allowFailure:!0,timeoutMs:15e3});if(0!==n.exitCode)throw new O("COMMAND_FAILED",`Failed to resolve iOS simulator app container for ${t}`,{appBundleId:t,stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode,hint:"Ensure the iOS simulator app is installed and booted, then retry perf."});let a=n.stdout.trim();if(0===a.length)throw new O("APP_NOT_INSTALLED",`No iOS simulator app container found for ${t}`,{appBundleId:t});return a}async function gL(e,t){let r="macos"===e.platform?["-axo","pid=,%cpu=,rss=,command="]:rO(e,["spawn",e.id,"ps","-axo","pid=,%cpu=,rss=,command="]);return(function(e){let t=[];for(let r of eK(e)){let e=r.match(/^(\d+)\s+([0-9]+(?:\.[0-9]+)?)\s+(\d+)\s+(.+)$/);if(!e)continue;let[n,a,i,o]=e.slice(1);if(void 0===n||void 0===a||void 0===i||void 0===o)continue;let s=Number(n),l=Number(a),u=Number(i),d=o.trim();Number.isFinite(s)&&Number.isFinite(l)&&Number.isFinite(u)&&t.push({pid:s,cpuPercent:l,rssKb:u,command:d})}return t})(("macos"===e.platform?await rN("ps",r,{timeoutMs:15e3}):await rM(r,{timeoutMs:15e3})).stdout).filter(e=>{var r,n;let a;return r=e.command,n=t,a=function(e){let[t=""]=e.trim().split(/\s+/,1);return t}(r),!!(n.executablePath&&(r===n.executablePath||a===n.executablePath||r.startsWith(`${n.executablePath} `)))||f.basename(a)===n.executableName})}function g$(e){return{cpu:{usagePercent:w_(e.usagePercent),measuredAt:e.measuredAt,method:e.cpuMethod,matchedProcesses:e.matchedProcesses},memory:{residentMemoryKb:Math.round(e.residentMemoryKb),measuredAt:e.measuredAt,method:e.memoryMethod,matchedProcesses:e.matchedProcesses}}}function gT(e){let t=e?.attributes.fmt?.trim()??"";return t?t.replace(/\s+\(\d+\)$/,"").trim():null}function gF(e,t){let r=oW(e,t);if(r)return r;let n=`${e}
64
- ${t}`.toLowerCase();return n.includes("no device matched")||n.includes("failed to find device")?oH:n.includes("timed out")?"Keep the iOS device unlocked and connected by cable, keep the app active, then retry perf.":"Ensure the iOS device is unlocked, trusted, visible to xctrace, and the target app stays active while perf samples it."}function gU(e,t){return null===e?t:null===t?e:Math.max(e,t)}async function gV(e,t={}){var r,n,a;let i,o,s,l,u=(s=(o=(i=function(e){let t=[];for(let r of e){if("open"!==r.command)continue;let e=r.result?.startup;e&&"object"==typeof e&&"number"==typeof e.durationMs&&Number.isFinite(e.durationMs)&&"string"==typeof e.measuredAt&&0!==e.measuredAt.trim().length&&e.method===wv&&t.push({durationMs:Math.max(0,Math.round(e.durationMs)),measuredAt:e.measuredAt,method:wv,appTarget:"string"==typeof e.appTarget&&e.appTarget.length>0?e.appTarget:void 0,appBundleId:"string"==typeof e.appBundleId&&e.appBundleId.length>0?e.appBundleId:void 0})}return t.slice(-20)}((r=e).actions)).at(-1))?{available:!0,lastDurationMs:o.durationMs,lastMeasuredAt:o.measuredAt,method:wv,sampleCount:i.length,samples:i}:{available:!1,reason:"No startup sample captured yet. Run open <app|url> in this session first.",method:wv},{session:r.name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{startup:s,fps:{available:!1,reason:"Dropped-frame sampling is currently available only on Android."},memory:{available:!1,reason:wI},cpu:{available:!1,reason:wI}},sampling:{startup:{method:wv,description:"Elapsed wall-clock time around dispatching the open command for the active session app target.",unit:"ms"},...function(e){if("android"===e.device.platform)return{memory:{method:wE,description:"Memory snapshot from adb shell dumpsys meminfo <package>. Values are reported in kilobytes.",unit:"kB"},cpu:{method:wC,description:"Aggregated CPU usage for app processes matched from adb shell dumpsys cpuinfo.",unit:"percent"},fps:{method:wN,description:"Rendered-frame health from the current adb shell dumpsys gfxinfo <package> framestats window. Dropped frames use Android gfxinfo janky-frame/frame-deadline data when available; this is not video recording FPS.",unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}};var t=e.device;let r="ios"===t.platform&&"device"===t.kind?{method:gc,description:"Rendered-frame hitch health from xctrace Animation Hitches on connected iOS devices. Dropped frames are counted from native hitch rows for the attached app process, with total frames from the same trace frame-lifetime table.",unit:"percent",primaryField:"droppedFramePercent",window:"short 2s xctrace Animation Hitches record of the active app process",resetsAfterRead:!1}:{method:gc,description:"Unavailable on iOS simulators and macOS because local Apple tooling does not expose reliable app frame hitches for these targets.",unit:"percent",primaryField:"droppedFramePercent"};if("ios"===t.platform&&"device"===t.kind)return{fps:r,memory:{method:gy,description:"Resident memory snapshot from a short xctrace Activity Monitor sample on the connected iOS device.",unit:"kB"},cpu:{method:gg,description:"Recent CPU usage snapshot from a short xctrace Activity Monitor sample on the connected iOS device.",unit:"percent"}};let n="macos"===t.platform?"host ps for the running macOS app executable resolved from the bundle ID.":"xcrun simctl spawn ps for the running iOS simulator app executable resolved from the bundle ID.";return{fps:r,memory:{method:gw,description:`Resident memory snapshot from ${n}`,unit:"kB"},cpu:{method:gh,description:`Recent CPU usage snapshot from ${n}`,unit:"percent"}}}(r)}});return"android"!==(n=e).device.platform&&"ios"!==n.device.platform&&"macos"!==n.device.platform||(e.appBundleId?"android"===e.device.platform?await gG(u,e,t):await gq(u,e):(a=u,l="android"===e.device.platform?"No Android app package is associated with this session. Run open <app> first.":"No Apple app bundle ID is associated with this session. Run open <app> first.",a.metrics.fps={available:!1,reason:l},a.metrics.memory={available:!1,reason:l},a.metrics.cpu={available:!1,reason:l})),u}async function gG(e,t,r){let n=await gj(t,r);e.metrics.memory=gW(n.memory),e.metrics.cpu=gW(n.cpu),e.metrics.fps=gz(gW(n.fps),t)}async function gq(e,t){let r=await gB(t);e.metrics.memory=gW(r.memory),e.metrics.cpu=gW(r.cpu),e.metrics.fps=gz(gW(r.fps),t)}async function gj(e,t){let r=e.appBundleId,n={adb:t.androidAdb},[a,i,o]=await Promise.allSettled([w$(e.device,r,n),wL(e.device,r,n),wO(e.device,r,n)]);return{memory:a,cpu:i,fps:o}}async function gB(e){let t=e.appBundleId,r=await gH(gI(e.device,t)),n=await gH(gv(e.device,t));if("fulfilled"===n.status){let e=n.value;return{memory:{status:"fulfilled",value:e.memory},cpu:{status:"fulfilled",value:e.cpu},fps:r}}return{memory:{status:"rejected",reason:n.reason},cpu:{status:"rejected",reason:n.reason},fps:r}}async function gH(e){try{return{status:"fulfilled",value:await e}}catch(e){return{status:"rejected",reason:e}}}function gW(e){if("fulfilled"===e.status)return{available:!0,...e.value};let t=P(e.reason);return{available:!1,reason:t.message,error:t}}function gz(e,t){var r,n;let a,i;if(!0!==e.available)return e;let o=(r=t.actions,a=gK((n=e).windowStartedAt),i=gK(n.windowEndedAt)??gK(n.measuredAt),void 0===a||void 0===i?[]:r.filter(e=>e.ts>=a&&e.ts<=i).map(e=>({command:e.command,at:new Date(e.ts).toISOString(),offsetMs:Math.max(0,Math.round(e.ts-a)),target:function(e){let t=e.result;if(t)for(let e of["refLabel","ref","appName","appBundleId"]){let r=t[e];if("string"==typeof r&&r.length>0)return r}}(e)})).slice(-12));return 0===o.length?e:{...e,relatedActions:o}}function gK(e){if("string"!=typeof e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}let gJ=["path","start","stop","doctor","mark","clear"],gX=`logs requires ${gJ.slice(0,-1).join(", ")}, or ${gJ.at(-1)}`,gY=["dump","log"],gZ=`network requires ${gY.join(" or ")}`,gQ=["summary","headers","body","all"],g0=`network include mode must be one of: ${gQ.join(", ")}`;async function g1(e){let{req:t}=e;return"perf"===t.command?g2(e):"logs"===t.command?g3(e):"network"===t.command?g9(e):null}async function g2(e){let{sessionName:t,sessionStore:r,androidAdbExecutor:n}=e,a=r.get(t);if(!a)return cm("SESSION_NOT_FOUND","perf requires an active session. Run open first.");try{return{ok:!0,data:await gV(a,{androidAdb:n})}}catch(e){return{ok:!1,error:P(e)}}}async function g3(e){let{req:t,sessionName:r,sessionStore:n}=e,a=n.get(r);if(!a)return cm("SESSION_NOT_FOUND","logs requires an active session");if(!cF("logs",a.device))return cm("UNSUPPORTED_OPERATION","logs is not supported on this device");let i=(t.positionals?.[0]??"path").toLowerCase(),o=!!t.flags?.restart;return gJ.includes(i)?o&&"clear"!==i?cm("INVALID_ARGS","logs --restart is only supported with logs clear"):"path"===i?function(e,t,r){let n=r.resolveAppLogPath(t),a=function(e){if(!l.existsSync(e))return{exists:!1,sizeBytes:0};let t=l.statSync(e);return{exists:!0,sizeBytes:t.size,modifiedAt:t.mtime.toISOString()}}(n);return{ok:!0,data:{path:n,active:!!e.appLog,state:e.appLog?.getState()??"inactive",backend:e.appLog?e.appLog.backend:"macos"===e.device.platform?"macos":"ios"===e.device.platform?"device"===e.device.kind?"ios-device":"ios-simulator":"android",sizeBytes:a.sizeBytes,modifiedAt:a.modifiedAt,startedAt:e.appLog?.startedAt?new Date(e.appLog.startedAt).toISOString():void 0,hint:'Grep the file for token-efficient debugging, e.g. grep -n "Error\\|Exception" <path>'}}}(a,r,n):"doctor"===i?g5(a,r,n):"mark"===i?function(e,t,r){let n,a=e.positionals?.slice(1).join(" ")??"",i=r.resolveAppLogPath(t);return ic(i),n=`[agent-device][mark][${new Date().toISOString()}] ${a.trim()||"marker"}
65
- `,l.appendFileSync(i,n,"utf8"),{ok:!0,data:{path:i,marked:!0}}}(t,r,n):"clear"===i?g4(a,r,n,o):"start"===i?g8(a,r,n):"stop"===i?g6(a,r,n):cm("INVALID_ARGS",gX):cm("INVALID_ARGS",gX)}async function g5(e,t,r){let n=r.resolveAppLogPath(t),a=await iv(e.device,e.appBundleId);return{ok:!0,data:{path:n,active:!!e.appLog,state:e.appLog?.getState()??"inactive",checks:a.checks,notes:a.notes}}}async function g4(e,t,r,n){if(e.appLog&&!n)return cm("INVALID_ARGS","logs clear requires logs to be stopped first; run logs stop");if(n&&!e.appBundleId)return cm("INVALID_ARGS","logs clear --restart requires an app session; run open <app> first");let a=r.resolveAppLogPath(t);if(!n)return{ok:!0,data:iI(a)};e.appLog&&await iy(e.appLog);let i=iI(a),o=r.resolveAppLogPidPath(t);try{let n=await ih(e.device,e.appBundleId,a,o);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:n.backend,outPath:a,startedAt:n.startedAt,getState:n.getState,stop:n.stop,wait:n.wait}}),{ok:!0,data:{...i,restarted:!0}}}catch(n){return r.set(t,{...e,appLog:void 0}),{ok:!1,error:P(n)}}}async function g8(e,t,r){if(e.appLog)return cm("INVALID_ARGS","app log already streaming; run logs stop first");if(!e.appBundleId)return cm("INVALID_ARGS","logs start requires an app session; run open <app> first");let n=r.resolveAppLogPath(t),a=r.resolveAppLogPidPath(t);try{let i=await ih(e.device,e.appBundleId,n,a);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:i.backend,outPath:n,startedAt:i.startedAt,getState:i.getState,stop:i.stop,wait:i.wait}}),{ok:!0,data:{path:n,started:!0}}}catch(e){return{ok:!1,error:P(e)}}}async function g6(e,t,r){if(!e.appLog)return cm("INVALID_ARGS","no app log stream active");let n=e.appLog.outPath;return await iy(e.appLog),r.set(t,{...e,appLog:void 0}),{ok:!0,data:{path:n,stopped:!0}}}async function g9(e){let{req:t,sessionName:r,sessionStore:n}=e,a=n.get(r);if(!a)return cm("SESSION_NOT_FOUND","network requires an active session");if(!cF("network",a.device))return cm("UNSUPPORTED_OPERATION","network is not supported on this device");let i=(t.positionals?.[0]??"dump").toLowerCase();if(!gY.includes(i))return cm("INVALID_ARGS",gZ);let o=t.positionals?.[1]?Number.parseInt(t.positionals[1],10):25;if(!Number.isInteger(o)||o<1||o>200)return cm("INVALID_ARGS","network dump limit must be an integer in range 1..200");let s=function(e){let t=e.positionals?.[2]?.toLowerCase(),r=e.flags?.networkInclude;if(t&&r&&t!==r)return cm("INVALID_ARGS","network include mode was provided both positionally and via --include with different values");let n=(r??t??"summary").toLowerCase();return gQ.includes(n)?{ok:!0,include:n}:cm("INVALID_ARGS",g0)}(t);if(!s.ok)return s;let{include:l}=s,u=await ip({device:a.device,appBundleId:a.appBundleId,appLogState:a.appLog?.getState(),appLogStartedAt:a.appLog?.startedAt,appLogPath:n.resolveAppLogPath(r),maxEntries:o,include:l,maxPayloadChars:2048,maxScanLines:4e3});return{ok:!0,data:{...u.dump,active:!!a.appLog,state:a.appLog?.getState()??"inactive",backend:u.backend,notes:u.notes}}}let g7=/^[A-Z_][A-Z0-9_]*$/,ye=/(\\\$\{)|\$\{([A-Za-z_][A-Za-z0-9_.]*)(?::-((?:[^}\\]|\\.)*))?\}/g,yt="AD_VAR_";function yr(e){return e.startsWith("AD_")}function yn(e){return new O("INVALID_ARGS",`The AD_* namespace is reserved for built-in variables. Rename ${e} to avoid the AD_ prefix.`)}function ya(e){let t={};for(let[r,n]of Object.entries(e)){if("string"!=typeof n||!r.startsWith(yt))continue;let e=r.slice(yt.length);0!==e.length&&g7.test(e)&&(yr(e)||(t[e]=n))}return t}function yi(e){let t={};for(let r of e){let e=r.indexOf("=");if(e<=0)throw new O("INVALID_ARGS",`Invalid -e entry "${r}": expected KEY=VALUE.`);let n=r.slice(0,e);if(!g7.test(n))throw new O("INVALID_ARGS",`Invalid -e key "${n}": keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(yr(n))throw yn(n);t[n]=r.slice(e+1)}return t}function yo(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function ys(e){if(e&&"object"==typeof e&&!Array.isArray(e)){let t={};for(let[r,n]of Object.entries(e))"string"==typeof n&&(t[r]=n);return t}return process.env}function yl(e,t,r){return e.replace(ye,(e,n,a,i)=>{if(n)return"${";if(!a)return e;if(Object.prototype.hasOwnProperty.call(t.values,a))return String(t.values[a]);if(void 0!==i)return i.replace(/\\(.)/g,"$1");throw new O("INVALID_ARGS",`Unresolved variable \${${a}} at ${r.file}:${r.line}.`)})}function yu(e,t,r){return e?function e(t,r,n){return"string"==typeof t?yl(t,r,n):Array.isArray(t)?t.map(t=>e(t,r,n)):t&&"object"==typeof t?Object.fromEntries(Object.entries(t).map(([t,a])=>[t,e(a,r,n)])):t}(e,t,r):e}let yd=new Set(["ios","android","macos","linux"]),yc=new Set(["mobile","tv","desktop"]);function yp(e){let t=e.split(/\r?\n/),r={};for(let[e,n]of t.entries()){let t=n.trim();if(0===t.length||t.startsWith("#"))continue;if(yf(t)){!function(e,t,r){let{key:n,value:a}=function(e,t){let r=e.slice(3).replace(/^[\s]+/,""),n=r.indexOf("=");if(n<=0)throw new O("INVALID_ARGS",`Invalid env directive on line ${t}: expected "env KEY=VALUE".`);let a=r.slice(0,n);if(!g7.test(a))throw new O("INVALID_ARGS",`Invalid env key "${a}" on line ${t}: keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(a.startsWith("AD_"))throw new O("INVALID_ARGS",`Invalid env key "${a}" on line ${t}: the AD_* namespace is reserved for built-in variables. Rename ${a} to avoid the AD_ prefix.`);return{key:a,value:function(e,t){if(0===e.length)return"";if(e.startsWith('"'))try{let t=JSON.parse(e);if("string"!=typeof t)throw Error("not a string literal");return t}catch{throw new O("INVALID_ARGS",`Invalid quoted env value on line ${t}.`)}return e}(r.slice(n+1),t)}}(t,r),i=e.env??{};if(Object.prototype.hasOwnProperty.call(i,n))throw new O("INVALID_ARGS",`Duplicate env directive "${n}" on line ${r}.`);i[n]=a,e.env=i}(r,t,e+1);continue}if(!t.startsWith("context "))break;let a=t.match(/(?:^|\s)platform=([^\s]+)/);if(a){let e=a[1];e&&yd.has(e)&&ym(r,"platform",e)}let i=t.match(/(?:^|\s)target=([^\s]+)/);if(i){let e=i[1];e&&yc.has(e)&&ym(r,"target",e)}let o=t.match(/(?:^|\s)timeout=(\d+)/);if(o){let e=Number(o[1]);Number.isFinite(e)&&e>=1&&ym(r,"timeoutMs",Math.floor(e))}let s=t.match(/(?:^|\s)retries=(\d+)/);if(s){let e=Number(s[1]);Number.isFinite(e)&&e>=0&&ym(r,"retries",Math.floor(e))}}return r}function yf(e){return"env"===e||e.startsWith("env ")||e.startsWith("env ")}function ym(e,t,r){let n=e[t];if(void 0!==n)throw new O("INVALID_ARGS",n===r?`Duplicate replay test metadata "${t}" in context header.`:`Conflicting replay test metadata "${t}" in context header: ${String(n)} vs ${String(r)}.`);e[t]=r}function yh(e){return!!e&&!Number.isNaN(Number(e))}let yw=/[*?[\]{}]/;function yg(e){return"maestro"===e}async function yy(e){let t,{filePath:r,sessionName:n,requestId:a,timeoutMs:i,platform:o,target:s,artifactsDir:l,runReplay:u,cleanupSession:d}=e;rs(a);let c=new Set,p=!1,f=u({filePath:r,sessionName:n,platform:o,target:s,requestId:a,artifactsDir:l,artifactPaths:c}).catch(e=>{let t=D(e);return cm(t.code,t.message)}).finally(()=>{ru(a)});try{return"number"==typeof i?await Promise.race([f,new Promise(e=>{t=setTimeout(()=>{p=!0,rl(a),e(function(e,t=[]){return{ok:!1,error:{code:"COMMAND_FAILED",message:`TIMEOUT after ${e}ms`,hint:"Replay test timeouts are cooperative; the active command may take a short grace period to stop.",details:{reason:"timeout",timeoutMs:e,timeoutMode:"cooperative",artifactPaths:t}}}}(i,[...c]))},i)})]):await f}finally{t&&clearTimeout(t),p&&(await yv(f)||eM({level:"warn",phase:"test_timeout_cleanup_race",data:{session:n,requestId:a,graceMs:2e3}}));try{await d(n)}catch(e){eM({level:"warn",phase:"test_cleanup_failed",data:{session:n,error:D(e).message}})}}}async function yv(e){return await Promise.race([e.then(()=>!0),x(2e3).then(()=>!1)])}async function yI(e){let{req:t,sessionName:r,runReplay:n,cleanupSession:a}=e;if((t.positionals?.length??0)===0)return cm("INVALID_ARGS","test requires at least one path or glob");try{var i,o,s,u,d,c;let e,p,m,h,w,g=function(e){var t,r,n;let{inputs:a,cwd:i,platformFilter:o,replayBackend:s}=e,u=(t=s,new Set(yg(t)?[".ad",".yaml",".yml"]:[".ad"])),d=i??process.cwd(),c=[...new Set(a.flatMap(e=>(function(e,t,r){var n,a;let i=aE.expandHome(e,t);if(l.existsSync(i)){let t=l.statSync(i);if(t.isDirectory())return[...r].map(e=>`**/*${e}`).flatMap(e=>l.globSync(e,{cwd:i}).map(e=>f.join(i,e)));if(t.isFile()){if(!r.has(f.extname(i)))throw new O("INVALID_ARGS",`test does not support this file type: ${e}`);return[i]}return[]}if(n=e,!yw.test(n)&&(a=i,!yw.test(a)))throw new O("INVALID_ARGS",`test input not found: ${e}`);let o=f.isAbsolute(i)?i:e;return l.globSync(o,{cwd:f.isAbsolute(i)?void 0:t}).map(e=>f.isAbsolute(e)?e:f.resolve(t,e)).filter(e=>r.has(f.extname(e))&&function(e){try{return l.statSync(e).isFile()}catch{return!1}}(e))})(e,d,u)))].map(e=>f.normalize(e)).sort((e,t)=>e.localeCompare(t)),p=[];for(let e of c){let t=yp(l.readFileSync(e,"utf8"));if(!o){p.push({kind:"run",path:e,metadata:t});continue}if(!t.platform){yg(s)?p.push({kind:"run",path:e,metadata:t}):p.push({kind:"skip",path:e,reason:"skipped-by-filter",message:`missing platform metadata for --platform ${o}`});continue}r=o,n=t.platform,("apple"===r?"apple"===n||"ios"===n||"macos"===n:n===r)&&p.push({kind:"run",path:e,metadata:t})}if(0===p.filter(e=>"run"===e.kind).length){let e=o?` for --platform ${o}`:"";throw new O("INVALID_ARGS",`No replay tests matched${e}.`)}return p}({inputs:t.positionals,cwd:t.meta?.cwd,platformFilter:t.flags?.platform,replayBackend:t.flags?.replayBackend}),y=(i=t.meta?.requestId,(i?.trim()||`${process.pid}-${Date.now().toString(36)}`).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"suite"),v=function(e){let{artifactsDir:t,cwd:r,suiteInvocationId:n}=e,a=aE.expandHome(t??".agent-device/test-artifacts",r);return f.join(a,n)}({artifactsDir:"string"==typeof t.flags?.artifactsDir?t.flags.artifactsDir:void 0,cwd:t.meta?.cwd,suiteInvocationId:y}),I=[],b=Date.now(),A=0;for(let e of g){if("skip"===e.kind){I.push({file:e.path,status:"skipped",durationMs:0,reason:e.reason,message:e.message});continue}A+=1;let i=await yb({entry:e,sessionName:r,suiteInvocationId:y,caseIndex:A-1,cwd:t.meta?.cwd,requestId:t.meta?.requestId,retries:function(e,t){let r="number"==typeof e?e:t;return"number"!=typeof r?0:Math.max(0,Math.min(3,r))}(t.flags?.retries,e.metadata.retries),timeoutMs:(o=t.flags?.timeoutMs,s=e.metadata.timeoutMs,"number"==typeof o?o:s),suiteArtifactsDir:v,runReplay:n,cleanupSession:a});if(I.push(i),t.flags?.failFast===!0)break}let S=(u=g.length,d=I,c=Date.now()-b,e=d.filter(e=>"passed"===e.status).length,m=(p=d.filter(e=>"failed"===e.status)).length,h=d.filter(e=>"skipped"===e.status).length,w=e+m,{total:u,executed:w,passed:e,failed:m,skipped:h,notRun:Math.max(0,u-w-h),durationMs:c,failures:p,tests:d});return{ok:!0,data:S}}catch(t){let e=D(t);return cm(e.code,e.message)}}async function yb(e){var t,r;let n,a,{entry:i,sessionName:o,suiteInvocationId:s,caseIndex:u,cwd:d,requestId:c,retries:p,timeoutMs:m,suiteArtifactsDir:h,runReplay:w,cleanupSession:g}=e,y=Date.now(),v=f.join(h,(t=i.path,(0===(a=d?f.relative(d,t):f.basename(t)).length||a.startsWith("..")?f.basename(t):a).toLowerCase().replace(/[\\/]+/g,"__").replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"test")),I="",b=0;for(let e=0;e<=p;e+=1){b=e+1;let t=function(e,t,r,n,a=0){let i=f.basename(r,f.extname(r)).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${e}:test:${t}:${n+1}${i?`-${i}`:""}:attempt-${a+1}`}(o,s,i.path,u,e),a=f.join(v,`attempt-${b}`);r=i.path,l.mkdirSync(a,{recursive:!0}),l.copyFileSync(r,f.join(a,"replay.ad"));let d=function(e){let{requestId:t,suiteInvocationId:r,filePath:n,caseIndex:a,attemptIndex:i}=e;return ro(`${t??r}:test:${a+1}:${f.basename(n)}:attempt:${i+1}`,r)}({requestId:c,suiteInvocationId:s,filePath:i.path,caseIndex:u,attemptIndex:e}),h=await yy({filePath:i.path,sessionName:t,requestId:d,timeoutMs:m,platform:i.metadata.platform,target:i.metadata.target,artifactsDir:a,runReplay:w,cleanupSession:g});if(!function(e){let{response:t,filePath:r,sessionName:n,attempts:a,maxAttempts:i,attemptArtifactsDir:o}=e,s=[...function(e){let t=e.ok?e.data?.artifactPaths:e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>"string"==typeof e))]:[]}(t)];t.ok||"string"!=typeof t.error.logPath||s.push(t.error.logPath);let u=function(e,t){let r=[],n=new Map;for(let a of e){if(!function(e){try{return l.statSync(e).isFile()}catch{return!1}}(a))continue;let e=function(e,t){let r=f.extname(e),n=r?e.slice(0,-r.length):e,a=t.get(e)??0;return(t.set(e,a+1),0===a)?e:`${n}-${a+1}${r}`}(f.basename(a),n),i=f.join(t,e);f.resolve(a)!==f.resolve(i)&&l.copyFileSync(a,i),r.push(i)}return r}(s,o),d=[`file: ${r}`,`session: ${n}`,`attempt: ${a}/${i}`,`status: ${t.ok?"passed":"failed"}`];if(t.ok){let e="number"==typeof t.data?.replayed?t.data.replayed:0,r="number"==typeof t.data?.healed?t.data.healed:0;d.push(`replayed: ${e}`,`healed: ${r}`)}else d.push(`code: ${t.error.code}`,`message: ${t.error.message}`),t.error.hint&&d.push(`hint: ${t.error.hint}`),t.error.diagnosticId&&d.push(`diagnosticId: ${t.error.diagnosticId}`),t.error.logPath&&d.push(`logPath: ${t.error.logPath}`),t.error.details?.reason==="timeout"&&d.push("timeoutMode: cooperative");u.length>0&&d.push(`copiedArtifacts: ${u.map(e=>f.basename(e)).join(", ")}`);let c=f.join(o,"result.txt"),p=`${d.join("\n")}
66
- `;l.writeFileSync(c,p),t.ok||l.writeFileSync(f.join(o,"failure.txt"),p)}({response:h,filePath:i.path,sessionName:t,attempts:b,maxAttempts:p+1,attemptArtifactsDir:a}),n=h,I=t,h.ok)break}let A=Date.now()-y;if(n?.ok)return{file:i.path,session:I,status:"passed",durationMs:A,attempts:b,artifactsDir:v,replayed:"number"==typeof n.data?.replayed?n.data.replayed:0,healed:"number"==typeof n.data?.healed?n.data.healed:0};let S=n?.ok?{code:"COMMAND_FAILED",message:"Unknown replay test failure"}:n?.error??{code:"COMMAND_FAILED",message:"Unknown replay test failure"};return{file:i.path,session:I,status:"failed",durationMs:A,attempts:b,artifactsDir:v,error:S}}function yA(e,t=[],r){return{ts:Date.now(),command:e,positionals:t,flags:r??{}}}function yS(e,t,r){let n=new Set(r),a=Object.keys(e).filter(e=>!n.has(e));if(a.length>0)throw yR(`Maestro ${t} field "${a[0]}" is not supported yet.`)}function y_(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function yx(e){return e.map((e,t)=>{if("string"==typeof e||y_(e))return e;throw new O("INVALID_ARGS",`Unsupported Maestro command at index ${t+1}: expected a scalar or one-key map.`)})}function yN(e,t){if(null==e)return{};if(!y_(e))throw new O("INVALID_ARGS",`${t} expects a map.`);let r={};for(let[t,n]of Object.entries(e))("string"==typeof n||"number"==typeof n||"boolean"==typeof n)&&(r[t]=String(n));return r}function yM(e,t){return y_(e)&&"number"==typeof e.timeout&&Number.isFinite(e.timeout)?Math.max(0,Math.floor(e.timeout)):t}function yk(e,t){if(e.appId)return e.appId;throw new O("INVALID_ARGS",`${t} requires appId in the Maestro flow config.`)}function yD(e,t){if("string"==typeof t)return t;throw new O("INVALID_ARGS",`${e} expects a string value.`)}function yP(e,t){return e.replace(/\$\{([A-Za-z_][A-Za-z0-9_.]*)\}/g,(e,r)=>Object.prototype.hasOwnProperty.call(t.env,r)?String(t.env[r]):e)}function yO(e){throw yR(`Maestro command "${e}" is not supported yet.`)}function yR(e){throw new O("INVALID_ARGS",`${e} See supported/unsupported Maestro compatibility at https://github.com/callstackincubator/agent-device/issues/558. If this syntax matters for your flows, comment there or open a focused issue at https://github.com/callstackincubator/agent-device/issues/new.`)}function yC(e,t,r){var n,a;if(null==e)return yA("open",[yP(yk(t,"launchApp"),r)]);if("string"==typeof e)return yA("open",[yP(e,r)]);if(!y_(e))throw new O("INVALID_ARGS","launchApp expects a string or map.");yS(e,"launchApp",["appId","stopApp","clearState","clearKeychain","arguments","permissions","launchArguments"]),yT(e,"permissions"),yT(e,"clearKeychain");let i=yP("string"==typeof e.appId?e.appId:yk(t,"launchApp"),r),o=(n=e,a=r,[...yL(n.arguments,"launchApp.arguments",a),...yL(n.launchArguments,"launchApp.launchArguments",a)]),s=!0===e.clearState;return yA("open",[i],{...!s&&(!0===e.stopApp||o.length>0)?{relaunch:!0}:{},...s?{clearAppState:!0}:{},...o.length>0?{launchArgs:o}:{}})}function yE(e,t,r){if(null==e)return yA("close",[yP(yk(t,"stopApp"),r)]);if("string"==typeof e)return yA("close",[yP(e,r)]);throw new O("INVALID_ARGS","stopApp expects a string appId or no value.")}function yL(e,t,r){if(null==e)return[];if("string"==typeof e)return[yP(e,r)];if(Array.isArray(e))return e.map((e,n)=>y$(e,`${t}[${n}]`,r));if(y_(e))return Object.entries(e).flatMap(([e,n])=>[yP(e,r),y$(n,`${t}.${e}`,r)]);throw new O("INVALID_ARGS",`${t} expects a string, list, or map.`)}function y$(e,t,r){if("string"==typeof e)return yP(e,r);if("number"==typeof e||"boolean"==typeof e)return String(e);throw new O("INVALID_ARGS",`${t} must be a string, number, or boolean.`)}function yT(e,t){if(void 0!==e[t])throw yR(`Maestro launchApp field "${t}" is not supported yet.`)}function yF(e){let t=e.match(/^(\d+),(\d+)$/);if(!t)throw yR('Only absolute Maestro point selectors like "100,200" are supported.');return{x:Number(t[1]),y:Number(t[2])}}function yU(e){let t=e.match(/^\s*(\d+)\s*,\s*(\d+)\s*$/);if(t)return{kind:"absolute",x:Number(t[1]),y:Number(t[2])};let r=e.match(/^\s*(\d+(?:\.\d+)?)%\s*,\s*(\d+(?:\.\d+)?)%\s*$/);if(r)return{kind:"percent",x:Number(r[1]),y:Number(r[2])};throw yR('Only Maestro swipe coordinates like "100,200" or "50%,75%" are supported.')}let yV="__maestroRunFlowWhen",yG="__maestroRetry",yq="__maestroRunScript",yj="__maestroAssertVisible",yB="__maestroAssertNotVisible",yH="__maestroPressEnter",yW="__maestroWaitForAnimationToEnd",yz="__maestroScrollUntilVisible",yK="__maestroSwipeScreen",yJ="__maestroSwipeOn",yX="__maestroTapOn",yY="__maestroTapPointPercent";function yZ(e){if(null==e)return yA("type",["\b".repeat(50)]);if("number"==typeof e&&Number.isInteger(e)&&e>0)return yA("type",["\b".repeat(e)]);if(!y_(e))throw new O("INVALID_ARGS","eraseText expects empty, a positive count, or a map.");if(yS(e,"eraseText",["charactersToErase"]),void 0===e.charactersToErase)return yA("type",["\b".repeat(50)]);if("number"!=typeof e.charactersToErase||!Number.isInteger(e.charactersToErase)||e.charactersToErase<=0)throw new O("INVALID_ARGS","eraseText.charactersToErase must be a positive integer.");return yA("type",["\b".repeat(e.charactersToErase)])}function yQ(e){return"number"==typeof e&&Number.isFinite(e)?String(Math.max(16,Math.floor(e))):void 0}function y0(e,t){let r=e.toLowerCase();switch(r){case"up":case"down":case"left":case"right":return r;default:throw yR(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`)}}function y1(e){return y0(e,"swipe direction")}function y2(e,t,r=[],n){if("string"==typeof e)return y3(yP(e,n));if(!y_(e))throw new O("INVALID_ARGS",`${t} expects a string or selector map.`);yS(e,t,["id","text","enabled","selected",...r]);let a=[],i=[];if("boolean"==typeof e.enabled&&i.push(y4("enabled",String(e.enabled))),"boolean"==typeof e.selected&&i.push(y4("selected",String(e.selected))),"string"==typeof e.id&&a.push(y4("id",yP(e.id,n)),...i),"string"==typeof e.text&&0===a.length)return y3(yP(e.text,n),i);if("string"==typeof e.label&&0===a.length&&a.push(y4("label",yP(e.label,n)),...i),0===a.length&&i.length>0&&a.push(...i),0===a.length)throw new O("INVALID_ARGS",`${t} selector map must include one of id, text, label, enabled, or selected.`);return a.join(" ")}function y3(e,t=[]){return[[y4("label",e),...t].join(" "),[y4("text",e),...t].join(" "),[y4("id",e),...t].join(" ")].join(" || ")}function y5(e){let t=yQ(e.duration);return t?[t]:[]}function y4(e,t){return`${e}=${JSON.stringify(t)}`}function y8(e){var t,r;if(!y_(e))return;let n={},a="number"==typeof(t=e.repeat)&&Number.isInteger(t)&&t>0?t:void 0,i="number"==typeof(r=e.delay)&&Number.isInteger(r)&&r>=0?r:void 0;return a&&a>1&&(n.count=a),void 0!==i&&(n.intervalMs=i),!0===e.optional&&(n.maestro={optional:!0}),Object.keys(n).length>0?n:void 0}function y6(e){let t=y8(e)??{};return{...t,maestro:{...t.maestro??{},allowNonHittableCoordinateFallback:!0}}}function y9(e){let t={doubleTap:!0};return y_(e)&&"number"==typeof e.delay&&Number.isInteger(e.delay)&&(t.intervalMs=Math.max(0,e.delay)),t}class y7{index=0;tokens;context;constructor(e,t){this.tokens=e,this.context=t}parse(){let e=this.parseOr();if(this.peek())throw new O("INVALID_ARGS","Unsupported trailing runFlow.when.true expression.");return e}parseOr(){let e=this.parseAnd();for(;this.consumeOperator("||");)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator("&&");)e=this.parsePrimary()&&e;return e}parsePrimary(){let e=this.peek();if(!e)throw new O("INVALID_ARGS","Incomplete runFlow.when.true expression.");if("boolean"===e.type)return this.index+=1,e.value;if("paren"===e.type&&"("===e.value){this.index+=1;let e=this.parseOr();if(!this.consumeParen(")"))throw new O("INVALID_ARGS","Unclosed runFlow.when.true parenthesis.");return e}return this.parsePlatformComparison()}parsePlatformComparison(){this.expectPlatform();let e=this.expectEqualityOperator(),t=this.expectString().toLowerCase(),r=this.context.platform;return"=="===e?r===t:r!==t}expectPlatform(){if(this.peek()?.type!=="platform")throw new O("INVALID_ARGS","runFlow.when.true supports maestro.platform comparisons.");this.index+=1}expectEqualityOperator(){let e=this.peek();if(e?.type==="operator"&&("=="===e.value||"!="===e.value))return this.index+=1,e.value;throw new O("INVALID_ARGS","runFlow.when.true comparison requires == or !=.")}expectString(){let e=this.peek();if(e?.type==="string")return this.index+=1,e.value;throw new O("INVALID_ARGS","runFlow.when.true comparison requires a string literal.")}consumeOperator(e){let t=this.peek();return t?.type==="operator"&&t.value===e&&(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type==="paren"&&t.value===e&&(this.index+=1,!0)}peek(){return this.tokens[this.index]}}function ve(e){return{command:e.command,positionals:e.positionals,flags:e.flags,...void 0!==e.runtime?{runtime:e.runtime}:{}}}function vt(e,t,r){let n="string"==typeof e?yP(e,t):e,a="number"==typeof n?n:"string"==typeof n&&/^\d+$/.test(n)?Number(n):void 0;if(void 0===a||!Number.isInteger(a)||a<0)throw new O("INVALID_ARGS",`${r} must be a non-negative integer or \${VAR} resolving to one.`);return a}let vr=`
58
+ `.trim();async function ha(e,t={}){let r,n=t.pollMs??150,a=t.attempts??12,i=0;for(let t=0;t<a;t+=1){let t=0;try{t=l.statSync(e).size}catch{t=0}if(t>0&&t===r){if((i+=1)>=2)return}else i=0;r=t,await e8(n)}}async function hi(e){try{let t=await ho(),r=await R(t,[e],{allowFailure:!0,timeoutMs:1e4,env:m5()});if(0===r.exitCode)return!0;if(hl(r.stderr,r.stdout))return hu(e);return!1}catch(r){var t;if((t=r)instanceof D&&("TOOL_MISSING"===t.code||hl(String(t.details?.stderr??""),String(t.details?.stdout??""))))return hu(e);throw r}}async function ho(){t??=m8({source:hn,cacheName:"video-validator",timeoutMs:3e4});try{return await t}catch(e){throw t=void 0,e}}async function hs(e,t={}){let r=t.pollMs??150,n=t.attempts??12;for(let t=0;t<n;t+=1){if(await hi(e))return;await e8(r)}}function hl(e,t){let r=`${e}
59
+ ${t}`;return/\b(no such module ['"]AVFoundation['"]|unable to find utility ["']swiftc?["']|xcrun: error: unable to find utility ["']swiftc?["'])\b/i.test(r)}function hu(e){try{let t=l.statSync(e);if(!t.isFile()||t.size<=0)return!1}catch{return!1}let t=function(e){try{let t=l.openSync(e,"r");try{let e=l.fstatSync(t).size,r=0,n=[];for(;r+8<=e&&n.length<16;){let e=Buffer.alloc(8);if(8>l.readSync(t,e,0,8,r))break;let a=e.readUInt32BE(0),i=e.toString("latin1",4,8);if(n.push(i),1===a){let e=Buffer.alloc(8);if(8>l.readSync(t,e,0,8,r+8))break;a=Number(e.readBigUInt64BE(0))}if(!Number.isFinite(a)||a<=0)break;r+=a}return n}finally{l.closeSync(t)}}catch{return[]}}(e);return t.includes("ftyp")&&t.includes("moov")}function hd(e){let t=f.parse(e);return f.join(t.dir,`${t.name}.gesture-telemetry.json`)}function hc(e){return[...e].sort((e,t)=>e.tMs-t.tMs)}function hp(e){let t=f.dirname(g(import.meta.url)),r=[g(new URL(`./${e}`,import.meta.url)),f.resolve(t,`../../ios-runner/AgentDeviceRunner/RecordingScripts/${e}`),f.resolve(t,`../../../ios-runner/AgentDeviceRunner/RecordingScripts/${e}`),f.resolve(process.cwd(),`ios-runner/AgentDeviceRunner/RecordingScripts/${e}`)];for(let e of r)if(l.existsSync(e))return e;throw new D("COMMAND_FAILED",`Missing recording helper script: ${e}`,{hint:"Ensure ios-runner/AgentDeviceRunner/RecordingScripts is present in this checkout or bundled with the package.",scriptName:e,searchedPaths:r})}async function hf(e){var t;let r,n,{videoPath:a,scriptPath:i,scriptArgs:o,commandDescription:s}=e;await ha(a),await hs(a);let u=(t=a,r=f.parse(t),n=`${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`,f.join(r.dir,`.${r.name}.agent-device-${n}${r.ext||".mp4"}`));try{let e=await m4({sourcePath:i});await R(e,["--input",a,"--output",u,...o],{timeoutMs:12e4,env:m5()}),await hs(u),l.renameSync(u,a)}catch(t){let e=t instanceof D?t:new D("COMMAND_FAILED",String(t),void 0,t instanceof Error?t:void 0);throw new D("COMMAND_FAILED",s,{...e.details,videoPath:a,script:i},e)}finally{l.rmSync(u,{force:!0})}}async function hm(e){let{videoPath:t,trimStartMs:r}=e;r>0&&await hf({videoPath:t,scriptPath:n??=hp("recording-trim.swift"),scriptArgs:["--trim-start-ms",String(r)],commandDescription:"Failed to trim the start of the iOS recording"})}async function hh(e){let{videoPath:t,telemetryPath:n,targetLabel:a="recording"}=e;await hf({videoPath:t,scriptPath:r??=hp("recording-overlay.swift"),scriptArgs:["--events",n],commandDescription:`Failed to add touch overlays to the ${a}`})}async function hw(e){let{videoPath:t,quality:r,targetLabel:n="recording"}=e;await hf({videoPath:t,scriptPath:a??=hp("recording-resize.swift"),scriptArgs:["--quality",String(r)],commandDescription:`Failed to resize the ${n}`})}function hg(e){return e instanceof Error?e.message:String(e)}function hy(e,t){return e.stderr.trim()||e.stdout.trim()||`${t} exited with code ${e.exitCode}`}async function hv(e){let{recording:t,deps:r,trimStartMs:n,targetLabel:a}=e,i=function(e){var t,r,n;let a,i,{recording:o,trimStartMs:s}=e,u=(a=hd((t={videoPath:o.outPath,events:o.gestureEvents,trimStartMs:s}).videoPath),i={version:1,generatedAt:new Date().toISOString(),events:(r=t.events,(n=t.trimStartMs??0)>0?hc(r.flatMap(e=>{let t=e.tMs-n,r="durationMs"in e?e.durationMs:void 0;return("number"==typeof r?t+r:t)<=0?[]:[{...e,tMs:Math.max(0,t)}]})):hc(r))},l.writeFileSync(a,JSON.stringify(i,null,2)),a);return o.telemetryPath=u,u}({recording:t,trimStartMs:n});if(!t.showTouches)return void eN({level:"debug",phase:"record_stop_overlay_skipped",data:{reason:"hide_touches"}});if(0===t.gestureEvents.length)return void eN({level:"debug",phase:"record_stop_overlay_skipped",data:{reason:"no_gesture_events"}});let o=function(e=process.platform){if("darwin"!==e)return"touch overlay burn-in is only available on macOS hosts; returning raw video plus gesture telemetry"}();if(o){t.overlayWarning??=o;return}try{await e_("record_stop_overlay_export",()=>r.overlayRecordingTouches({videoPath:t.outPath,telemetryPath:i,targetLabel:a}),{targetLabel:a,gestureEventCount:t.gestureEvents.length})}catch(e){t.overlayWarning??=`failed to overlay recording touches: ${hg(e)}`}}async function hI(e,t,r){return await Y(z(e),t,r)}async function hb(e,t){let r=await hI(e,["shell","ps","-o","pid=","-p",t],{allowFailure:!0});return 0===r.exitCode&&r.stdout.split(/\s+/).map(e=>e.trim()).includes(t)}async function hA(e,t){for(let r=0;r<40;r+=1){if(!await hb(e,t))return!0;await e8(250)}return!await hb(e,t)}async function hS(e,t){let r,n=0;for(let a=0;a<20;a+=1){let a=await hI(e,["shell","stat","-c","%s",t],{allowFailure:!0}),i=0===a.exitCode?a.stdout.trim():"";if(i.length>0&&i===r){if((n+=1)>=4)return}else n=0;r=i,await e8(250)}}async function hx(e,t,r){for(let n=0;n<8;n+=1){let a=await hI(e,["shell","stat","-c","%s",t],{allowFailure:!0}),i=0===a.exitCode?Number(a.stdout.trim()):NaN;if(Number.isFinite(i)&&i>0)return!0;if(!await hb(e,r))break;if(n+1>=2)return!0;await e8(250)}return!1}async function h_(e){let t,{deps:r,deviceId:n,remotePath:a,outPath:i}=e;for(let e=0;e<2;e+=1){try{l.rmSync(i,{force:!0})}catch{}let o=z(n),s=await e7(a,i,{allowFailure:!0,device:o});if(0!==s.exitCode)t=hy(s,"adb pull");else{await r.waitForStableFile(i,{pollMs:250,attempts:20});let t=await r.isPlayableVideo(i);if(eN({level:"debug",phase:"record_stop_android_pull_validation",data:{deviceId:n,remotePath:a,outPath:i,attempt:e+1,fileSize:(()=>{try{return l.statSync(i).size}catch{return 0}})(),playable:t}}),t)return;eN({level:"warn",phase:"record_stop_android_invalid_video_retry",data:{deviceId:n,remotePath:a,outPath:i,attempt:e+1}})}e<1&&await e8(750)}return t?`failed to copy recording from device: ${t}`:"failed to copy recording from device: pulled file is not a playable MP4"}async function hN(e){let{deviceId:t,quality:r}=e;if(void 0===r||r>=10)return;let n=await hI(t,["shell","wm","size"],{allowFailure:!0}),a=n.stdout.match(/Override size:\s*(\d+)x(\d+)/)??n.stdout.match(/Physical size:\s*(\d+)x(\d+)/);if(0!==n.exitCode||!a)throw Error(`failed to resolve Android screen size for recording quality: ${hy(n,"adb shell wm size")}`);return{width:hM(Number(a[1]),r),height:hM(Number(a[2]),r)}}function hM(e,t){return Math.max(2,2*Math.round(e*t/10/2))}async function hk(e,t){await hI(e,["shell","rm","-f",t],{allowFailure:!0})}async function hD(e,t){let r=await hI(e,["shell","kill","-9",t],{allowFailure:!0});return eN({level:"warn",phase:"record_stop_android_force_signal",data:{deviceId:e,remotePid:t,exitCode:r.exitCode,stdout:r.stdout.trim(),stderr:r.stderr.trim()}}),!(0!==r.exitCode&&await hb(e,t))&&await hA(e,t)}async function hP(e){var t;let r,n,{device:a,recordingBase:i}=e,o="failed to start recording: Android screenrecord did not begin producing frames";try{r=await hN({deviceId:a.id,quality:i.quality})}catch(e){return cM("COMMAND_FAILED",e instanceof Error?e.message:String(e))}for(let e of(t=Date.now(),n=`agent-device-recording-${t}.mp4`,[`/sdcard/${n}`,`/data/local/tmp/${n}`])){let t=await hI(a.id,["shell",function(e,t){let r=["screenrecord"];return t&&r.push("--size",`${t.width}x${t.height}`),r.push(e),`${r.join(" ")} >/dev/null 2>&1 & echo $!`}(e,r)],{allowFailure:!0});if(0!==t.exitCode){o=`failed to start recording: ${hy(t,"adb shell screenrecord")}`;continue}let n=t.stdout.split(/\r?\n/).map(e=>e.trim()).filter(e=>/^\d+$/.test(e)).at(-1);if(!n){o="failed to start recording: adb did not return a valid Android screenrecord pid",await hk(a.id,e);continue}if(eN({level:"debug",phase:"record_start_android_started",data:{deviceId:a.id,remotePath:e,remotePid:n}}),await hx(a.id,e,n))return{platform:"android",remotePath:e,remotePid:n,...i,startedAt:Date.now()};o="failed to start recording: Android screenrecord did not begin producing frames",await hD(a.id,n),await hk(a.id,e)}return cM("COMMAND_FAILED",o)}async function hO(e){let t,r,{deps:n,device:a,recording:i}=e;eN({level:"debug",phase:"record_stop_android_enter",data:{deviceId:a.id,remotePath:i.remotePath,remotePid:i.remotePid}});let o=await hI(a.id,["shell","kill","-2",i.remotePid],{allowFailure:!0});if(eN({level:"debug",phase:"record_stop_android_signal",data:{deviceId:a.id,remotePath:i.remotePath,remotePid:i.remotePid,exitCode:o.exitCode,stdout:o.stdout.trim(),stderr:o.stderr.trim()}}),0!==o.exitCode?await hb(a.id,i.remotePid)&&!await hD(a.id,i.remotePid)&&(t=`failed to stop recording: ${hy(o,"adb shell kill")}`):await hA(a.id,i.remotePid)||await hD(a.id,i.remotePid)||(t=`failed to stop recording: Android screenrecord pid ${i.remotePid} did not exit`),!t){await hS(a.id,i.remotePath);let e=await h_({deps:n,deviceId:a.id,remotePath:i.remotePath,outPath:i.outPath});if(e)return await s(),cM("COMMAND_FAILED",e);await hv({recording:i,deps:n,targetLabel:"Android recording"})}if(await s(),t)return cM("COMMAND_FAILED",t);if(r)return cM("COMMAND_FAILED",r);return null;async function s(){let e=await hI(a.id,["shell","rm","-f",i.remotePath],{allowFailure:!0});eN({level:"debug",phase:"record_stop_android_cleanup",data:{deviceId:a.id,remotePath:i.remotePath,exitCode:e.exitCode,stdout:e.stdout.trim(),stderr:e.stderr.trim()}}),0===e.exitCode||t||(r=`failed to clean up remote recording: ${hy(e,"adb shell rm")}`)}}function hR(e){let t=e.appBundleId?.trim();return t&&t.length>0?t:void 0}function hE(e,t,r){return{verbose:e.flags?.verbose,logPath:t,traceLogPath:r.trace?.outPath,requestId:e.meta?.requestId}}async function hC(e){let{req:t,activeSession:r,device:n,logPath:a,deps:i}=e,o=hR(r);try{await i.runIosRunnerCommand(n,{command:"recordStop",appBundleId:o},hE(t,a,r))}catch(e){eN({level:"warn",phase:"record_stop_runner_failed",data:{platform:n.platform,kind:n.kind,deviceId:n.id,session:r.name,error:hg(e)}})}}async function hL(e){let{req:t,activeSession:r,device:n,logPath:a,deps:i}=e,o=hR(r);if(o)try{await i.runIosRunnerCommand(n,{command:"snapshot",appBundleId:o,interactiveOnly:!0,compact:!0,depth:1},hE(t,a,r))}catch(e){eN({level:"warn",phase:"record_start_simulator_runner_warm_failed",data:{deviceId:n.id,session:r.name,appBundleId:o,error:hg(e)}})}}async function hT(e){let t,r,{req:n,activeSession:a,sessionStore:i,device:o,logPath:s,deps:l,fpsFlag:u,recordingBase:d,appBundleId:c}=e,p=`agent-device-recording-${Date.now()}.mp4`,f=`tmp/${p}`,m=hE(n,s,a),h=async()=>l.runIosRunnerCommand(o,{command:"recordStart",outPath:p,fps:u,quality:d.quality,appBundleId:c},m);try{let e=await h();t="number"==typeof e.recorderStartUptimeMs?e.recorderStartUptimeMs:void 0,r="number"==typeof e.targetAppReadyUptimeMs?e.targetAppReadyUptimeMs:void 0}catch(n){var w,g;if(!hg(n).toLowerCase().includes("recording already in progress"))return cM("COMMAND_FAILED",`failed to start recording: ${hg(n)}`);eN({level:"warn",phase:"record_start_runner_desynced",data:{platform:o.platform,kind:o.kind,deviceId:o.id,session:a.name,error:hg(n)}});let e=(w=o.id,g=a.name,i.toArray().find(e=>e.name!==g&&"ios"===e.device.platform&&"device"===e.device.kind&&e.device.id===w&&e.recording?.platform==="ios-device-runner"));if(e)return cM("COMMAND_FAILED",`failed to start recording: recording already in progress in session '${e.name}'`);try{await l.runIosRunnerCommand(o,{command:"recordStop",appBundleId:c},m)}catch{}try{let e=await h();t="number"==typeof e.recorderStartUptimeMs?e.recorderStartUptimeMs:void 0,r="number"==typeof e.targetAppReadyUptimeMs?e.targetAppReadyUptimeMs:void 0}catch(e){return cM("COMMAND_FAILED",`failed to start recording: ${hg(e)}`)}}return{platform:"ios-device-runner",remotePath:f,runnerStartedAtUptimeMs:t,targetAppReadyUptimeMs:r,...d}}async function h$(e){let{req:t,activeSession:r,device:n,logPath:a,deps:i,fpsFlag:o,recordingBase:s,appBundleId:l}=e;try{await i.runIosRunnerCommand(n,{command:"recordStart",outPath:s.outPath,fps:o,quality:s.quality,appBundleId:l},hE(t,a,r))}catch(e){return cM("COMMAND_FAILED",`failed to start recording: ${hg(e)}`)}return{platform:"macos-runner",...s}}async function hF(e){let{req:t,activeSession:r,device:n,logPath:a,deps:i,recording:o}=e;await hC({req:t,activeSession:r,device:n,logPath:a,deps:i});let s={stdout:"",stderr:"",exitCode:1};for(let e of n_)if(0===(s=await i.runCmd("xcrun",["devicectl","device","copy","from","--device",n.id,"--source",o.remotePath,"--destination",o.outPath,"--domain-type","appDataContainer","--domain-identifier",e],{allowFailure:!0})).exitCode)break;if(0!==s.exitCode){let e=s.stderr.trim()||s.stdout.trim()||`devicectl exited with code ${s.exitCode}`;return cM("COMMAND_FAILED",`failed to copy recording from device: ${e}`)}let l="number"!=typeof o.runnerStartedAtUptimeMs||"number"!=typeof o.targetAppReadyUptimeMs?0:Math.max(0,o.targetAppReadyUptimeMs-o.runnerStartedAtUptimeMs);return l>0&&await i.trimRecordingStart({videoPath:o.outPath,trimStartMs:l}),await hv({recording:o,deps:i,trimStartMs:l,targetLabel:"iOS recording"}),null}async function hU(e){let{req:t,activeSession:r,device:n,logPath:a,deps:i,recording:o}=e;return await hC({req:t,activeSession:r,device:n,logPath:a,deps:i}),await hv({recording:o,deps:i,targetLabel:"macOS recording"}),null}async function hV(e){let{deps:t,recording:r}=e;r.child.kill("SIGINT");let n=await hG(r.wait,5e3);return n||(await hq(t,r,"SIGINT"),(n=await hG(r.wait,2e3))||(r.child.kill("SIGTERM"),await hq(t,r,"SIGTERM"),n=await hG(r.wait,2e3)))?n:(r.child.kill("SIGKILL"),await hq(t,r,"SIGKILL"),await hG(r.wait,2e3))}async function hG(e,t){return await Promise.race([e,e8(t).then(()=>null)])}async function hq(e,t,r){await hj(e,t,r)||await hB(e,t.outPath,r)}async function hB(e,t,r){let n,a=`simctl.*recordVideo.*${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`;try{n=await e.runCmd("pgrep",["-f",a],{allowFailure:!0})}catch(e){eN({level:"warn",phase:"record_stop_ios_simulator_pgrep_failed",data:{outPath:t,signal:r,error:hg(e)}});return}let i=hW(hK(n.stdout)),o=hz(i,r);eN({level:o>0?"warn":"debug",phase:"record_stop_ios_simulator_signal_recorders",data:{outPath:t,signal:r,matchedPidCount:i.length,signaled:o,pgrepExitCode:n.exitCode}})}async function hj(e,t,r){let n=t.recorderPid??t.child.pid;if("number"!=typeof n||!Number.isInteger(n)||n<=0)return eN({level:"debug",phase:"record_stop_ios_simulator_owned_recorder_unavailable",data:{outPath:t.outPath,signal:r,reason:"missing_recorder_pid"}}),!1;let a=await hH(e,n,t.outPath,r),i=hW([n,...a.pids]),o=hz(i,r);return eN({level:o>0?"warn":"debug",phase:"record_stop_ios_simulator_signal_owned_recorder",data:{outPath:t.outPath,signal:r,recorderPid:n,childPidCount:a.pids.length,matchedPidCount:i.length,signaled:o,pgrepExitCode:a.exitCode}}),o>0}async function hH(e,t,r,n){let a;try{a=await e.runCmd("pgrep",["-P",String(t)],{allowFailure:!0})}catch(e){return eN({level:"warn",phase:"record_stop_ios_simulator_owned_pgrep_failed",data:{outPath:r,signal:n,parentPid:t,error:hg(e)}}),{pids:[]}}return{pids:hK(a.stdout),exitCode:a.exitCode}}function hW(e){return Array.from(new Set(e)).filter(e=>Number.isInteger(e)&&e>0&&e!==process.pid)}function hz(e,t){let r=0;for(let n of e)try{process.kill(n,t),r+=1}catch{}return r}function hK(e){return e.split(/\s+/).map(e=>Number(e)).filter(e=>Number.isInteger(e)&&e>0)}async function hJ(e){"ios"!==e.platform||0!==e.gestureEvents.length&&await e8(350)}async function hX(e){for(let t=0;t<2;t+=1){try{if(l.statSync(e).size>0)return Date.now()}catch{}if(t+1>=2)break;await e8(250)}return Date.now()}async function hY(e){let t,r,{req:n,activeSession:a,device:i,logPath:o,deps:s,recordingBase:l,resolvedOut:u}=e;l.showTouches&&await hL({req:n,activeSession:a,device:i,logPath:o,deps:s});let{child:d,wait:c}=s.startIosSimulatorRecording({device:i,outPath:u}),p=await hX(u);if(l.showTouches)try{let e=Date.now(),l=await s.runIosRunnerCommand(i,{command:"uptime",appBundleId:hR(a)},hE(n,o,a)),u=Date.now();t=Math.round((e+u)/2),r="number"==typeof l.currentUptimeMs?l.currentUptimeMs:void 0}catch{}return{platform:"ios",child:d,wait:c,...l,recorderPid:d.pid,startedAt:p,gestureClockOriginAtMs:void 0===r?void 0:t,gestureClockOriginUptimeMs:r}}async function hZ(e){let t,{req:r,sessionName:n,sessionStore:a,activeSession:i,device:o,logPath:s,deps:u}=e;if(i.recording)return cM("INVALID_ARGS","recording already in progress");let d=r.flags?.fps,c=r.flags?.quality;if(void 0!==d&&(!Number.isInteger(d)||d<1||d>120))return cM("INVALID_ARGS","fps must be an integer between 1 and 120");if(void 0!==c&&(!Number.isInteger(c)||c<5||c>10))return cM("INVALID_ARGS","quality must be an integer between 5 and 10");if(!cY("record",o))return cM("UNSUPPORTED_OPERATION","record is not supported on this device");let p=r.positionals?.[1]??`./recording-${Date.now()}.mp4`,m=aq.expandHome(p,r.meta?.cwd),h={outPath:m,clientOutPath:r.meta?.clientArtifactPaths?.outPath,startedAt:Date.now(),quality:r.flags?.quality,showTouches:r.flags?.hideTouches!==!0,gestureEvents:[]};if(l.mkdirSync(f.dirname(m),{recursive:!0}),l.rmSync(m,{force:!0}),"ios"===o.platform&&"device"===o.kind){let e=hR(i);if(!e)return cM("INVALID_ARGS","record on physical iOS devices requires an active app session; run open <app> first");t=await hT({req:r,activeSession:i,sessionStore:a,device:o,logPath:s,deps:u,fpsFlag:d,recordingBase:h,appBundleId:e})}else if("macos"===o.platform){let e=hR(i);if(!e)return cM("INVALID_ARGS","record on macOS requires an active app session; run open <app> first");t=await h$({req:r,activeSession:i,device:o,logPath:s,deps:u,fpsFlag:d,recordingBase:h,appBundleId:e})}else t="ios"===o.platform?await hY({req:r,activeSession:i,device:o,logPath:s,deps:u,recordingBase:h,resolvedOut:m}):await hP({device:o,recordingBase:h});return"ok"in t?t:(i.recording=t,a.set(n,i),a.recordAction(i,{command:r.command,positionals:r.positionals??[],flags:r.flags??{},result:{action:"start",showTouches:t.showTouches}}),{ok:!0,data:{recording:"started",outPath:t.clientOutPath??p,showTouches:t.showTouches}})}async function hQ(e){let{deps:t,device:r,recording:n}=e;if("android"===n.platform)return await hO({deps:t,device:r,recording:n});await e_("record_stop_tail_settle",()=>t.waitForRecordingTail(n),{platform:n.platform,gestureEventCount:n.gestureEvents.length});let a=await e_("record_stop_ios_simulator_process",()=>hV({deps:t,recording:n}),{outPath:n.outPath});if(!a)return cM("COMMAND_FAILED","failed to stop recording: simctl recordVideo did not exit after 5000ms and forced cleanup");if(0!==a.exitCode)return cM("COMMAND_FAILED",`failed to stop recording: ${hy(a,"simctl recordVideo")}`);if(await e_("record_stop_video_stable",()=>t.waitForStableFile(n.outPath,{pollMs:150,attempts:12}),{outPath:n.outPath}),!await e_("record_stop_video_playable_check",()=>t.isPlayableVideo(n.outPath),{outPath:n.outPath}))return cM("COMMAND_FAILED",`failed to stop recording: ${n.outPath} was not finalized into a playable video`);if(void 0!==n.quality&&n.quality<10){let e=n.quality;try{await e_("record_stop_resize",()=>t.resizeRecording({videoPath:n.outPath,quality:e,targetLabel:"iOS recording"}),{outPath:n.outPath,quality:e})}catch(e){n.overlayWarning=`failed to resize recording: ${hg(e)}`}}return await e_("record_stop_finalize_overlay",()=>hv({recording:n,deps:t,targetLabel:"iOS recording"}),{outPath:n.outPath,showTouches:n.showTouches,gestureEventCount:n.gestureEvents.length}),null}async function h0(e){var t;let r,{req:n,activeSession:a,device:i,logPath:o,deps:s}=e;if(!a.recording)return cM("INVALID_ARGS","no active recording");let l=a.recording,u=l.invalidatedReason;a.recording=void 0;let d="ios-device-runner"===l.platform?await hF({req:n,activeSession:a,device:i,logPath:o,deps:s,recording:l}):"macos-runner"===l.platform?await hU({req:n,activeSession:a,device:i,logPath:o,deps:s,recording:l}):await hQ({deps:s,device:i,recording:l});if(d)return d;if(u&&"ios"===l.platform&&l.showTouches)l.overlayWarning??=`overlay unavailable: ${u}`;else if(u)return cM("COMMAND_FAILED",u);return r=[{field:"outPath",path:(t=l).outPath,localPath:t.clientOutPath,fileName:f.basename(t.clientOutPath??t.outPath)}],t.telemetryPath&&r.push({field:"telemetryPath",path:t.telemetryPath,localPath:function(e){if(e.clientOutPath)return hd(e.clientOutPath)}(t),fileName:f.basename(t.telemetryPath)}),{ok:!0,data:{recording:"stopped",outPath:t.outPath,telemetryPath:t.telemetryPath,artifacts:r,showTouches:t.showTouches,overlayWarning:t.overlayWarning}}}async function h1(e){let{req:t,sessionName:r,sessionStore:n,logPath:a}=e,i={runCmd:async(e,t,r)=>"xcrun"===e?await rR(t,r):await R(e,t,r),startIosSimulatorRecording:e=>cT.resolve(void 0).startIosSimulatorRecording(e),runIosRunnerCommand:am,waitForRecordingTail:hJ,waitForStableFile:ha,isPlayableVideo:hi,trimRecordingStart:hm,resizeRecording:hw,overlayRecordingTouches:hh},o=n.get(r),s=o?.device??await oO(t.flags??{});o||await o6(s);let l=o??{name:r,device:s,createdAt:Date.now(),actions:[]},u=(t.positionals?.[0]??"").toLowerCase();if(!["start","stop"].includes(u))return cM("INVALID_ARGS","record requires start|stop");if("start"===u)return hZ({req:t,sessionName:r,sessionStore:n,activeSession:l,device:s,logPath:a,deps:i});let d=await h0({req:t,activeSession:l,device:s,logPath:a,deps:i});return d.ok&&n.recordAction(l,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:{action:"stop",outPath:d.data?.outPath,showTouches:d.data?.showTouches}}),d}async function h2(e){let{req:t,sessionName:r,sessionStore:n,logPath:a}=e,i=t.command;if("record"===i)return h1({req:t,sessionName:r,sessionStore:n,logPath:a});if("trace"===i){let e=(t.positionals?.[0]??"").toLowerCase();if(!["start","stop"].includes(e))return cM("INVALID_ARGS","trace requires start|stop");let a=n.get(r);if(!a)return cM("SESSION_NOT_FOUND","No active session");if("start"===e){if(a.trace)return cM("INVALID_ARGS","trace already in progress");let e=t.positionals?.[1]??n.defaultTracePath(a),r=aq.expandHome(e);return l.mkdirSync(f.dirname(r),{recursive:!0}),l.appendFileSync(r,""),a.trace={outPath:r,startedAt:Date.now()},n.recordAction(a,{command:i,positionals:t.positionals??[],flags:t.flags??{},result:{action:"start",outPath:r}}),{ok:!0,data:{trace:"started",outPath:r}}}if(!a.trace)return cM("INVALID_ARGS","no active trace");let o=a.trace.outPath;if(t.positionals?.[1]){let e=aq.expandHome(t.positionals[1]);l.mkdirSync(f.dirname(e),{recursive:!0}),l.existsSync(o)?l.renameSync(o,e):l.appendFileSync(e,""),o=e}return a.trace=void 0,n.recordAction(a,{command:i,positionals:t.positionals??[],flags:t.flags??{},result:{action:"stop",outPath:o}}),{ok:!0,data:{trace:"stopped",outPath:o}}}return null}let h3=new Map;async function h5(e){let t=await A.mkdtemp(f.join(c.tmpdir(),"agent-device-materialized-"));try{let r=await h6(e.installablePath,f.join(t,"installable")),n=e.archivePath?await h6(e.archivePath,f.join(t,"archive")):void 0,a=o.randomUUID(),i=e.ttlMs??9e5,s=Date.now()+i,l=setTimeout(()=>{h4(a)},i);return h3.set(a,{rootPath:t,installablePath:r,archivePath:n,tenantId:e.tenantId,sessionName:e.sessionName,expiresAt:s,timer:l}),{materializationId:a,installablePath:r,...n?{archivePath:n}:{},expiresAt:new Date(s).toISOString()}}catch(e){throw await A.rm(t,{recursive:!0,force:!0}),e}}async function h4(e,t){let r=h3.get(e);if(!r)throw new D("INVALID_ARGS",`Materialized paths not found: ${e}`);if(r.tenantId&&r.tenantId!==t)throw new D("UNAUTHORIZED","Materialized paths belong to a different tenant");clearTimeout(r.timer),h3.delete(e),await A.rm(r.rootPath,{recursive:!0,force:!0})}async function h8(e){let t=Array.from(h3.entries()).filter(([,t])=>t.sessionName===e).map(([e])=>e);await Promise.all(t.map(async e=>{await h4(e)}))}async function h6(e,t){let r=await A.stat(e);await A.mkdir(t,{recursive:!0});let n=f.join(t,f.basename(e));return r.isDirectory()?await A.cp(e,n,{recursive:!0}):await A.copyFile(e,n),n}async function h9(e){var t;let r="ios"===(t=e.flags?.platform)||"android"===t?t:void 0;if(e.session){if(r&&e.session.device.platform!==r)throw new D("INVALID_ARGS",`install_from_source requested platform ${r}, but session is bound to ${e.session.device.platform}`);return await o6(e.session.device),e.session.device}if(!r)throw new D("INVALID_ARGS",'install_from_source requires platform "ios" or "android" when no session is provided');let n=await oO(e.flags??{});return await o6(n),n}async function h7(e){let{prepared:t,retention:r,req:n,session:a,sessionName:i}=e;if(r.enabled)return await h5({archivePath:t.archivePath,installablePath:t.installablePath,tenantId:n.meta?.tenantId,sessionName:a?i:void 0,ttlMs:r.ttlMs})}function we(e){return e?{...e.archivePath?{archivePath:e.archivePath}:{},installablePath:e.installablePath,materializationId:e.materializationId,materializationExpiresAt:e.expiresAt}:{}}async function wt(e){let{req:t,sessionName:r,sessionStore:n}=e,a=n.get(r);try{let e,i,o=(e=function(e){let t=e.meta?.installSource;if(!t)throw new D("INVALID_ARGS","install_from_source requires a source payload");switch(t.kind){case"url":if(!t.url||0===t.url.trim().length)throw new D("INVALID_ARGS","install_from_source url source requires a non-empty url");return t;case"path":if(!t.path||0===t.path.trim().length)throw new D("INVALID_ARGS","install_from_source path source requires a non-empty path");return t;case"github-actions-artifact":throw new D("UNSUPPORTED_OPERATION","install_from_source github-actions-artifact sources require a compatible remote daemon");default:throw new D("UNSUPPORTED_OPERATION",`install_from_source ${String(t.kind)} sources require a compatible remote daemon`)}}(t),(i=t.meta?.uploadedArtifactId)&&"path"===e.kind?{source:{kind:"path",path:iE(i,t.meta?.tenantId)},cleanup:()=>{iC(i)}}:{source:e,cleanup:()=>{}}),s=function(e){let t=e.meta?.retainMaterializedPaths===!0,r=e.meta?.materializedPathRetentionMs;if(!t)return{enabled:!1};if(void 0!==r&&r<=0)throw new D("INVALID_ARGS","install_from_source retentionMs must be a positive integer");return{enabled:!0,ttlMs:r}}(t),l=await h9({session:a,flags:t.flags});if(!cY("install",l))return cM("UNSUPPORTED_OPERATION","install_from_source is not supported on this device");let u=rw(t.meta?.requestId),d=async(e,i)=>{let l;try{var u;l=await h7({prepared:e,retention:s,req:t,session:a,sessionName:r});let o=await i(l),d=eV(o,(u=o,`Installed: ${e3(u)}`));return!function(e){let{session:t,sessionStore:r,req:n,data:a}=e;t&&r.recordAction(t,{command:"install_source",positionals:[],flags:n.flags??{},result:a})}({session:a,sessionStore:n,req:t,data:d}),{ok:!0,data:d}}catch(e){throw l&&await h4(l.materializationId,t.meta?.tenantId).catch(()=>{}),e}finally{await e.cleanup(),o.cleanup()}};if("ios"===l.platform){let{installIosInstallablePath:e}=await Promise.resolve(ra),{prepareIosInstallArtifact:t}=await Promise.resolve(ri),r=await t(o.source,{signal:u});return await d(r,async t=>{if(await e(l,r.installablePath),!r.bundleId)throw new D("COMMAND_FAILED","Installed iOS app identity could not be resolved from the artifact");return{...we(t),bundleId:r.bundleId,...r.appName?{appName:r.appName}:{},launchTarget:r.bundleId}})}let{prepareAndroidInstallArtifact:c}=await import("../1769.js"),{installAndroidInstallablePathAndResolvePackageName:p}=await import("../1769.js"),f=await c(o.source,{signal:u});return await d(f,async e=>{let t=await p(l,f.installablePath,f.packageName);if(!t)throw new D("COMMAND_FAILED","Installed Android app identity could not be resolved from the artifact or device state");let{inferAndroidAppName:r}=await import("../1769.js"),n=r(t);return{...we(e),packageName:t,...n?{appName:n}:{},launchTarget:t}})}catch(e){return{ok:!1,error:k(e)}}}async function wr(e){let{req:t}=e;try{let e=t.meta?.materializationId?.trim();if(!e)throw new D("INVALID_ARGS","release_materialized_paths requires a materializationId");return await h4(e,t.meta?.tenantId),{ok:!0,data:{released:!0,materializationId:e}}}catch(e){return{ok:!1,error:k(e)}}}let wn="shared_prefs/ReactNativeDevPrefs.xml",wa="debug_http_host",wi="dev_server_https",wo="RCT_jsLocation",ws="RCT_packager_scheme",wl="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.",wu='<?xml version="1.0" encoding="utf-8" standalone="yes" ?>\n<map>\n</map>\n';function wd(e){return void 0!==eg(e)}async function wc(e){let{device:t,appId:r,runtime:n}=e;if(!r)return;let a=eg(n);if(a){if("android"===t.platform)return void await wf(t,r,a);"ios"===t.platform&&"simulator"===t.kind&&await wg(t,r,a)}}async function wp(e){let{device:t,appId:r}=e;if(r){if("android"===t.platform)return void await wm(t,r);"ios"===t.platform&&"simulator"===t.kind&&await wy(t,r)}}async function wf(e,t,r){var n,a,i,o,s,l;let u,d;wA(t);let c=(n=await wh(e,t),a=wa,i=`${r.host}:${r.port}`,u=` <string name="${wS(a)}">${wS(i)}</string>`,wI(wb(n,a),u));o=c,s=wi,l="https"===r.scheme,d=` <boolean name="${wS(s)}" value="${l?"true":"false"}" />`,c=wI(wb(o,s),d),await ww(e,t,c)}async function wm(e,t){wA(t);let r=await wh(e,t),n=wb(r,wa),a=wb(n,wi);a!==r&&await ww(e,t,a)}async function wh(e,t){let r=await Y(e,["shell","run-as",t,"cat",wn],{allowFailure:!0});return 0!==r.exitCode?wu:wv(r.stdout)}async function ww(e,t,r){let n=["shell","run-as",t,"id"],a=await Y(e,n,{allowFailure:!0});if(0!==a.exitCode){let e=wx(a.stdout,a.stderr);throw new D("COMMAND_FAILED",e?`Failed to access Android app sandbox for ${t}`:`Failed to probe Android app sandbox for ${t}`,{package:t,cmd:"adb",args:n,stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode,hint:e?wl:"adb shell run-as probe failed. Check adb connectivity and that the device is reachable. Inspect stderr/details for more information."})}try{await Y(e,["shell","run-as",t,"mkdir","-p","shared_prefs"]),await Y(e,["shell","run-as",t,"tee",wn],{stdin:r.trimEnd()})}catch(n){let e=M(n);if("TOOL_MISSING"===e.code)throw e;let r=wx("string"==typeof e.details?.stdout?e.details.stdout:"","string"==typeof e.details?.stderr?e.details.stderr:"");throw new D("COMMAND_FAILED",r?`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:r?wl:"adb run-as succeeded, but writing ReactNativeDevPrefs.xml failed. Inspect stderr/details for the failing shell command."},e)}}async function wg(e,t,r){await rR(rT(e,["spawn",e.id,"defaults","write",t,wo,"-string",`${r.host}:${r.port}`])),await rR(rT(e,["spawn",e.id,"defaults","write",t,ws,"-string",r.scheme]))}async function wy(e,t){await rR(rT(e,["spawn",e.id,"defaults","delete",t,wo]),{allowFailure:!0}),await rR(rT(e,["spawn",e.id,"defaults","delete",t,ws]),{allowFailure:!0})}function wv(e){let t=e.trim();return t.includes("<map")&&t.includes("</map>")?`${t}
60
+ `:wu}function wI(e,t){return wv(e).replace("</map>",`${t}
61
+ </map>`)}function wb(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return wv(e).replace(RegExp(`^\\s*<string name="${r}">[\\s\\S]*?<\\/string>\\n?`,"m"),"").replace(RegExp(`^\\s*<boolean name="${r}" value="(?:true|false)"\\s*\\/?>\\n?`,"m"),"")}function wA(e){if("binary"!==ed(e))return;let t=X(e);throw new D("INVALID_ARGS",t,{package:e,hint:t})}function wS(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function wx(e,t){let r=`${e}
62
+ ${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=>r.includes(e))}let w_=["platform","metroHost","metroPort","bundleUrl","launchUrl"];function wN(e){return e?[e.metroHost,e.metroPort,e.bundleUrl,e.launchUrl].filter(e=>void 0!==e&&""!==e).length:0}function wM(e,t){if(void 0!==e){if("string"!=typeof e)throw new D("INVALID_ARGS",`Invalid open runtime ${t}: expected string.`);return eh(e)}}function wk(e){if(void 0!==e){if(!Number.isInteger(e)||e<1||e>65535)throw new D("INVALID_ARGS",`Invalid runtime metroPort: ${String(e)}. Use an integer between 1 and 65535.`);return e}}function wD(e){if("ios"===e||"android"===e)return e}async function wP(e){let{replacedStoredRuntime:t,previousRuntime:r,runtime:n,session:a}=e;!t||!a?.appBundleId||!wd(r)||wd(n)||await wp({device:a.device,appId:a.appBundleId})}async function wO(e){var t,r;let{req:n,sessionName:a,sessionStore:i}=e,o=(n.positionals?.[0]??"show").toLowerCase(),s=i.get(a),l=i.getRuntimeHints(a);if(!["set","show","clear"].includes(o))return cM("INVALID_ARGS","runtime requires set, show, or clear");if("clear"===o){wd(l)&&s?.appBundleId&&await wp({device:s.device,appId:s.appBundleId});let e=i.clearRuntimeHints(a);return{ok:!0,data:{session:a,cleared:e}}}if("show"===o)return{ok:!0,data:{session:a,configured:!!l,runtime:l}};let u=wD(n.flags?.platform??l?.platform??s?.device.platform);if(!u)return cM("INVALID_ARGS","runtime set only supports iOS and Android sessions. Pass --platform ios|android or open an iOS/Android session first.");if(s&&s.device.platform!==u)return cM("INVALID_ARGS",`runtime set targets ${u}, but session "${a}" is already bound to ${s.device.platform}.`);let d={platform:(t=n.flags,r={platform:u,metroHost:eh(t?.metroHost),metroPort:wk(t?.metroPort),bundleUrl:eh(t?.bundleUrl),launchUrl:eh(t?.launchUrl)}).platform??l?.platform,metroHost:r.metroHost??l?.metroHost,metroPort:r.metroPort??l?.metroPort,bundleUrl:r.bundleUrl??l?.bundleUrl,launchUrl:r.launchUrl??l?.launchUrl};return 0===wN(d)?cM("INVALID_ARGS","runtime set requires at least one hint such as --metro-host, --metro-port, --bundle-url, or --launch-url."):(i.setRuntimeHints(a,d),{ok:!0,data:{session:a,configured:!0,runtime:d}})}let wR="open-command-roundtrip",wE="Not implemented for this platform in this release.",wC=new Set(["app","desktop","frontmost-app"]);async function wL(e){if("app"===e||"desktop"===e||"menubar"===e)return{};let t=await l5();return{appBundleId:t.bundleId,appName:t.appName}}function wT(e){let t=e.replaceAll(",","").match(/^-?\d+(?:\.\d+)?/);if(!t)return null;let r=Number(t[0]);return Number.isFinite(r)?r:null}function w$(e){return Math.round(10*e)/10}function wF(e){return Math.round(10*e)/10}let wU="adb-shell-dumpsys-gfxinfo-framestats";function wV(e,t,r){let n=t.get(r);if(void 0===n)return null;let a=Number(e[n]);return Number.isFinite(a)?a:null}function wG(e){return 0===e.length?{}:{firstFrameNs:Math.min(...e.map(e=>e.intendedVsyncNs)),lastFrameNs:Math.max(...e.map(e=>e.frameCompletedNs))}}function wq(e,t){if(void 0!==e&&void 0!==t)return Math.max(0,Math.round((t-e)/1e6))}function wB(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=e.match(RegExp(`^\\s*${r}:\\s*([0-9][0-9,]*)`,"im"));if(!n)return;let a=n[1];return void 0===a?void 0:wT(a)??void 0}async function wj(e,t,r={}){var n,a,i,o,s,l,u,d;let c=tn(e,r.adb);try{let u,d,p,f,m,h,w,g,y,v,I,b=(n=(await c(["shell","dumpsys","gfxinfo",t,"framestats"],{timeoutMs:15e3})).stdout,a=new Date().toISOString(),function(e,t){if(/no process found for:/i.test(e))throw new D("COMMAND_FAILED",`Android gfxinfo did not find a running process for ${t}`,{metric:"fps",package:t,hint:"Run open <app> for this session again to ensure the Android app is active, then retry perf after the interaction you want to inspect."})}(n,t),p=function(e){let t=e.split(/\nProfile data in ms:\n/i)[0]??"",r=wB(t,"Total frames rendered"),n=t.match(/^\s*Janky frames:\s*([0-9][0-9,]*)\s*\(([0-9.]+)%\)/im);if(void 0===r||!n)return;let a=n[1],i=n[2];if(void 0===a||void 0===i)return;let o=wT(a)??void 0,s=Number(i);if(void 0===o||!Number.isFinite(s)||r<0)return;let l=wB(t,"Uptime"),u=wB(t,"Stats since");return{droppedFramePercent:w$(s),droppedFrameCount:o,totalFrameCount:r,sampleWindowMs:function(e){let{uptimeMs:t,statsSinceNs:r}=e;if(void 0===t||void 0===r)return;let n=t-Math.round(r/1e6);return n>=0?n:void 0}({uptimeMs:l,statsSinceNs:u}),uptimeMs:l,statsSinceNs:u}}(n),f=function(e){let t=[],r=null;for(let a of e.split("\n")){var n;let e=a.trim();if(0===e.length||"---PROFILEDATA---"===e)continue;let i=e.split(",").map(e=>e.trim());if((n=i).includes("IntendedVsync")&&n.includes("FrameCompleted")){r=new Map(i.map((e,t)=>[e,t]));continue}let o=function(e,t){if(!t||e.length<t.size)return;let r=wV(e,t,"Flags"),n=wV(e,t,"IntendedVsync"),a=wV(e,t,"FrameCompleted");if(0===r&&null!==n&&null!==a&&!(n<=0)&&!(a<=n))return{intendedVsyncNs:n,frameCompletedNs:a,durationNs:a-n}}(i,r);o&&t.push(o)}return t.sort((e,t)=>e.intendedVsyncNs-t.intendedVsyncNs)}(n),m=function(e,t,r){let n=function(e){var t;let r=(t=e.map(e=>e.intendedVsyncNs),[...new Set(t.filter(e=>Number.isFinite(e)))].sort((e,t)=>e-t)),n=[];for(let e=1;e<r.length;e+=1){let t=r[e]-r[e-1];t>=4e6&&t<=5e7&&n.push(t)}if(0!==n.length){let e,t;return e=[...n].sort((e,t)=>e-t),t=Math.floor(e.length/2),e.length%2==1?e[t]:(e[t-1]+e[t])/2}}(e);if(t||0!==e.length||function(e){throw new D("COMMAND_FAILED",`Failed to parse Android framestats output for ${e}`,{metric:"fps",package:e,hint:"Retry perf after exercising the app screen. If the problem persists, capture adb shell dumpsys gfxinfo <package> framestats output for debugging."})}(r),t||void 0!==n)return n;throw new D("COMMAND_FAILED",`Failed to infer Android frame deadline from framestats output for ${r}`,{metric:"fps",package:r,hint:"Retry perf after a longer interaction window so consecutive Android frame timestamps are available."})}(f,p,t),h=Date.parse(a),w=function(e){let{frames:t,measuredAtMs:r,summary:n}=e,a=wG(t),i=n?.statsSinceNs,o=i??a.firstFrameNs,s=wq(o,a.lastFrameNs),l=n?.sampleWindowMs??s;if(!Number.isFinite(r)||n?.uptimeMs===void 0||void 0===o)return{sampleWindowMs:l,windowStartNs:o};let u=r-n.uptimeMs;return{sampleWindowMs:l,windowStartNs:o,windowStartedAt:new Date(u+o/1e6).toISOString(),windowEndedAt:function(e){let{deviceBootWallClockMs:t,measuredAtMs:r,summaryStartNs:n,lastFrameNs:a}=e;return void 0!==n?new Date(r).toISOString():void 0===a?void 0:new Date(t+a/1e6).toISOString()}({deviceBootWallClockMs:u,measuredAtMs:r,summaryStartNs:i,lastFrameNs:a.lastFrameNs}),timestampSource:"estimated-from-device-uptime"}}({frames:f,measuredAtMs:h,summary:p}),g=function(e){let{frames:t,frameDeadlineNs:r,summaryDroppedFrameCount:n}=e;return void 0!==n?n<=0?[]:[...t].sort((e,t)=>t.durationNs-e.durationNs).slice(0,n).sort((e,t)=>e.intendedVsyncNs-t.intendedVsyncNs):void 0===r?[]:t.filter(e=>e.durationNs>r)}({frames:f,frameDeadlineNs:m,summaryDroppedFrameCount:p?.droppedFrameCount}),y=p?.sampleWindowMs??w.sampleWindowMs??function(e){if(0===e.length)return;let t=wG(e);return wq(t.firstFrameNs,t.lastFrameNs)}(f),i=p,o=f,s=g,u=i?.totalFrameCount??o.length,d=i?.droppedFrameCount??s.length,v={totalFrameCount:u,droppedFrameCount:d,droppedFramePercent:i?.droppedFramePercent??(u>0?w$(d/u*100):0)},I=function(e){let{droppedFrames:t,timing:r,measuredAtMs:n,summary:a}=e;if(0===t.length)return;let i=function(e){let{frames:t,windowStartNs:r,measuredAtMs:n,uptimeMs:a}=e;if(0===t.length||void 0===r)return[];let i=[],o=[];for(let e of t){let t=o.at(-1);if(!t||e.intendedVsyncNs-t.frameCompletedNs<=5e8){o.push(e);continue}i.push(o),o=[e]}return o.length>0&&i.push(o),i.map(e=>(function(e){let{frames:t,windowStartNs:r,measuredAtMs:n,uptimeMs:a}=e,i=Math.min(...t.map(e=>e.intendedVsyncNs)),o=Math.max(...t.map(e=>e.frameCompletedNs)),s=Math.max(0,Math.round((i-r)/1e6)),l=Math.max(s,Math.round((o-r)/1e6)),u=void 0!==a&&Number.isFinite(n)?n-a:void 0;return{startOffsetMs:s,endOffsetMs:l,startAt:void 0===u?void 0:new Date(u+i/1e6).toISOString(),endAt:void 0===u?void 0:new Date(u+o/1e6).toISOString(),missedDeadlineFrameCount:t.length,worstFrameMs:wF(Math.max(...t.map(e=>e.durationNs))/1e6)}})({frames:e,windowStartNs:r,measuredAtMs:n,uptimeMs:a})).sort((e,t)=>t.missedDeadlineFrameCount-e.missedDeadlineFrameCount||t.worstFrameMs-e.worstFrameMs).slice(0,3).sort((e,t)=>e.startOffsetMs-t.startOffsetMs)}({frames:t,windowStartNs:r.windowStartNs,measuredAtMs:n,uptimeMs:a?.uptimeMs});return i.length>0?i:void 0}({droppedFrames:g,timing:w,measuredAtMs:h,summary:p}),{...v,sampleWindowMs:y,...(l=m,{frameDeadlineMs:void 0===l?void 0:wF(l/1e6),refreshRateHz:void 0===l?void 0:wF(1e9/l)}),windowStartedAt:w.windowStartedAt,windowEndedAt:w.windowEndedAt,timestampSource:w.timestampSource,measuredAt:a,method:wU,source:p?"android-gfxinfo-summary":"framestats-rows",worstWindows:I&&I.length>0?I:void 0});return await wH(e,t,r),b}catch(e){throw u=t,(d=e)instanceof D?new D(d.code,d.message,{...d.details??{},metric:"fps",package:u},d):new D("COMMAND_FAILED",`Failed to sample Android fps for ${u}`,{metric:"fps",package:u},d)}}async function wH(e,t,r={}){let n=tn(e,r.adb);try{await n(["shell","dumpsys","gfxinfo",t,"reset"],{allowFailure:!0,timeoutMs:3e3})}catch{}}let wW="adb-shell-dumpsys-cpuinfo",wz="adb-shell-dumpsys-meminfo";async function wK(e,t,r={}){let n=tn(e,r.adb);try{let e=await n(["shell","dumpsys","cpuinfo"],{timeoutMs:15e3});return function(e,t,r){let n=new Set,a=0;for(let r of eG(e)){var i,o;let e=r.match(/^([0-9]+(?:\.[0-9]+)?)%\s+\d+\/([^\s]+):\s/);if(!e)continue;let s=e[1],l=e[2];if(void 0===s||void 0===l)continue;let u=Number(s);Number.isFinite(u)&&(i=l,o=t,i===o||i.startsWith(`${o}:`))&&(a+=u,n.add(l))}return{usagePercent:w$(a),measuredAt:r,method:wW,matchedProcesses:[...n]}}(e.stdout,t,new Date().toISOString())}catch(e){throw wX("cpu",t,e)}}async function wJ(e,t,r={}){let n=tn(e,r.adb);try{let e=await n(["shell","dumpsys","meminfo",t],{timeoutMs:15e3});return function(e,t,r){if(/no process found for:/i.test(e))throw new D("COMMAND_FAILED",`Android meminfo did not find a running process for ${t}`,{metric:"memory",package:t,hint:"Run open <app> for this session again to ensure the Android app is active, then retry perf."});let n=wY(e,"TOTAL PSS")??function(e){for(let t of e.split("\n")){let e=t.trim();if(!/^TOTAL\b(?!\s+PSS:)/.test(e))continue;let r=e.split(/\s+/).slice(1).find(e=>null!==wT(e));if(!r)break;return wT(r)??void 0}}(e);if(void 0===n)throw new D("COMMAND_FAILED",`Failed to parse Android meminfo output for ${t}`,{metric:"memory",package:t,hint:"Retry perf after reopening the app session. If the problem persists, capture adb shell dumpsys meminfo output for debugging."});return{totalPssKb:n,totalRssKb:wY(e,"TOTAL RSS"),measuredAt:r,method:wz}}(e.stdout,t,new Date().toISOString())}catch(e){throw wX("memory",t,e)}}function wX(e,t,r){return r instanceof D?new D(r.code,r.message,{...r.details??{},metric:e,package:t},r):new D("COMMAND_FAILED",`Failed to sample Android ${e} for ${t}`,{metric:e,package:t},r)}function wY(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=e.match(RegExp(`${r}:\\s*([0-9][0-9,]*)`,"i"));if(!n)return;let a=n[1];return void 0===a?void 0:wT(a)??void 0}async function wZ(e,t,r){if(("ios"===e.platform||"macos"===e.platform)&&t)return ef(t)?"macos"===e.platform?void 0:"device"===e.kind?ee(r,t):void 0:await wQ(e,t)}async function wQ(e,t){try{let{resolveIosApp:r}=await Promise.resolve(ra);return await r(e,t)}catch{return}}async function w0(e,t){if(!("android"!==e.platform||!t||ef(t)))try{let{resolveAndroidApp:r}=await import("../1769.js"),n=await r(e,t);return"package"===n.type?n.value:void 0}catch{return}}async function w1(e,t,r){if(r||"android"!==e.platform||!t||!ef(t))return r;try{let{getAndroidAppState:t}=await import("../1769.js"),n=await t(e);return n.package?.trim()||r}catch{return r}}async function w2(e,t,r,n){return await wZ(e,t,r)??await n(e,t)??("android"===e.platform&&t&&ef(t)?r:void 0)}function w3(e){return cM("INVALID_ARGS",e)}function w5(e,t,r,n){try{return function(e){let{device:t,surfaceFlag:r,openTarget:n,existingSurface:a}=e;if(("macos"===t.platform||"linux"===t.platform)&&!r)return a??"app";if("linux"===t.platform){if(!r)return"app";let e=th(r);if(!wC.has(e))throw new D("INVALID_ARGS",`Linux supports --surface app, desktop, and frontmost-app (got "${r}")`);if("app"!==e&&n)throw new D("INVALID_ARGS",`open --surface ${e} does not accept an app target`);return e}if("macos"!==t.platform){if(r)throw new D("INVALID_ARGS","surface is only supported on macOS and Linux");return"app"}let i=r?th(r):"app";if("app"!==i&&"menubar"!==i&&n)throw new D("INVALID_ARGS",`open --surface ${i} does not accept an app target`);return i}({device:e,surfaceFlag:t,openTarget:r,existingSurface:n})}catch(e){return cM(e instanceof D?e.code:"INVALID_ARGS",String(e.message))}}function w4(e){let{shouldRelaunch:t,openTarget:r,surface:n,device:a}=e;return t?r&&ef(r)?w3("open --relaunch does not support URL targets."):"app"!==n?w3("open --relaunch is supported only for app surfaces."):"android"===a.platform&&r&&"binary"===ed(r)?w3(X(r)):null:null}async function w8(e){let{req:t,sessionName:r,sessionStore:n,device:a,surface:i,openTarget:o,existingSession:s}=e;await o6(a);let{appBundleId:l,appName:u}=await w6({device:a,surface:i,openTarget:o,existingAppBundleId:s?.appBundleId}),d=function(e){try{return{ok:!0,data:function(e){let{req:t,sessionStore:r,sessionName:n,device:a}=e,i=r.getRuntimeHints(n),o=function(e){let{runtime:t,sessionName:r,platform:n}=e;if(void 0===t)return;if(!t||"object"!=typeof t||Array.isArray(t))throw new D("INVALID_ARGS","open runtime must be an object.");let a=Object.keys(t).find(e=>!w_.includes(e));if(a)throw new D("INVALID_ARGS",`Invalid open runtime field: ${a}. Supported fields are ${w_.join(", ")}.`);return{platform:function(e,t,r){if(void 0===e)return r;if("ios"!==e&&"android"!==e)throw new D("INVALID_ARGS",`Invalid open runtime platform: ${String(e)}. Use "ios" or "android".`);if(r&&e!==r)throw new D("INVALID_ARGS",`open runtime targets ${e}, but session "${t}" is bound to ${r}.`);return e}(t.platform,r,n),metroHost:wM(t.metroHost,"metroHost"),metroPort:function(e){if(void 0!==e){if("number"!=typeof e)throw new D("INVALID_ARGS","Invalid open runtime metroPort: expected integer.");return wk(e)}}(t.metroPort),bundleUrl:wM(t.bundleUrl,"bundleUrl"),launchUrl:wM(t.launchUrl,"launchUrl")}}({runtime:t.runtime,sessionName:n,platform:wD(a.platform)});return void 0===t.runtime?{runtime:function(e,t,r){let n=e.getRuntimeHints(t);if(!n)return;let a=r?.platform,i=wD(a);if(n.platform&&r&&!i)throw new D("INVALID_ARGS",`Session runtime hints are only supported on iOS and Android sessions, but session "${t}" is bound to ${a}.`);if(n.platform&&i&&n.platform!==i)throw new D("INVALID_ARGS",`Session runtime hints target ${n.platform}, but session "${t}" is bound to ${a}. Clear the runtime hints or use a different session.`);return i&&n.platform!==i?{...n,platform:i}:n}(r,n,a),previousRuntime:i,replacedStoredRuntime:!1}:{runtime:o&&wN(o)>0?o:void 0,previousRuntime:i,replacedStoredRuntime:!0}}(e)}}catch(t){let e=M(t);return cM(e.code,e.message,e.details)}}({req:t,sessionStore:n,sessionName:r,device:a});if(!d.ok)return{type:"response",response:d};if(s){let{runtime:e,previousRuntime:t,replacedStoredRuntime:r}=d.data;await wP({replacedStoredRuntime:r,previousRuntime:t,runtime:e,session:s})}return{type:"details",details:{appBundleId:l,appName:u,runtime:d.data.runtime}}}async function w6(e){let{device:t,surface:r,openTarget:n,existingAppBundleId:a}=e,i=await wL(r);return{appBundleId:i.appBundleId??await w2(t,n,a,w0),appName:i.appName??n}}let w9=new Map;async function w7(e){let{device:t,closeTarget:r,outFlag:n,context:a}=e;"android"!==t.platform&&await ae(t.id),await ch(t,"close",[r],n,a),await cO(t,300)}async function ge(e){var t,r;let n,{runtime:a,device:i,req:o,logPath:s,appBundleId:l,traceLogPath:u,openPositionals:d}=e,c=a?.launchUrl;if(!c||0===d.length||d.length>1)return;let p=d[0]?.trim();!p||ef(p)||await ch(i,"open",[c],o.flags?.out,{...(t=s,r=o.flags,n=c5(t,r,l,u),delete n.launchConsole,n)})}async function gt(e){var t,r,n,a;let i,{req:o,sessionName:s,sessionStore:l,logPath:u,device:d,openTarget:c,openPositionals:p,appName:f,surface:m,appBundleId:h,runtime:w,existingSession:g}=e,y=o.flags?.relaunch===!0,v=g?.trace?.outPath,I=h,b=Date.now(),A={};if(y&&c){let e=I??c,t=Date.now();await w7({device:d,closeTarget:e,outFlag:o.flags?.out,context:{...c5(u,o.flags,I??g?.appBundleId,v)}}),A.relaunchCloseDurationMs=Math.max(0,Date.now()-t)}let S=Date.now();await wc({device:d,appId:I,runtime:w}),A.runtimeHintsDurationMs=Math.max(0,Date.now()-S);let x="ios"===d.platform&&"app"===m&&p.length>0,_={verbose:o.flags?.verbose,logPath:u,traceLogPath:v,requestId:o.meta?.requestId};x&&I?(A.runnerPrewarmKind="session",A.runnerPrewarmScheduled=!0,i=function(e,t={}){return"ios"!==e.platform?void 0:ad(e,{requestId:t.requestId})?void eN({level:"debug",phase:"ios_runner_session_prewarm_skipped_scoped_provider",data:{deviceId:e.id}}):n8(e,t).then(()=>{}).catch(t=>{eN({level:"warn",phase:"ios_runner_session_prewarm_failed",data:{deviceId:e.id,error:t instanceof Error?t.message:String(t)}})})}(d,_)):x&&(A.runnerPrewarmKind="xctestrun",A.runnerPrewarmScheduled=!0,i=function(e,t={}){return"ios"!==e.platform?void 0:ad(e,{requestId:t.requestId})?void eN({level:"debug",phase:"ios_runner_xctestrun_prewarm_skipped_scoped_provider",data:{deviceId:e.id}}):nO(e,t).then(()=>{}).catch(t=>{eN({level:"warn",phase:"ios_runner_xctestrun_prewarm_failed",data:{deviceId:e.id,error:t instanceof Error?t.message:String(t)}})})}(d,_));let N=Date.now();await ch(d,"open",p,o.flags?.out,{...c5(u,o.flags,I)}),A.openDispatchDurationMs=Math.max(0,Date.now()-N);let M=Date.now();if(await ge({runtime:w,device:d,req:o,logPath:u,appBundleId:I,traceLogPath:v,openPositionals:p}),A.launchUrlDurationMs=Math.max(0,Date.now()-M),y&&i){let e=Date.now();await i,A.runnerPrewarmWaited=!0,A.runnerPrewarmDurationMs=Math.max(0,Date.now()-e)}else i&&(A.runnerPrewarmWaited=!1);I=await w1(d,c,I),"android"===d.platform&&I&&await wH(d,I);let k=c?(t=I,{durationMs:Math.max(0,Date.now()-N),measuredAt:new Date().toISOString(),method:wR,appTarget:c,appBundleId:t}):void 0,D=Date.now();if(await cO(d,300),A.postOpenSettleDurationMs=Math.max(0,Date.now()-D),rh(o.meta?.requestId)){let e=rg();return cM(e.code,e.message,e.details)}g&&cQ(g,"open",g.snapshot);let P=function(e){let{existingSession:t,sessionName:r,device:n,surface:a,appBundleId:i,appName:o,saveScript:s}=e;return t?{...t,device:n,surface:a,appBundleId:i,appName:o,recordSession:t.recordSession||s,snapshot:void 0}:{name:r,device:n,createdAt:Date.now(),surface:a,appBundleId:i,appName:o,recordSession:s,actions:[]}}({existingSession:g,sessionName:s,device:d,surface:m,appBundleId:I,appName:f,saveScript:!!o.flags?.saveScript});void 0!==o.runtime&&(r=l,n=s,(a=w)&&(0===wN(a)?r.clearRuntimeHints(n):r.setRuntimeHints(n,a))),A.totalDurationMs=Math.max(0,Date.now()-b);let O=function(e){let{sessionName:t,appName:r,appBundleId:n,surface:a,startup:i,timing:o,device:s,runtime:l,runtimeHintCount:u}=e,d={session:t,surface:a};return r&&(d.appName=r),n&&(d.appBundleId=n),i&&(d.startup=i),o&&(d.timing=o),l&&u(l)>0&&(d.runtime=l),s&&(d.platform=s.platform,d.target=s.target??"mobile",d.device=s.name,d.id=s.id,d.kind=s.kind,"android"===s.platform&&(d.serial=s.id)),s?.platform==="ios"&&(d.device_udid=s.id,d.ios_simulator_device_set=s.simulatorSetPath??null),{...d,...eJ(`Opened: ${r??n??t}`)}}({sessionName:s,appName:f,appBundleId:I,surface:m,startup:k,timing:A,device:d,runtime:w,runtimeHintCount:wN});return l.recordAction(P,{command:"open",positionals:p,flags:o.flags??{},runtime:void 0!==o.runtime?w:void 0,result:O}),l.set(s,P),{ok:!0,data:O}}async function gr(e){let{req:t,sessionName:r,logPath:n,sessionStore:a}=e;if(a.has(r)){let e=a.get(r);if(!e)return cM("SESSION_NOT_FOUND",`Session "${r}" not found.`);let i=t.flags?.relaunch===!0,o=t.positionals?.[0],s=o??(i?e.appName:void 0),l=w5(e.device,t.flags?.surface,s,e.surface);if("string"!=typeof l)return l;if(!s&&"app"===l)return i?w3("open --relaunch requires an app name or an active session app."):w3("Session already active. Close it first or pass a new --session name.");let u=w4({shouldRelaunch:i,openTarget:s,surface:l,device:e.device});if(u)return u;let d=await cE(e.device),c=await w8({req:t,sessionName:r,sessionStore:a,device:d,surface:l,openTarget:s,existingSession:e});return"response"===c.type?c.response:await gt({req:t,sessionName:r,sessionStore:a,logPath:n,device:d,openTarget:s,openPositionals:o?t.positionals??[]:s?[s]:[],appBundleId:c.details.appBundleId,appName:c.details.appName,runtime:c.details.runtime,surface:l,existingSession:e})}let i=t.flags?.relaunch===!0,o=t.positionals?.[0];if(i&&!o)return w3("open --relaunch requires an app argument.");let s=function(e){let{shouldRelaunch:t,openTarget:r,platform:n}=e;return t?r&&ef(r)?w3("open --relaunch does not support URL targets."):"android"===n&&r&&"binary"===ed(r)?w3(X(r)):null:null}({shouldRelaunch:i,openTarget:o,platform:t.flags?.platform==="android"?"android":void 0});if(s)return s;let l=await oO(t.flags??{}),u=w5(l,t.flags?.surface,o);if("string"!=typeof u)return u;let d=w4({shouldRelaunch:i,openTarget:o,surface:u,device:l});return d||await r4(w9,l.id,async()=>{let e=a.toArray().find(e=>e.device.id===l.id);if(e)return cM("DEVICE_IN_USE",`Device is already in use by session "${e.name}".`,{session:e.name,deviceId:l.id,deviceName:l.name,hint:`Run agent-device session list and reuse --session ${e.name}, or close that session before opening a new one on this device.`});let i=await w8({req:t,sessionName:r,sessionStore:a,device:l,surface:u,openTarget:o});return"response"===i.type?i.response:await gt({req:t,sessionName:r,sessionStore:a,logPath:n,device:l,openTarget:o,openPositionals:t.positionals??[],appBundleId:i.details.appBundleId,appName:i.details.appName,runtime:i.details.runtime,surface:u})})}async function gn(e){let t=await Y(e,["emu","kill"],{allowFailure:!0,timeoutMs:15e3});return{success:0===t.exitCode,exitCode:t.exitCode,stdout:String(t.stdout??""),stderr:String(t.stderr??"")}}async function ga(e){let{device:t,shutdownRequested:r}=e;if(r&&(cP(t)||"android"===t.platform&&"emulator"===t.kind))try{return cP(t)?await lT(t):await gn(t)}catch(t){let e=k(t);return{success:!1,exitCode:-1,stdout:"",stderr:e.message,error:e}}}async function gi(e){if(await ae(e.device.id),"macos"!==e.device.platform)return;let t="frontmost-app"===e.surface?{surface:"frontmost-app"}:e.appBundleId?{bundleId:e.appBundleId}:{};await l6("dismiss",t).catch(t=>{eN({level:"debug",phase:"macos_close_alert_dismiss_failed",data:{session:e.name,error:t instanceof Error?t.message:String(t)}})})}async function go(e,t){e.appLog&&await iN(e.appLog),r8(e.device.platform)&&await gi(e),await h8(t).catch(()=>{})}async function gs(e){let t,{req:r,sessionName:n,logPath:a,sessionStore:i}=e,o=i.get(n);if(!o)return await gl(r,a);o.appLog&&await iN(o.appLog),r.positionals&&r.positionals.length>0&&(r8(o.device.platform)&&await gi(o),await ch(o.device,"close",r.positionals,r.flags?.out,{...c5(a,r.flags,o.appBundleId,o.trace?.outPath)}),await cO(o.device,300)),r8(o.device.platform)&&(t=(r.positionals?.length??0)>0,!cP(o.device)||t||r.flags?.shutdown||o.recording)?await gi(o):r8(o.device.platform)&&eN({level:"debug",phase:"ios_runner_retained_after_close",data:{session:o.name,deviceId:o.device.id}}),wd(i.getRuntimeHints(n))&&o.appBundleId&&await wp({device:o.device,appId:o.appBundleId}).catch(()=>{}),i.recordAction(o,{command:"close",positionals:r.positionals??[],flags:r.flags??{},result:{session:n,...eJ(`Closed: ${n}`)}}),r.flags?.saveScript&&(o.recordSession=!0),i.writeSessionLog(o),await h8(n).catch(()=>{}),i.delete(n);let s=await ga({device:o.device,shutdownRequested:r.flags?.shutdown});return s?{ok:!0,data:eV({session:n,shutdown:s},`Closed: ${n}`)}:{ok:!0,data:{session:n,...eJ(`Closed: ${n}`)}}}async function gl(e,t){if(!e.positionals||0===e.positionals.length)return cM("SESSION_NOT_FOUND","No active session");let r=await cR({session:void 0,flags:e.flags,ensureReady:!0});return await ch(r,"close",e.positionals,e.flags?.out,{...c5(t,e.flags)}),await cO(r,300),{ok:!0,data:{app:e.positionals[0],...eJ(`Closed: ${e.positionals[0]}`)}}}let gu={ios:async(e,t,r)=>{let{reinstallIosApp:n}=await Promise.resolve(ra);return await n(e,t,r)},android:async(e,t,r)=>{let{reinstallAndroidApp:n}=await import("../1769.js");return await n(e,t,r)}},gd={ios:async(e,t,r)=>{let{installIosApp:n}=await Promise.resolve(ra),a=await n(e,r,{appIdentifierHint:t});return{bundleId:a.bundleId,appName:a.appName,launchTarget:a.launchTarget}},android:async(e,t,r)=>{let{installAndroidApp:n}=await import("../1769.js"),a=await n(e,r);return{package:a.packageName,appName:a.appName,launchTarget:a.launchTarget}}};async function gc(e){let{req:t,command:r,sessionName:n,sessionStore:a,deployOps:i}=e,o=a.get(n),s=t.flags??{},u=ck(r,o,s);if(u)return u;let d=t.positionals?.[0]?.trim(),c=t.positionals?.[1]?.trim();if(!d||!c)return cM("INVALID_ARGS",`${r} requires: ${r} <app> <path-to-app-binary>`);let p=t.meta?.uploadedArtifactId;try{var f;let e,n=p?iE(p,t.meta?.tenantId):aq.expandHome(c);if(!l.existsSync(n))return cM("INVALID_ARGS",`App binary not found: ${n}`);let u=await cR({session:o,flags:s,ensureReady:!1});if(!cY(r,u))return cM("UNSUPPORTED_OPERATION",`${r} is not supported on this device`);if("ios"===u.platform){let t=await i.ios(u,d,n),r=t.bundleId;e=r?{app:d,appPath:n,platform:"ios",appId:r,bundleId:r,appName:t.appName,launchTarget:t.launchTarget}:{app:d,appPath:n,platform:"ios",appName:t.appName,launchTarget:t.launchTarget}}else{let t=await i.android(u,d,n),r=t.package;e=r?{app:d,appPath:n,platform:"android",appId:r,package:r,packageName:r,appName:t.appName,launchTarget:t.launchTarget}:{app:d,appPath:n,platform:"android",appName:t.appName,launchTarget:t.launchTarget}}let m=eV(e,(f=e,`Installed: ${f.appName??eL(f)}`));return o&&a.recordAction(o,{command:r,positionals:t.positionals??[],flags:t.flags??{},result:m??{}}),{ok:!0,data:m}}finally{p&&iC(p)}}async function gp(e,t,r){return await rr(e,t,r)}async function gf(e){let{req:t,sessionName:r,sessionStore:n}=e;if("session_list"===t.command)return{ok:!0,data:{sessions:n.toArray().map(e=>({name:e.name,platform:e.device.platform,target:e.device.target??"mobile",surface:e.surface??"app",device:e.device.name,id:e.device.id,device_id:e.device.id,createdAt:e.createdAt,..."ios"===e.device.platform&&{device_udid:e.device.id,ios_simulator_device_set:e.device.simulatorSetPath??null}}))}};if("devices"===t.command)try{let e=ec(t.flags?.androidDeviceAllowlist),r=t.flags?.platform,n=r9({simulatorSetPath:Z(t.flags?.iosSimulatorDeviceSet),platform:r,target:t.flags?.target}),a=await oL({platform:r,target:t.flags?.target,deviceName:t.flags?.device,udid:t.flags?.udid,serial:t.flags?.serial,iosSimulatorSetPath:n,androidSerialAllowlist:e?Array.from(e).sort():void 0}),i=r?a.filter(e=>{var t,n;return t=e,!(n=r)||("apple"===n?r8(t.platform):t.platform===n)}):a,o=(t.flags?.target?i.filter(e=>(e.target??"mobile")===t.flags?.target):i).map(({simulatorSetPath:e,...t})=>t);return{ok:!0,data:{devices:o}}}catch(t){let e=M(t);return cM(e.code,e.message,e.details)}if("apps"===t.command){let e=n.get(r),a=t.flags??{},i=ck(t.command,e,a);if(i)return i;let o=await cR({session:e,flags:a,ensureReady:!0});if(!cY("apps",o))return cM("UNSUPPORTED_OPERATION","apps is not supported on this device");let s=eA(t.flags?.appsFilter);return r8(o.platform)?{ok:!0,data:{apps:(await u3(o,s)).map(e=>e.name&&e.name!==e.bundleId?`${e.name} (${e.bundleId})`:e.bundleId)}}:{ok:!0,data:{apps:(await H(o,s)).map(e=>e.name&&e.name!==e.package?`${e.name} (${e.package})`:e.package)}}}return null}async function gm(e){let{ensureAndroidEmulatorBooted:t}=await import("../1769.js");return await t(e)}let gh='iOS appstate requires an active session on the target device. Run open first (for example: open --session sim --platform ios --device "<name>" <app>).',gw='macOS appstate requires an active session on the target device. Run open first (for example: open --session macos --platform macos "System Settings").';async function gg(e){let{req:t,sessionName:r,sessionStore:n}=e,a=n.get(r),i=t.flags??{},o=i.platform;if(!a&&"string"==typeof i?.session&&i.session.trim().length>0)return cM("SESSION_NOT_FOUND","ios"===o?`No active session "${r}". Run open with --session ${r} first.`:`No active session "${r}". Run open with --session ${r} first, or omit --session to query by device selector.`);let s=ck("appstate",a,i);if(s)return s;let l=r8(a?.device.platform)&&function(e,t){if(!t)return!1;if(!cD(e))return!0;let r=e?.platform;return!(r&&!r6(t.device.platform,r)||e?.target&&e.target!==(t.device.target??"mobile")||e?.udid&&e.udid!==t.device.id||e?.serial&&e.serial!==t.device.id)&&(!e?.device||e.device.trim().toLowerCase()===t.device.name.trim().toLowerCase())}(i,a);if("ios"===o&&!l)return cM("SESSION_NOT_FOUND",gh);if("macos"===o&&!l)return cM("SESSION_NOT_FOUND",gw);if(l&&a){let e=a.appName??a.appBundleId;if(!a.appName&&!a.appBundleId){if("macos"===a.device.platform&&a.surface&&"app"!==a.surface&&"frontmost-app"!==a.surface)return{ok:!0,data:{platform:a.device.platform,appName:a.surface,appBundleId:a.appBundleId,source:"session",surface:a.surface}};let e="macos"===a.device.platform?"macOS":"iOS";return cM("COMMAND_FAILED",`No foreground app is tracked for this ${e} session. Open an app in the session, then retry appstate.`)}return{ok:!0,data:{platform:a.device.platform,appName:e??"unknown",appBundleId:a.appBundleId,source:"session",surface:a.surface??"app",..."ios"===a.device.platform?{device_udid:a.device.id,ios_simulator_device_set:a.device.simulatorSetPath??null}:{}}}}let u=await cR({session:a,flags:i,ensureReady:!0});if("ios"===u.platform)return cM("SESSION_NOT_FOUND",gh);if("macos"===u.platform)return cM("SESSION_NOT_FOUND",gw);let{getAndroidAppState:d}=await import("../1769.js"),c=await d(u);return{ok:!0,data:{platform:"android",package:c.package,activity:c.activity}}}async function gy(e){let{req:t,sessionName:r,sessionStore:n}=e;if("boot"===t.command){let e,a=n.get(r),i=t.flags??{},o=ck(t.command,a,i);if(o)return o;let s="android"===(i.platform??a?.device.platform),l=!0===i.headless;if(l&&!s)return cM("INVALID_ARGS","boot --headless is supported only for Android emulators.");let u=cC({flags:i,sessionDevice:a?.device}),d=s&&!!u,c=!1;try{e=await cR({session:a,flags:i,ensureReady:!1})}catch(r){let t=M(r);if(s&&l&&!u&&"DEVICE_NOT_FOUND"===t.code)return cM("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");if(!d||"DEVICE_NOT_FOUND"!==t.code||!u)throw r;e=await gm({avdName:u,serial:i.serial,headless:l}),c=!0}if(i.target&&(e.target??"mobile")!==i.target)return cM("DEVICE_NOT_FOUND",`No ${e.platform} device found matching --target ${i.target}.`);if(s&&l){if("android"!==e.platform||"emulator"!==e.kind)return cM("INVALID_ARGS","boot --headless is supported only for Android emulators.");if(!c){let t=cC({flags:i,sessionDevice:a?.device,resolvedDevice:e});if(!t)return cM("INVALID_ARGS","boot --headless requires --device <avd-name> (or an Android emulator session target).");e=await gm({avdName:t,serial:i.serial,headless:!0})}await o6(e)}else("android"!==e.platform||!0!==e.booted)&&await o6(e);return cY("boot",e)?{ok:!0,data:{platform:e.platform,target:e.target??"mobile",device:e.name,id:e.id,kind:e.kind,booted:!0}}:cM("UNSUPPORTED_OPERATION","boot is not supported on this device")}return"appstate"===t.command?await gg({req:t,sessionName:r,sessionStore:n}):null}function gv(e,t){for(let r of e){if(t(r))return r;let e=gv(r.children,t);if(e)return e}}function gI(e,t){let r=[];for(let n of e)t(n)&&r.push(n),r.push(...gI(n.children,t));return r}function gb(e,t){let r=gv(e,e=>"schema"===e.name&&e.attributes.name===t);return r?r.children.filter(e=>"col"===e.name).map(e=>{let t;return t=e.children.find(e=>"mnemonic"===e.name),t?.text??null??""}):[]}function gA(e){if(!e||e.children.some(e=>"sentinel"===e.name)||!e.text)return null;let t=Number(e.text);return Number.isFinite(t)?t:null}function gS(e,t){return e?e.attributes.ref?t.get(e.attributes.ref)?.numberValue??null:gA(e):null}let gx="xctrace-animation-hitches";function g_(e,t){let r=no(e),n=gb(r,t);return{rows:0===n.length?[]:gI(r,e=>"row"===e.name),schema:n}}function gN(e,t){for(let r of e)gN(r.children,t),r.attributes.id&&t.set(r.attributes.id,{numberValue:gA(r),process:gM(r)})}function gM(e){if(!e||e.children.some(e=>"sentinel"===e.name))return null;let t=gA(gv(e.children,e=>"pid"===e.name)),r=(e.attributes.fmt??"").replace(/\s+\(\d+\)$/,"").trim();return null===t&&0===r.length?null:{pid:t??void 0,name:r.length>0?r:void 0}}let gk="ps-process-snapshot",gD="ps-process-snapshot",gP="xctrace-activity-monitor",gO="xctrace-activity-monitor";async function gR(e,t){if("ios"===e.platform&&"device"===e.kind)return await gq(e,t);let r=await gG(e,t),n=await gK(e,r);if(0===n.length)throw new D("COMMAND_FAILED",`No running process found for ${t}`,{appBundleId:t,hint:"Run open <app> for this session again to ensure the Apple app is active, then retry perf."});let a=new Date().toISOString();return gJ({usagePercent:n.reduce((e,t)=>e+t.cpuPercent,0),residentMemoryKb:n.reduce((e,t)=>e+t.rssKb,0),measuredAt:a,matchedProcesses:[r.executableName],cpuMethod:gk,memoryMethod:gD})}async function gE(e,t){var r;let n,a,i,o,s,l;if("ios"!==e.platform||"device"!==e.kind)throw new D("COMMAND_FAILED","Apple frame-health sampling is currently available only on connected iOS devices.",{metric:"fps",platform:e.platform,deviceKind:e.kind});let u=await gB(e,t),d=await gC(e,t,u);return n=g_((r={hitchesXml:d.hitchesXml,frameLifetimesXml:d.frameLifetimesXml,displayInfoXml:d.displayInfoXml,processIds:u.map(e=>e.pid),processNames:av(u.map(e=>f.basename(g(e.executable)))),windowStartedAt:d.windowStartedAt,windowEndedAt:d.windowEndedAt,measuredAt:d.windowEndedAt}).frameLifetimesXml,"hitches-frame-lifetimes").rows.length,a=function(e){if(!e)return;let{rows:t,schema:r}=g_(e,"device-display-info"),n=r.indexOf("max-refresh-rate");if(n<0)return;let a=new Map;for(let e of t){gN(e.children,a);let t=gS(e.children[n],a);if(null!==t&&t>0)return t}}(r.displayInfoXml),o=(i=(function(e){let t,r,n=no(e),a=Object.values(r={start:(t=gb(n,"hitches")).indexOf("start"),duration:t.indexOf("duration"),process:t.indexOf("process"),isSystem:t.indexOf("is-system")}).every(e=>e>=0)?r:null;if(!a)return[];let i=new Map;return gI(n,e=>"row"===e.name).map(e=>(function(e,t,r){var n,a,i;let o;if(gN(e.children,r),!0===(n=e.children[t.isSystem],null===(o=gS(n,r))?null:0!==o))return null;let s=gS(e.children[t.start],r),l=gS(e.children[t.duration],r);if(null===s||null===l)return null;let u=(a=e.children[t.process],i=r,a?a.attributes.ref?i.get(a.attributes.ref)?.process??null:gM(a):null);return{startNs:s,durationNs:l,pid:u?.pid,processName:u?.name}})(e,a,i)).filter(e=>!!e)})(r.hitchesXml).filter(e=>{var t,n,a;return t=e,n=r.processIds,a=r.processNames,!!(void 0!==t.pid&&n.includes(t.pid))||!!t.processName&&a.includes(t.processName)})).length,s=Math.max(0,Math.round(Date.parse(r.windowEndedAt)-Date.parse(r.windowStartedAt))),l=function(e,t){if(0===e.length)return[];let r=[...e].sort((e,t)=>e.startNs-t.startNs),n=[],a=[];for(let e of r){let t=a.at(-1);if(!t||e.startNs-(t.startNs+t.durationNs)<=5e8){a.push(e);continue}n.push(a),a=[e]}return a.length>0&&n.push(a),n.map(e=>{var r,n;let a,i,o,s;return r=e,n=t,a=Math.min(...r.map(e=>e.startNs)),i=Math.max(...r.map(e=>e.startNs+e.durationNs)),s=Math.max(o=Math.max(0,Math.round(a/1e6)),Math.round(i/1e6)),{startOffsetMs:o,endOffsetMs:s,startAt:new Date(n+o).toISOString(),endAt:new Date(n+s).toISOString(),missedDeadlineFrameCount:r.length,worstFrameMs:w$(Math.max(...r.map(e=>e.durationNs))/1e6)}}).sort((e,t)=>t.missedDeadlineFrameCount-e.missedDeadlineFrameCount||t.worstFrameMs-e.worstFrameMs).slice(0,3).sort((e,t)=>e.startOffsetMs-t.startOffsetMs)}(i,Date.parse(r.windowStartedAt)),{droppedFramePercent:n>0?w$(o/n*100):0,droppedFrameCount:o,totalFrameCount:n,sampleWindowMs:s,windowStartedAt:r.windowStartedAt,windowEndedAt:r.windowEndedAt,measuredAt:r.measuredAt,method:gx,matchedProcesses:[...new Set(i.map(e=>e.processName).filter(e=>"string"==typeof e&&e.length>0))],frameDeadlineMs:void 0===a?void 0:w$(1e3/a),refreshRateHz:a,worstWindows:l.length>0?l:void 0}}async function gC(e,t,r){let n=await d.mkdtemp(f.join(c.tmpdir(),"agent-device-ios-frame-perf-")),a=f.join(n,"animation-hitches.trace"),i=f.join(n,"hitches.xml"),o=f.join(n,"frame-lifetimes.xml"),s=f.join(n,"display-info.xml");try{let n=await gL({device:e,appBundleId:t,tracePath:a,template:"Animation Hitches",duration:"2s",targetPids:r.map(e=>e.pid),validateTraceOutput:!0,failureMessage:`Failed to record iOS frame-health sample for ${t}`});await gF(e,t,a,"hitches",i),await gF(e,t,a,"hitches-frame-lifetimes",o);let l=await gU(e,t,a,"device-display-info",s);return{windowStartedAt:n.startedAt,windowEndedAt:n.endedAt,hitchesXml:await d.readFile(i,"utf8"),frameLifetimesXml:await d.readFile(o,"utf8"),displayInfoXml:l?await d.readFile(s,"utf8"):void 0}}finally{await d.rm(n,{recursive:!0,force:!0}).catch(()=>{})}}async function gL(e){let{device:t,appBundleId:r,tracePath:n,template:a,duration:i}=e,o=e.allProcesses?["--all-processes"]:(e.targetPids??[]).flatMap(e=>["--attach",String(e)]),s=["xctrace","record","--template",a,"--device",t.id,...o,"--time-limit",i,"--output",n,"--quiet","--no-prompt"],l=await gT(s,e.tracePath);if(0===l.result.exitCode)return e.validateTraceOutput&&await g$(e,l.result.stdout,l.result.stderr),{startedAt:l.startedAt,endedAt:l.endedAt,capturedAtMs:l.capturedAtMs};throw new D("COMMAND_FAILED",e.failureMessage,{cmd:"xcrun",args:s,exitCode:l.result.exitCode,stdout:l.result.stdout,stderr:l.result.stderr,appBundleId:r,deviceId:t.id,hint:gY(l.result.stdout,l.result.stderr)})}async function gT(e,t){let r;for(let n=1;n<=3;n+=1){n>1&&(await d.rm(t,{recursive:!0,force:!0}).catch(()=>{}),await new Promise(e=>setTimeout(e,1500)));let a=new Date().toISOString(),i=await rR(e,{allowFailure:!0,timeoutMs:6e4});if(r={result:i,startedAt:a,endedAt:new Date().toISOString(),capturedAtMs:Date.now()},0===i.exitCode||!function(e){let t=`${e.stdout}
63
+ ${e.stderr}`.toLowerCase();return t.includes("_lockkperf")||t.includes("could not lock kperf")||t.includes("likely another session just started")}(i))break}return r}async function g$(e,t,r){let n=await d.stat(e.tracePath).catch(()=>null);if(!(n?.isDirectory()===!0?(await d.readdir(e.tracePath).catch(()=>[])).length>0:(n?.size??0)>0))throw new D("COMMAND_FAILED",`${e.failureMessage}: xctrace produced no trace data`,{tracePath:e.tracePath,appBundleId:e.appBundleId,deviceId:e.device.id,stdout:t,stderr:r,hint:"Keep the iOS device unlocked and connected by cable, keep the app active, then retry perf."})}async function gF(e,t,r,n,a){let i=["xctrace","export","--input",r,"--xpath",`/trace-toc/run/data/table[@schema="${n}"]`,"--output",a],o=await rR(i,{allowFailure:!0,timeoutMs:15e3});if(0!==o.exitCode)throw new D("COMMAND_FAILED",`Failed to export iOS device ${n} data`,{cmd:"xcrun",args:i,exitCode:o.exitCode,stdout:o.stdout,stderr:o.stderr,appBundleId:t,deviceId:e.id,hint:gY(o.stdout,o.stderr)})}async function gU(e,t,r,n,a){try{return await gF(e,t,r,n,a),!0}catch{return!1}}async function gV(e){let t=no(e),r=gb(t,"activity-monitor-process-live");if(0===r.length)throw new D("COMMAND_FAILED","Failed to parse xctrace activity-monitor-process-live schema");let n=r.indexOf("pid"),a=r.indexOf("process"),i=r.indexOf("cpu-total"),o=r.indexOf("memory-real");if(n<0||a<0||i<0||o<0)throw new D("COMMAND_FAILED","xctrace activity-monitor-process-live export is missing expected columns");let s=gI(t,e=>"row"===e.name),l=[],u=new Map;for(let e of s){var d,c;let t=e.children;if(0===t.length)continue;for(let e of t){let t=gv(e.children,e=>"pid"===e.name&&"string"==typeof e.attributes.id);if(t?.attributes.id){let e=Number(t.text);u.set(t.attributes.id,{numberValue:Number.isFinite(e)?e:null})}e.attributes.id&&u.set(e.attributes.id,{numberValue:gA(e),processName:gX(e)})}let r=gS(t[n],u),s=(d=t[a],c=u,d?d.attributes.ref?c.get(d.attributes.ref)?.processName??null:gX(d):null);null!==r&&Number.isFinite(r)&&s&&l.push({pid:r,processName:s,cpuTimeNs:gS(t[i],u),residentMemoryBytes:gS(t[o],u)})}return l}async function gG(e,t){let r="macos"===e.platform?await gW(t):await gz(e,t),n="macos"===e.platform?f.join(r,"Contents","Info.plist"):f.join(r,"Info.plist"),a=await lF(n,"CFBundleExecutable");if(!a)throw new D("COMMAND_FAILED",`Failed to resolve executable for ${t}`,{appBundleId:t,appPath:r});return{executableName:a,executablePath:"macos"===e.platform?f.join(r,"Contents","MacOS",a):f.join(r,a)}}async function gq(e,t){let r=await gB(e,t),n=await gj(e,t),a=await gj(e,t),i=gH(await gV(n.xml),r,t,e),o=gH(await gV(a.xml),r,t,e),s=a.capturedAtMs-n.capturedAtMs;if(s<=0)throw new D("COMMAND_FAILED",`Invalid Activity Monitor sample window for ${t}`,{appBundleId:t,deviceId:e.id});if(null===i.cpuTimeNs||null===o.cpuTimeNs||null===o.residentMemoryBytes)throw new D("COMMAND_FAILED",`Incomplete Activity Monitor sample for ${t}`,{appBundleId:t,deviceId:e.id,hint:"Keep the app running in the foreground while perf samples the device, then retry."});return gJ({usagePercent:Math.max(0,o.cpuTimeNs-i.cpuTimeNs)/(1e6*s)*100,residentMemoryKb:o.residentMemoryBytes/1024,measuredAt:new Date(a.capturedAtMs).toISOString(),matchedProcesses:o.matchedProcesses,cpuMethod:gP,memoryMethod:gO})}async function gB(e,t){let r=(await o1(e,"all")).find(e=>e.bundleId===t);if(!r)throw new D("APP_NOT_INSTALLED",`No iOS device app found for ${t}`,{appBundleId:t,deviceId:e.id});if(!r.url)throw new D("COMMAND_FAILED",`Missing app bundle URL for ${t}`,{appBundleId:t,deviceId:e.id});let n=r.url.replace(/\/$/,""),a=g(n),i=(await o2(e)).filter(e=>e.executable.startsWith(`${n}/`));if(0===i.length)throw new D("COMMAND_FAILED",`No running process found for ${t}`,{appBundleId:t,deviceId:e.id,appBundlePath:a,hint:"Run open <app> for this session again to ensure the iOS app is active, then retry perf."});return i}async function gj(e,t){let r=await d.mkdtemp(f.join(c.tmpdir(),"agent-device-ios-perf-")),n=f.join(r,"sample.trace"),a=f.join(r,"activity-monitor-process-live.xml");try{let r=await gL({device:e,appBundleId:t,tracePath:n,template:"Activity Monitor",duration:"1s",allProcesses:!0,failureMessage:`Failed to record iOS device Activity Monitor sample for ${t}`});return await gF(e,t,n,"activity-monitor-process-live",a),{capturedAtMs:r.capturedAtMs,xml:await d.readFile(a,"utf8")}}finally{await d.rm(r,{recursive:!0,force:!0}).catch(()=>{})}}function gH(e,t,r,n){let a=new Set(t.map(e=>e.pid)),i=new Set(t.map(e=>f.basename(g(e.executable)))),o=e.filter(e=>a.has(e.pid)||i.has(e.processName));if(0===o.length)throw new D("COMMAND_FAILED",`No Activity Monitor sample found for ${r}`,{appBundleId:r,deviceId:n.id,hint:"Keep the app running in the foreground while perf samples the device, then retry."});let s=new Map;for(let e of o){let t=s.get(e.pid);if(!t){s.set(e.pid,e);continue}s.set(e.pid,{pid:e.pid,processName:e.processName||t.processName,cpuTimeNs:gZ(t.cpuTimeNs,e.cpuTimeNs),residentMemoryBytes:gZ(t.residentMemoryBytes,e.residentMemoryBytes)})}let l=[...s.values()],u=l.map(e=>e.cpuTimeNs).filter(e=>null!==e),d=l.map(e=>e.residentMemoryBytes).filter(e=>null!==e);return{cpuTimeNs:u.length>0?u.reduce((e,t)=>e+t,0):null,residentMemoryBytes:d.length>0?d.reduce((e,t)=>e+t,0):null,matchedProcesses:av(l.map(e=>e.processName))}}async function gW(e){let t=`kMDItemCFBundleIdentifier == "${e.replaceAll('"','\\"')}"`,r=await rO("mdfind",[t],{allowFailure:!0,timeoutMs:15e3});if(0!==r.exitCode)throw new D("COMMAND_FAILED",`Failed to resolve macOS app bundle for ${e}`,{appBundleId:e,stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode});let n=r.stdout.split("\n").map(e=>e.trim()).find(e=>e.endsWith(".app"));if(!n)throw new D("APP_NOT_INSTALLED",`No macOS app found for ${e}`,{appBundleId:e});return n}async function gz(e,t){let r=rT(e,["get_app_container",e.id,t,"app"]),n=await rR(r,{allowFailure:!0,timeoutMs:15e3});if(0!==n.exitCode)throw new D("COMMAND_FAILED",`Failed to resolve iOS simulator app container for ${t}`,{appBundleId:t,stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode,hint:"Ensure the iOS simulator app is installed and booted, then retry perf."});let a=n.stdout.trim();if(0===a.length)throw new D("APP_NOT_INSTALLED",`No iOS simulator app container found for ${t}`,{appBundleId:t});return a}async function gK(e,t){let r="macos"===e.platform?["-axo","pid=,%cpu=,rss=,command="]:rT(e,["spawn",e.id,"ps","-axo","pid=,%cpu=,rss=,command="]);return(function(e){let t=[];for(let r of eG(e)){let e=r.match(/^(\d+)\s+([0-9]+(?:\.[0-9]+)?)\s+(\d+)\s+(.+)$/);if(!e)continue;let[n,a,i,o]=e.slice(1);if(void 0===n||void 0===a||void 0===i||void 0===o)continue;let s=Number(n),l=Number(a),u=Number(i),d=o.trim();Number.isFinite(s)&&Number.isFinite(l)&&Number.isFinite(u)&&t.push({pid:s,cpuPercent:l,rssKb:u,command:d})}return t})(("macos"===e.platform?await rO("ps",r,{timeoutMs:15e3}):await rR(r,{timeoutMs:15e3})).stdout).filter(e=>{var r,n;let a;return r=e.command,n=t,a=function(e){let[t=""]=e.trim().split(/\s+/,1);return t}(r),!!(n.executablePath&&(r===n.executablePath||a===n.executablePath||r.startsWith(`${n.executablePath} `)))||f.basename(a)===n.executableName})}function gJ(e){return{cpu:{usagePercent:w$(e.usagePercent),measuredAt:e.measuredAt,method:e.cpuMethod,matchedProcesses:e.matchedProcesses},memory:{residentMemoryKb:Math.round(e.residentMemoryKb),measuredAt:e.measuredAt,method:e.memoryMethod,matchedProcesses:e.matchedProcesses}}}function gX(e){let t=e?.attributes.fmt?.trim()??"";return t?t.replace(/\s+\(\d+\)$/,"").trim():null}function gY(e,t){let r=o4(e,t);if(r)return r;let n=`${e}
64
+ ${t}`.toLowerCase();return n.includes("no device matched")||n.includes("failed to find device")?o5:n.includes("timed out")?"Keep the iOS device unlocked and connected by cable, keep the app active, then retry perf.":"Ensure the iOS device is unlocked, trusted, visible to xctrace, and the target app stays active while perf samples it."}function gZ(e,t){return null===e?t:null===t?e:Math.max(e,t)}async function gQ(e,t={}){var r,n,a;let i,o,s,l,u=(s=(o=(i=function(e){let t=[];for(let r of e){if("open"!==r.command)continue;let e=r.result?.startup;e&&"object"==typeof e&&"number"==typeof e.durationMs&&Number.isFinite(e.durationMs)&&"string"==typeof e.measuredAt&&0!==e.measuredAt.trim().length&&e.method===wR&&t.push({durationMs:Math.max(0,Math.round(e.durationMs)),measuredAt:e.measuredAt,method:wR,appTarget:"string"==typeof e.appTarget&&e.appTarget.length>0?e.appTarget:void 0,appBundleId:"string"==typeof e.appBundleId&&e.appBundleId.length>0?e.appBundleId:void 0})}return t.slice(-20)}((r=e).actions)).at(-1))?{available:!0,lastDurationMs:o.durationMs,lastMeasuredAt:o.measuredAt,method:wR,sampleCount:i.length,samples:i}:{available:!1,reason:"No startup sample captured yet. Run open <app|url> in this session first.",method:wR},{session:r.name,platform:r.device.platform,device:r.device.name,deviceId:r.device.id,metrics:{startup:s,fps:{available:!1,reason:"Dropped-frame sampling is currently available only on Android."},memory:{available:!1,reason:wE},cpu:{available:!1,reason:wE}},sampling:{startup:{method:wR,description:"Elapsed wall-clock time around dispatching the open command for the active session app target.",unit:"ms"},...function(e){if("android"===e.device.platform)return{memory:{method:wz,description:"Memory snapshot from adb shell dumpsys meminfo <package>. Values are reported in kilobytes.",unit:"kB"},cpu:{method:wW,description:"Aggregated CPU usage for app processes matched from adb shell dumpsys cpuinfo.",unit:"percent"},fps:{method:wU,description:"Rendered-frame health from the current adb shell dumpsys gfxinfo <package> framestats window. Dropped frames use Android gfxinfo janky-frame/frame-deadline data when available; this is not video recording FPS.",unit:"percent",primaryField:"droppedFramePercent",window:"since previous Android gfxinfo reset or app process start",resetsAfterRead:!0,relatedActionsLimit:12}};var t=e.device;let r="ios"===t.platform&&"device"===t.kind?{method:gx,description:"Rendered-frame hitch health from xctrace Animation Hitches on connected iOS devices. Dropped frames are counted from native hitch rows for the attached app process, with total frames from the same trace frame-lifetime table.",unit:"percent",primaryField:"droppedFramePercent",window:"short 2s xctrace Animation Hitches record of the active app process",resetsAfterRead:!1}:{method:gx,description:"Unavailable on iOS simulators and macOS because local Apple tooling does not expose reliable app frame hitches for these targets.",unit:"percent",primaryField:"droppedFramePercent"};if("ios"===t.platform&&"device"===t.kind)return{fps:r,memory:{method:gO,description:"Resident memory snapshot from a short xctrace Activity Monitor sample on the connected iOS device.",unit:"kB"},cpu:{method:gP,description:"Recent CPU usage snapshot from a short xctrace Activity Monitor sample on the connected iOS device.",unit:"percent"}};let n="macos"===t.platform?"host ps for the running macOS app executable resolved from the bundle ID.":"xcrun simctl spawn ps for the running iOS simulator app executable resolved from the bundle ID.";return{fps:r,memory:{method:gD,description:`Resident memory snapshot from ${n}`,unit:"kB"},cpu:{method:gk,description:`Recent CPU usage snapshot from ${n}`,unit:"percent"}}}(r)}});return"android"!==(n=e).device.platform&&"ios"!==n.device.platform&&"macos"!==n.device.platform||(e.appBundleId?"android"===e.device.platform?await g0(u,e,t):await g1(u,e):(a=u,l="android"===e.device.platform?"No Android app package is associated with this session. Run open <app> first.":"No Apple app bundle ID is associated with this session. Run open <app> first.",a.metrics.fps={available:!1,reason:l},a.metrics.memory={available:!1,reason:l},a.metrics.cpu={available:!1,reason:l})),u}async function g0(e,t,r){let n=await g2(t,r);e.metrics.memory=g4(n.memory),e.metrics.cpu=g4(n.cpu),e.metrics.fps=g8(g4(n.fps),t)}async function g1(e,t){let r=await g3(t);e.metrics.memory=g4(r.memory),e.metrics.cpu=g4(r.cpu),e.metrics.fps=g8(g4(r.fps),t)}async function g2(e,t){let r=e.appBundleId,n={adb:t.androidAdb},[a,i,o]=await Promise.allSettled([wJ(e.device,r,n),wK(e.device,r,n),wj(e.device,r,n)]);return{memory:a,cpu:i,fps:o}}async function g3(e){let t=e.appBundleId,r=await g5(gE(e.device,t)),n=await g5(gR(e.device,t));if("fulfilled"===n.status){let e=n.value;return{memory:{status:"fulfilled",value:e.memory},cpu:{status:"fulfilled",value:e.cpu},fps:r}}return{memory:{status:"rejected",reason:n.reason},cpu:{status:"rejected",reason:n.reason},fps:r}}async function g5(e){try{return{status:"fulfilled",value:await e}}catch(e){return{status:"rejected",reason:e}}}function g4(e){if("fulfilled"===e.status)return{available:!0,...e.value};let t=k(e.reason);return{available:!1,reason:t.message,error:t}}function g8(e,t){var r,n;let a,i;if(!0!==e.available)return e;let o=(r=t.actions,a=g6((n=e).windowStartedAt),i=g6(n.windowEndedAt)??g6(n.measuredAt),void 0===a||void 0===i?[]:r.filter(e=>e.ts>=a&&e.ts<=i).map(e=>({command:e.command,at:new Date(e.ts).toISOString(),offsetMs:Math.max(0,Math.round(e.ts-a)),target:function(e){let t=e.result;if(t)for(let e of["refLabel","ref","appName","appBundleId"]){let r=t[e];if("string"==typeof r&&r.length>0)return r}}(e)})).slice(-12));return 0===o.length?e:{...e,relatedActions:o}}function g6(e){if("string"!=typeof e)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}let g9=["path","start","stop","doctor","mark","clear"],g7=`logs requires ${g9.slice(0,-1).join(", ")}, or ${g9.at(-1)}`,ye=["dump","log"],yt=`network requires ${ye.join(" or ")}`,yr=["summary","headers","body","all"],yn=`network include mode must be one of: ${yr.join(", ")}`;async function ya(e){let{req:t}=e;return"perf"===t.command?yi(e):"logs"===t.command?yo(e):"network"===t.command?yc(e):null}async function yi(e){let{sessionName:t,sessionStore:r,androidAdbExecutor:n}=e,a=r.get(t);if(!a)return cM("SESSION_NOT_FOUND","perf requires an active session. Run open first.");try{return{ok:!0,data:await gQ(a,{androidAdb:n})}}catch(e){return{ok:!1,error:k(e)}}}async function yo(e){let{req:t,sessionName:r,sessionStore:n}=e,a=n.get(r);if(!a)return cM("SESSION_NOT_FOUND","logs requires an active session");if(!cY("logs",a.device))return cM("UNSUPPORTED_OPERATION","logs is not supported on this device");let i=(t.positionals?.[0]??"path").toLowerCase(),o=!!t.flags?.restart;return g9.includes(i)?o&&"clear"!==i?cM("INVALID_ARGS","logs --restart is only supported with logs clear"):"path"===i?function(e,t,r){let n=r.resolveAppLogPath(t),a=function(e){if(!l.existsSync(e))return{exists:!1,sizeBytes:0};let t=l.statSync(e);return{exists:!0,sizeBytes:t.size,modifiedAt:t.mtime.toISOString()}}(n);return{ok:!0,data:{path:n,active:!!e.appLog,state:e.appLog?.getState()??"inactive",backend:e.appLog?e.appLog.backend:"macos"===e.device.platform?"macos":"ios"===e.device.platform?"device"===e.device.kind?"ios-device":"ios-simulator":"android",sizeBytes:a.sizeBytes,modifiedAt:a.modifiedAt,startedAt:e.appLog?.startedAt?new Date(e.appLog.startedAt).toISOString():void 0,hint:'Grep the file for token-efficient debugging, e.g. grep -n "Error\\|Exception" <path>'}}}(a,r,n):"doctor"===i?ys(a,r,n):"mark"===i?function(e,t,r){let n,a=e.positionals?.slice(1).join(" ")??"",i=r.resolveAppLogPath(t);return iI(i),n=`[agent-device][mark][${new Date().toISOString()}] ${a.trim()||"marker"}
65
+ `,l.appendFileSync(i,n,"utf8"),{ok:!0,data:{path:i,marked:!0}}}(t,r,n):"clear"===i?yl(a,r,n,o):"start"===i?yu(a,r,n):"stop"===i?yd(a,r,n):cM("INVALID_ARGS",g7):cM("INVALID_ARGS",g7)}async function ys(e,t,r){let n=r.resolveAppLogPath(t),a=await iM(e.device,e.appBundleId);return{ok:!0,data:{path:n,active:!!e.appLog,state:e.appLog?.getState()??"inactive",checks:a.checks,notes:a.notes}}}async function yl(e,t,r,n){if(e.appLog&&!n)return cM("INVALID_ARGS","logs clear requires logs to be stopped first; run logs stop");if(n&&!e.appBundleId)return cM("INVALID_ARGS","logs clear --restart requires an app session; run open <app> first");let a=r.resolveAppLogPath(t);if(!n)return{ok:!0,data:ik(a)};e.appLog&&await iN(e.appLog);let i=ik(a),o=r.resolveAppLogPidPath(t);try{let n=await iS(e.device,e.appBundleId,a,o);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:n.backend,outPath:a,startedAt:n.startedAt,getState:n.getState,stop:n.stop,wait:n.wait}}),{ok:!0,data:{...i,restarted:!0}}}catch(n){return r.set(t,{...e,appLog:void 0}),{ok:!1,error:k(n)}}}async function yu(e,t,r){if(e.appLog)return cM("INVALID_ARGS","app log already streaming; run logs stop first");if(!e.appBundleId)return cM("INVALID_ARGS","logs start requires an app session; run open <app> first");let n=r.resolveAppLogPath(t),a=r.resolveAppLogPidPath(t);try{let i=await iS(e.device,e.appBundleId,n,a);return r.set(t,{...e,appLog:{platform:e.device.platform,backend:i.backend,outPath:n,startedAt:i.startedAt,getState:i.getState,stop:i.stop,wait:i.wait}}),{ok:!0,data:{path:n,started:!0}}}catch(e){return{ok:!1,error:k(e)}}}async function yd(e,t,r){if(!e.appLog)return cM("INVALID_ARGS","no app log stream active");let n=e.appLog.outPath;return await iN(e.appLog),r.set(t,{...e,appLog:void 0}),{ok:!0,data:{path:n,stopped:!0}}}async function yc(e){let{req:t,sessionName:r,sessionStore:n}=e,a=n.get(r);if(!a)return cM("SESSION_NOT_FOUND","network requires an active session");if(!cY("network",a.device))return cM("UNSUPPORTED_OPERATION","network is not supported on this device");let i=(t.positionals?.[0]??"dump").toLowerCase();if(!ye.includes(i))return cM("INVALID_ARGS",yt);let o=t.positionals?.[1]?Number.parseInt(t.positionals[1],10):25;if(!Number.isInteger(o)||o<1||o>200)return cM("INVALID_ARGS","network dump limit must be an integer in range 1..200");let s=function(e){let t=e.positionals?.[2]?.toLowerCase(),r=e.flags?.networkInclude;if(t&&r&&t!==r)return cM("INVALID_ARGS","network include mode was provided both positionally and via --include with different values");let n=(r??t??"summary").toLowerCase();return yr.includes(n)?{ok:!0,include:n}:cM("INVALID_ARGS",yn)}(t);if(!s.ok)return s;let{include:l}=s,u=await ib({device:a.device,appBundleId:a.appBundleId,appLogState:a.appLog?.getState(),appLogStartedAt:a.appLog?.startedAt,appLogPath:n.resolveAppLogPath(r),maxEntries:o,include:l,maxPayloadChars:2048,maxScanLines:4e3});return{ok:!0,data:{...u.dump,active:!!a.appLog,state:a.appLog?.getState()??"inactive",backend:u.backend,notes:u.notes}}}let yp=/^[A-Z_][A-Z0-9_]*$/,yf=/(\\\$\{)|\$\{([A-Za-z_][A-Za-z0-9_.]*)(?::-((?:[^}\\]|\\.)*))?\}/g,ym="AD_VAR_";function yh(e){return e.startsWith("AD_")}function yw(e){return new D("INVALID_ARGS",`The AD_* namespace is reserved for built-in variables. Rename ${e} to avoid the AD_ prefix.`)}function yg(e){let t={};for(let[r,n]of Object.entries(e)){if("string"!=typeof n||!r.startsWith(ym))continue;let e=r.slice(ym.length);0!==e.length&&yp.test(e)&&(yh(e)||(t[e]=n))}return t}function yy(e){let t={};for(let r of e){let e=r.indexOf("=");if(e<=0)throw new D("INVALID_ARGS",`Invalid -e entry "${r}": expected KEY=VALUE.`);let n=r.slice(0,e);if(!yp.test(n))throw new D("INVALID_ARGS",`Invalid -e key "${n}": keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(yh(n))throw yw(n);t[n]=r.slice(e+1)}return t}function yv(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function yI(e){if(e&&"object"==typeof e&&!Array.isArray(e)){let t={};for(let[r,n]of Object.entries(e))"string"==typeof n&&(t[r]=n);return t}return process.env}function yb(e,t,r){return e.replace(yf,(e,n,a,i)=>{if(n)return"${";if(!a)return e;if(Object.prototype.hasOwnProperty.call(t.values,a))return String(t.values[a]);if(void 0!==i)return i.replace(/\\(.)/g,"$1");throw new D("INVALID_ARGS",`Unresolved variable \${${a}} at ${r.file}:${r.line}.`)})}function yA(e,t,r){return e?function e(t,r,n){return"string"==typeof t?yb(t,r,n):Array.isArray(t)?t.map(t=>e(t,r,n)):t&&"object"==typeof t?Object.fromEntries(Object.entries(t).map(([t,a])=>[t,e(a,r,n)])):t}(e,t,r):e}let yS=new Set(["ios","android","macos","linux"]),yx=new Set(["mobile","tv","desktop"]);function y_(e){let t=e.split(/\r?\n/),r={};for(let[e,n]of t.entries()){let t=n.trim();if(0===t.length||t.startsWith("#"))continue;if(yN(t)){!function(e,t,r){let{key:n,value:a}=function(e,t){let r=e.slice(3).replace(/^[\s]+/,""),n=r.indexOf("=");if(n<=0)throw new D("INVALID_ARGS",`Invalid env directive on line ${t}: expected "env KEY=VALUE".`);let a=r.slice(0,n);if(!yp.test(a))throw new D("INVALID_ARGS",`Invalid env key "${a}" on line ${t}: keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(a.startsWith("AD_"))throw new D("INVALID_ARGS",`Invalid env key "${a}" on line ${t}: the AD_* namespace is reserved for built-in variables. Rename ${a} to avoid the AD_ prefix.`);return{key:a,value:function(e,t){if(0===e.length)return"";if(e.startsWith('"'))try{let t=JSON.parse(e);if("string"!=typeof t)throw Error("not a string literal");return t}catch{throw new D("INVALID_ARGS",`Invalid quoted env value on line ${t}.`)}return e}(r.slice(n+1),t)}}(t,r),i=e.env??{};if(Object.prototype.hasOwnProperty.call(i,n))throw new D("INVALID_ARGS",`Duplicate env directive "${n}" on line ${r}.`);i[n]=a,e.env=i}(r,t,e+1);continue}if(!t.startsWith("context "))break;let a=t.match(/(?:^|\s)platform=([^\s]+)/);if(a){let e=a[1];e&&yS.has(e)&&yM(r,"platform",e)}let i=t.match(/(?:^|\s)target=([^\s]+)/);if(i){let e=i[1];e&&yx.has(e)&&yM(r,"target",e)}let o=t.match(/(?:^|\s)timeout=(\d+)/);if(o){let e=Number(o[1]);Number.isFinite(e)&&e>=1&&yM(r,"timeoutMs",Math.floor(e))}let s=t.match(/(?:^|\s)retries=(\d+)/);if(s){let e=Number(s[1]);Number.isFinite(e)&&e>=0&&yM(r,"retries",Math.floor(e))}}return r}function yN(e){return"env"===e||e.startsWith("env ")||e.startsWith("env ")}function yM(e,t,r){let n=e[t];if(void 0!==n)throw new D("INVALID_ARGS",n===r?`Duplicate replay test metadata "${t}" in context header.`:`Conflicting replay test metadata "${t}" in context header: ${String(n)} vs ${String(r)}.`);e[t]=r}function yk(e){return!!e&&!Number.isNaN(Number(e))}let yD=/[*?[\]{}]/;function yP(e){return"maestro"===e}let yO=["failed to start daemon","runner did not accept connection","xcodebuild exited early","device is offline","device offline","device unauthorized"];function yR(e){var t,r,n,a;let i,o,s="ok"in(t=e)?t.ok?null:t.error:"failed"===t.status?t.error:null;return!!s&&(r=s.details,!!(i="string"==typeof r?.reason?r.reason:"")&&eo(i)||(n=s.code,a=s.message,o=`${n}
66
+ ${a}`.toLowerCase(),yO.some(e=>o.includes(e))))}async function yE(e){let t,{filePath:r,sessionName:n,requestId:a,timeoutMs:i,platform:o,target:s,artifactsDir:l,runReplay:u,cleanupSession:d}=e;rp(a);let c=new Set,p=!1,f=u({filePath:r,sessionName:n,platform:o,target:s,requestId:a,artifactsDir:l,artifactPaths:c}).catch(e=>({ok:!1,error:k(e)})).finally(()=>{rm(a)});try{return"number"==typeof i?await Promise.race([f,new Promise(e=>{t=setTimeout(()=>{p=!0,rf(a),e(function(e,t=[]){return{ok:!1,error:{code:"COMMAND_FAILED",message:`TIMEOUT after ${e}ms`,hint:"Replay test timeouts are cooperative; the active command may take a short grace period to stop.",details:{reason:"timeout",timeoutMs:e,timeoutMode:"cooperative",artifactPaths:t}}}}(i,[...c]))},i)})]):await f}finally{t&&clearTimeout(t),p&&(await yC(f)||eN({level:"warn",phase:"test_timeout_cleanup_race",data:{session:n,requestId:a,graceMs:2e3}}));try{await d(n)}catch(e){eN({level:"warn",phase:"test_cleanup_failed",data:{session:n,error:k(e).message}})}}}async function yC(e){return await Promise.race([e.then(()=>!0),S(2e3).then(()=>!1)])}async function yL(e){let{req:t,sessionName:r,runReplay:n,cleanupSession:a}=e;if((t.positionals?.length??0)===0)return cM("INVALID_ARGS","test requires at least one path or glob");try{var i,o,s,u,d,c;let e,p,m,h,w,g=function(e){var t,r,n;let{inputs:a,cwd:i,platformFilter:o,replayBackend:s}=e,u=(t=s,new Set(yP(t)?[".ad",".yaml",".yml"]:[".ad"])),d=i??process.cwd(),c=[...new Set(a.flatMap(e=>(function(e,t,r){var n,a;let i=aq.expandHome(e,t);if(l.existsSync(i)){let t=l.statSync(i);if(t.isDirectory())return[...r].map(e=>`**/*${e}`).flatMap(e=>l.globSync(e,{cwd:i}).map(e=>f.join(i,e)));if(t.isFile()){if(!r.has(f.extname(i)))throw new D("INVALID_ARGS",`test does not support this file type: ${e}`);return[i]}return[]}if(n=e,!yD.test(n)&&(a=i,!yD.test(a)))throw new D("INVALID_ARGS",`test input not found: ${e}`);let o=f.isAbsolute(i)?i:e;return l.globSync(o,{cwd:f.isAbsolute(i)?void 0:t}).map(e=>f.isAbsolute(e)?e:f.resolve(t,e)).filter(e=>r.has(f.extname(e))&&function(e){try{return l.statSync(e).isFile()}catch{return!1}}(e))})(e,d,u)))].map(e=>f.normalize(e)).sort((e,t)=>e.localeCompare(t)),p=[];for(let e of c){let t=y_(l.readFileSync(e,"utf8"));if(!o){p.push({kind:"run",path:e,metadata:t});continue}if(!t.platform){yP(s)?p.push({kind:"run",path:e,metadata:t}):p.push({kind:"skip",path:e,reason:"skipped-by-filter",message:`missing platform metadata for --platform ${o}`});continue}r=o,n=t.platform,("apple"===r?"apple"===n||"ios"===n||"macos"===n:n===r)&&p.push({kind:"run",path:e,metadata:t})}if(0===p.filter(e=>"run"===e.kind).length){let e=o?` for --platform ${o}`:"";throw new D("INVALID_ARGS",`No replay tests matched${e}.`)}return p}({inputs:t.positionals,cwd:t.meta?.cwd,platformFilter:t.flags?.platform,replayBackend:t.flags?.replayBackend}),y=(i=t.meta?.requestId,(i?.trim()||`${process.pid}-${Date.now().toString(36)}`).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"suite"),v=function(e){let{artifactsDir:t,cwd:r,suiteInvocationId:n}=e,a=aq.expandHome(t??".agent-device/test-artifacts",r);return f.join(a,n)}({artifactsDir:"string"==typeof t.flags?.artifactsDir?t.flags.artifactsDir:void 0,cwd:t.meta?.cwd,suiteInvocationId:y}),I=[],b=Date.now(),A=0;for(let[e,i]of g.entries()){if("skip"===i.kind){iB({type:"replay-test",file:i.path,status:"skip",index:e+1,total:g.length,message:i.message}),I.push({file:i.path,status:"skipped",durationMs:0,reason:i.reason,message:i.message});continue}A+=1;let l=await yT({entry:i,sessionName:r,suiteInvocationId:y,caseIndex:A-1,cwd:t.meta?.cwd,requestId:t.meta?.requestId,retries:function(e,t){let r="number"==typeof e?e:t;return"number"!=typeof r?0:Math.max(0,Math.min(3,r))}(t.flags?.retries,i.metadata.retries),timeoutMs:(o=t.flags?.timeoutMs,s=i.metadata.timeoutMs,"number"==typeof o?o:s),suiteArtifactsDir:v,suiteIndex:e+1,suiteTotal:g.length,runReplay:n,cleanupSession:a});if(I.push(l),t.flags?.failFast===!0||yR(l))break}let S=(u=g.length,d=I,c=Date.now()-b,e=d.filter(e=>"passed"===e.status).length,m=(p=d.filter(e=>"failed"===e.status)).length,h=d.filter(e=>"skipped"===e.status).length,w=e+m,{total:u,executed:w,passed:e,failed:m,skipped:h,notRun:Math.max(0,u-w-h),durationMs:c,failures:p,tests:d});return{ok:!0,data:S}}catch(t){let e=M(t);return cM(e.code,e.message)}}async function yT(e){var t,r;let n,a,{entry:i,sessionName:o,suiteInvocationId:s,caseIndex:u,cwd:d,requestId:c,retries:p,timeoutMs:m,suiteArtifactsDir:h,suiteIndex:w,suiteTotal:g,runReplay:y,cleanupSession:v}=e,I=Date.now(),b=f.join(h,(t=i.path,(0===(a=d?f.relative(d,t):f.basename(t)).length||a.startsWith("..")?f.basename(t):a).toLowerCase().replace(/[\\/]+/g,"__").replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"test")),A="",S=0;for(let e=0;e<=p;e+=1){S=e+1;let t=function(e,t,r,n,a=0){let i=f.basename(r,f.extname(r)).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return`${e}:test:${t}:${n+1}${i?`-${i}`:""}:attempt-${a+1}`}(o,s,i.path,u,e),a=f.join(b,`attempt-${S}`);r=i.path,l.mkdirSync(a,{recursive:!0}),function(e,t){let r=f.join(t,"replay.ad");if(l.copyFileSync(e,r),!function(e){let t=f.extname(e).toLowerCase();return".yml"===t||".yaml"===t}(e))return;let n=f.join(t,f.basename(e));f.resolve(n)!==f.resolve(r)&&l.copyFileSync(e,n)}(r,a);let d=function(e){let{requestId:t,suiteInvocationId:r,filePath:n,caseIndex:a,attemptIndex:i}=e;return rc(`${t??r}:test:${a+1}:${f.basename(n)}:attempt:${i+1}`,r)}({requestId:c,suiteInvocationId:s,filePath:i.path,caseIndex:u,attemptIndex:e}),h=await yE({filePath:i.path,sessionName:t,requestId:d,timeoutMs:m,platform:i.metadata.platform,target:i.metadata.target,artifactsDir:a,runReplay:y,cleanupSession:v});if(!function(e){let{response:t,filePath:r,sessionName:n,attempts:a,maxAttempts:i,attemptArtifactsDir:o}=e,s=[...function(e){let t=e.ok?e.data?.artifactPaths:e.error.details?.artifactPaths;return Array.isArray(t)?[...new Set(t.filter(e=>"string"==typeof e))]:[]}(t)];t.ok||"string"!=typeof t.error.logPath||s.push(t.error.logPath);let u=function(e,t){let r=[],n=new Map;for(let a of e){if(!function(e){try{return l.statSync(e).isFile()}catch{return!1}}(a))continue;let e=function(e,t){let r=f.extname(e),n=r?e.slice(0,-r.length):e,a=t.get(e)??0;return(t.set(e,a+1),0===a)?e:`${n}-${a+1}${r}`}(f.basename(a),n),i=f.join(t,e);f.resolve(a)!==f.resolve(i)&&l.copyFileSync(a,i),r.push(i)}return r}(s,o),d=[`file: ${r}`,`session: ${n}`,`attempt: ${a}/${i}`,`status: ${t.ok?"passed":"failed"}`];if(t.ok){let e="number"==typeof t.data?.replayed?t.data.replayed:0,r="number"==typeof t.data?.healed?t.data.healed:0;d.push(`replayed: ${e}`,`healed: ${r}`)}else d.push(`code: ${t.error.code}`,`message: ${t.error.message}`),t.error.hint&&d.push(`hint: ${t.error.hint}`),t.error.diagnosticId&&d.push(`diagnosticId: ${t.error.diagnosticId}`),t.error.logPath&&d.push(`logPath: ${t.error.logPath}`),t.error.details?.reason==="timeout"&&d.push("timeoutMode: cooperative");u.length>0&&d.push(`copiedArtifacts: ${u.map(e=>f.basename(e)).join(", ")}`);let c=f.join(o,"result.txt"),p=`${d.join("\n")}
67
+ `;l.writeFileSync(c,p),t.ok||l.writeFileSync(f.join(o,"failure.txt"),p)}({response:h,filePath:i.path,sessionName:t,attempts:S,maxAttempts:p+1,attemptArtifactsDir:a}),n=h,A=t,h.ok||yR(h)||e>=p)break;iB({type:"replay-test",file:i.path,status:"fail",index:w,total:g,attempt:S,maxAttempts:p+1,retrying:!0,message:h.error.message})}let x=Date.now()-I;if(n?.ok)return iB({type:"replay-test",file:i.path,status:"pass",index:w,total:g,attempt:S,maxAttempts:p+1,durationMs:x,artifactsDir:b}),{file:i.path,session:A,status:"passed",durationMs:x,attempts:S,artifactsDir:b,replayed:"number"==typeof n.data?.replayed?n.data.replayed:0,healed:"number"==typeof n.data?.healed?n.data.healed:0};let _=n?.ok?{code:"COMMAND_FAILED",message:"Unknown replay test failure"}:n?.error??{code:"COMMAND_FAILED",message:"Unknown replay test failure"};return iB({type:"replay-test",file:i.path,status:"fail",index:w,total:g,attempt:S,maxAttempts:p+1,durationMs:x,artifactsDir:b,message:_.message}),{file:i.path,session:A,status:"failed",durationMs:x,attempts:S,artifactsDir:b,error:_}}function y$(e,t=[],r){return{ts:Date.now(),command:e,positionals:t,flags:r??{}}}function yF(e,t,r){let n=new Set(r),a=Object.keys(e).filter(e=>!n.has(e));if(a.length>0)throw yz(`Maestro ${t} field "${a[0]}" is not supported yet.`)}function yU(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function yV(e){return e.map((e,t)=>{if("string"==typeof e||yU(e))return e;throw new D("INVALID_ARGS",`Unsupported Maestro command at index ${t+1}: expected a scalar or one-key map.`)})}function yG(e,t){if(null==e)return{};if(!yU(e))throw new D("INVALID_ARGS",`${t} expects a map.`);let r={};for(let[t,n]of Object.entries(e))("string"==typeof n||"number"==typeof n||"boolean"==typeof n)&&(r[t]=String(n));return r}function yq(e,t){return yU(e)&&"number"==typeof e.timeout&&Number.isFinite(e.timeout)?Math.max(0,Math.floor(e.timeout)):t}function yB(e,t){if(e.appId)return e.appId;throw new D("INVALID_ARGS",`${t} requires appId in the Maestro flow config.`)}function yj(e,t){if("string"==typeof t)return t;throw new D("INVALID_ARGS",`${e} expects a string value.`)}function yH(e,t){return e.replace(/\$\{([A-Za-z_][A-Za-z0-9_.]*)\}/g,(e,r)=>Object.prototype.hasOwnProperty.call(t.env,r)?String(t.env[r]):e)}function yW(e){throw yz(`Maestro command "${e}" is not supported yet.`)}function yz(e){throw new D("INVALID_ARGS",`${e} See supported/unsupported Maestro compatibility at https://github.com/callstackincubator/agent-device/issues/558. If this syntax matters for your flows, comment there or open a focused issue at https://github.com/callstackincubator/agent-device/issues/new.`)}function yK(e,t,r){var n,a;if(null==e)return y$("open",[yH(yB(t,"launchApp"),r)]);if("string"==typeof e)return y$("open",[yH(e,r)]);if(!yU(e))throw new D("INVALID_ARGS","launchApp expects a string or map.");yF(e,"launchApp",["appId","stopApp","clearState","clearKeychain","arguments","permissions","launchArguments"]),yZ(e,"permissions"),yZ(e,"clearKeychain");let i=yH("string"==typeof e.appId?e.appId:yB(t,"launchApp"),r),o=(n=e,a=r,[...yX(n.arguments,"launchApp.arguments",a),...yX(n.launchArguments,"launchApp.launchArguments",a)]),s=!0===e.clearState;return y$("open",[i],{...!s&&(!0===e.stopApp||o.length>0)?{relaunch:!0}:{},...s?{clearAppState:!0}:{},...o.length>0?{launchArgs:o}:{}})}function yJ(e,t,r){if(null==e)return y$("close",[yH(yB(t,"stopApp"),r)]);if("string"==typeof e)return y$("close",[yH(e,r)]);throw new D("INVALID_ARGS","stopApp expects a string appId or no value.")}function yX(e,t,r){if(null==e)return[];if("string"==typeof e)return[yH(e,r)];if(Array.isArray(e))return e.map((e,n)=>yY(e,`${t}[${n}]`,r));if(yU(e))return Object.entries(e).flatMap(([e,n])=>[yH(e,r),yY(n,`${t}.${e}`,r)]);throw new D("INVALID_ARGS",`${t} expects a string, list, or map.`)}function yY(e,t,r){if("string"==typeof e)return yH(e,r);if("number"==typeof e||"boolean"==typeof e)return String(e);throw new D("INVALID_ARGS",`${t} must be a string, number, or boolean.`)}function yZ(e,t){if(void 0!==e[t])throw yz(`Maestro launchApp field "${t}" is not supported yet.`)}function yQ(e){let t=e.match(/^(\d+),(\d+)$/);if(!t)throw yz('Only absolute Maestro point selectors like "100,200" are supported.');return{x:Number(t[1]),y:Number(t[2])}}function y0(e){let t=e.match(/^\s*(\d+)\s*,\s*(\d+)\s*$/);if(t)return{kind:"absolute",x:Number(t[1]),y:Number(t[2])};let r=e.match(/^\s*(\d+(?:\.\d+)?)%\s*,\s*(\d+(?:\.\d+)?)%\s*$/);if(r)return{kind:"percent",x:Number(r[1]),y:Number(r[2])};throw yz('Only Maestro swipe coordinates like "100,200" or "50%,75%" are supported.')}let y1="__maestroRunFlowWhen",y2="__maestroRetry",y3="__maestroRunScript",y5="__maestroAssertVisible",y4="__maestroAssertNotVisible",y8="__maestroPressEnter",y6="__maestroWaitForAnimationToEnd",y9="__maestroScrollUntilVisible",y7="__maestroSwipeScreen",ve="__maestroSwipeOn",vt="__maestroTapOn",vr="__maestroTapPointPercent";function vn(e){if(null==e)return y$("type",["\b".repeat(50)]);if("number"==typeof e&&Number.isInteger(e)&&e>0)return y$("type",["\b".repeat(e)]);if(!yU(e))throw new D("INVALID_ARGS","eraseText expects empty, a positive count, or a map.");if(yF(e,"eraseText",["charactersToErase"]),void 0===e.charactersToErase)return y$("type",["\b".repeat(50)]);if("number"!=typeof e.charactersToErase||!Number.isInteger(e.charactersToErase)||e.charactersToErase<=0)throw new D("INVALID_ARGS","eraseText.charactersToErase must be a positive integer.");return y$("type",["\b".repeat(e.charactersToErase)])}function va(e){return"number"==typeof e&&Number.isFinite(e)?String(Math.max(16,Math.floor(e))):void 0}function vi(e,t){let r=e.toLowerCase();switch(r){case"up":case"down":case"left":case"right":return r;default:throw yz(`Maestro ${t} must be UP, DOWN, LEFT, or RIGHT.`)}}function vo(e){return vi(e,"swipe direction")}function vs(e,t,r=[],n){if("string"==typeof e)return vl(yH(e,n));if(!yU(e))throw new D("INVALID_ARGS",`${t} expects a string or selector map.`);yF(e,t,["id","text","enabled","selected",...r]);let a=[],i=[];if("boolean"==typeof e.enabled&&i.push(vd("enabled",String(e.enabled))),"boolean"==typeof e.selected&&i.push(vd("selected",String(e.selected))),"string"==typeof e.id&&a.push(vd("id",yH(e.id,n)),...i),"string"==typeof e.text&&0===a.length)return vl(yH(e.text,n),i);if("string"==typeof e.label&&0===a.length&&a.push(vd("label",yH(e.label,n)),...i),0===a.length&&i.length>0&&a.push(...i),0===a.length)throw new D("INVALID_ARGS",`${t} selector map must include one of id, text, label, enabled, or selected.`);return a.join(" ")}function vl(e,t=[]){return[[vd("label",e),...t].join(" "),[vd("text",e),...t].join(" "),[vd("id",e),...t].join(" ")].join(" || ")}function vu(e){let t=va(e.duration);return t?[t]:[]}function vd(e,t){return`${e}=${JSON.stringify(t)}`}function vc(e){var t,r;if(!yU(e))return;let n={},a="number"==typeof(t=e.repeat)&&Number.isInteger(t)&&t>0?t:void 0,i="number"==typeof(r=e.delay)&&Number.isInteger(r)&&r>=0?r:void 0;return a&&a>1&&(n.count=a),void 0!==i&&(n.intervalMs=i),!0===e.optional&&(n.maestro={optional:!0}),Object.keys(n).length>0?n:void 0}function vp(e){let t=vc(e)??{};return{...t,maestro:{...t.maestro??{},allowNonHittableCoordinateFallback:!0}}}function vf(e){let t={doubleTap:!0};return yU(e)&&"number"==typeof e.delay&&Number.isInteger(e.delay)&&(t.intervalMs=Math.max(0,e.delay)),t}class vm{index=0;tokens;context;constructor(e,t){this.tokens=e,this.context=t}parse(){let e=this.parseOr();if(this.peek())throw new D("INVALID_ARGS","Unsupported trailing runFlow.when.true expression.");return e}parseOr(){let e=this.parseAnd();for(;this.consumeOperator("||");)e=this.parseAnd()||e;return e}parseAnd(){let e=this.parsePrimary();for(;this.consumeOperator("&&");)e=this.parsePrimary()&&e;return e}parsePrimary(){let e=this.peek();if(!e)throw new D("INVALID_ARGS","Incomplete runFlow.when.true expression.");if("boolean"===e.type)return this.index+=1,e.value;if("paren"===e.type&&"("===e.value){this.index+=1;let e=this.parseOr();if(!this.consumeParen(")"))throw new D("INVALID_ARGS","Unclosed runFlow.when.true parenthesis.");return e}return this.parsePlatformComparison()}parsePlatformComparison(){this.expectPlatform();let e=this.expectEqualityOperator(),t=this.expectString().toLowerCase(),r=this.context.platform;return"=="===e?r===t:r!==t}expectPlatform(){if(this.peek()?.type!=="platform")throw new D("INVALID_ARGS","runFlow.when.true supports maestro.platform comparisons.");this.index+=1}expectEqualityOperator(){let e=this.peek();if(e?.type==="operator"&&("=="===e.value||"!="===e.value))return this.index+=1,e.value;throw new D("INVALID_ARGS","runFlow.when.true comparison requires == or !=.")}expectString(){let e=this.peek();if(e?.type==="string")return this.index+=1,e.value;throw new D("INVALID_ARGS","runFlow.when.true comparison requires a string literal.")}consumeOperator(e){let t=this.peek();return t?.type==="operator"&&t.value===e&&(this.index+=1,!0)}consumeParen(e){let t=this.peek();return t?.type==="paren"&&t.value===e&&(this.index+=1,!0)}peek(){return this.tokens[this.index]}}function vh(e){return{command:e.command,positionals:e.positionals,flags:e.flags,...void 0!==e.runtime?{runtime:e.runtime}:{}}}function vw(e,t,r){let n="string"==typeof e?yH(e,t):e,a="number"==typeof n?n:"string"==typeof n&&/^\d+$/.test(n)?Number(n):void 0;if(void 0===a||!Number.isInteger(a)||a<0)throw new D("INVALID_ARGS",`${r} must be a non-negative integer or \${VAR} resolving to one.`);return a}let vg=`
67
68
  const fs = require('node:fs');
68
69
  const input = JSON.parse(fs.readFileSync(0, 'utf8'));
69
70
  if (typeof fetch !== 'function') {
@@ -84,16 +85,16 @@ fetch(input.url, {
84
85
  console.error(error && error.stack ? error.stack : String(error));
85
86
  process.exit(1);
86
87
  });
87
- `;function vn(e){if("string"!=typeof e)throw new O("COMMAND_FAILED",`Maestro runScript json() expected a string body, received ${typeof e}.`);if(0===e.trim().length)throw new O("COMMAND_FAILED","Maestro runScript json() received an empty body. Check the preceding http response status and setup server output.");try{return JSON.parse(e,va)}catch(t){throw new O("COMMAND_FAILED",`Maestro runScript json() could not parse response body: ${t instanceof Error?t.message:String(t)}`,{bodyPreview:e.slice(0,1e3)},t instanceof Error?t:void 0)}}function va(e,t){return"__proto__"===e||"constructor"===e||"prototype"===e?void 0:t}let vi={launchApp:({value:e,config:t,context:r})=>[yC(e,t,r)],tapOn:({value:e,context:t})=>[function(e,t){if("string"==typeof e)return yA(yX,[y3(yP(e,t))],y6(e));if(y_(e)&&"string"==typeof e.point){yS(e,"tapOn",["point","repeat","delay","optional","label"]);let t=yU(e.point);return"percent"===t.kind?yA(yY,[String(t.x),String(t.y)],y8(e)):yA("click",[String(t.x),String(t.y)],y8(e))}y_(e)&&yS(e,"tapOn",["id","text","childOf","enabled","index","selected","repeat","delay","optional","label"]);let r=y6(e);return yA(yX,[y2(e,"tapOn",["repeat","delay","optional","label","index","childOf"],t),...function(e,t){if(!y_(e))return[];let r={};if(void 0!==e.index){if("number"!=typeof e.index||!Number.isInteger(e.index)||e.index<0)throw new O("INVALID_ARGS","tapOn.index must be a non-negative integer.");r.index=e.index}return void 0!==e.childOf&&(r.childOf=y2(e.childOf,"tapOn.childOf",[],t)),Object.keys(r).length>0?[JSON.stringify(r)]:[]}(e,t)],r)}(e,t)],doubleTapOn:({value:e,context:t})=>[function(e,t){if(y_(e)&&"string"==typeof e.point){yS(e,"doubleTapOn",["point","delay"]);let t=yF(e.point);return yA("click",[String(t.x),String(t.y)],y9(e))}return y_(e)&&yS(e,"doubleTapOn",["id","text","enabled","selected","delay"]),yA("click",[y2(e,"doubleTapOn",["delay"],t)],y9(e))}(e,t)],longPressOn:({value:e,context:t})=>[function(e,t){if(y_(e)&&"string"==typeof e.point){yS(e,"longPressOn",["point"]);let t=yF(e.point);return yA("longpress",[String(t.x),String(t.y),"3000"])}return y_(e)&&yS(e,"longPressOn",["id","text","enabled","selected"]),yA("click",[y2(e,"longPressOn",[],t)],{holdMs:3e3})}(e,t)],inputText:({value:e,context:t})=>[yA("type",[yP(function(e){if("string"==typeof e)return e;if(!y_(e))throw new O("INVALID_ARGS","inputText expects a string or map.");if(yS(e,"inputText",["text","label"]),"string"!=typeof e.text)throw new O("INVALID_ARGS","inputText map requires a string text field.");return e.text}(e),t)])],eraseText:({value:e})=>[yZ(e)],pasteText:({value:e,context:t,name:r})=>[yA("type",[yP(yD(r,e),t)])],openLink:({value:e,config:t,context:r,name:n})=>{var a,i,o,s,l,u;let d;return[(a=e,i=t,o=r,s=n,d=yP((l=a,u=s,"string"==typeof l?l:y_(l)?(yS(l,u,["link"]),yD(`${u}.link`,l.link)):yD(u,l)),o),"ios"===o.platform&&i.appId?yA("open",[yP(yk(i,s),o),d]):yA("open",[d]))]},assertVisible:({value:e,context:t,name:r})=>[yA(yj,[y2(e,r,[],t),"5000"])],assertNotVisible:({value:e,context:t,name:r})=>[yA(yB,[y2(e,r,[],t)])],extendedWaitUntil:({value:e,context:t})=>(function(e,t){if(!y_(e))throw new O("INVALID_ARGS","extendedWaitUntil expects a map.");yS(e,"extendedWaitUntil",["visible","notVisible","timeout"]);let r=e.visible??e.notVisible;if(void 0===r)throw yR("Only Maestro extendedWaitUntil.visible/notVisible is supported.");let n=y2(r,"extendedWaitUntil",[],t),a=String(yM(e,3e4));return void 0!==e.notVisible?[yA("wait",[a]),yA("is",["hidden",n])]:[yA(yj,[n,a])]})(e,t),takeScreenshot:({value:e,context:t,name:r})=>[yA("screenshot",[yP(yD(r,e),t)])],scroll:({value:e})=>[function(e){if(null!=e)throw yR("Maestro scroll options are not supported yet.");return yA("scroll",["down"])}(e)],scrollUntilVisible:({value:e,context:t})=>(function(e,t){if("string"==typeof e)return[yA(yz,[y3(yP(e,t)),"5000","down"])];if(!y_(e))throw new O("INVALID_ARGS","scrollUntilVisible expects a string or map.");yS(e,"scrollUntilVisible",["element","direction","timeout"]);let r=y2(e.element,"scrollUntilVisible.element",[],t),n="string"==typeof e.direction?y0(e.direction,"scrollUntilVisible.direction"):"down";return[yA(yz,[r,String(yM(e,5e3)),n])]})(e,t),swipe:({value:e,context:t})=>[function(e,t){var r,n,a;let i;if(!y_(e))throw new O("INVALID_ARGS","swipe expects a map.");yS(e,"swipe",["start","end","direction","duration","from","label"]);let o=e.from??("string"==typeof e.label?e.label:void 0);return void 0!==o?(r=e,n=o,a=t,i=y1("string"==typeof r.direction?r.direction:"up"),yA(yJ,[y2(n,"swipe.from",[],a),i,...y5(r)])):"string"==typeof e.direction?yA(yK,["direction",y1(e.direction),...y5(e)]):function(e){let{start:t,end:r}=function(e){if("string"==typeof e.start&&"string"==typeof e.end)return{start:yU(e.start),end:yU(e.end)};throw yR("Only Maestro swipe start/end coordinates are supported.")}(e);var n=t,a=r,i=yQ(e.duration);if("absolute"===n.kind&&"absolute"===a.kind)return yA("swipe",[String(n.x),String(n.y),String(a.x),String(a.y),...i?[i]:[]]);if("percent"===n.kind&&"percent"===a.kind)return yA(yK,["percent",String(n.x),String(n.y),String(a.x),String(a.y),...i?[i]:[]]);throw yR("Maestro swipe start/end must both be absolute pixels or both be percentages.")}(e)}(e,t)],hideKeyboard:()=>[yA("keyboard",["dismiss"])],pressKey:({value:e})=>[function(e){let t=yD("pressKey",e).toLowerCase();if("back"===t)return yA("back");if("enter"===t||"return"===t)return yA(yH);if("home"===t)return yA("home");throw yR(`Maestro pressKey "${t}" is not supported yet.`)}(e)],back:()=>[yA("back")],waitForAnimationToEnd:({value:e})=>[yA(yW,[String(yM(e,15e3))])],stopApp:({value:e,config:t,context:r})=>[yE(e,t,r)],runScript:({value:e,context:t})=>{let r;return[yA(yq,[function(e,t){if(f.isAbsolute(e))return e;if(!t.baseDir)throw new O("INVALID_ARGS","runScript file paths require replay input to have a source path.");return f.resolve(t.baseDir,e)}((r=function(e,t){if("string"==typeof e)return{file:yP(e,t),env:{}};if(!y_(e))throw new O("INVALID_ARGS","runScript expects a file path string or map.");return yS(e,"runScript",["file","env"]),{file:yP(yD("runScript.file",e.file),t),env:Object.fromEntries(Object.entries(yN(e.env,"runScript.env")).map(([e,r])=>[e,yP(r,t)]))}}(e,t)).file,t)],{...Object.keys(r.env).length>0?{maestro:{runScriptEnv:r.env}}:{}})]},runFlow:({value:e,config:t,context:r,deps:n})=>(function(e,t,r,n,a){if("string"==typeof e)return n.parseRunFlowFile(yP(e,r),r).actions;if(!y_(e))throw new O("INVALID_ARGS","runFlow expects a file path string or map.");yS(e,"runFlow",["file","commands","env","when","label"]);let i=function(e,t){var r,n;if(null==e)return{shouldRun:!0};if(!y_(e))throw new O("INVALID_ARGS","runFlow.when expects a map.");return(yS(e,"runFlow.when",["platform","visible","notVisible","true"]),!function(e,t){if(void 0!==e.true&&!function(e,t){let r;if("boolean"==typeof e)return e;if("string"!=typeof e)throw new O("INVALID_ARGS","runFlow.when.true expects a boolean or expression string.");return new y7(function(e){let t=[],r=0;for(;r<e.length;){var n,a;let i=e.slice(r),o=(n=i,/^\s+/.exec(n)?.[0].length??0);if(o>0){r+=o;continue}let s=function(e){let t="maestro.platform";return e.startsWith(t)?{token:{type:"platform"},length:t.length}:null}(a=i)??function(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{token:{type:"operator",value:t},length:t.length}:null}(a)??function(e){let t=e[0];return"("===t||")"===t?{token:{type:"paren",value:t},length:1}:null}(a)??function(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{token:{type:"string",value:t[2]??""},length:t[0].length}:null}(a)??function(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{token:{type:"boolean",value:"true"===t},length:t.length}:null}(a);if(s){t.push(s.token),r+=s.length;continue}throw new O("INVALID_ARGS",`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`)}return t}((r=yP(e,t).trim()).startsWith("${")&&r.endsWith("}")?r.slice(2,-1).trim():r),{platform:t.platform}).parse()}(e.true,t))return!1;if(void 0===e.platform)return!0;let r=function(e,t){if("string"!=typeof e)throw new O("INVALID_ARGS",`${t} expects Android, iOS, or Web.`);let r=e.trim().toLowerCase();if("android"===r||"ios"===r||"web"===r)return r;throw new O("INVALID_ARGS",`${t} expects Android, iOS, or Web.`)}(e.platform,"runFlow.when.platform");if(!t.platform)throw new O("INVALID_ARGS","Maestro runFlow.when.platform requires replay to be run with --platform ios|android.");return r===t.platform}(e,t))?{shouldRun:!1}:{shouldRun:!0,...(r=e,n=t,{...void 0!==r.visible?{visibleSelector:y2(r.visible,"runFlow.when.visible",[],n)}:{},...void 0!==r.notVisible?{notVisibleSelector:y2(r.notVisible,"runFlow.when.notVisible",[],n)}:{}})}}(e.when,r);if(!i.shouldRun)return[];let o={...r,env:{...r.env,...yN(e.env,"runFlow.env"),...r.envOverrides}};var s=function(e,t,r,n,a){if("string"==typeof e.file)return n.parseRunFlowFile(yP(e.file,r),r).actions;if(Array.isArray(e.commands))return a(yx(e.commands),t,r,n);throw new O("INVALID_ARGS","runFlow map requires either file or commands.")}(e,t,o,n,a),l=i;if(!l.visibleSelector&&!l.notVisibleSelector)return s;if(l.visibleSelector&&l.notVisibleSelector)throw yR("Maestro runFlow.when cannot combine visible and notVisible yet.");return[yA(yV,l.visibleSelector?["visible",l.visibleSelector]:["notVisible",l.notVisibleSelector??""],{batchSteps:s.map(ve)})]})(e,t,r,n,vl),repeat:({value:e,config:t,context:r,deps:n})=>(function(e,t,r,n,a){var i;if(!y_(e))throw new O("INVALID_ARGS","repeat expects a map.");if(yS(e,"repeat",["times","commands","while"]),void 0!==e.while)throw yR("Maestro repeat.while is not supported yet. Only deterministic repeat.times is supported.");let o=(i=e.times,vt(i,r,"repeat.times"));if(!Array.isArray(e.commands))throw new O("INVALID_ARGS","repeat requires a commands list.");if(o>1e3)throw new O("INVALID_ARGS","repeat.times must be <= 1000 for deterministic replay expansion.");let s=yx(e.commands);return Array.from({length:o}).flatMap(()=>a(s,t,r,n))})(e,t,r,n,vl),retry:({value:e,config:t,context:r,deps:n})=>(function(e,t,r,n,a){var i,o;if(!y_(e))throw new O("INVALID_ARGS","retry expects a map.");if(yS(e,"retry",["maxRetries","commands"]),!Array.isArray(e.commands))throw new O("INVALID_ARGS","retry requires a commands list.");let s=(i=e.maxRetries,o=r,void 0===i?1:vt(i,o,"retry.maxRetries")),l=a(yx(e.commands),t,r,n);return[yA(yG,[String(s)],{batchSteps:l.map(ve)})]})(e,t,r,n,vl)},vo={launchApp:(e,t)=>[yC(void 0,e,t)],scroll:()=>[yA("scroll",["down"])],hideKeyboard:()=>[yA("keyboard",["dismiss"])],eraseText:()=>[yZ(void 0)],back:()=>[yA("back")],waitForAnimationToEnd:()=>[yA(yW,["15000"])],stopApp:(e,t)=>[yE(void 0,e,t)]};function vs(e,t,r,n,a){try{return function(e,t,r,n){if("string"==typeof e){var a,i,o;let n;return a=e,i=t,o=r,(n=vo[a])?n(i,o):yO(a)}let s=Object.entries(e);if(1!==s.length)throw new O("INVALID_ARGS","Maestro command maps must contain exactly one command.");let[l,u]=s[0],d=vi[l];return d?d({value:u,config:t,context:r,deps:n,name:l}):yO(l)}(e,t,n,a)}catch(e){if(e instanceof O&&!/\bline \d+\b/.test(e.message))throw new O(e.code,`${e.message} (line ${r})`,e.details);throw e}}function vl(e,t,r,n){return e.flatMap((e,a)=>vs(e,t,a+1,r,n))}function vu(e,t){let{config:r,commands:n}=function(e){if(0===e.length)throw new O("INVALID_ARGS","Maestro flow is empty.");if(Array.isArray(e[0]))return{config:{},commands:yx(e[0])};let t=function(e){if(!y_(e))throw new O("INVALID_ARGS","Maestro flow config must be a YAML map.");return{..."string"==typeof e.appId&&e.appId.length>0?{appId:e.appId}:{},...y_(e.env)?{env:yN(e.env,"env")}:{},...Array.isArray(e.onFlowStart)?{onFlowStart:yx(e.onFlowStart)}:{},...Array.isArray(e.onFlowComplete)?{onFlowComplete:yx(e.onFlowComplete)}:{}}}(e[0]),r=e[1];if(!Array.isArray(r))throw new O("INVALID_ARGS","Maestro flow must contain a command list after the YAML document separator.");return{config:t,commands:yx(r)}}(function(e){let t=N(e);for(let e of t)if(e.errors.length>0){let t=e.errors[0]?.message??"Invalid Maestro YAML flow.";throw new O("INVALID_ARGS",`Invalid Maestro YAML flow: ${t}`)}return t.map(e=>e.toJSON()).filter(e=>null!==e)}(e)),a={...t,env:{...t.env,...r.env??{},...t.envOverrides}},{actions:i,actionLines:o}=function(e){let{config:t,commands:r,commandLines:n,context:a}=e,i=[...t.onFlowStart??[],...r,...t.onFlowComplete??[]],o=[...Array.from({length:t.onFlowStart?.length??0},()=>1),...n,...Array.from({length:t.onFlowComplete?.length??0},()=>n.at(-1)??1)],s=[],l=[];for(let[e,r]of i.entries()){let n=o[e]??e+1,i=vs(r,t,n,a,{parseRunFlowFile:vc});s.push(...i),i.forEach(()=>l.push(n))}return function(e,t){let r=[],n=[];for(let a=0;a<e.length;a+=1){let i=e[a],o=function(e,t,r){var n;let a=e[r],i=e[r+1],o=function(e){if(e?.command!=="type"||e.flags&&Object.keys(e.flags).length>0)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(i),s=function(e){if(e?.command!==yX)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(a);if(!i||null===o||null===s)return null;let l=t[r]??1;if(n=s,!/\b(input|textfield|textarea|field|email|password|username|search|query)\b/i.test(n.replace(/([a-z])([A-Z])/g,"$1 $2")))return{actions:[vd(a)],actionLines:[l],consumed:1};let u=e[r+2];return u?.command!==yH?{actions:[vd(a)],actionLines:[l],consumed:1}:{actions:[{...a,command:"wait",positionals:[s,"30000"]},{...i,command:"fill",positionals:[s,o],flags:a.flags},u],actionLines:[l,l,t[r+2]??l],consumed:3}}(e,t,a);if(o){r.push(...o.actions),n.push(...o.actionLines),a+=o.consumed-1;continue}r.push(i),n.push(t[a]??1)}return{actions:r,actionLines:n}}(s,l)}({config:r,commands:n,commandLines:function(e){let t=e.split(/\r?\n/),r=t.findIndex(e=>"---"===e.trim()),n=-1===r?0:r+1,a=[];for(let e=n;e<t.length;e+=1)/^-\s+/.test(t[e]??"")&&a.push(e+1);return a}(e),context:a});return{actions:i,actionLines:o,metadata:{env:r.env}}}function vd(e){let t={...e.flags?.maestro??{}};return delete t.allowNonHittableCoordinateFallback,{...e,flags:{...e.flags??{},maestro:{...t}}}}function vc(e,t){let r=function(e,t){if(f.isAbsolute(e))return e;if(!t.baseDir)throw new O("INVALID_ARGS","runFlow file paths require replay input to have a source path.");return f.resolve(t.baseDir,e)}(e,t);if(t.visitedPaths.has(r))throw new O("INVALID_ARGS",`Maestro runFlow cycle detected at ${r}.`);let n=l.readFileSync(r,"utf8"),a=new Set(t.visitedPaths);return a.add(r),vu(n,{...t,baseDir:f.dirname(r),visitedPaths:a})}let vp={maestro:{parse:function(e,t={}){var r;let n;return vu(e,(n=(r=t).visitedPaths??new Set,r.sourcePath&&n.add(f.resolve(r.sourcePath)),{baseDir:r.sourcePath?f.dirname(r.sourcePath):void 0,platform:function(e){if(e){let t;return"android"===(t=e.trim().toLowerCase())?"android":"ios"===t?"ios":void 0}}(r.platform),env:{},envOverrides:r.env??{},visitedPaths:n}))}}};function vf(e){if(0===e.length)return{selectorExpression:null,selectorTimeout:null};let t=e[e.length-1],r=void 0!==t&&/^\d+$/.test(t)?t:null,n=tB(null!==r?e.slice(0,-1):e.slice());return!n||n.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:n.selectorExpression,selectorTimeout:r}}async function vm(e){let{action:t,sessionName:r,logPath:n,sessionStore:a}=e;if(!(ay(t.command)||["fill","get","is","wait"].includes(t.command)))return null;let i=a.get(r);if(!i)return null;let o=(function(e){let t=[],r=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>"string"==typeof e)?e.result.selectorChain:[];if(t.push(...r),ay(e.command)){let r=function(e){let t=e.positionals??[];if("longpress"!==e.command)return t;let r=t.at(-1);return t.length>1&&vh(r)?t.slice(0,-1):t}(e),n=r[0]??"";n&&!n.startsWith("@")&&t.push(r.join(" "))}if("fill"===e.command){let r=e.positionals?.[0]??"";r&&!r.startsWith("@")&&Number.isNaN(Number(r))&&t.push(r)}if("get"===e.command){let r=e.positionals?.[1]??"";r&&!r.startsWith("@")&&t.push(e.positionals.slice(1).join(" "))}if("is"===e.command){let{split:r}=tK(e.positionals);r&&t.push(r.selectorExpression)}if("wait"===e.command){let{selectorExpression:r}=vf(e.positionals??[]);r&&t.push(r)}return ac(t).filter(e=>e.trim().length>0)})(t).map(e=>tW(e)).filter(e=>null!==e);if(0===o.length)return null;let s=ay(t.command)||"fill"===t.command,l=ay(t.command)||"fill"===t.command||"get"===t.command&&t.positionals?.[0]==="text",u=await vw(i,t,n,s,a);for(let e of o){let r=tQ(u.nodes,e,{platform:i.device.platform,requireRect:s,requireUnique:!0,disambiguateAmbiguous:l});if(!r)continue;let n=t2(r.node,i.device.platform,{action:"fill"===t.command?"fill":ay(t.command)?"click":"get"}).join(" || ");if(ay(t.command))return{...t,positionals:"longpress"===t.command?function(e,t){let r="number"==typeof e.result?.durationMs?String(e.result.durationMs):function(e){let t=e.at(-1);return e.length>1&&vh(t)?t:void 0}(e.positionals??[]);return r?[t,r]:[t]}(t,n):[n]};if("fill"===t.command){let e=ad(t);if(!e)continue;return{...t,positionals:[n,e]}}if("get"===t.command){let e=t.positionals?.[0];if("text"!==e&&"attrs"!==e)continue;return{...t,positionals:[e,n]}}if("is"===t.command){let{predicate:e,split:r}=tK(t.positionals);if(!e)continue;let a=r?.rest.join(" ").trim()??"",i=[e,n];return"text"===e&&a.length>0&&i.push(a),{...t,positionals:i}}if("wait"===t.command){let{selectorTimeout:e}=vf(t.positionals??[]),r=[n];return e&&r.push(e),{...t,positionals:r}}}return null}function vh(e){return void 0!==e&&""!==e.trim()&&Number.isFinite(Number(e))}async function vw(e,t,r,n,a){let i=pc(await cr(e.device,"snapshot",[],t.flags?.out,{...cH(r,{...t.flags??{},snapshotInteractiveOnly:n,snapshotCompact:n},e.appBundleId,e.trace?.outPath)}),{...t.flags??{},snapshotInteractiveOnly:n,snapshotCompact:n});return ph(e,i),a.set(e.name,e),i}let vg=new WeakMap,vy=new WeakMap;function vv(e,t,r){return{ok:!1,error:{code:e,message:t,...r?{details:r}:{}}}}async function vI(e){var t;let r,n=await e.invoke({...e.baseReq,command:"snapshot",positionals:[],flags:{...e.baseReq.flags,noRecord:!0,snapshotRaw:!0,snapshotForceFull:!0}});return n.ok&&e.scope&&(t=e.scope,(r=p9(vb(n.data)))&&vg.set(t,r)),n}function vb(e){if("object"==typeof e&&null!==e&&Array.isArray(e.nodes))return e}function vA(e){let t={ts:Date.now(),command:e.command,positionals:e.positionals??[],flags:e.flags??{}};return e.runtime&&"object"==typeof e.runtime&&(t.runtime=e.runtime),t}let vS=new Map([["button",0],["link",0],["textfield",0],["textview",0],["searchfield",0],["switch",0],["slider",0],["cell",1],["statictext",2]]);function v_(e,t,r,n,a){let i=vD(e,t,n);if(r.childOf){let t=vD(e,r.childOf,n);if(0===t.length)return{ok:!1,message:`Maestro childOf parent did not match: ${r.childOf}`};let a=vL(e.nodes);i=i.filter(r=>t.some(t=>{var n,i,o;return n=e.nodes,i=r,o=t,!!function(e,t,r,n){let a=t;for(;"number"==typeof a.parentIndex&&(a=r.get(a.parentIndex)??e[a.parentIndex]);){let e=n(a);if(e)return e}return null}(n,i,a,e=>e===o||e.index===o.index?e:null)}))}let o=vN(e.nodes,i),s=vO(e.nodes,o.matches,r.index,vk(t),a);if(!s){let e=r.index??0;return{ok:!1,message:o.blockedByReactNativeOverlay?`Maestro selector matched ${i.length} element(s), but React Native overlay is covering app content: ${t}`:`Maestro selector did not match index ${e}: ${t}`}}return{ok:!0,node:s.node,rect:s.rect}}function vx(e,t,r,n){var a;let i,o,s=vD(e,t,r),l=(i=(a={nodes:e.nodes,matches:s,platform:r}).matches.filter(e=>tE({predicate:"visible",node:e,nodes:a.nodes,platform:a.platform}).pass),{matches:(o=vN(a.nodes,i)).matches,blockedByReactNativeOverlay:o.blockedByReactNativeOverlay}),u=vO(e.nodes,l.matches,void 0,vk(t),n,!0);return u?{ok:!0,node:u.node,rect:u.rect,matches:l.matches.length}:{ok:!1,message:s.length>0?l.blockedByReactNativeOverlay?`Maestro selector matched ${s.length} element(s), but React Native overlay is covering app content: ${t}`:`Maestro selector matched ${s.length} element(s), but none were visible: ${t}`:`Maestro selector did not match: ${t}`}}function vN(e,t){let r=td(e);if(!r.detected)return{matches:t,blockedByReactNativeOverlay:!1};let n=new Set([...r.dismissNodes,...r.minimizeNodes,...r.collapsedNodes].map(e=>e.index)),a=t.filter(e=>n.has(e.index));return{matches:a,blockedByReactNativeOverlay:t.length>0&&0===a.length}}function vM(e){return e?.platform==="android"?"android":"ios"}function vk(e){let t=tY(e).selectors.flatMap(e=>e.terms);if(0===t.length||!t.some(e=>"label"===e.key||"text"===e.key)||!t.every(e=>["label","text","id"].includes(e.key)))return null;let r=t.map(e=>"string"==typeof e.value?e.value:""),n=r[0];return n&&r.every(e=>e===n)?n:null}function vD(e,t,r){for(let n of tY(t).selectors){let t=e.nodes.filter(e=>(function(e,t,r){return!!t0(e,t,r)||t.terms.every(t=>(function(e,t,r){var n,a,i;return"string"!=typeof t.value||"id"!==(n=t.key)&&"label"!==n&&"text"!==n&&"value"!==n?t0(e,{raw:t.key,terms:[t]},r):vP((a=e,"id"===(i=t.key)?a.identifier:"label"===i?a.label:"value"===i?a.value:tH(a)),t.value)})(e,t,r))})(e,n,r));if(t.length>0)return t}return[]}function vP(e,t){let r=e??"";if(t4(r)===t4(t))return!0;try{return new RegExp(t).test(r)}catch{return!1}}function vO(e,t,r,n,a,i=!1){var o,s,l;let u,d=vL(e),c=t.map(t=>{let r=function(e,t,r){if(t.rect&&t.rect.width>0&&t.rect.height>0)return{rect:t.rect,inherited:!1};if(t.rect)return null;let n=function(e,t,r){let n=t;for(;"number"==typeof n.parentIndex&&(n=r.get(n.parentIndex)??e[n.parentIndex]);)if(n.rect)return n.rect.width>0&&n.rect.height>0?n.rect:null;return null}(e,t,r);return n?{rect:n,inherited:!0}:null}(e,t,d);return r?{node:t,rect:r.rect,inheritedRect:r.inherited}:null}).filter(e=>!!e),p=n&&void 0===r?(o=c,s=a,l=i,u=o.filter(e=>{var t,r;let n,a;return t=e.rect,r=s,n=r?.referenceWidth??1/0,a=r?.referenceHeight??1/0,t.x<n&&t.y<a&&t.x+t.width>0&&t.y+t.height>0}),l||u.length>0?u:o):c;return void 0!==r?p[r]??null:p.sort((e,t)=>(function(e,t,r){var n,a;let i=function(e,t,r){if(r){let n=vE(e.node,r)-vE(t.node,r);if(0!==n)return n}let n=vC(e.node)-vC(t.node);if(0!==n)return n;let a=Number(e.inheritedRect)-Number(t.inheritedRect);if(0!==a)return a;let i=r&&vC(e.node)===vC(t.node)?vR(t.rect)-vR(e.rect):vR(e.rect)-vR(t.rect);return 0!==i?i:0}(e,t,r);if(0!==i)return i;if(n=e.rect,a=t.rect,Math.round(n.x)!==Math.round(a.x)||Math.round(n.y)!==Math.round(a.y)||Math.round(n.width)!==Math.round(a.width)||Math.round(n.height)!==Math.round(a.height))return e.node.index-t.node.index;let o=(t.node.depth??0)-(e.node.depth??0);return 0!==o?o:t.node.index-e.node.index})(e,t,n))[0]??null}function vR(e){return e.width*e.height}function vC(e){return vS.get(e.type?.toLowerCase()??"")??3}function vE(e,t){let r=[e.label,tH(e),e.identifier,e.value].filter(e=>!!e);return r.some(e=>e===t)?0:r.some(e=>t4(e)===t4(t))?1:r.some(e=>vP(e,t))?2:3}function vL(e){return new Map(e.map(e=>[e.index,e]))}async function v$(e){let t,[r,n="5000"]=e.positionals;if(!r)return vv("INVALID_ARGS","assertVisible requires a selector.");let a=Number(n);if(!Number.isFinite(a)||a<0)return vv("INVALID_ARGS","assertVisible timeout must be a non-negative number.");let i=Date.now(),o=a+1e3;do{let n=await vI(e);if(t=n,n.ok){let a=vb(n.data);if(!a)return vv("COMMAND_FAILED","Unable to read snapshot data for assertVisible.");let o=vx(a,r,vM(e.baseReq.flags),p9(a));if(o.ok)return!function(e,t,r){if(!e)return;let n=vb(t);n&&vy.set(e,{snapshot:n,frame:p9(n),selector:r})}(e.scope,n.data,r),{ok:!0,data:{selector:r,matches:o.matches,nodeIndex:o.node.index,nodeType:o.node.type,nodeLabel:o.node.label,nodeIdentifier:o.node.identifier,rect:o.rect,waitedMs:Date.now()-i}};t=vv("COMMAND_FAILED",o.message,{selector:r})}if(Date.now()-i>=o)break;await e2(250)}while(Date.now()-i<=o);return t??vv("COMMAND_FAILED",`Expected visible but did not match: ${r}`,{selector:r,timeoutMs:a})}async function vT(e){let t,[r]=e.positionals;if(!r)return vv("INVALID_ARGS","assertNotVisible requires a selector.");let n=Date.now(),a=0;for(;Date.now()-n<=3e3;){let n=await e.invoke({...e.baseReq,command:"is",positionals:["visible",r],flags:{...e.baseReq.flags,noRecord:!0}});if(n.ok)a=0,t=n;else if(!function(e){let t=e.error.details;return t?.command==="is"&&("selector_not_found"===t.reason||"predicate_failed"===t.reason)}(n))return n;else if((a+=1)>=2)return{ok:!0,data:{pass:!0,selector:r,stableSamples:a,timeoutMs:3e3}};await e2(250)}return vv("COMMAND_FAILED",`Expected not visible but matched: ${r}`,{selector:r,timeoutMs:3e3,lastResponse:t})}async function vF(e){let t,r,n=Number(e.positionals[0]??15e3);if(!Number.isFinite(n)||n<0)return vv("INVALID_ARGS","waitForAnimationToEnd timeout must be a number.");let a=Date.now();for(;Date.now()-a<n;){let a=await vI(e),i=function(e,t,r){let n=function(e){if(!e.ok)return null;let t=vb(e.data);return t?JSON.stringify(t.nodes.map(e=>({index:e.index,parentIndex:e.parentIndex,type:e.type,identifier:e.identifier,label:e.label,value:e.value,rect:e.rect?{x:Math.round(e.rect.x),y:Math.round(e.rect.y),width:Math.round(e.rect.width),height:Math.round(e.rect.height)}:void 0}))):null}(e);return e.ok?n?t===n?{done:!0,response:{ok:!0,data:{stable:!0,timeoutMs:r}}}:{done:!1,signature:n}:{done:!0,response:e}:{done:!1}}(a,t,n);if(i.done)return i.response;t=i.signature??t,r=a,await e2(250)}return r?.ok===!1?r:{ok:!0,data:{stable:!1,timeoutMs:n}}}async function vU(e){let t=function(e){let[t,r]=e;return("visible"===t||"notVisible"===t)&&r?{ok:!0,mode:t,predicate:"visible"===t?"visible":"hidden",selector:r}:{ok:!1,response:vv("INVALID_ARGS","runFlow.when requires visible/notVisible and a selector.")}}(e.positionals);if(!t.ok)return t.response;let r=await vG(e,t);return r.ok?r.matched?await vq(e,t):{ok:!0,data:{skipped:!0,condition:t.mode,selector:t.selector}}:r.response}async function vV(e){let t,[r="1"]=e.positionals,n=Number(r);if(!Number.isInteger(n)||n<0)return vv("INVALID_ARGS","retry.maxRetries must be a non-negative integer.");let a=(e.batchSteps??[]).map(vA);for(let r=0;r<=n;r+=1){let n=await vj(e,a,r);if(n.ok)return{ok:!0,data:{attempts:r+1,retried:r>0}};t=n}return t??vv("COMMAND_FAILED","retry commands failed.")}async function vG(e,t){let r=await vI(e);if(!r.ok)return{ok:!1,response:r};let n=vb(r.data);if(!n)return{ok:!1,response:vv("COMMAND_FAILED","Unable to read snapshot data for runFlow.when.")};let a=vx(n,t.selector,vM(e.baseReq.flags),p9(n)).ok;return{ok:!0,matched:"visible"===t.mode?a:!a}}async function vq(e,t){let r=(e.batchSteps??[]).map(vA);for(let[t,n]of r.entries()){let r=await e.invokeReplayAction({action:n,line:e.line,step:e.step+t/1e3});if(!r.ok)return r}return{ok:!0,data:{ran:r.length,condition:t.mode,selector:t.selector}}}async function vj(e,t,r){for(let[n,a]of t.entries()){let t=await e.invokeReplayAction({action:a,line:e.line,step:e.step+r+n/1e3});if(!t.ok)return t}return{ok:!0,data:{ran:t.length}}}let vB=.35,vH=120,vW=360,vz=8,vK=120,vJ=70,vX=168,vY=48;function vZ(e,t){return Math.round(Math.min(vW,Math.max(vH,"number"==typeof e?e*vB:0,1.5*t)))}function vQ(e,t,r){return Math.round(Math.min(r,Math.max(t,e)))}function v0(e){return{x:v1(e.x,e.width),y:v1(e.y,e.height)}}function v1(e,t){if(t<=1)return Math.floor(e);let r=Math.ceil(e),n=Math.floor(e+t-1);return vQ(e+t/2,r,n)}async function v2(e){var t,r,n;let[a,i="5000",o="down"]=e.positionals;if(!a)return vv("INVALID_ARGS","scrollUntilVisible requires a selector.");let s=Number(i);if(!Number.isFinite(s)||s<=0)return vv("INVALID_ARGS","scrollUntilVisible timeout must be a positive number.");let l=vk(a),u=Math.max(1,Math.ceil(s/500)),d=null;for(let t=0;t<u;t+=1){let r=await Ir(e,a,l,Math.min(500,Math.max(1,s-500*t)));if(r.ok)return r;if(d=r,t===u-1)break;let n=await e.invoke({...e.baseReq,command:"scroll",positionals:[o]});if(!n.ok)return n}return t=d,r=a,n=s,t?{ok:!1,error:{...t.error,message:`scrollUntilVisible timed out after ${n}ms for selector: ${r}. Last wait: ${t.error.message}`}}:vv("COMMAND_FAILED",`scrollUntilVisible timed out after ${n}ms for selector: ${r}`)}async function v3(e){let[t,r]=e.positionals,n=Number(t),a=Number(r);if(!Number.isFinite(n)||!Number.isFinite(a))return vv("INVALID_ARGS","tapOn percentage point requires numeric x/y values.");let i=await vI(e);if(!i.ok)return i;let o=vb(i.data);if(!o)return vv("COMMAND_FAILED","Unable to read snapshot data for Maestro percentage point tap.");let s=p9(o);return s?await e.invoke({...e.baseReq,command:"click",positionals:[String(Math.round(s.referenceWidth*n/100)),String(Math.round(s.referenceHeight*a/100))]}):vv("COMMAND_FAILED","Unable to resolve screen size for Maestro percentage point tap.")}async function v5(e){let t=await v9(e);return t.ok?await v6(e,t,t.durationMs):t.response}async function v4(e){var t,r,n,a;let i,[o,s]=e.positionals;if(!o)return vv("INVALID_ARGS","tapOn requires a selector.");let l=function(e){if(!e)return{ok:!0,value:null};try{let t=JSON.parse(e);return{ok:!0,value:t}}catch{return{ok:!1,response:vv("INVALID_ARGS","tapOn runtime options must be valid JSON.")}}}(s);if(!l.ok)return l.response;let u=Date.now(),d=(t=e,t.baseReq.flags?.maestro?.optional===!0?3e3:3e4);for(;Date.now()-u<d;){let t=await In(e,o,l.value??{});if(!t.retry)return t.response;i=t.response,await e2(250)}return r=e,n=o,a=i,r.baseReq.flags?.maestro?.optional===!0?{ok:!0,data:{skipped:!0,optional:!0,selector:n}}:a??vv("COMMAND_FAILED",`tapOn timed out for selector: ${n}`)}async function v8(e){let[t,r="up",n]=e.positionals;if(!t)return vv("INVALID_ARGS","swipe.label requires a label selector.");let a=await Io(e,t,{},"swipe.label");if(!a.ok)return a.response;let i=function(e,t){let r=v0(e.rect),n=e.frame,a=vZ(n?.referenceWidth,e.rect.width),i=vZ(n?.referenceHeight,e.rect.height),o=vz,s=n?n.referenceWidth-o:r.x+a,l=n?n.referenceHeight-o:r.y+i;switch(t.toLowerCase()){case"up":return{ok:!0,start:r,end:{x:r.x,y:vQ(r.y-i,o,l)}};case"down":return{ok:!0,start:r,end:{x:r.x,y:vQ(r.y+i,o,l)}};case"left":return{ok:!0,start:r,end:{x:vQ(r.x-a,o,s),y:r.y}};case"right":return{ok:!0,start:r,end:{x:vQ(r.x+a,o,s),y:r.y}};default:return{ok:!1,message:"swipe.label direction must be up, down, left, or right."}}}(a.target,r);return i.ok?await v6(e,i,n):vv("INVALID_ARGS",i.message)}async function v6(e,t,r){return await e.invoke({...e.baseReq,command:"swipe",positionals:[String(t.start.x),String(t.start.y),String(t.end.x),String(t.end.y),...r?[r]:[]]})}async function v9(e){var t;let r=((t=e.scope)?vg.get(t):void 0)??await v7(e);if(!r)return{ok:!1,response:vv("COMMAND_FAILED","Unable to resolve screen size for Maestro swipe.")};let[n,...a]=e.positionals;return"direction"===n?function(e,t){let[r,n]=e;if(!r)return{ok:!1,response:vv("INVALID_ARGS","Maestro direction swipe requires a direction.")};switch(r){case"up":return{ok:!0,start:Ie(t,50,80,8),end:Ie(t,50,20,8),durationMs:n};case"down":return{ok:!0,start:Ie(t,50,20,8),end:Ie(t,50,80,8),durationMs:n};case"left":return{ok:!0,start:Ie(t,80,50,8),end:Ie(t,20,50,8),durationMs:n};case"right":return{ok:!0,start:Ie(t,20,50,8),end:Ie(t,80,50,8),durationMs:n};default:return{ok:!1,response:vv("INVALID_ARGS","Maestro swipe direction must be UP, DOWN, LEFT, or RIGHT.")}}}(a,r):"percent"===n?function(e,t,r){var n,a,i,o,s;let[l,u,d,c,p]=e,f=[l,u,d,c].map(Number);if(f.some(e=>!Number.isFinite(e)))return{ok:!1,response:vv("INVALID_ARGS","Maestro percentage swipe requires numeric points.")};let[m,h,w,g]=f,y=(n=r,a=m,i=h,o=w,s=g,"android"!==n||i!==s||50!==i||50>Math.abs(o-a)?s:65);return{ok:!0,start:Ie(t,m,y,1),end:Ie(t,w,y,1),durationMs:p}}(a,r,vM(e.baseReq.flags)):{ok:!1,response:vv("INVALID_ARGS","Maestro screen swipe requires direction or percent.")}}async function v7(e){let t=await vI(e);if(t.ok)return p9(vb(t.data))}function Ie(e,t,r,n){return{x:It(Math.round(e.referenceWidth*t/100),n,e.referenceWidth),y:It(Math.round(e.referenceHeight*r/100),n,e.referenceHeight)}}function It(e,t,r){return Math.min(Math.max(t,r-t),Math.max(t,e))}async function Ir(e,t,r,n){let a=await e.invoke({...e.baseReq,command:"wait",positionals:[t,String(n)]});return a.ok||!r?a:await e.invoke({...e.baseReq,command:"find",positionals:[r,"wait",String(n)]})}async function In(e,t,r){let n=vk(t),a=await Ia(e,t,r);return a.response.ok?{retry:!1,response:a.response}:a.targetResolved&&n?await Ii(e,n):{retry:!0,response:a.response}}async function Ia(e,t,r){var n,a;let i=await Io(e,t,r,"tapOn");if(!i.ok)return{response:i.response,targetResolved:!1};let o=(n=i.target,a=null!==vk(t),!function(e,t,r){if(!t||r.height<vJ||r.width<vK)return!1;let n=e.type?.toLowerCase();return"cell"===n||"other"===n||"scrollview"===n}(n.node,a,n.rect)?v0(n.rect):{x:v1(n.rect.x,Math.min(n.rect.width,vX)),y:v1(n.rect.y,Math.min(n.rect.height,vY))});return{response:await e.invoke({...e.baseReq,command:"click",positionals:[String(o.x),String(o.y)]}),targetResolved:!0}}async function Ii(e,t){let r=await e.invoke({...e.baseReq,command:"find",positionals:[t,"click"],flags:{...e.baseReq.flags,findFirst:!0}});return r.ok?{retry:!1,response:r}:{retry:!0,response:r}}async function Io(e,t,r,n){let a=function(e,t,r){let n=function(e,t){if(!e)return;let r=vy.get(e);return vy.delete(e),r?.selector===t?r:void 0}(e.scope,t);if(!n)return{ok:!1};let a=v_(n.snapshot,t,r,vM(e.baseReq.flags),n.frame);return a.ok?{ok:!0,target:{node:a.node,rect:a.rect,frame:n.frame}}:{ok:!1}}(e,t,r);if(a.ok)return a;let i=await vI(e);if(!i.ok)return{ok:!1,response:i};let o=vb(i.data);if(!o)return{ok:!1,response:vv("COMMAND_FAILED",`Unable to read snapshot data for ${n}.`)};let s=p9(o),l=v_(o,t,r,vM(e.baseReq.flags),s);if(!l.ok){let e=vk(t);if(e){let t,r,n=(t=function(e,t){let r=t4(t);if(!r)return[];let n=[],a=[];for(let t of e.nodes){let e=[t.label,tH(t),t.identifier,t.value].filter(e=>!!e).map(e=>t4(e));e.some(e=>e===r)?n.push(t):e.some(e=>e.includes(r))&&a.push(t)}return n.length>0?n:a}(o,e),(r=vO(o.nodes,t,void 0,e,s))?{ok:!0,node:r.node,rect:r.rect}:{ok:!1,message:`Maestro fuzzy text did not match: ${e}`});if(n.ok)return{ok:!0,target:{node:n.node,rect:n.rect,frame:s}}}}return l.ok?{ok:!0,target:{node:l.node,rect:l.rect,frame:s}}:{ok:!1,response:vv("ELEMENT_NOT_FOUND",l.message,{selector:t,options:r,command:n})}}async function Is(e){switch(e.command){case yj:return await v$(e);case yB:return await vT(e);case yG:return await vV(e);case yH:return await Il(e);case yW:return await vF(e);case yz:return await v2(e);case yK:return await v5(e);case yJ:return await v8(e);case yX:return await v4(e);case yY:return await v3(e);case yV:return await vU(e);case yq:return function(e){let[t]=e.positionals;if(!t)return vv("INVALID_ARGS","runScript requires a file path.");try{let r=function(e){let{scriptPath:t,env:r}=e,n=l.readFileSync(t,"utf8"),a=Object.create(null);try{var i,o;M.runInNewContext(n,(i=r,o=a,{...i,output:o,json:vn,http:{post:(e,t)=>(function(e,t,r){let n=L(process.execPath,["-e",vr],{stdin:JSON.stringify({method:e,url:t,headers:r?.headers??{},body:r?.body??""}),timeoutMs:3e4,allowFailure:!0});if(0!==n.exitCode){let r;throw new O("COMMAND_FAILED",`Maestro runScript http.${e.toLowerCase()} failed for ${t}: ${(r=n.stderr.trim()).length>0?r.slice(0,1e3):"request process exited without stderr"}`,{exitCode:n.exitCode,stderr:n.stderr})}try{return JSON.parse(n.stdout)}catch(r){throw new O("COMMAND_FAILED",`Maestro runScript http.${e.toLowerCase()} returned invalid JSON for ${t}`,{stdout:n.stdout.slice(0,1e3),stderr:n.stderr.slice(0,1e3)},r instanceof Error?r:void 0)}})("POST",e,t)}}),{filename:t,timeout:3e4})}catch(e){throw new O("COMMAND_FAILED",`Maestro runScript failed for ${t}: ${e instanceof Error?e.message:String(e)}`,{scriptPath:t},e instanceof Error?e:void 0)}return function(e,t){for(let r of Object.keys(e))if(r.includes("."))throw new O("INVALID_ARGS",`Maestro runScript output key cannot contain ".": ${r}`,{scriptPath:t,key:r})}(a,t),Object.fromEntries(Object.entries(a).map(([e,t])=>{var r;return[`output.${e}`,(r=t,"string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):JSON.stringify(r))]}))}({scriptPath:t,env:{...e.scope.values,...e.baseReq.flags?.maestro?.runScriptEnv??{}}});return{ok:!0,data:{outputEnv:r}}}catch(t){let e=D(t);return vv(e.code,e.message,e.details)}}(e);default:return}}async function Il(e){let t=await e.invoke({...e.baseReq,command:"keyboard",positionals:["enter"]});return t.ok?t:await e.invoke({...e.baseReq,command:"type",positionals:["\n"]})}async function Iu(e){var t;let{req:r,sessionName:n,action:a,scope:i,filePath:o,line:s,step:l,tracePath:u,invoke:d}=e,c=(t={file:o,line:s},{...a,positionals:(a.positionals??[]).map(e=>yl(e,i,t)),flags:yu(a.flags,i,t)??{},runtime:yu(a.runtime,i,t)}),p=Date.now();Ic(u,{type:"replay_action_start",ts:new Date(p).toISOString(),replayPath:o,line:s,step:l,command:c.command,positionals:c.positionals??[]});let f=await Id({req:r,sessionName:n,resolved:c,scope:i,line:s,step:l,invoke:d,invokeReplayAction:e=>Iu({req:r,sessionName:n,action:e.action,scope:i,filePath:o,line:e.line,step:e.step,tracePath:u,invoke:d})}),m=Date.now();return Ic(u,{type:"replay_action_stop",ts:new Date(m).toISOString(),replayPath:o,line:s,step:l,command:c.command,ok:f.ok,durationMs:m-p,errorCode:f.ok?void 0:f.error.code}),f}async function Id(e){var t;let{req:r,sessionName:n,resolved:a,scope:i,line:o,step:s,invoke:l,invokeReplayAction:u}=e,d=(t=r.flags,t9(t,{...a.flags??{}})),c={token:r.token,session:n,flags:d,runtime:a.runtime,meta:r.meta},p=await Is({command:a.command,baseReq:c,positionals:a.positionals??[],batchSteps:a.flags?.batchSteps,scope:i,line:o,step:s,invoke:l,invokeReplayAction:u})??await l({...c,command:a.command,positionals:a.positionals??[]});if(p.ok){let e=function(e){if(!e||"object"!=typeof e)return null;let t=e.outputEnv;if(!t||"object"!=typeof t||Array.isArray(t))return null;let r=Object.entries(t).filter(e=>"string"==typeof e[1]);return r.length>0?Object.fromEntries(r):null}(p.data);e&&Object.assign(i.values,e)}return p}function Ic(e,t){e&&l.appendFileSync(e,`${JSON.stringify(t)}
88
- `)}async function Ip(e){let{req:t,sessionName:r,logPath:n,sessionStore:a,invoke:i}=e,o=t.positionals?.[0];if(!o)return cm("INVALID_ARGS","replay requires a path");let s="",u=new Set;try{var d,c;s=aE.expandHome(o,t.meta?.cwd);let e=l.readFileSync(s,"utf8"),p=e.trimStart()[0];if("{"===p||"["===p)return cm("INVALID_ARGS","replay accepts .ad script files. JSON replay payloads are no longer supported.");let m=function(e,t,r={}){var n;let a=function(e){let t=e?.replayBackend;if("string"!=typeof t)return;let r=vp[t];if(!r)throw new O("INVALID_ARGS",`Unsupported replay backend "${t}".`);return r}(t);return a?{...a.parse(e,{...r,platform:t?.platform,env:(n=t,{...ya(ys(n?.replayShellEnv)),...yi(yo(n?.replayEnv))})}),updateUnsupportedMessage:"replay -u is not supported for compat flow input. Convert to .ad first, then update that replay file."}:{...function(e){let t=[],r=[],n=e.split(/\r?\n/),a=!1;for(let[e,i]of n.entries()){let n=i.trim();if(0===n.length||n.startsWith("#"))continue;if(yf(n)){if(a)throw new O("INVALID_ARGS",`env directives must precede all actions (line ${e+1}).`);continue}let o=function(e){let t=e.trim();if(0===t.length||t.startsWith("#"))return null;let[r,...n]=function(e){let t=[],r=0;for(;r<e.length&&!((r=function(e,t){let r=t;for(;r<e.length&&/\s/.test(e.charAt(r));)r+=1;return r}(e,r))>=e.length);){let n='"'===e[r]?function(e,t){let r=!1,n=t+1;for(;n<e.length;n+=1){let t=e.charAt(n);if('"'===t&&!r)break;if(r){r=!1;continue}r="\\"===t}if(n>=e.length)throw new O("INVALID_ARGS",`Invalid replay script line: ${e}`);return{value:JSON.parse(e.slice(t,n+1)),nextCursor:n+1}}(e,r):function(e,t){let r=t;for(;r<e.length&&!/\s/.test(e.charAt(r));)r+=1;return{value:e.slice(t,r),nextCursor:r}}(e,r);t.push(n.value),r=n.nextCursor}return t}(t);if(void 0===r||"context"===r)return null;let a={ts:Date.now(),command:r,positionals:[],flags:{}};if("snapshot"===r){a.positionals=[];for(let e=0;e<n.length;e+=1){let t=n[e];if("-i"===t){a.flags.snapshotInteractiveOnly=!0;continue}if("-c"===t){a.flags.snapshotCompact=!0;continue}if("--raw"===t){a.flags.snapshotRaw=!0;continue}if("--force-full"===t){a.flags.snapshotForceFull=!0;continue}if(("-d"===t||"--depth"===t)&&e+1<n.length){let t=Number(n[e+1]);Number.isFinite(t)&&t>=0&&(a.flags.snapshotDepth=Math.floor(t)),e+=1;continue}if(("-s"===t||"--scope"===t)&&e+1<n.length){a.flags.snapshotScope=n[e+1],e+=1;continue}if("--backend"===t&&e+1<n.length){e+=1;continue}}return a}if("open"===r){let e=function(e){var t;let r=[],n={};for(let t of e){if("--relaunch"===t){n.relaunch=!0;continue}r.push(t)}let a=ak(r);return{positionals:a.positionals,flags:n,runtime:(t=a.flags).platform||t.metroHost||void 0!==t.metroPort||t.bundleUrl||t.launchUrl?a.flags:void 0}}(n);return a.positionals=e.positionals,Object.assign(a.flags,e.flags),a.runtime=e.runtime,a}if("runtime"===r){let e=ak(n);return a.positionals=e.positionals,Object.assign(a.flags,e.flags),a}if(ag(r)){let e=aM(r,n);Object.assign(a.flags,e.flags);let t=e.positionals[0];if(void 0===t)return a;if(t.startsWith("@"))return a.positionals=[t],e.positionals[1]&&(a.result={refLabel:e.positionals[1]}),a;let i=e.positionals[0],o=e.positionals[1];return yh(i)&&yh(o)&&e.positionals.length>=2?a.positionals=[i,o]:a.positionals=[e.positionals.join(" ")],a}if("fill"===r){let e=aM(r,n);if(Object.assign(a.flags,e.flags),!(e.positionals.length>=2))return a.positionals=e.positionals,a;let[t,i,...o]=e.positionals;return t.startsWith("@")?(o.length>0?(a.positionals=[t,o.join(" ")],a.result={refLabel:i}):a.positionals=[t,i],a):(a.positionals=[t,[i,...o].join(" ")],a)}if("get"===r){let e=n[0],t=n[1];return void 0===e||void 0===t?a.positionals=n:t.startsWith("@")?(a.positionals=[e,t],n[2]&&(a.result={refLabel:n[2]})):a.positionals=[e,n.slice(1).join(" ")],a}if("swipe"===r||"type"===r){let e=aM(r,n);return Object.assign(a.flags,e.flags),a.positionals=e.positionals,a}if("record"===r){let e=[];for(let t=0;t<n.length;t+=1){let r=n[t];if("--hide-touches"===r){a.flags.hideTouches=!0;continue}if("--fps"===r&&t+1<n.length){let e=Number(n[t+1]);Number.isFinite(e)&&(a.flags.fps=Math.floor(e)),t+=1;continue}if("--quality"===r&&t+1<n.length){let e=Number(n[t+1]);Number.isFinite(e)&&(a.flags.quality=Math.floor(e)),t+=1;continue}e.push(r)}return a.positionals=e,a}if("screenshot"===r){let e=[];for(let t=0;t<n.length;t+=1){let r=n[t],i=eF({args:n,index:t,flags:a.flags});if(i.handled){t=i.nextIndex;continue}e.push(r)}return a.positionals=e,a}return a.positionals=n,a}(i);o&&(t.push(o),r.push(e+1),a=!0)}return{actions:t,actionLines:r}}(e),metadata:yp(e)}}(e,t.flags,{sourcePath:s}),h=m.metadata,w=h.platform||h.target?{...t,flags:(d=t.flags,c=h,{...d??{},...void 0!==c.platform&&d?.platform===void 0?{platform:c.platform}:{},...void 0!==c.target&&d?.target===void 0?{target:c.target}:{}})}:t,g=m.actions,y=m.actionLines;if(t.flags?.replayUpdate===!0&&m.updateUnsupportedMessage)return cm("INVALID_ARGS",m.updateUnsupportedMessage);if(t.flags?.replayUpdate===!0&&h.env&&Object.keys(h.env).length>0)return cm("INVALID_ARGS","replay -u does not yet preserve env directives. Temporarily remove the env lines, run replay -u, then restore them.");if(t.flags?.replayUpdate===!0&&function(e){for(let t of e){for(let e of t.positionals??[])if("string"==typeof e&&e.includes("${"))return!0;if(Ih(t.flags)||Ih(t.runtime))return!0}return!1}(g))return cm("INVALID_ARGS","replay -u does not yet preserve ${VAR} substitutions. Resolve or inline the variables before running with -u.");let v=function(e){let t={};if(e.builtins)for(let[r,n]of Object.entries(e.builtins))t[r]=n;for(let r of[e.fileEnv,e.shellEnv,e.cliEnv])if(r)for(let[e,n]of Object.entries(r)){if(yr(e))throw yn(e);t[e]=n}return{values:t}}({builtins:function(e){let{req:t,sessionName:r,metadata:n,resolvedPath:a}=e,i=t.flags??{},o=t.meta?.cwd??process.cwd(),s={AD_SESSION:r,AD_FILENAME:f.relative(o,a)||a},l=i.platform??n.platform;l&&(s.AD_PLATFORM=l);let u=i.target??n.target;u&&(s.AD_TARGET=u);let d=i.device;"string"==typeof d&&d.length>0&&(s.AD_DEVICE=d);let c=i.artifactsDir;return"string"==typeof c&&c.length>0&&(s.AD_ARTIFACTS=c),s}({req:w,sessionName:r,metadata:h,resolvedPath:s}),fileEnv:h.env,shellEnv:ya(ys(t.flags?.replayShellEnv)),cliEnv:yi(yo(t.flags?.replayEnv))}),I=t.flags?.replayUpdate===!0,b=0;for(let e=0;e<g.length;e+=1){let t=g[e];if(!t||"replay"===t.command)continue;let o=await Iu({req:w,sessionName:r,action:t,scope:v,filePath:s,line:y[e]??0,step:e+1,tracePath:a.get(r)?.trace?.outPath,invoke:i});if(o.ok){Im(o).forEach(e=>u.add(e));continue}if(!I)return If(o,t,e,s,[...u]);let l=await vm({action:t,sessionName:r,logPath:n,sessionStore:a});if(!l)return If(o,t,e,s,[...u]);if(g[e]=l,!(o=await Iu({req:w,sessionName:r,action:l,scope:v,filePath:s,line:y[e]??0,step:e+1,tracePath:a.get(r)?.trace?.outPath,invoke:i})).ok)return If(o,l,e,s,[...u]);Im(o).forEach(e=>u.add(e)),b+=1}return I&&b>0&&function(e,t,r){let n=[];if(r){let e=r.device.kind?` kind=${r.device.kind}`:"",t=r.device.target?` target=${r.device.target}`:"";n.push(`context platform=${r.device.platform}${t} device=${ab(r.device.name)}${e} theme=unknown`)}for(let e of t){var a;n.push((a=e,aP(a,{runtimeIncludeAllPositionals:!0})))}let i=`${n.join("\n")}
89
- `,o=`${e}.tmp-${process.pid}-${Date.now()}`;l.writeFileSync(o,i),l.renameSync(o,e)}(s,g,a.get(r)),{ok:!0,data:{replayed:g.length,healed:b,session:r,artifactPaths:[...u]}}}catch(t){let e=D(t);return cm(e.code,e.message,u.size>0?{artifactPaths:[...u]}:void 0)}}function If(e,t,r,n,a=[]){let i;if(e.ok)return e;let o=r+1;return{ok:!1,error:{code:e.error.code,message:`Replay failed at step ${o} (${i=(t.positionals??[]).map(e=>aI(e)),[t.command,...i].join(" ")}): ${e.error.message}`,hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath,details:{...e.error.details??{},replayPath:n,step:o,action:t.command,positionals:t.positionals??[],artifactPaths:a}}}}function Im(e){if(!e.ok||!e.data)return[];let t=[];if("string"==typeof e.data.path&&t.push(e.data.path),"string"==typeof e.data.outPath&&t.push(e.data.outPath),Array.isArray(e.data.artifacts))for(let r of e.data.artifacts){if(!r||"object"!=typeof r)continue;let e="string"==typeof r.localPath?r.localPath:void 0,n="string"==typeof r.path?r.path:void 0;e?t.push(e):n&&t.push(n)}return[...new Set(t.filter(e=>(function(e){try{return l.statSync(e).isFile()}catch{return!1}})(e)))]}function Ih(e){return"string"==typeof e?e.includes("${"):Array.isArray(e)?e.some(Ih):!!e&&"object"==typeof e&&Object.values(e).some(Ih)}async function Iw(e){let{req:t,sessionName:r,logPath:n,sessionStore:a,invoke:i}=e;return"replay"===t.command?await Ip({req:t,sessionName:r,logPath:n,sessionStore:a,invoke:i}):"test"===t.command?await yI({req:t,sessionName:r,runReplay:async({filePath:e,sessionName:r,platform:o,target:s,requestId:l,artifactsDir:u,artifactPaths:d})=>{let c=function(e){let{parentFlags:t,platform:r,target:n,artifactsDir:a}=e;return void 0===r&&void 0===n&&void 0===a?t:{...t??{},...void 0!==r?{platform:r}:{},...void 0!==n?{target:n}:{},...void 0!==a?{artifactsDir:a}:{}}}({parentFlags:t.flags,platform:o,target:s,artifactsDir:u});return await Ip({req:{...t,command:"replay",session:r,positionals:[e],flags:c,meta:l?{...t.meta??{},requestId:l}:t.meta},sessionName:r,logPath:n,sessionStore:a,invoke:async e=>{var t;return t=await i(e),d&&Im(t).forEach(e=>d.add(e)),t}})},cleanupSession:async e=>{a.get(e)&&await w5({req:{token:t.token,session:e,command:"close",positionals:[],flags:{},meta:t.meta},sessionName:e,logPath:n,sessionStore:a})}}):null}let Ig=ek.inventory,Iy=ek.state,Iv=ek.observability,II=ek.replay;async function Ib(e){let{req:t,sessionName:r,logPath:n,sessionStore:a,command:i,positionals:o,recordPositionals:s,deriveNextSession:l}=e,u=a.get(r),d=t.flags??{},c=ch(i,u,d);if(c)return c;let p=await cv({session:u,flags:d,ensureReady:!0});if(!cF(i,p))return cm("UNSUPPORTED_OPERATION",`${i} is not supported on this device`);let f=await cr(p,i,o,t.flags?.out,{...cH(n,t.flags,u?.appBundleId,u?.trace?.outPath)});if(u){let e=l?await l(u,f,p):u;a.recordAction(e,{command:i,positionals:s??o,flags:t.flags??{},result:f??{}}),e!==u&&a.set(r,e)}return{ok:!0,data:f??{}}}async function IA(e){let{req:t,sessionName:r,logPath:n,sessionStore:a}=e,i=a.get(r),o=t.flags??{},s=ch(eP.clipboard,i,o);if(s)return s;let l=(t.positionals?.[0]??"").toLowerCase();if("read"!==l&&"write"!==l)return cm("INVALID_ARGS","clipboard requires a subcommand: read or write");let u=await cv({session:i,flags:o,ensureReady:!0});if(!cF(eP.clipboard,u))return cm("UNSUPPORTED_OPERATION","clipboard is not supported on this device");let d=await cr(u,eP.clipboard,t.positionals??[],t.flags?.out,{...cH(n,t.flags,i?.appBundleId,i?.trace?.outPath)});return i&&a.recordAction(i,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:d??{}}),{ok:!0,data:{platform:u.platform,...d??{}}}}async function IS(e){let{req:t,sessionName:r,logPath:n,sessionStore:a,invoke:i,invokeReplayAction:o,androidAdbExecutor:s}=e;if(Ig.has(t.command))return await ge({req:t,sessionName:r,sessionStore:a});if("runtime"===t.command)return await wy({req:t,sessionName:r,sessionStore:a});if(Iy.has(t.command))return await gi({req:t,sessionName:r,sessionStore:a});if(t.command===eP.clipboard)return await IA({req:t,sessionName:r,logPath:n,sessionStore:a});if(t.command===eP.keyboard){let e=a.get(r),i=t.positionals?.[0]?.trim().toLowerCase();return e||"dismiss"!==i&&"enter"!==i&&"return"!==i||"ios"!==(t.flags??{}).platform?await Ib({req:t,sessionName:r,logPath:n,sessionStore:a,command:eP.keyboard,positionals:t.positionals??[]}):cm("SESSION_NOT_FOUND","iOS keyboard action requires an active session so the target app stays foregrounded. Run open first.")}if(Iv.has(t.command))return await g1({req:t,sessionName:r,sessionStore:a,androidAdbExecutor:s});if(t.command===eP.install||t.command===eP.reinstall)return await w9({req:t,command:t.command,sessionName:r,sessionStore:a,deployOps:t.command===eP.install?w6:w8});if(t.command===eJ.installSource)return await hZ({req:t,sessionName:r,sessionStore:a});if(t.command===eJ.releaseMaterializedPaths)return await hQ({req:t});if(t.command===eP.push){let e,i=t.positionals?.[0]?.trim(),o=t.positionals?.[1]?.trim();return i&&o?await Ib({req:t,sessionName:r,logPath:n,sessionStore:a,command:eP.push,positionals:[i,"file"===(e=d7(o,{subject:"Push payload",cwd:t.meta?.cwd,expandPath:(e,t)=>aE.expandHome(e,t)})).kind?e.path:e.text],recordPositionals:[i,o]}):cm("INVALID_ARGS","push requires <bundle|package> <payload.json|inline-json>")}return t.command===eP.triggerAppEvent?await Ib({req:t,sessionName:r,logPath:n,sessionStore:a,command:eP.triggerAppEvent,positionals:t.positionals??[],deriveNextSession:async(e,t)=>{let r="string"==typeof t?.eventUrl?t.eventUrl:void 0,n=r?await wj(e.device,r,e.appBundleId,wG)??e.appBundleId:e.appBundleId;return{...e,appBundleId:n}}}):t.command===eP.open?await wQ({req:t,sessionName:r,logPath:n,sessionStore:a}):II.has(t.command)?await Iw({req:t,sessionName:r,logPath:n,sessionStore:a,invoke:o??i}):t.command===eP.batch?await w7(t,r,i):t.command===eP.close?await w5({req:t,sessionName:r,logPath:n,sessionStore:a}):null}let I_=new Set(["com.android.permissioncontroller","com.google.android.permissioncontroller","com.google.android.packageinstaller","com.android.packageinstaller"]),Ix=new Set(["android","com.android.systemui"]),IN=/^android:id\/(?:alertTitle|message|button[123]|parentPanel|buttonPanel|contentPanel)$/i,IM=/^android:id\/button[123]$/i,Ik=/(?:^|:)id\/permission_/i,ID=/\b(?:is(?:n't| not) responding|keeps stopping|has stopped|close app|app info)\b/i,IP=/^(?:ok|allow|allow all|while using the app|only this time|yes|continue|save|confirm|turn on|open settings)$/i,IO=/^(?:cancel|deny|don.t allow|don’t allow|not now|no|dismiss|close|close app|later|skip)$/i;function IR(e,t){let r=t[0];if(!r)return;let n=IC(e,r.index);for(let r of t.slice(1)){let t=new Set(IC(e,r.index));for(let e=n.length-1;e>=0;e-=1)t.has(n[e])||n.splice(e,1)}return n[n.length-1]}function IC(e,t){let r=new Map(e.map(e=>[e.index,e])),n=[],a=r.get(t);for(;a;)n.push(a.index),a=void 0===a.parentIndex?void 0:r.get(a.parentIndex);return n.reverse()}function IE(e,t){let r=new Map;for(let t of e){if(void 0===t.parentIndex)continue;let e=r.get(t.parentIndex)??[];e.push(t),r.set(t.parentIndex,e)}let n=new Set([t]),a=[t];for(let e of a)for(let t of r.get(e)??[])n.has(t.index)||(n.add(t.index),a.push(t.index));return e.filter(e=>n.has(e.index))}function IL(e){let t=e.type??"",r=e.identifier??"";return!!(e.hittable||/\bbutton\b/i.test(t)||IM.test(r)||/(?:^|:)id\/permission_(?:allow|deny)/i.test(r))}function I$(e){if(!e)return"";let t=[e.label,e.value].filter(e=>"string"==typeof e&&e.trim().length>0);return t[0]?.trim()??""}async function IT(e,t,r={}){if("wait"===t)return await IF(e,r.timeoutMs??1e4);if("get"===t){var n;let t=await IG(e);return{kind:"alertStatus",platform:"android",action:"get",alert:n=t?.alert??null,...n?eV("Alert visible"):eV("No alert visible")}}return await IU(e,t)}async function IF(e,t){let r=Date.now(),n=await IV(e,t);if(!n)throw new O("COMMAND_FAILED","alert wait timed out");return{kind:"alertWait",platform:"android",action:"wait",alert:n.alert,waitedMs:Date.now()-r,...eV("Alert visible")}}async function IU(e,t){var r;let n,a,i=await IV(e,2e3);if(!i)throw new O("COMMAND_FAILED","alert not found",{hint:"If a sheet is visible in snapshot but alert reports no alert, it is likely app-owned UI. Use snapshot -i and press the visible label/ref."});let o=(r=i.buttons,n="accept"===t?"accept":"dismiss",(a=r.find(e=>e.role===n))||("dismiss"===t?r.find(e=>"neutral"===e.role)??null:1===r.length?r[0]??null:null));if(o)return await sb(e,o.x,o.y),Iq(t,i.alert,o.label);if("dismiss"===t)return await sS(e),Iq(t,i.alert,"Back");throw new O("COMMAND_FAILED","alert accept found an alert but no accept button",{alert:i.alert,hint:"Inspect alert get --json for visible buttons, then use press by visible label/ref if needed."})}async function IV(e,t){let r=Date.now();for(;Date.now()-r<t;){let t=await IG(e);if(t)return t;await e2(300)}return null}async function IG(e){return function(e){var t,r,n,a;let i,o=function(e){let t=e.filter(e=>{var t;let r;return r=(t=e).bundleId??"",I_.has(r)||Ik.test(t.identifier??"")});if(t.length)return{nodes:t,source:"permission"};let r=function(e){let t=e.filter(e=>{var t;let r;return r=(t=e).bundleId??"",Ix.has(r)&&ID.test(I$(t))});if(0===t.length)return[];let r=IR(e,t);return void 0===r?t:IE(e,r).filter(e=>e.bundleId&&Ix.has(e.bundleId))}(e);return r.length?{nodes:r,source:"system-dialog"}:{nodes:function(e){var t;let r,n,a=e.filter(e=>{var t;return t=e.type??"",/(?:^|[.$])[^.]*Dialog$/i.test(t)}),i=e.filter(e=>IN.test(e.identifier??"")),o=a.length?[...a,...i]:(r=(t=i).some(e=>IM.test(e.identifier??"")),n=t.some(e=>!IM.test(e.identifier??"")),r&&n?t:[]);if(0===o.length)return[];let s=IR(e,o);return void 0===s?o:IE(e,s)}(e),source:"native-dialog"}}(e),s=o.nodes;if(0===s.length)return null;let l=function(e){let t=new Set,r=[];for(let n of e){let e=I$(n);if(!e||!n.rect||!IL(n))continue;let a=e.trim().toLowerCase();if(!a||t.has(a))continue;t.add(a);let i=tV(n.rect);r.push({label:e,x:i.x,y:i.y,role:function(e,t){var r;let n=(r=e.identifier??"",/(?:^|:)id\/button1$/i.test(r)?"accept":/(?:^|:)id\/button2$/i.test(r)?"dismiss":/(?:^|:)id\/button3$/i.test(r)?"neutral":/(?:^|:)id\/permission_allow/i.test(r)?"accept":/(?:^|:)id\/permission_deny/i.test(r)?"dismiss":null);return n||(IP.test(t.trim())?"accept":IO.test(t.trim())?"dismiss":"neutral")}(n,e)})}return r}(s),u=s.filter(e=>I$(e)&&!IL(e)),d=I$((t=u).find(e=>/(?:^|:)id\/(?:alertTitle|permission_message)$/i.test(e.identifier??"")))||I$(t[0]),c=(r=u,n=d,(i=r.map(e=>I$(e)).filter(e=>e&&e!==n)).length?[...new Set(i)].join("\n"):void 0),p=(a=s,a.find(e=>e.bundleId)?.bundleId);return{alert:{...d?{title:d}:{},...c?{message:c}:{},buttons:l.map(e=>e.label),platform:"android",source:o.source,...p?{packageName:p}:{}},buttons:l}}((await eN("snapshot_capture",async()=>await o6(e,{helperWaitForIdleTimeoutMs:0,includeHiddenContentHints:!1}),{backend:"android",purpose:"alert"})).nodes)}function Iq(e,t,r){return{kind:"alertHandled",platform:"android",action:e,handled:!0,alert:t,button:r,...eV(`Alert ${e}ed`)}}async function Ij(e){var t;let{req:r,logPath:n,session:a,device:i}=e,o="accept"===(t=r.positionals?.[0])||"dismiss"===t||"wait"===t?t:"get",s=a?"frontmost-app"===a.surface?{surface:"frontmost-app"}:{bundleId:a.appBundleId,surface:a.surface}:{};if(!cF("alert",i))return cm("UNSUPPORTED_OPERATION","alert is not supported on this device");if("android"===i.platform){let t=ej(r.positionals?.[1])??1e4;return Iz(e,await IT(i,o,{timeoutMs:t}))}if("macos"===i.platform){let t=async e=>await lK(e,s);return await IB(e,o,t)}let l={verbose:r.flags?.verbose,logPath:n,traceLogPath:a?.trace?.outPath,requestId:r.meta?.requestId},u=async e=>await ao(i,{command:"alert",action:e,appBundleId:a?.appBundleId},l);return await IB(e,o,u)}async function IB(e,t,r){if("wait"===t)return await IH(e,r);let n="accept"===t||"dismiss"===t?t:"get";return"accept"===n||"dismiss"===n?await IW(e,n,r):Iz(e,await r("get"))}async function IH(e,t){let r=ej(e.req.positionals?.[1])??1e4,n=Date.now();for(;Date.now()-n<r;){try{return Iz(e,await t("get"))}catch{}await e2(300)}return cm("COMMAND_FAILED","alert wait timed out")}async function IW(e,t,r){var n,a;let i,o,s=Date.now();for(;Date.now()-s<2e3;){try{return Iz(e,await r(t))}catch(t){o=t;let e=String(t?.message??"").toLowerCase();if(!e.includes("alert not found")&&!e.includes("no alert"))break}await e2(300)}throw(n=o)instanceof O&&(a=n,(i=String(a?.message??"").toLowerCase()).includes("alert not found")||i.includes("no alert"))?new O(n.code,n.message,{...n.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."}):n}function Iz(e,t){return f_(e.sessionStore,e.session,e.req,t),{ok:!0,data:t}}async function IK(e){let{req:t,logPath:r,sessionStore:n,session:a,device:i,parsed:o}=e,{setting:s,state:l,permissionTarget:u,latitude:d,longitude:c}=o;if(!cF("settings",i))return cm("UNSUPPORTED_OPERATION","settings is not supported on this device");if("macos"===i.platform&&!tm(s))return cm("INVALID_ARGS",tD(s));let p=a?.appBundleId,f="permission"===s?[s,l,u??"",t.positionals?.[3]??"",p??""]:"location"===s&&"set"===l?[s,l,d??"",c??"",p??""]:[s,l,p??""],m=await cr(i,"settings",f,t.flags?.out,{...cH(r,t.flags,p,a?.trace?.outPath)});return f_(n,a,t,m??{setting:s,state:l}),{ok:!0,data:m??{setting:s,state:l}}}async function IJ(e){var t,r;let n;if("snapshot"!==e.command||"android"!==e.device.platform)return;let a=P(e.error);if("COMMAND_FAILED"===(t=a).code&&(r=t,n=`${r.message}
90
- ${r.hint??""}`,/Android UI hierarchy dump timed out/i.test(n)||/Stock UIAutomator fallback was skipped/i.test(n)||/Android accessibility snapshots can be blocked/i.test(n)||function(e){if(!e||"object"!=typeof e)return!1;let t=String(e.errorType??""),r=String(e.message??"");return/TimeoutException/i.test(t)||/timed out/i.test(r)}(t.details?.helper)||function(e){var t;if(!e)return!1;let r=e?.timeoutMs,n=e?.cmd,a=Array.isArray(t=e?.args)?t.map(String):"string"==typeof t?t.split(/\s+/):[];return"number"==typeof r&&"adb"===n&&a.includes("uiautomator")&&a.includes("dump")}(t.details)))return{ok:!1,error:{...a,details:{...a.details??{},androidSnapshotTimeoutScreenshot:await IX(e)}}}}async function IX(e){try{var t,r,n;let a=await d.mkdtemp(f.join(c.tmpdir(),"agent-device-android-snapshot-timeout-")),i=f.join(a,"snapshot-timeout-overlay-refs.png"),o=(t=await cr(e.device,"screenshot",[i],void 0,{...cH(e.logPath,{screenshotNoStabilize:!0},e.session?.appBundleId,e.session?.trace?.outPath),surface:e.session?.surface}),r=i,(n=t,"object"==typeof n&&null!==n&&"path"in n&&"string"==typeof n.path)?t.path:r);await d.access(o);let s=await IY(o,e.session);return eM({level:"warn",phase:"android_snapshot_timeout_screenshot_captured",data:{path:o,overlayRefCount:"overlayRefCount"in s?s.overlayRefCount:void 0,overlayRefsAnnotated:"overlayRefsAnnotated"in s?s.overlayRefsAnnotated:void 0}}),s}catch(t){let e=P(t);return eM({level:"warn",phase:"android_snapshot_timeout_screenshot_failed",data:{error:e.message}}),{captureFailed:!0,error:e.message}}}async function IY(e,t){if(!t?.snapshot)return{path:e,overlayRefsRequested:!0,overlayRefsAnnotated:!1,overlayRefSource:"unavailable",overlayRefCount:0};try{let r=await pH({screenshotPath:e,snapshot:t.snapshot});return{path:e,overlayRefsRequested:!0,overlayRefsAnnotated:r.length>0,overlayRefCount:r.length,overlayRefSource:"session-snapshot",overlayRefs:r}}catch(r){let t=P(r);return eM({level:"warn",phase:"android_snapshot_timeout_screenshot_overlay_failed",data:{path:e,error:t.message}}),{path:e,overlayRefsRequested:!0,overlayRefsAnnotated:!1,overlayRefSource:"session-snapshot",overlayRefCount:0,overlayAnnotationError:t.message}}}async function IZ(e){return await I0({...e,command:"snapshot",unsupportedMessage:"snapshot is not supported on this device",execute:async({runtime:e,sessionName:t,req:r,snapshotScope:n})=>{let a=await e.capture.snapshot({session:t,interactiveOnly:r.flags?.snapshotInteractiveOnly,compact:r.flags?.snapshotCompact,depth:r.flags?.snapshotDepth,scope:n,raw:r.flags?.snapshotRaw,forceFull:r.flags?.snapshotForceFull});return{data:a,record:{kind:"snapshot",nodes:a.nodes.length,truncated:a.truncated}}}})}async function IQ(e){return await I0({...e,command:"diff",unsupportedMessage:"diff is not supported on this device",execute:async({runtime:e,sessionName:t,req:r,snapshotScope:n})=>{let a=await e.capture.diffSnapshot({session:t,interactiveOnly:r.flags?.snapshotInteractiveOnly,compact:r.flags?.snapshotCompact,depth:r.flags?.snapshotDepth,scope:n,raw:r.flags?.snapshotRaw});return{data:a,record:{kind:"diff",mode:"snapshot",baselineInitialized:a.baselineInitialized,summary:a.summary}}}})}async function I0(e){let{req:t,sessionName:r,logPath:n,sessionStore:a}=e,{session:i,device:o}=await fA(a,r,t.flags);if(!cF(e.command,o))return cm("UNSUPPORTED_OPERATION",e.unsupportedMessage);let s=function(e,t){let r;if(!e||!e.trim().startsWith("@"))return{ok:!0,scope:e};if(!t?.snapshot)return cm("INVALID_ARGS","Ref scope requires an existing snapshot in session.");let n=tT(e.trim());if(!n)return cm("INVALID_ARGS",`Invalid ref scope: ${e}`);for(let e of[t.snapshot,...t.snapshotScopeSource?[t.snapshotScopeSource]:[]]){let t=tF(e.nodes,n);if(r=t?tX(t,e.nodes):void 0)break}return r?{ok:!0,scope:r}:cm("COMMAND_FAILED",`Ref ${e} not found or has no label`)}(t.flags?.snapshotScope,i);return s.ok?await fS(i,o,async()=>{var l,u;let d,c,p=function(e){let{req:t,sessionName:r,logPath:n,sessionStore:a,session:i,device:o,snapshotScope:s}=e;return tM({backend:function(e){let{req:t,logPath:r,session:n,device:a,snapshotScope:i}=e;return{platform:a.platform,captureSnapshot:async(e,o)=>{let s=await pi({device:a,session:n,flags:t.flags,outPath:o?.outPath??t.flags?.out,logPath:r,snapshotScope:i});return{snapshot:s.snapshot,analysis:s.analysis,androidSnapshot:s.androidSnapshot,freshness:s.freshness,appName:n?.appBundleId?n.appName??n.appBundleId:void 0,appBundleId:n?.appBundleId}}}}({req:t,logPath:n,session:i,device:o,snapshotScope:s}),...fL("snapshot"),sessions:pw({sessionName:r,getSession:()=>a.get(r),recordOptions:{includeSnapshot:!0},setRecord:e=>{var n;let i=function(e){if(!e.snapshot)throw new O("UNKNOWN","snapshot runtime did not produce session state");return e}(e),s=a.get(r);a.set(r,function(e){var t,r;let{current:n,sessionName:a,device:i,record:o,refScopedSnapshot:s}=e,l=(t=n,r=o,s&&r.snapshot?.nodes.length===0&&t?.snapshot!==void 0),u=l?n.snapshot:o.snapshot,d=function(e){let{session:t,sessionName:r,device:n,snapshot:a,appBundleId:i}=e;return t?{...t,snapshot:a}:{name:r,device:n,createdAt:Date.now(),appBundleId:i,snapshot:a,actions:[]}}({session:n,sessionName:a,device:i,snapshot:u,appBundleId:o.appBundleId});return d.snapshotScopeSource=function(e){let{current:t,keepCurrentSnapshot:r,refScopedSnapshot:n}=e;if(n)return r?t?.snapshotScopeSource:t?.snapshotScopeSource??t?.snapshot}({current:n,keepCurrentSnapshot:l,refScopedSnapshot:s}),o.appName&&(d.appName=o.appName),d}({current:s,sessionName:r,device:o,record:i,refScopedSnapshot:(n=t,n.flags?.snapshotScope?.trim().startsWith("@")===!0)}))}})})}({req:t,sessionName:r,logPath:n,sessionStore:a,session:i,device:o,snapshotScope:s.scope});try{c=await e.execute({runtime:p,sessionName:r,req:t,snapshotScope:s.scope})}catch(r){let t=await IJ({error:r,command:e.command,logPath:n,session:i,device:o});if(!t)throw r;return t}return(d=(l={req:t,sessionName:r,sessionStore:a,result:c.record}).sessionStore.get(l.sessionName))&&l.sessionStore.recordAction(d,{command:l.req.command,positionals:l.req.positionals??[],flags:l.req.flags??{},result:"snapshot"===(u=l.result).kind?{nodes:u.nodes,truncated:u.truncated}:{mode:u.mode,baselineInitialized:u.baselineInitialized,summary:u.summary}}),{ok:!0,data:c.data}}):s}let I1=ek.snapshot,I2={snapshot:async({req:e,sessionName:t,logPath:r,sessionStore:n})=>await IZ({req:e,sessionName:t,logPath:r,sessionStore:n}),diff:async({req:e,sessionName:t,logPath:r,sessionStore:n})=>e.positionals?.[0]!=="snapshot"?cm("INVALID_ARGS","diff currently supports only: diff snapshot"):await IQ({req:e,sessionName:t,logPath:r,sessionStore:n}),wait:async({req:e,sessionName:t,logPath:r,sessionStore:n})=>await fY({req:e,sessionName:t,logPath:r,sessionStore:n}),alert:async({req:e,sessionName:t,logPath:r,sessionStore:n})=>{let{session:a,device:i}=await fA(n,t,e.flags);return await fS(a,i,async()=>await Ij({req:e,logPath:r,sessionStore:n,session:a,device:i}))},settings:async({req:e,sessionName:t,logPath:r,sessionStore:n})=>{let a,i,o,s=(a=e.positionals?.[0]?.toLowerCase(),i=e.positionals?.[1]?.toLowerCase(),o=e.positionals?.[2]?.toLowerCase(),a&&i&&("permission"!==a||o)&&("location"!==a||"set"!==i||e.positionals?.[2]&&e.positionals?.[3])?{ok:!0,parsed:{setting:a,state:i,permissionTarget:o,latitude:e.positionals?.[2],longitude:e.positionals?.[3]}}:cm("INVALID_ARGS",tv));if(!s.ok)return s;let{session:l,device:u}=await fA(n,t,e.flags);return await fS(l,u,async()=>await IK({req:e,logPath:r,sessionStore:n,session:l,device:u,parsed:s.parsed}))}};async function I3(e){let t=e.req.command;if(!I1.has(t))return null;let r=I2[t];return r?await r(e):cm("COMMAND_FAILED",`Snapshot command has no handler: ${t}`)}async function I5(e){let{req:t,sessionName:r,logPath:n,sessionStore:a,leaseRegistry:i,invoke:o,invokeReplayAction:s,androidAdbExecutor:l,contextFromFlags:u}=e,d=await mq({req:t,leaseRegistry:i});if(d)return d;let c=await IS({req:t,sessionName:r,logPath:n,sessionStore:a,invoke:o,invokeReplayAction:s,androidAdbExecutor:l});if(c)return c;let p=await I3({req:t,sessionName:r,logPath:n,sessionStore:a});if(p)return p;let f=await mj({req:t,sessionName:r,logPath:n,sessionStore:a,contextFromFlags:u});if(f)return f;let m=await hj({req:t,sessionName:r,sessionStore:a,logPath:n});if(m)return m;let h=await mt({req:t,sessionName:r,logPath:n,sessionStore:a,invoke:o});if(h)return h;let w=await mT({req:t,sessionName:r,logPath:n,sessionStore:a,contextFromFlags:u});return w||null}function I4(e,t){if(!t)return[];let r=[],n=e.device,a=t.platform;if(a&&!r2(n.platform,a)&&r.push({key:"platform",value:t.platform}),t.target&&t.target!==(n.target??"mobile")&&r.push({key:"target",value:t.target}),t.udid&&("ios"!==n.platform||t.udid!==n.id)&&r.push({key:"udid",value:t.udid}),t.serial&&("android"!==n.platform||t.serial!==n.id)&&r.push({key:"serial",value:t.serial}),t.device&&t.device.trim().toLowerCase()!==n.name.trim().toLowerCase()&&r.push({key:"device",value:t.device}),t.iosSimulatorDeviceSet){let e=t.iosSimulatorDeviceSet.trim(),a=n.simulatorSetPath?.trim();("ios"!==n.platform||"simulator"!==n.kind||e!==a)&&r.push({key:"iosSimulatorDeviceSet",value:t.iosSimulatorDeviceSet})}if(t.androidDeviceAllowlist){let e=es(t.androidDeviceAllowlist);"android"===n.platform&&e.has(n.id)||r.push({key:"androidDeviceAllowlist",value:t.androidDeviceAllowlist})}return r}function I8(e){return`${function(e){switch(e){case"iosSimulatorDeviceSet":return"--ios-simulator-device-set";case"androidDeviceAllowlist":return"--android-device-allowlist";default:return`--${e}`}}(e.key)}=${e.value}`}let I6=["target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist"],I9=new Set([eP.apps,eP.devices]);function I7(e){return"string"==typeof e&&e.trim().length>0}let be=ek.selectorValidationExempt,bt=ek.leaseAdmissionExempt,br=new Set(bt);async function bn(e){let{req:t,sessionName:r,sessionStore:n}=e,a=n.get(r);if(a)return`device:${a.device.id}`;if("open"===t.command||cw(t.flags))try{let e=await oy(t.flags??{});return`device:${e.id}`}catch{}return`session:${r}`}let ba=new WeakMap;async function bi(e){var t,r;let n,a,i,{sessionStore:o,leaseRegistry:s}=e,l=(n={...(t=function(e){let t=eC(e.meta?.sessionIsolation??e.flags?.sessionIsolation),r=e.meta?.tenantId??e.flags?.tenant,n=eO(r);if(r&&!n)throw new O("INVALID_ARGS","Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");if("tenant"!==t)return e;if(!n)throw new O("INVALID_ARGS","session isolation mode tenant requires --tenant (or meta.tenantId).");let a=e.session||"default";return a.startsWith(`${n}:`)?{...e,meta:{...e.meta,tenantId:n,sessionIsolation:t}}:{...e,session:`${n}:${a}`,meta:{...e.meta,tenantId:n,sessionIsolation:t}}}(e.req)).flags??{}},((a=tp(t.command,n))||!t.flags)&&a?{...t,flags:n}:t);eM({level:"info",phase:"request_start",data:{session:l.session,command:l.command,tenant:l.meta?.tenantId,isolation:l.meta?.sessionIsolation}});let u=l.command;!function(e,t){if(bt.has(e.command)||e.meta?.sessionIsolation!=="tenant")return;let r=mG(e);t.assertLeaseAdmission({tenantId:r.tenantId,runId:r.runId,leaseId:r.leaseId,backend:r.leaseBackend})}(l,s);let d=function(e,t){var r;let n,a=e.session||"default";if(r=e,"string"==typeof(n=r.flags?.session)&&n.trim().length>0||"default"!==a||t.has(a))return a;let i=t.toArray(),o=i[0];return void 0!==o&&1===i.length?o.name:a}(l,o),c=br.has(u)?null:await bn({req:l,sessionName:d,sessionStore:o}),p=(r=s,(i=ba.get(r))||(i=new Map,ba.set(r,i)),i);return{req:l,command:u,sessionName:d,throwIfCanceled:()=>rf(l.meta?.requestId),runLocked:async e=>(rf(l.meta?.requestId),c)?await r0(p,c,async()=>(rf(l.meta?.requestId),await e())):await e()}}function bo(e){var t,r;let{scope:n,logPath:a,sessionStore:i,trackDownloadableArtifact:o}=e;n.throwIfCanceled();let s=i.get(n.sessionName);s&&(!function(e){var t,r;let n,a;if(!((a=(r=e).recording)&&"ios"===r.device.platform&&"ios"!==a.platform&&!1!==a.showTouches))return;let i=e.recording,o=(t=e.device.id,(n=nX.get(t))?{sessionId:n.sessionId,alive:n4(n.child.pid)}:null);if(!i.runnerSessionId){o?.alive&&(i.runnerSessionId=o.sessionId);return}if(!o?.alive){i.invalidatedReason??="iOS runner session exited during recording";return}o.sessionId!==i.runnerSessionId&&(i.invalidatedReason??="iOS runner session restarted during recording")}(s),i.set(n.sessionName,s));let l=function(e,t){let r=e.meta?.lockPolicy;if(!r)return e;let n={...e.flags??{}},a=I9.has(e.command),i=a?[]:t?I4(t,n):function(e,t,r){var n,a;let i=[];if(void 0!==e.platform&&t&&(n=e.platform,a=t,n&&a&&n!==a&&("apple"===n?!r1(a):"apple"!==a||!r1(n)))&&i.push({key:"platform",value:e.platform}),"open"===r)return i;for(let t of I6){let r=e[t];I7(r)&&i.push({key:t,value:r})}return i}(n,e.meta?.lockPlatform,e.command),o=e.meta?.lockPlatform;if(0===i.length){var s,l,u;return s=a,l=t,u=n,!o||l||void 0!==u.platform||s&&I6.some(e=>I7(u[e]))||(n.platform=o),{...e,flags:n}}if("strip"===r)return function(e,t,r,n){if(n){(function(e,t){for(let r of t)delete e[r.key]})(e,t),e.platform=n.device.platform;return}var a=e,i=r;for(let e of I6)delete a[e];i&&(a.platform=i)}(n,i,o,t),{...e,flags:n};throw new O("INVALID_ARGS",`${e.command} cannot override session lock policy with ${i.map(I8).join(", ")}. Unset those selectors or remove the request lock policy.`)}(n.req,s),u=e=>(function(e,t,r){let n=e_();if(!t.ok){eM({level:"error",phase:"request_failed",data:{code:t.error.code,message:t.error.message}});let e=ex({force:!0})??void 0;return{ok:!1,error:P(new O(k(t.error.code),t.error.message,{...t.error.details??{},hint:t.error.hint,diagnosticId:t.error.diagnosticId,logPath:t.error.logPath}),{diagnosticId:n.diagnosticId,logPath:e})}}return eM({level:"info",phase:"request_success"}),ex(),{ok:!0,data:function(e,t,r){var n,a;let i;if(!t)return t;let o=(n=e,i=Array.isArray((a=t).artifacts)?[...a.artifacts]:[],"screenshot"!==n.command||i.some(e=>e?.field==="path")||"string"!=typeof a.path||i.push({field:"path",path:a.path,localPath:n.meta?.clientArtifactPaths?.path,fileName:f.basename(n.meta?.clientArtifactPaths?.path??a.path)}),i.filter(e=>!!(e&&"string"==typeof e.field&&"string"==typeof e.path&&"string"==typeof e.localPath&&e.localPath.length>0)));return 0===o.length?t:{...t,artifacts:o.map(t=>{let n=t.path;return{field:t.field,artifactId:r({artifactPath:n,tenantId:e.meta?.tenantId,fileName:t.fileName}),fileName:t.fileName,localPath:t.localPath}})}}(e,t.data,r)}})(l,e,o);if(s?.recording?.invalidatedReason&&"record"!==(t=n.command)&&"close"!==t)return{type:"response",response:u({ok:!1,error:{code:"COMMAND_FAILED",message:s.recording.invalidatedReason}})};!s||l.meta?.lockPolicy||(r=n.command,be.has(r))||function(e,t){let r=I4(e,t);if(0!==r.length){var n;let t,a,i;throw new O("INVALID_ARGS",`Session "${e.name}" is bound to ${(t=(n=e).device.platform,a=n.device.name.trim(),i=n.device.id,`${t} device "${a}" (${i})`)} and cannot be used with ${r.map(I8).join(", ")}. Use a different --session name or close this session first.`)}}(s,l.flags);let d=(e,t,r)=>{let n;return{...cH(a,e,t,r,n=e_().requestId),requestId:n}};return{type:"scope",scope:{req:l,sessionName:n.sessionName,existingSession:s,finalize:u,contextFromFlags:d,handlerContextFromFlags:(e,t,r)=>({...d(e,t,r),surface:i.get(n.sessionName)?.surface})}}}async function bs(e){let{lockedScope:t,logPath:r,sessionStore:n}=e,a=n.get(t.sessionName);if(!a)return t.finalize({ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session. Run open first."}});let i=await fw({req:t.req,session:a,sessionName:t.sessionName,logPath:r,sessionStore:n,contextFromFlags:t.contextFromFlags});return t.finalize(i)}function bl(e){eM({level:"error",phase:"request_failed",data:{error:e instanceof Error?e.message:String(e)}});let t=e_(),r=ex({force:!0})??void 0;return{ok:!1,error:P(e,{diagnosticId:t.diagnosticId,logPath:r})}}async function bu(e,t=5e3){await Promise.all(e.map(async e=>{let r;await new Promise(n=>{r=setTimeout(()=>{!function(e){e.destroyConnections?.();let t="closeAllConnections"in e?e.closeAllConnections:void 0;if("function"==typeof t)return t.call(e);let r="closeIdleConnections"in e?e.closeIdleConnections:void 0;"function"==typeof r&&r.call(e)}(e),n()},t);try{e.close(()=>n())}catch{n()}}),r&&clearTimeout(r)}))}function bd(e){l.existsSync(e)&&l.unlinkSync(e)}function bc(e){if(!l.existsSync(e))return null;try{let t=JSON.parse(l.readFileSync(e,"utf8"));if(!Number.isInteger(t.pid)||t.pid<=0)return null;return t}catch{return null}}function bp(e){let t=bc(e);if(!t||t.pid===process.pid)try{l.existsSync(e)&&l.unlinkSync(e)}catch{}}function bf(e){if(void 0===e)return;let t=Number(e);if(Number.isInteger(t))return t}(async function(e={}){let t,r,n=e.env??process.env,a=e.stdout??process.stdout,i=e.stderr??process.stderr,s=e.exit??(e=>process.exit(e)),{baseDir:u,infoPath:d,lockPath:c,logPath:p,sessionsDir:h}=ez(n.AGENT_DEVICE_STATE_DIR),w=eX(n.AGENT_DEVICE_DAEMON_SERVER_MODE);var g,y,v,I=h;if(l.existsSync(I))for(let e of l.readdirSync(I,{withFileTypes:!0})){if(!e.isDirectory())continue;let t=f.join(I,e.name,aL);if(l.existsSync(t))try{let e=a$(l.readFileSync(t,"utf8"));if(e&&function(e){let t,r=eh(e.pid);if(!r||e.startTime&&r!==e.startTime)return!1;let n=eg(e.pid);return!!n&&!!((t=n.toLowerCase().replaceAll("\\","/")).includes("log stream")||t.includes("logcat")||t.includes("devicectl device log stream"))&&(!e.command||n===e.command)}(e))try{process.kill(e.pid,"SIGTERM")}catch{}}catch{}finally{aF(t)}}let b=new aE(h),A=new i1({maxActiveSimulatorLeases:bf(n.AGENT_DEVICE_MAX_SIMULATOR_LEASES),defaultLeaseTtlMs:bf(n.AGENT_DEVICE_LEASE_TTL_MS),minLeaseTtlMs:bf(n.AGENT_DEVICE_LEASE_MIN_TTL_MS),maxLeaseTtlMs:bf(n.AGENT_DEVICE_LEASE_MAX_TTL_MS)}),S=eE(),_=o.randomBytes(24).toString("hex"),x=eh(process.pid)??void 0,N=e0(),M=function(e){let{logPath:t,token:r,androidAdbProvider:n,appleRunnerProvider:a,appleToolProvider:i,linuxToolProvider:o,appLogProvider:s,recordingProvider:l,deviceInventoryProvider:u,trackDownloadableArtifact:d}=e,{sessionStore:c,leaseRegistry:p}=e;async function f(e){let m=!!(e.meta?.debug||e.flags?.verbose);return await eA({session:e.session,requestId:e.meta?.requestId,command:e.command,debug:m,logPath:t},async()=>{if(e.token!==r)return{ok:!1,error:P(new O("UNAUTHORIZED","Invalid token"))};try{return await ob(u,async()=>{let u=await bi({req:e,sessionStore:c,leaseRegistry:p});return await u.runLocked(async()=>{let e=bo({scope:u,logPath:t,sessionStore:c,trackDownloadableArtifact:d});if("response"===e.type)return e.response;let m=e.scope;return await cN({req:m.req,existingSession:m.existingSession,providers:{androidAdbProvider:n,appleRunnerProvider:a,appleToolProvider:i,linuxToolProvider:o,appLogProvider:s,recordingProvider:l}},async e=>{let n=await I5({req:m.req,sessionName:m.sessionName,logPath:t,sessionStore:c,leaseRegistry:p,invoke:f,invokeReplayAction:function(e){let{parentScope:t,providerScope:r,handleRequest:n,deps:a}=e;return async e=>{var i,o;if(i=e,o=t,!(i.session===o.sessionName&&ek.replayScopedAction.has(i.command)))return await n(e);if(e.token!==a.token)return{ok:!1,error:P(new O("UNAUTHORIZED","Invalid token"))};try{let i=await bi({req:e,sessionStore:a.sessionStore,leaseRegistry:a.leaseRegistry});if(i.sessionName!==t.sessionName)return await n(e);let o=bo({scope:i,logPath:a.logPath,sessionStore:a.sessionStore,trackDownloadableArtifact:a.trackDownloadableArtifact});if("response"===o.type)return o.response;let s=o.scope,l=await I5({req:s.req,sessionName:s.sessionName,logPath:a.logPath,sessionStore:a.sessionStore,leaseRegistry:a.leaseRegistry,invoke:n,androidAdbExecutor:r.androidAdbExecutor,contextFromFlags:s.handlerContextFromFlags});if(l)return s.finalize(l);return await bs({lockedScope:s,logPath:a.logPath,sessionStore:a.sessionStore})}catch(e){return bl(e)}}}({parentScope:m,providerScope:e,handleRequest:f,deps:{logPath:t,token:r,sessionStore:c,leaseRegistry:p,trackDownloadableArtifact:d}}),androidAdbExecutor:e.androidAdbExecutor,contextFromFlags:m.handlerContextFromFlags});return n?m.finalize(n):await bs({lockedScope:m,logPath:t,sessionStore:c})})})})}catch(e){return bl(e)}})}return f}({logPath:p,token:_,sessionStore:b,leaseRegistry:A,trackDownloadableArtifact:iA}),k=async e=>{await eA({command:"daemon",session:"daemon",logPath:p,debug:!0},async()=>{eM({level:"error",phase:"daemon_fatal",data:{error:e instanceof Error?e.message:String(e)}}),ex({force:!0})})},R=async e=>{let t=w3(e,e.name).catch(t=>{i.write(`Daemon session teardown error (${e.name}): ${t instanceof Error?t.message:String(t)}
91
- `)});await Promise.race([t,e2(5e3).then(()=>{i.write(`Daemon session teardown timed out (${e.name}).
92
- `)})]),b.writeSessionLog(e),b.delete(e.name)},C=async()=>{let e=b.toArray();await Promise.all(e.map(R))},E=async()=>{let e,t,r=[];if("http"!==w){let t,n,a=(t=new Set,(n=m.createServer(e=>{t.add(e),e.on("close",()=>t.delete(e));let r="",n=0,a=new Set,i=!1,o=()=>{if(!i&&0!==n){for(let e of(i=!0,a))rl(e);eM({level:"warn",phase:"request_client_disconnected",data:{inFlightRequests:n}}),(async()=>{try{let e=Date.now()+15e3;for(;n>0&&Date.now()<e&&(await n3(),!(n<=0));)await e2(200)}catch(e){eM({level:"error",phase:"request_client_disconnect_abort_failed",data:{message:e instanceof Error?e.message:String(e),inFlightRequests:n}})}})()}};e.setEncoding("utf8"),e.on("close",o),e.on("error",o),e.on("data",async t=>{let i=(r+=t).indexOf("\n");for(;-1!==i;){let t,o,s=r.slice(0,i).trim();if(r=r.slice(i+1),0===s.length){i=r.indexOf("\n");continue}n+=1;try{let e=JSON.parse(s);if(o=ro(e.meta?.requestId,"socket"),e.meta={...e.meta,requestId:o},a.add(o),rs(o),rd(o))throw rp();t=await M(e)}catch(e){t={ok:!1,error:P(e)}}finally{n-=1,o&&(a.delete(o),ru(o))}e.destroyed||e.write(`${JSON.stringify(t)}
93
- `),i=r.indexOf("\n")}})})).destroyConnections=()=>{for(let e of t)e.destroy();t.clear()},n);r.push(a),e=await new Promise((e,t)=>{a.once("error",t),a.listen(0,"127.0.0.1",()=>{a.off("error",t);let r=a.address();"object"==typeof r&&r?.port?e(r.port):t(new O("COMMAND_FAILED","Failed to bind socket server"))})})}if("socket"!==w){let e=await iK({handleRequest:M,token:_});r.push(e),t=await new Promise((t,r)=>{e.once("error",r),e.listen(0,"127.0.0.1",()=>{e.off("error",r);let n=e.address();"object"==typeof n&&n?.port?t(n.port):r(new O("COMMAND_FAILED","Failed to bind HTTP server"))})})}return{servers:r,socketPort:e,httpPort:t}};if(!function(e,t,r){l.existsSync(e)||l.mkdirSync(e,{recursive:!0});let n=JSON.stringify(r,null,2),a=()=>{try{return l.writeFileSync(t,n,{flag:"wx",mode:384}),!0}catch(e){if("EEXIST"===e.code)return!1;throw e}};if(a())return!0;let i=bc(t);if(i?.pid&&i.pid!==process.pid&&eI(i.pid,i.processStartTime))return!1;try{l.unlinkSync(t)}catch{}return a()}(u,c,{pid:process.pid,version:S,startedAt:Date.now(),processStartTime:x}))return i.write("Daemon lock is held by another process; exiting.\n"),s(0),null;let L=[];try{let e,n=await E();L=n.servers,t=n.socketPort,r=n.httpPort,g=t,y=r,v={socketPort:g,httpPort:y,token:_,version:S,codeSignature:N,processStartTime:x},l.existsSync(u)||l.mkdirSync(u,{recursive:!0}),l.writeFileSync(p,""),e=v.socketPort&&v.httpPort?"dual":v.httpPort?"http":"socket",l.writeFileSync(d,JSON.stringify({port:v.socketPort,httpPort:v.httpPort,transport:e,token:v.token,pid:process.pid,version:v.version,codeSignature:v.codeSignature,processStartTime:v.processStartTime,stateDir:u},null,2),{mode:384}),g&&a.write(`AGENT_DEVICE_DAEMON_PORT=${g}
88
+ `;function vy(e){if("string"!=typeof e)throw new D("COMMAND_FAILED",`Maestro runScript json() expected a string body, received ${typeof e}.`);if(0===e.trim().length)throw new D("COMMAND_FAILED","Maestro runScript json() received an empty body. Check the preceding http response status and setup server output.");try{return JSON.parse(e,vv)}catch(t){throw new D("COMMAND_FAILED",`Maestro runScript json() could not parse response body: ${t instanceof Error?t.message:String(t)}`,{bodyPreview:e.slice(0,1e3)},t instanceof Error?t:void 0)}}function vv(e,t){return"__proto__"===e||"constructor"===e||"prototype"===e?void 0:t}let vI={launchApp:({value:e,config:t,context:r})=>[yK(e,t,r)],tapOn:({value:e,context:t})=>[function(e,t){if("string"==typeof e)return y$(vt,[vl(yH(e,t))],vp(e));if(yU(e)&&"string"==typeof e.point){yF(e,"tapOn",["point","repeat","delay","optional","label"]);let t=y0(e.point);return"percent"===t.kind?y$(vr,[String(t.x),String(t.y)],vc(e)):y$("click",[String(t.x),String(t.y)],vc(e))}yU(e)&&yF(e,"tapOn",["id","text","childOf","enabled","index","selected","repeat","delay","optional","label"]);let r=vp(e);return y$(vt,[vs(e,"tapOn",["repeat","delay","optional","label","index","childOf"],t),...function(e,t){if(!yU(e))return[];let r={};if(void 0!==e.index){if("number"!=typeof e.index||!Number.isInteger(e.index)||e.index<0)throw new D("INVALID_ARGS","tapOn.index must be a non-negative integer.");r.index=e.index}return void 0!==e.childOf&&(r.childOf=vs(e.childOf,"tapOn.childOf",[],t)),Object.keys(r).length>0?[JSON.stringify(r)]:[]}(e,t)],r)}(e,t)],doubleTapOn:({value:e,context:t})=>[function(e,t){if(yU(e)&&"string"==typeof e.point){yF(e,"doubleTapOn",["point","delay"]);let t=yQ(e.point);return y$("click",[String(t.x),String(t.y)],vf(e))}return yU(e)&&yF(e,"doubleTapOn",["id","text","enabled","selected","delay"]),y$("click",[vs(e,"doubleTapOn",["delay"],t)],vf(e))}(e,t)],longPressOn:({value:e,context:t})=>[function(e,t){if(yU(e)&&"string"==typeof e.point){yF(e,"longPressOn",["point"]);let t=yQ(e.point);return y$("longpress",[String(t.x),String(t.y),"3000"])}return yU(e)&&yF(e,"longPressOn",["id","text","enabled","selected"]),y$("click",[vs(e,"longPressOn",[],t)],{holdMs:3e3})}(e,t)],inputText:({value:e,context:t})=>[y$("type",[yH(function(e){if("string"==typeof e)return e;if(!yU(e))throw new D("INVALID_ARGS","inputText expects a string or map.");if(yF(e,"inputText",["text","label"]),"string"!=typeof e.text)throw new D("INVALID_ARGS","inputText map requires a string text field.");return e.text}(e),t)])],eraseText:({value:e})=>[vn(e)],pasteText:({value:e,context:t,name:r})=>[y$("type",[yH(yj(r,e),t)])],openLink:({value:e,config:t,context:r,name:n})=>{var a,i,o,s,l,u;let d;return[(a=e,i=t,o=r,s=n,d=yH((l=a,u=s,"string"==typeof l?l:yU(l)?(yF(l,u,["link"]),yj(`${u}.link`,l.link)):yj(u,l)),o),"ios"===o.platform&&i.appId?y$("open",[yH(yB(i,s),o),d]):y$("open",[d]))]},assertVisible:({value:e,context:t,name:r})=>[y$(y5,[vs(e,r,[],t),"5000"])],assertNotVisible:({value:e,context:t,name:r})=>[y$(y4,[vs(e,r,[],t)])],extendedWaitUntil:({value:e,context:t})=>(function(e,t){if(!yU(e))throw new D("INVALID_ARGS","extendedWaitUntil expects a map.");yF(e,"extendedWaitUntil",["visible","notVisible","timeout"]);let r=e.visible??e.notVisible;if(void 0===r)throw yz("Only Maestro extendedWaitUntil.visible/notVisible is supported.");let n=vs(r,"extendedWaitUntil",[],t),a=String(yq(e,3e4));return void 0!==e.notVisible?[y$("wait",[a]),y$("is",["hidden",n])]:[y$(y5,[n,a])]})(e,t),takeScreenshot:({value:e,context:t,name:r})=>[y$("screenshot",[yH(yj(r,e),t)])],scroll:({value:e})=>[function(e){if(null!=e)throw yz("Maestro scroll options are not supported yet.");return y$("scroll",["down"])}(e)],scrollUntilVisible:({value:e,context:t})=>(function(e,t){if("string"==typeof e)return[y$(y9,[vl(yH(e,t)),"5000","down"])];if(!yU(e))throw new D("INVALID_ARGS","scrollUntilVisible expects a string or map.");yF(e,"scrollUntilVisible",["element","direction","timeout"]);let r=vs(e.element,"scrollUntilVisible.element",[],t),n="string"==typeof e.direction?vi(e.direction,"scrollUntilVisible.direction"):"down";return[y$(y9,[r,String(yq(e,5e3)),n])]})(e,t),swipe:({value:e,context:t})=>[function(e,t){var r,n,a;let i;if(!yU(e))throw new D("INVALID_ARGS","swipe expects a map.");yF(e,"swipe",["start","end","direction","duration","from","label"]);let o=e.from??("string"==typeof e.label?e.label:void 0);return void 0!==o?(r=e,n=o,a=t,i=vo("string"==typeof r.direction?r.direction:"up"),y$(ve,[vs(n,"swipe.from",[],a),i,...vu(r)])):"string"==typeof e.direction?y$(y7,["direction",vo(e.direction),...vu(e)]):function(e){let{start:t,end:r}=function(e){if("string"==typeof e.start&&"string"==typeof e.end)return{start:y0(e.start),end:y0(e.end)};throw yz("Only Maestro swipe start/end coordinates are supported.")}(e);var n=t,a=r,i=va(e.duration);if("absolute"===n.kind&&"absolute"===a.kind)return y$("swipe",[String(n.x),String(n.y),String(a.x),String(a.y),...i?[i]:[]]);if("percent"===n.kind&&"percent"===a.kind)return y$(y7,["percent",String(n.x),String(n.y),String(a.x),String(a.y),...i?[i]:[]]);throw yz("Maestro swipe start/end must both be absolute pixels or both be percentages.")}(e)}(e,t)],hideKeyboard:()=>[y$("keyboard",["dismiss"])],pressKey:({value:e})=>[function(e){let t=yj("pressKey",e).toLowerCase();if("back"===t)return y$("back");if("enter"===t||"return"===t)return y$(y8);if("home"===t)return y$("home");throw yz(`Maestro pressKey "${t}" is not supported yet.`)}(e)],back:()=>[y$("back")],waitForAnimationToEnd:({value:e})=>[y$(y6,[String(yq(e,15e3))])],stopApp:({value:e,config:t,context:r})=>[yJ(e,t,r)],runScript:({value:e,context:t})=>{let r;return[y$(y3,[function(e,t){if(f.isAbsolute(e))return e;if(!t.baseDir)throw new D("INVALID_ARGS","runScript file paths require replay input to have a source path.");return f.resolve(t.baseDir,e)}((r=function(e,t){if("string"==typeof e)return{file:yH(e,t),env:{}};if(!yU(e))throw new D("INVALID_ARGS","runScript expects a file path string or map.");return yF(e,"runScript",["file","env"]),{file:yH(yj("runScript.file",e.file),t),env:Object.fromEntries(Object.entries(yG(e.env,"runScript.env")).map(([e,r])=>[e,yH(r,t)]))}}(e,t)).file,t)],{...Object.keys(r.env).length>0?{maestro:{runScriptEnv:r.env}}:{}})]},runFlow:({value:e,config:t,context:r,deps:n})=>(function(e,t,r,n,a){if("string"==typeof e)return n.parseRunFlowFile(yH(e,r),r).actions;if(!yU(e))throw new D("INVALID_ARGS","runFlow expects a file path string or map.");yF(e,"runFlow",["file","commands","env","when","label"]);let i=function(e,t){var r,n;if(null==e)return{shouldRun:!0};if(!yU(e))throw new D("INVALID_ARGS","runFlow.when expects a map.");return(yF(e,"runFlow.when",["platform","visible","notVisible","true"]),!function(e,t){if(void 0!==e.true&&!function(e,t){let r;if("boolean"==typeof e)return e;if("string"!=typeof e)throw new D("INVALID_ARGS","runFlow.when.true expects a boolean or expression string.");return new vm(function(e){let t=[],r=0;for(;r<e.length;){var n,a;let i=e.slice(r),o=(n=i,/^\s+/.exec(n)?.[0].length??0);if(o>0){r+=o;continue}let s=function(e){let t="maestro.platform";return e.startsWith(t)?{token:{type:"platform"},length:t.length}:null}(a=i)??function(e){let t=/^(==|!=|&&|\|\|)/.exec(e)?.[1];return t?{token:{type:"operator",value:t},length:t.length}:null}(a)??function(e){let t=e[0];return"("===t||")"===t?{token:{type:"paren",value:t},length:1}:null}(a)??function(e){let t=/^(['"])(.*?)\1/.exec(e);return t?{token:{type:"string",value:t[2]??""},length:t[0].length}:null}(a)??function(e){let t=/^(true|false)\b/.exec(e)?.[1];return t?{token:{type:"boolean",value:"true"===t},length:t.length}:null}(a);if(s){t.push(s.token),r+=s.length;continue}throw new D("INVALID_ARGS",`Unsupported runFlow.when.true expression near "${i.slice(0,24)}".`)}return t}((r=yH(e,t).trim()).startsWith("${")&&r.endsWith("}")?r.slice(2,-1).trim():r),{platform:t.platform}).parse()}(e.true,t))return!1;if(void 0===e.platform)return!0;let r=function(e,t){if("string"!=typeof e)throw new D("INVALID_ARGS",`${t} expects Android, iOS, or Web.`);let r=e.trim().toLowerCase();if("android"===r||"ios"===r||"web"===r)return r;throw new D("INVALID_ARGS",`${t} expects Android, iOS, or Web.`)}(e.platform,"runFlow.when.platform");if(!t.platform)throw new D("INVALID_ARGS","Maestro runFlow.when.platform requires replay to be run with --platform ios|android.");return r===t.platform}(e,t))?{shouldRun:!1}:{shouldRun:!0,...(r=e,n=t,{...void 0!==r.visible?{visibleSelector:vs(r.visible,"runFlow.when.visible",[],n)}:{},...void 0!==r.notVisible?{notVisibleSelector:vs(r.notVisible,"runFlow.when.notVisible",[],n)}:{}})}}(e.when,r);if(!i.shouldRun)return[];let o={...r,env:{...r.env,...yG(e.env,"runFlow.env"),...r.envOverrides}};var s=function(e,t,r,n,a){if("string"==typeof e.file)return n.parseRunFlowFile(yH(e.file,r),r).actions;if(Array.isArray(e.commands))return a(yV(e.commands),t,r,n);throw new D("INVALID_ARGS","runFlow map requires either file or commands.")}(e,t,o,n,a),l=i;if(!l.visibleSelector&&!l.notVisibleSelector)return s;if(l.visibleSelector&&l.notVisibleSelector)throw yz("Maestro runFlow.when cannot combine visible and notVisible yet.");return[y$(y1,l.visibleSelector?["visible",l.visibleSelector]:["notVisible",l.notVisibleSelector??""],{batchSteps:s.map(vh)})]})(e,t,r,n,vS),repeat:({value:e,config:t,context:r,deps:n})=>(function(e,t,r,n,a){var i;if(!yU(e))throw new D("INVALID_ARGS","repeat expects a map.");if(yF(e,"repeat",["times","commands","while"]),void 0!==e.while)throw yz("Maestro repeat.while is not supported yet. Only deterministic repeat.times is supported.");let o=(i=e.times,vw(i,r,"repeat.times"));if(!Array.isArray(e.commands))throw new D("INVALID_ARGS","repeat requires a commands list.");if(o>1e3)throw new D("INVALID_ARGS","repeat.times must be <= 1000 for deterministic replay expansion.");let s=yV(e.commands);return Array.from({length:o}).flatMap(()=>a(s,t,r,n))})(e,t,r,n,vS),retry:({value:e,config:t,context:r,deps:n})=>(function(e,t,r,n,a){var i,o;if(!yU(e))throw new D("INVALID_ARGS","retry expects a map.");if(yF(e,"retry",["maxRetries","commands"]),!Array.isArray(e.commands))throw new D("INVALID_ARGS","retry requires a commands list.");let s=(i=e.maxRetries,o=r,void 0===i?1:vw(i,o,"retry.maxRetries")),l=a(yV(e.commands),t,r,n);return[y$(y2,[String(s)],{batchSteps:l.map(vh)})]})(e,t,r,n,vS)},vb={launchApp:(e,t)=>[yK(void 0,e,t)],scroll:()=>[y$("scroll",["down"])],hideKeyboard:()=>[y$("keyboard",["dismiss"])],eraseText:()=>[vn(void 0)],back:()=>[y$("back")],waitForAnimationToEnd:()=>[y$(y6,["15000"])],stopApp:(e,t)=>[yJ(void 0,e,t)]};function vA(e,t,r,n,a){try{return function(e,t,r,n){if("string"==typeof e){var a,i,o;let n;return a=e,i=t,o=r,(n=vb[a])?n(i,o):yW(a)}let s=Object.entries(e);if(1!==s.length)throw new D("INVALID_ARGS","Maestro command maps must contain exactly one command.");let[l,u]=s[0],d=vI[l];return d?d({value:u,config:t,context:r,deps:n,name:l}):yW(l)}(e,t,n,a)}catch(e){if(e instanceof D&&!/\bline \d+\b/.test(e.message))throw new D(e.code,`${e.message} (line ${r})`,e.details);throw e}}function vS(e,t,r,n){return e.flatMap((e,a)=>vA(e,t,a+1,r,n))}function vx(e,t){let{config:r,commands:n}=function(e){if(0===e.length)throw new D("INVALID_ARGS","Maestro flow is empty.");if(Array.isArray(e[0]))return{config:{},commands:yV(e[0])};let t=function(e){if(!yU(e))throw new D("INVALID_ARGS","Maestro flow config must be a YAML map.");return{..."string"==typeof e.appId&&e.appId.length>0?{appId:e.appId}:{},...yU(e.env)?{env:yG(e.env,"env")}:{},...Array.isArray(e.onFlowStart)?{onFlowStart:yV(e.onFlowStart)}:{},...Array.isArray(e.onFlowComplete)?{onFlowComplete:yV(e.onFlowComplete)}:{}}}(e[0]),r=e[1];if(!Array.isArray(r))throw new D("INVALID_ARGS","Maestro flow must contain a command list after the YAML document separator.");return{config:t,commands:yV(r)}}(function(e){let t=x(e);for(let e of t)if(e.errors.length>0){let t=e.errors[0]?.message??"Invalid Maestro YAML flow.";throw new D("INVALID_ARGS",`Invalid Maestro YAML flow: ${t}`)}return t.map(e=>e.toJSON()).filter(e=>null!==e)}(e)),a={...t,env:{...t.env,...r.env??{},...t.envOverrides}},{actions:i,actionLines:o}=function(e){let{config:t,commands:r,commandLines:n,context:a}=e,i=[...t.onFlowStart??[],...r,...t.onFlowComplete??[]],o=[...Array.from({length:t.onFlowStart?.length??0},()=>1),...n,...Array.from({length:t.onFlowComplete?.length??0},()=>n.at(-1)??1)],s=[],l=[];for(let[e,r]of i.entries()){let n=o[e]??e+1,i=vA(r,t,n,a,{parseRunFlowFile:vN});s.push(...i),i.forEach(()=>l.push(n))}return function(e,t){let r=[],n=[];for(let a=0;a<e.length;a+=1){let i=e[a],o=function(e,t,r){var n;let a=e[r],i=e[r+1],o=function(e){if(e?.command!=="type"||e.flags&&Object.keys(e.flags).length>0)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(i),s=function(e){if(e?.command!==vt)return null;let[t,...r]=e.positionals??[];return r.length>0||"string"!=typeof t?null:t}(a);if(!i||null===o||null===s)return null;let l=t[r]??1;if(n=s,!/\b(input|textfield|textarea|field|email|password|username|search|query)\b/i.test(n.replace(/([a-z])([A-Z])/g,"$1 $2")))return{actions:[v_(a)],actionLines:[l],consumed:1};let u=e[r+2];return u?.command!==y8?{actions:[v_(a)],actionLines:[l],consumed:1}:{actions:[{...a,command:"wait",positionals:[s,"30000"]},{...i,command:"fill",positionals:[s,o],flags:a.flags},u],actionLines:[l,l,t[r+2]??l],consumed:3}}(e,t,a);if(o){r.push(...o.actions),n.push(...o.actionLines),a+=o.consumed-1;continue}r.push(i),n.push(t[a]??1)}return{actions:r,actionLines:n}}(s,l)}({config:r,commands:n,commandLines:function(e){let t=e.split(/\r?\n/),r=t.findIndex(e=>"---"===e.trim()),n=-1===r?0:r+1,a=[];for(let e=n;e<t.length;e+=1)/^-\s+/.test(t[e]??"")&&a.push(e+1);return a}(e),context:a});return{actions:i,actionLines:o,metadata:{env:r.env}}}function v_(e){let t={...e.flags?.maestro??{}};return delete t.allowNonHittableCoordinateFallback,{...e,flags:{...e.flags??{},maestro:{...t}}}}function vN(e,t){let r=function(e,t){if(f.isAbsolute(e))return e;if(!t.baseDir)throw new D("INVALID_ARGS","runFlow file paths require replay input to have a source path.");return f.resolve(t.baseDir,e)}(e,t);if(t.visitedPaths.has(r))throw new D("INVALID_ARGS",`Maestro runFlow cycle detected at ${r}.`);let n=l.readFileSync(r,"utf8"),a=new Set(t.visitedPaths);return a.add(r),vx(n,{...t,baseDir:f.dirname(r),visitedPaths:a})}let vM={maestro:{parse:function(e,t={}){var r;let n;return vx(e,(n=(r=t).visitedPaths??new Set,r.sourcePath&&n.add(f.resolve(r.sourcePath)),{baseDir:r.sourcePath?f.dirname(r.sourcePath):void 0,platform:function(e){if(e){let t;return"android"===(t=e.trim().toLowerCase())?"android":"ios"===t?"ios":void 0}}(r.platform),env:{},envOverrides:r.env??{},visitedPaths:n}))}}};function vk(e){if(0===e.length)return{selectorExpression:null,selectorTimeout:null};let t=e[e.length-1],r=void 0!==t&&/^\d+$/.test(t)?t:null,n=tJ(null!==r?e.slice(0,-1):e.slice());return!n||n.rest.length>0?{selectorExpression:null,selectorTimeout:null}:{selectorExpression:n.selectorExpression,selectorTimeout:r}}async function vD(e){let{action:t,sessionName:r,logPath:n,sessionStore:a}=e;if(!(aN(t.command)||["fill","get","is","wait"].includes(t.command)))return null;let i=a.get(r);if(!i)return null;let o=(function(e){let t=[],r=Array.isArray(e.result?.selectorChain)&&e.result?.selectorChain.every(e=>"string"==typeof e)?e.result.selectorChain:[];if(t.push(...r),aN(e.command)){let r=function(e){let t=e.positionals??[];if("longpress"!==e.command)return t;let r=t.at(-1);return t.length>1&&vP(r)?t.slice(0,-1):t}(e),n=r[0]??"";n&&!n.startsWith("@")&&t.push(r.join(" "))}if("fill"===e.command){let r=e.positionals?.[0]??"";r&&!r.startsWith("@")&&Number.isNaN(Number(r))&&t.push(r)}if("get"===e.command){let r=e.positionals?.[1]??"";r&&!r.startsWith("@")&&t.push(e.positionals.slice(1).join(" "))}if("is"===e.command){let{split:r}=tQ(e.positionals);r&&t.push(r.selectorExpression)}if("wait"===e.command){let{selectorExpression:r}=vk(e.positionals??[]);r&&t.push(r)}return av(t).filter(e=>e.trim().length>0)})(t).map(e=>tY(e)).filter(e=>null!==e);if(0===o.length)return null;let s=aN(t.command)||"fill"===t.command,l=aN(t.command)||"fill"===t.command||"get"===t.command&&t.positionals?.[0]==="text",u=await vO(i,t,n,s,a);for(let e of o){let r=t5(u.nodes,e,{platform:i.device.platform,requireRect:s,requireUnique:!0,disambiguateAmbiguous:l});if(!r)continue;let n=t6(r.node,i.device.platform,{action:"fill"===t.command?"fill":aN(t.command)?"click":"get"}).join(" || ");if(aN(t.command))return{...t,positionals:"longpress"===t.command?function(e,t){let r="number"==typeof e.result?.durationMs?String(e.result.durationMs):function(e){let t=e.at(-1);return e.length>1&&vP(t)?t:void 0}(e.positionals??[]);return r?[t,r]:[t]}(t,n):[n]};if("fill"===t.command){let e=ay(t);if(!e)continue;return{...t,positionals:[n,e]}}if("get"===t.command){let e=t.positionals?.[0];if("text"!==e&&"attrs"!==e)continue;return{...t,positionals:[e,n]}}if("is"===t.command){let{predicate:e,split:r}=tQ(t.positionals);if(!e)continue;let a=r?.rest.join(" ").trim()??"",i=[e,n];return"text"===e&&a.length>0&&i.push(a),{...t,positionals:i}}if("wait"===t.command){let{selectorTimeout:e}=vk(t.positionals??[]),r=[n];return e&&r.push(e),{...t,positionals:r}}}return null}function vP(e){return void 0!==e&&""!==e.trim()&&Number.isFinite(Number(e))}async function vO(e,t,r,n,a){let i=px(await ch(e.device,"snapshot",[],t.flags?.out,{...c5(r,{...t.flags??{},snapshotInteractiveOnly:n,snapshotCompact:n},e.appBundleId,e.trace?.outPath)}),{...t.flags??{},snapshotInteractiveOnly:n,snapshotCompact:n});return pk(e,i),a.set(e.name,e),i}let vR=new WeakMap;function vE(e,t,r){return{ok:!1,error:{code:e,message:t,...r?{details:r}:{}}}}async function vC(e){var t;let r,n=await e.invoke({...e.baseReq,command:"snapshot",positionals:[],flags:{...e.baseReq.flags,noRecord:!0,snapshotRaw:!0,snapshotForceFull:!0}});return n.ok&&e.scope&&(t=e.scope,(r=fc(vL(n.data)))&&vR.set(t,r)),n}function vL(e){if("object"==typeof e&&null!==e&&Array.isArray(e.nodes))return e}function vT(e){let t={ts:Date.now(),command:e.command,positionals:e.positionals??[],flags:e.flags??{}};return e.runtime&&"object"==typeof e.runtime&&(t.runtime=e.runtime),t}let v$=new Map([["button",0],["link",0],["textfield",0],["textview",0],["searchfield",0],["switch",0],["slider",0],["cell",1],["statictext",2]]);function vF(e,t,r,n){var a;let i,o,s=vq(e,t,r),l=(i=(a={nodes:e.nodes,matches:s,platform:r}).matches.filter(e=>tU({predicate:"visible",node:e,nodes:a.nodes,platform:a.platform}).pass),{matches:(o=vU(a.nodes,i)).matches,blockedByReactNativeOverlay:o.blockedByReactNativeOverlay}),u=vH(e.nodes,l.matches,void 0,vG(t),n,!0);return u?{ok:!0,node:u.node,rect:u.rect,matches:l.matches.length}:{ok:!1,message:s.length>0?l.blockedByReactNativeOverlay?`Maestro selector matched ${s.length} element(s), but React Native overlay is covering app content: ${t}`:`Maestro selector matched ${s.length} element(s), but none were visible: ${t}`:`Maestro selector did not match: ${t}`}}function vU(e,t){let r=tm(e);if(!r.detected)return{matches:t,blockedByReactNativeOverlay:!1};let n=new Set([...r.dismissNodes,...r.minimizeNodes,...r.collapsedNodes].map(e=>e.index)),a=t.filter(e=>n.has(e.index));return{matches:a,blockedByReactNativeOverlay:t.length>0&&0===a.length}}function vV(e){return e?.platform==="android"?"android":"ios"}function vG(e){let t=t2(e).selectors.flatMap(e=>e.terms);if(0===t.length||!t.some(e=>"label"===e.key||"text"===e.key)||!t.every(e=>["label","text","id"].includes(e.key)))return null;let r=t.map(e=>"string"==typeof e.value?e.value:""),n=r[0];return n&&r.every(e=>e===n)?n:null}function vq(e,t,r){for(let n of t2(t).selectors){let t=e.nodes.filter(e=>(function(e,t,r){return!!t4(e,t,r)||t.terms.every(t=>(function(e,t,r){var n,a,i;return"string"!=typeof t.value||"id"!==(n=t.key)&&"label"!==n&&"text"!==n&&"value"!==n?t4(e,{raw:t.key,terms:[t]},r):vB((a=e,"id"===(i=t.key)?a.identifier:"label"===i?a.label:"value"===i?a.value:tX(a)),t.value)})(e,t,r))})(e,n,r));if(t.length>0)return t}return[]}function vB(e,t){let r=e??"";if(re(r)===re(t))return!0;try{return new RegExp(t).test(r)}catch{return!1}}function vj(e,t,r){if(t.rect&&t.rect.width>0&&t.rect.height>0)return{rect:t.rect,inherited:!1};if(t.rect)return null;let n=function(e,t,r){let n=t;for(;"number"==typeof n.parentIndex&&(n=r.get(n.parentIndex)??e[n.parentIndex]);)if(n.rect)return n.rect.width>0&&n.rect.height>0?n.rect:null;return null}(e,t,r);return n?{rect:n,inherited:!0}:null}function vH(e,t,r,n,a,i=!1,o=!1){var s,l,u,d,c,p,f,m,h,w,g,y,v,I,b,A,S,x,_;let N,M,k=vZ(e),D=(s=e,l=t,u=k,d=n,c=r,p=a,f=i,N=l.map(e=>{var t;let r;return(r=vj(s,t=e,u))?{node:t,rect:r.rect,inheritedRect:r.inherited}:null}).filter(e=>!!e),d&&void 0===c?(m=N,h=p,w=f,M=m.filter(e=>{var t,r;let n,a;return t=e.rect,r=h,n=r?.referenceWidth??1/0,a=r?.referenceHeight??1/0,t.x<n&&t.y<a&&t.x+t.width>0&&t.y+t.height>0}),w||M.length>0?M:m):N),P=function(e,t,r,n,a){var i,o;if(void 0!==r)return t[r]??null;let s=(i=t,o=n,i.sort((e,t)=>(function(e,t,r){var n,a;let i=function(e,t,r){if(r){let n=vX(e.node,r)-vX(t.node,r);if(0!==n)return n}let n=vz(e.node)-vz(t.node);if(0!==n)return n;let a=Number(e.inheritedRect)-Number(t.inheritedRect);if(0!==a)return a;let i=r&&vz(e.node)===vz(t.node)?vW(t.rect)-vW(e.rect):vW(e.rect)-vW(t.rect);return 0!==i?i:0}(e,t,r);if(0!==i)return i;if(n=e.rect,a=t.rect,Math.round(n.x)!==Math.round(a.x)||Math.round(n.y)!==Math.round(a.y)||Math.round(n.width)!==Math.round(a.width)||Math.round(n.height)!==Math.round(a.height))return e.node.index-t.node.index;let o=(t.node.depth??0)-(e.node.depth??0);return 0!==o?o:t.node.index-e.node.index})(e,t,o))[0]??null);return a&&n&&s?function(e,t,r){var n,a;let i,o,s;if(n=t,a=r,!(("other"===(i=t8(n.node.type??""))||"scrollview"===i||"scroll-area"===i)&&!(n.rect.width<120)&&!(n.rect.height<32)&&!(n.rect.height>80)&&1>=vX(n.node,a)))return null;let l=[];for(let n of e)n.parentIndex===t.node.index&&n.rect&&function(e,t,r){let n=t8(e.type??"");return!("button"!==n&&"cell"!==n&&"other"!==n||1>=vX(e,r))&&!(e.rect.width<16)&&!(e.rect.height<16)&&!!vJ(t,e.rect)&&function(e,t){let r=Math.max(e.y,t.y);return Math.max(0,Math.min(e.y+e.height,t.y+t.height)-r)/Math.max(1,Math.min(e.height,t.height))}(t,e.rect)>=.5}(n,t.rect,r)&&l.push(n);if(l.sort((e,t)=>e.rect.x-t.rect.x),0===l.length)return null;let u=(s=Math.floor((o=[...l.map(e=>e.rect.width)].sort((e,t)=>e-t)).length/2),o[s]??0),d=(function(e,t){let r=[],n=e.x,a=e.x+e.width;for(let i of t){let t=Math.max(e.x,i.x),o=Math.min(a,i.x+i.width);t>n&&r.push({x:n,width:t-n}),n=Math.max(n,o)}return a>n&&r.push({x:n,width:a-n}),r})(t.rect,l.map(e=>e.rect)).filter(e=>{var t,r;return t=e.width,r=u,!(t<24)&&!(r<24)&&t>=.4*r&&t<=1.6*r});if(1!==d.length)return null;let c=d[0];return c?{...t,rect:{x:c.x,y:t.rect.y,width:c.width,height:t.rect.height}}:null}(e,s,n)??s:s}(e,D,r,n,o);return g=e,y=P,v=k,I=o,b=a,y?I?(A=g,S=y,x=v,_=b,(vK(S.node)?null:vY(A,S.node,x,e=>{if(!vK(e))return null;let t=vj(A,e,x);return t&&function(e,t,r){if(!vJ(t,e))return!1;let n=vW(t),a=vW(e);if(a>0&&n>30*a)return!1;if(r){let e=r.referenceWidth*r.referenceHeight;if(e>0&&n>.5*e)return!1}return!0}(S.rect,t.rect,_)?{node:e,rect:t.rect}:null}))??{node:y.node,rect:y.rect}):{node:y.node,rect:y.rect}:null}function vW(e){return e.width*e.height}function vz(e){return v$.get(t8(e.type??""))??3}function vK(e){let t=t8(e.type??"");return!0===e.hittable||"button"===t||"link"===t||"cell"===t||"textfield"===t||"searchfield"===t||"switch"===t||"slider"===t}function vJ(e,t){return t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height}function vX(e,t){let r=[e.label,tX(e),e.identifier,e.value].filter(e=>!!e);return r.some(e=>e===t)?0:r.some(e=>re(e)===re(t))?1:r.some(e=>vB(e,t))?2:3}function vY(e,t,r,n){let a=t;for(;"number"==typeof a.parentIndex&&(a=r.get(a.parentIndex)??e[a.parentIndex]);){let e=n(a);if(e)return e}return null}function vZ(e){return new Map(e.map(e=>[e.index,e]))}async function vQ(e){let t,[r,n="5000"]=e.positionals;if(!r)return vE("INVALID_ARGS","assertVisible requires a selector.");let a=Number(n);if(!Number.isFinite(a)||a<0)return vE("INVALID_ARGS","assertVisible timeout must be a non-negative number.");let i=Date.now(),o=a+1e3;do{let n=await vC(e);if(t=n,n.ok){let a=vL(n.data);if(!a)return vE("COMMAND_FAILED","Unable to read snapshot data for assertVisible.");let o=vF(a,r,vV(e.baseReq.flags),fc(a));if(o.ok)return{ok:!0,data:{selector:r,matches:o.matches,nodeIndex:o.node.index,nodeType:o.node.type,nodeLabel:o.node.label,nodeIdentifier:o.node.identifier,rect:o.rect,waitedMs:Date.now()-i}};t=vE("COMMAND_FAILED",o.message,{selector:r})}if(Date.now()-i>=o)break;await e8(250)}while(Date.now()-i<=o);return t??vE("COMMAND_FAILED",`Expected visible but did not match: ${r}`,{selector:r,timeoutMs:a})}async function v0(e){let t,[r]=e.positionals;if(!r)return vE("INVALID_ARGS","assertNotVisible requires a selector.");let n=Date.now(),a=0;for(;Date.now()-n<=3e3;){let n=await e.invoke({...e.baseReq,command:"is",positionals:["visible",r],flags:{...e.baseReq.flags,noRecord:!0}});if(n.ok)a=0,t=n;else if(!function(e){let t=e.error.details;return t?.command==="is"&&("selector_not_found"===t.reason||"predicate_failed"===t.reason)}(n))return n;else if((a+=1)>=2)return{ok:!0,data:{pass:!0,selector:r,stableSamples:a,timeoutMs:3e3}};await e8(250)}return vE("COMMAND_FAILED",`Expected not visible but matched: ${r}`,{selector:r,timeoutMs:3e3,lastResponse:t})}async function v1(e){let t,r,n=Number(e.positionals[0]??15e3);if(!Number.isFinite(n)||n<0)return vE("INVALID_ARGS","waitForAnimationToEnd timeout must be a number.");let a=Date.now();for(;Date.now()-a<n;){let a=await vC(e),i=function(e,t,r){let n=function(e){if(!e.ok)return null;let t=vL(e.data);return t?JSON.stringify(t.nodes.map(e=>({index:e.index,parentIndex:e.parentIndex,type:e.type,identifier:e.identifier,label:e.label,value:e.value,rect:e.rect?{x:Math.round(e.rect.x),y:Math.round(e.rect.y),width:Math.round(e.rect.width),height:Math.round(e.rect.height)}:void 0}))):null}(e);return e.ok?n?t===n?{done:!0,response:{ok:!0,data:{stable:!0,timeoutMs:r}}}:{done:!1,signature:n}:{done:!0,response:e}:{done:!1}}(a,t,n);if(i.done)return i.response;t=i.signature??t,r=a,await e8(250)}return r?.ok===!1?r:{ok:!0,data:{stable:!1,timeoutMs:n}}}async function v2(e){let t=function(e){let[t,r]=e;return("visible"===t||"notVisible"===t)&&r?{ok:!0,mode:t,predicate:"visible"===t?"visible":"hidden",selector:r}:{ok:!1,response:vE("INVALID_ARGS","runFlow.when requires visible/notVisible and a selector.")}}(e.positionals);if(!t.ok)return t.response;let r=await v5(e,t);return r.ok?r.matched?await v4(e,t):{ok:!0,data:{skipped:!0,condition:t.mode,selector:t.selector}}:r.response}async function v3(e){let t,[r="1"]=e.positionals,n=Number(r);if(!Number.isInteger(n)||n<0)return vE("INVALID_ARGS","retry.maxRetries must be a non-negative integer.");let a=(e.batchSteps??[]).map(vT);for(let r=0;r<=n;r+=1){let n=await v8(e,a,r);if(n.ok)return{ok:!0,data:{attempts:r+1,retried:r>0}};t=n}return t??vE("COMMAND_FAILED","retry commands failed.")}async function v5(e,t){let r=await vC(e);if(!r.ok)return{ok:!1,response:r};let n=vL(r.data);if(!n)return{ok:!1,response:vE("COMMAND_FAILED","Unable to read snapshot data for runFlow.when.")};let a=vF(n,t.selector,vV(e.baseReq.flags),fc(n)).ok;return{ok:!0,matched:"visible"===t.mode?a:!a}}async function v4(e,t){let r=(e.batchSteps??[]).map(vT);for(let[t,n]of r.entries()){let r=await e.invokeReplayAction({action:n,line:e.line,step:e.step+t/1e3});if(!r.ok)return r}return{ok:!0,data:{ran:r.length,condition:t.mode,selector:t.selector}}}async function v8(e,t,r){for(let[n,a]of t.entries()){let t=await e.invokeReplayAction({action:a,line:e.line,step:e.step+r+n/1e3});if(!t.ok)return t}return{ok:!0,data:{ran:t.length}}}let v6=.35,v9=120,v7=360,Ie=8,It=120,Ir=70,In=168,Ia=48;function Ii(e,t){return Math.round(Math.min(v7,Math.max(v9,"number"==typeof e?e*v6:0,1.5*t)))}function Io(e,t,r){return Math.round(Math.min(r,Math.max(t,e)))}function Is(e){return{x:Il(e.x,e.width),y:Il(e.y,e.height)}}function Il(e,t){if(t<=1)return Math.floor(e);let r=Math.ceil(e),n=Math.floor(e+t-1);return Io(e+t/2,r,n)}async function Iu(e){var t,r,n;let[a,i="5000",o="down"]=e.positionals;if(!a)return vE("INVALID_ARGS","scrollUntilVisible requires a selector.");let s=Number(i);if(!Number.isFinite(s)||s<=0)return vE("INVALID_ARGS","scrollUntilVisible timeout must be a positive number.");let l=vG(a),u=Math.max(1,Math.ceil(s/500)),d=null;for(let t=0;t<u;t+=1){let r=await II(e,a,l,Math.min(500,Math.max(1,s-500*t)));if(r.ok)return r;if(d=r,t===u-1)break;let n=await e.invoke({...e.baseReq,command:"scroll",positionals:[o]});if(!n.ok)return n}return t=d,r=a,n=s,t?{ok:!1,error:{...t.error,message:`scrollUntilVisible timed out after ${n}ms for selector: ${r}. Last wait: ${t.error.message}`}}:vE("COMMAND_FAILED",`scrollUntilVisible timed out after ${n}ms for selector: ${r}`)}async function Id(e){let[t,r]=e.positionals,n=Number(t),a=Number(r);if(!Number.isFinite(n)||!Number.isFinite(a))return vE("INVALID_ARGS","tapOn percentage point requires numeric x/y values.");let i=await vC(e);if(!i.ok)return i;let o=vL(i.data);if(!o)return vE("COMMAND_FAILED","Unable to read snapshot data for Maestro percentage point tap.");let s=fc(o);return s?await e.invoke({...e.baseReq,command:"click",positionals:[String(Math.round(s.referenceWidth*n/100)),String(Math.round(s.referenceHeight*a/100))]}):vE("COMMAND_FAILED","Unable to resolve screen size for Maestro percentage point tap.")}async function Ic(e){let t=await Ih(e);return t.ok?await Im(e,t,t.durationMs):t.response}async function Ip(e){var t,r,n,a;let i,[o,s]=e.positionals;if(!o)return vE("INVALID_ARGS","tapOn requires a selector.");let l=function(e){if(!e)return{ok:!0,value:null};try{let t=JSON.parse(e);return{ok:!0,value:t}}catch{return{ok:!1,response:vE("INVALID_ARGS","tapOn runtime options must be valid JSON.")}}}(s);if(!l.ok)return l.response;let u=Date.now(),d=(t=e,t.baseReq.flags?.maestro?.optional===!0?3e3:3e4);for(;Date.now()-u<d;){let t=await Ib(e,o,l.value??{});if(!t.retry)return t.response;i=t.response,await e8(250)}return r=e,n=o,a=i,r.baseReq.flags?.maestro?.optional===!0?{ok:!0,data:{skipped:!0,optional:!0,selector:n}}:a??vE("COMMAND_FAILED",`tapOn timed out for selector: ${n}`)}async function If(e){let[t,r="up",n]=e.positionals;if(!t)return vE("INVALID_ARGS","swipe.label requires a label selector.");let a=await Ix(e,t,{},"swipe.label",{promoteTapTarget:!1});if(!a.ok)return a.response;let i=function(e,t){let r=Is(e.rect),n=e.frame,a=Ii(n?.referenceWidth,e.rect.width),i=Ii(n?.referenceHeight,e.rect.height),o=Ie,s=n?n.referenceWidth-o:r.x+a,l=n?n.referenceHeight-o:r.y+i;switch(t.toLowerCase()){case"up":return{ok:!0,start:r,end:{x:r.x,y:Io(r.y-i,o,l)}};case"down":return{ok:!0,start:r,end:{x:r.x,y:Io(r.y+i,o,l)}};case"left":return{ok:!0,start:r,end:{x:Io(r.x-a,o,s),y:r.y}};case"right":return{ok:!0,start:r,end:{x:Io(r.x+a,o,s),y:r.y}};default:return{ok:!1,message:"swipe.label direction must be up, down, left, or right."}}}(a.target,r);return i.ok?await Im(e,i,n):vE("INVALID_ARGS",i.message)}async function Im(e,t,r){return await e.invoke({...e.baseReq,command:"swipe",positionals:[String(t.start.x),String(t.start.y),String(t.end.x),String(t.end.y),...r?[r]:[]]})}async function Ih(e){var t;let r=((t=e.scope)?vR.get(t):void 0)??await Iw(e);if(!r)return{ok:!1,response:vE("COMMAND_FAILED","Unable to resolve screen size for Maestro swipe.")};let[n,...a]=e.positionals;return"direction"===n?function(e,t,r){let[n,a]=e;if(!n)return{ok:!1,response:vE("INVALID_ARGS","Maestro direction swipe requires a direction.")};switch(n){case"up":return{ok:!0,start:Iy(t,50,80,8),end:Iy(t,50,20,8),durationMs:a};case"down":return{ok:!0,start:Iy(t,50,20,8),end:Iy(t,50,80,8),durationMs:a};case"left":{let e=Ig(r,80,50,20,50);return{ok:!0,start:Iy(t,80,e,8),end:Iy(t,20,e,8),durationMs:a}}case"right":{let e=Ig(r,20,50,80,50);return{ok:!0,start:Iy(t,20,e,8),end:Iy(t,80,e,8),durationMs:a}}default:return{ok:!1,response:vE("INVALID_ARGS","Maestro swipe direction must be UP, DOWN, LEFT, or RIGHT.")}}}(a,r,vV(e.baseReq.flags)):"percent"===n?function(e,t,r){let[n,a,i,o,s]=e,l=[n,a,i,o].map(Number);if(l.some(e=>!Number.isFinite(e)))return{ok:!1,response:vE("INVALID_ARGS","Maestro percentage swipe requires numeric points.")};let[u,d,c,p]=l,f=Ig(r,u,d,c,p);return{ok:!0,start:Iy(t,u,f,1),end:Iy(t,c,f,1),durationMs:s}}(a,r,vV(e.baseReq.flags)):{ok:!1,response:vE("INVALID_ARGS","Maestro screen swipe requires direction or percent.")}}async function Iw(e){let t=await vC(e);if(t.ok)return fc(vL(t.data))}function Ig(e,t,r,n,a){return"android"!==e||r!==a||50!==r||50>Math.abs(n-t)?a:65}function Iy(e,t,r,n){return{x:Iv(Math.round(e.referenceWidth*t/100),n,e.referenceWidth),y:Iv(Math.round(e.referenceHeight*r/100),n,e.referenceHeight)}}function Iv(e,t,r){return Math.min(Math.max(t,r-t),Math.max(t,e))}async function II(e,t,r,n){let a=await e.invoke({...e.baseReq,command:"wait",positionals:[t,String(n)]});return a.ok||!r?a:await e.invoke({...e.baseReq,command:"find",positionals:[r,"wait",String(n)]})}async function Ib(e,t,r){let n=vG(t),a=await IA(e,t,r);return a.response.ok?{retry:!1,response:a.response}:a.targetResolved&&n?await IS(e,n):{retry:!0,response:a.response}}async function IA(e,t,r){var n,a;let i=await Ix(e,t,r,"tapOn",{promoteTapTarget:!0});if(!i.ok)return{response:i.response,targetResolved:!1};let o=(n=i.target,a=null!==vG(t),!function(e,t,r){if(!t||r.width<It)return!1;let n=t8(e.type??"");return!(r.height<Ir)&&("cell"===n||"other"===n||"scrollview"===n||"scroll-area"===n)}(n.node,a,n.rect)?Is(n.rect):{x:Il(n.rect.x,Math.min(n.rect.width,In)),y:Il(n.rect.y,Math.min(n.rect.height,Ia))});return{response:await e.invoke({...e.baseReq,command:"click",positionals:[String(o.x),String(o.y)]}),targetResolved:!0}}async function IS(e,t){let r=await e.invoke({...e.baseReq,command:"find",positionals:[t,"click"],flags:{...e.baseReq.flags,findFirst:!0}});return r.ok?{retry:!1,response:r}:{retry:!0,response:r}}async function Ix(e,t,r,n,a){let i=await vC(e);if(!i.ok)return{ok:!1,response:i};let o=vL(i.data);if(!o)return{ok:!1,response:vE("COMMAND_FAILED",`Unable to read snapshot data for ${n}.`)};let s=fc(o),l=function(e,t,r,n,a,i={}){let o=vq(e,t,n);if(r.childOf){let t=vq(e,r.childOf,n);if(0===t.length)return{ok:!1,message:`Maestro childOf parent did not match: ${r.childOf}`};let a=vZ(e.nodes);o=o.filter(r=>t.some(t=>{var n,i,o;return n=e.nodes,i=r,o=t,!!vY(n,i,a,e=>e===o||e.index===o.index?e:null)}))}let s=vU(e.nodes,o),l=vH(e.nodes,s.matches,r.index,vG(t),a,!1,i.promoteTapTarget);if(!l){let e=r.index??0;return{ok:!1,message:s.blockedByReactNativeOverlay?`Maestro selector matched ${o.length} element(s), but React Native overlay is covering app content: ${t}`:`Maestro selector did not match index ${e}: ${t}`}}return{ok:!0,node:l.node,rect:l.rect}}(o,t,r,vV(e.baseReq.flags),s,a);if(!l.ok){let e=vG(t);if(e){let t=function(e,t,r,n={}){let a=function(e,t){let r=re(t);if(!r)return[];let n=[],a=[];for(let t of e.nodes){let e=[t.label,tX(t),t.identifier,t.value].filter(e=>!!e).map(e=>re(e));e.some(e=>e===r)?n.push(t):e.some(e=>e.includes(r))&&a.push(t)}return n.length>0?n:a}(e,t),i=vH(e.nodes,a,void 0,t,r,!1,n.promoteTapTarget);return i?{ok:!0,node:i.node,rect:i.rect}:{ok:!1,message:`Maestro fuzzy text did not match: ${t}`}}(o,e,s,a);if(t.ok)return{ok:!0,target:{node:t.node,rect:t.rect,frame:s}}}}return l.ok?{ok:!0,target:{node:l.node,rect:l.rect,frame:s}}:{ok:!1,response:vE("ELEMENT_NOT_FOUND",l.message,{selector:t,options:r,command:n})}}async function I_(e){switch(e.command){case y5:return await vQ(e);case y4:return await v0(e);case y2:return await v3(e);case y8:return await IN(e);case y6:return await v1(e);case y9:return await Iu(e);case y7:return await Ic(e);case ve:return await If(e);case vt:return await Ip(e);case vr:return await Id(e);case y1:return await v2(e);case y3:return function(e){let[t]=e.positionals;if(!t)return vE("INVALID_ARGS","runScript requires a file path.");try{let r=function(e){let{scriptPath:t,env:r}=e,n=l.readFileSync(t,"utf8"),a=Object.create(null);try{var i,o;_.runInNewContext(n,(i=r,o=a,{...i,output:o,json:vy,http:{post:(e,t)=>(function(e,t,r){let n=E(process.execPath,["-e",vg],{stdin:JSON.stringify({method:e,url:t,headers:r?.headers??{},body:r?.body??""}),timeoutMs:3e4,allowFailure:!0});if(0!==n.exitCode){let r;throw new D("COMMAND_FAILED",`Maestro runScript http.${e.toLowerCase()} failed for ${t}: ${(r=n.stderr.trim()).length>0?r.slice(0,1e3):"request process exited without stderr"}`,{exitCode:n.exitCode,stderr:n.stderr})}try{return JSON.parse(n.stdout)}catch(r){throw new D("COMMAND_FAILED",`Maestro runScript http.${e.toLowerCase()} returned invalid JSON for ${t}`,{stdout:n.stdout.slice(0,1e3),stderr:n.stderr.slice(0,1e3)},r instanceof Error?r:void 0)}})("POST",e,t)}}),{filename:t,timeout:3e4})}catch(e){throw new D("COMMAND_FAILED",`Maestro runScript failed for ${t}: ${e instanceof Error?e.message:String(e)}`,{scriptPath:t},e instanceof Error?e:void 0)}return function(e,t){for(let r of Object.keys(e))if(r.includes("."))throw new D("INVALID_ARGS",`Maestro runScript output key cannot contain ".": ${r}`,{scriptPath:t,key:r})}(a,t),Object.fromEntries(Object.entries(a).map(([e,t])=>{var r;return[`output.${e}`,(r=t,"string"==typeof r?r:"number"==typeof r||"boolean"==typeof r?String(r):JSON.stringify(r))]}))}({scriptPath:t,env:{...e.scope.values,...e.baseReq.flags?.maestro?.runScriptEnv??{}}});return{ok:!0,data:{outputEnv:r}}}catch(t){let e=M(t);return vE(e.code,e.message,e.details)}}(e);default:return}}async function IN(e){let t=await e.invoke({...e.baseReq,command:"keyboard",positionals:["enter"]});return t.ok?t:await e.invoke({...e.baseReq,command:"type",positionals:["\n"]})}async function IM(e){var t;let{req:r,sessionName:n,action:a,scope:i,filePath:o,line:s,step:l,tracePath:u,invoke:d}=e,c=(t={file:o,line:s},{...a,positionals:(a.positionals??[]).map(e=>yb(e,i,t)),flags:yA(a.flags,i,t)??{},runtime:yA(a.runtime,i,t)}),p=Date.now();ID(u,{type:"replay_action_start",ts:new Date(p).toISOString(),replayPath:o,line:s,step:l,command:c.command,positionals:c.positionals??[]});let f=await Ik({req:r,sessionName:n,resolved:c,scope:i,line:s,step:l,invoke:d,invokeReplayAction:e=>IM({req:r,sessionName:n,action:e.action,scope:i,filePath:o,line:e.line,step:e.step,tracePath:u,invoke:d})}),m=Date.now();return ID(u,{type:"replay_action_stop",ts:new Date(m).toISOString(),replayPath:o,line:s,step:l,command:c.command,ok:f.ok,durationMs:m-p,errorCode:f.ok?void 0:f.error.code}),f}async function Ik(e){var t;let{req:r,sessionName:n,resolved:a,scope:i,line:o,step:s,invoke:l,invokeReplayAction:u}=e,d=(t=r.flags,rn(t,{...a.flags??{}})),c={token:r.token,session:n,flags:d,runtime:a.runtime,meta:r.meta},p=await I_({command:a.command,baseReq:c,positionals:a.positionals??[],batchSteps:a.flags?.batchSteps,scope:i,line:o,step:s,invoke:l,invokeReplayAction:u})??await l({...c,command:a.command,positionals:a.positionals??[]});if(p.ok){let e=function(e){if(!e||"object"!=typeof e)return null;let t=e.outputEnv;if(!t||"object"!=typeof t||Array.isArray(t))return null;let r=Object.entries(t).filter(e=>"string"==typeof e[1]);return r.length>0?Object.fromEntries(r):null}(p.data);e&&Object.assign(i.values,e)}return p}function ID(e,t){e&&l.appendFileSync(e,`${JSON.stringify(t)}
89
+ `)}async function IP(e){let{req:t,sessionName:r,logPath:n,sessionStore:a,invoke:i}=e,o=t.positionals?.[0];if(!o)return cM("INVALID_ARGS","replay requires a path");let s="",u=new Set;try{var d,c;s=aq.expandHome(o,t.meta?.cwd);let e=l.readFileSync(s,"utf8"),p=e.trimStart()[0];if("{"===p||"["===p)return cM("INVALID_ARGS","replay accepts .ad script files. JSON replay payloads are no longer supported.");let m=function(e,t,r={}){var n;let a=function(e){let t=e?.replayBackend;if("string"!=typeof t)return;let r=vM[t];if(!r)throw new D("INVALID_ARGS",`Unsupported replay backend "${t}".`);return r}(t);return a?{...a.parse(e,{...r,platform:t?.platform,env:(n=t,{...yg(yI(n?.replayShellEnv)),...yy(yv(n?.replayEnv))})}),updateUnsupportedMessage:"replay -u is not supported for compat flow input. Convert to .ad first, then update that replay file."}:{...function(e){let t=[],r=[],n=e.split(/\r?\n/),a=!1;for(let[e,i]of n.entries()){let n=i.trim();if(0===n.length||n.startsWith("#"))continue;if(yN(n)){if(a)throw new D("INVALID_ARGS",`env directives must precede all actions (line ${e+1}).`);continue}let o=function(e){let t=e.trim();if(0===t.length||t.startsWith("#"))return null;let[r,...n]=function(e){let t=[],r=0;for(;r<e.length&&!((r=function(e,t){let r=t;for(;r<e.length&&/\s/.test(e.charAt(r));)r+=1;return r}(e,r))>=e.length);){let n='"'===e[r]?function(e,t){let r=!1,n=t+1;for(;n<e.length;n+=1){let t=e.charAt(n);if('"'===t&&!r)break;if(r){r=!1;continue}r="\\"===t}if(n>=e.length)throw new D("INVALID_ARGS",`Invalid replay script line: ${e}`);return{value:JSON.parse(e.slice(t,n+1)),nextCursor:n+1}}(e,r):function(e,t){let r=t;for(;r<e.length&&!/\s/.test(e.charAt(r));)r+=1;return{value:e.slice(t,r),nextCursor:r}}(e,r);t.push(n.value),r=n.nextCursor}return t}(t);if(void 0===r||"context"===r)return null;let a={ts:Date.now(),command:r,positionals:[],flags:{}};if("snapshot"===r){a.positionals=[];for(let e=0;e<n.length;e+=1){let t=n[e];if("-i"===t){a.flags.snapshotInteractiveOnly=!0;continue}if("-c"===t){a.flags.snapshotCompact=!0;continue}if("--raw"===t){a.flags.snapshotRaw=!0;continue}if("--force-full"===t){a.flags.snapshotForceFull=!0;continue}if(("-d"===t||"--depth"===t)&&e+1<n.length){let t=Number(n[e+1]);Number.isFinite(t)&&t>=0&&(a.flags.snapshotDepth=Math.floor(t)),e+=1;continue}if(("-s"===t||"--scope"===t)&&e+1<n.length){a.flags.snapshotScope=n[e+1],e+=1;continue}if("--backend"===t&&e+1<n.length){e+=1;continue}}return a}if("open"===r){let e=function(e){var t;let r=[],n={};for(let t of e){if("--relaunch"===t){n.relaunch=!0;continue}r.push(t)}let a=aT(r);return{positionals:a.positionals,flags:n,runtime:(t=a.flags).platform||t.metroHost||void 0!==t.metroPort||t.bundleUrl||t.launchUrl?a.flags:void 0}}(n);return a.positionals=e.positionals,Object.assign(a.flags,e.flags),a.runtime=e.runtime,a}if("runtime"===r){let e=aT(n);return a.positionals=e.positionals,Object.assign(a.flags,e.flags),a}if(a_(r)){let e=aL(r,n);Object.assign(a.flags,e.flags);let t=e.positionals[0];if(void 0===t)return a;if(t.startsWith("@"))return a.positionals=[t],e.positionals[1]&&(a.result={refLabel:e.positionals[1]}),a;let i=e.positionals[0],o=e.positionals[1];return yk(i)&&yk(o)&&e.positionals.length>=2?a.positionals=[i,o]:a.positionals=[e.positionals.join(" ")],a}if("fill"===r){let e=aL(r,n);if(Object.assign(a.flags,e.flags),!(e.positionals.length>=2))return a.positionals=e.positionals,a;let[t,i,...o]=e.positionals;return t.startsWith("@")?(o.length>0?(a.positionals=[t,o.join(" ")],a.result={refLabel:i}):a.positionals=[t,i],a):(a.positionals=[t,[i,...o].join(" ")],a)}if("get"===r){let e=n[0],t=n[1];return void 0===e||void 0===t?a.positionals=n:t.startsWith("@")?(a.positionals=[e,t],n[2]&&(a.result={refLabel:n[2]})):a.positionals=[e,n.slice(1).join(" ")],a}if("swipe"===r||"type"===r){let e=aL(r,n);return Object.assign(a.flags,e.flags),a.positionals=e.positionals,a}if("record"===r){let e=[];for(let t=0;t<n.length;t+=1){let r=n[t];if("--hide-touches"===r){a.flags.hideTouches=!0;continue}if("--fps"===r&&t+1<n.length){let e=Number(n[t+1]);Number.isFinite(e)&&(a.flags.fps=Math.floor(e)),t+=1;continue}if("--quality"===r&&t+1<n.length){let e=Number(n[t+1]);Number.isFinite(e)&&(a.flags.quality=Math.floor(e)),t+=1;continue}e.push(r)}return a.positionals=e,a}if("screenshot"===r){let e=[];for(let t=0;t<n.length;t+=1){let r=n[t],i=eK({args:n,index:t,flags:a.flags});if(i.handled){t=i.nextIndex;continue}e.push(r)}return a.positionals=e,a}return a.positionals=n,a}(i);o&&(t.push(o),r.push(e+1),a=!0)}return{actions:t,actionLines:r}}(e),metadata:y_(e)}}(e,t.flags,{sourcePath:s}),h=m.metadata,w=h.platform||h.target?{...t,flags:(d=t.flags,c=h,{...d??{},...void 0!==c.platform&&d?.platform===void 0?{platform:c.platform}:{},...void 0!==c.target&&d?.target===void 0?{target:c.target}:{}})}:t,g=m.actions,y=m.actionLines;if(t.flags?.replayUpdate===!0&&m.updateUnsupportedMessage)return cM("INVALID_ARGS",m.updateUnsupportedMessage);if(t.flags?.replayUpdate===!0&&h.env&&Object.keys(h.env).length>0)return cM("INVALID_ARGS","replay -u does not yet preserve env directives. Temporarily remove the env lines, run replay -u, then restore them.");if(t.flags?.replayUpdate===!0&&function(e){for(let t of e){for(let e of t.positionals??[])if("string"==typeof e&&e.includes("${"))return!0;if(IE(t.flags)||IE(t.runtime))return!0}return!1}(g))return cM("INVALID_ARGS","replay -u does not yet preserve ${VAR} substitutions. Resolve or inline the variables before running with -u.");let v=function(e){let t={};if(e.builtins)for(let[r,n]of Object.entries(e.builtins))t[r]=n;for(let r of[e.fileEnv,e.shellEnv,e.cliEnv])if(r)for(let[e,n]of Object.entries(r)){if(yh(e))throw yw(e);t[e]=n}return{values:t}}({builtins:function(e){let{req:t,sessionName:r,metadata:n,resolvedPath:a}=e,i=t.flags??{},o=t.meta?.cwd??process.cwd(),s={AD_SESSION:r,AD_FILENAME:f.relative(o,a)||a},l=i.platform??n.platform;l&&(s.AD_PLATFORM=l);let u=i.target??n.target;u&&(s.AD_TARGET=u);let d=i.device;"string"==typeof d&&d.length>0&&(s.AD_DEVICE=d);let c=i.artifactsDir;return"string"==typeof c&&c.length>0&&(s.AD_ARTIFACTS=c),s}({req:w,sessionName:r,metadata:h,resolvedPath:s}),fileEnv:h.env,shellEnv:yg(yI(t.flags?.replayShellEnv)),cliEnv:yy(yv(t.flags?.replayEnv))}),I=t.flags?.replayUpdate===!0,b=0;for(let e=0;e<g.length;e+=1){let t=g[e];if(!t||"replay"===t.command)continue;let o=await IM({req:w,sessionName:r,action:t,scope:v,filePath:s,line:y[e]??0,step:e+1,tracePath:a.get(r)?.trace?.outPath,invoke:i});if(o.ok){IR(o).forEach(e=>u.add(e));continue}if(!I)return IO(o,t,e,s,[...u]);let l=await vD({action:t,sessionName:r,logPath:n,sessionStore:a});if(!l)return IO(o,t,e,s,[...u]);if(g[e]=l,!(o=await IM({req:w,sessionName:r,action:l,scope:v,filePath:s,line:y[e]??0,step:e+1,tracePath:a.get(r)?.trace?.outPath,invoke:i})).ok)return IO(o,l,e,s,[...u]);IR(o).forEach(e=>u.add(e)),b+=1}return I&&b>0&&function(e,t,r){let n=[];if(r){let e=r.device.kind?` kind=${r.device.kind}`:"",t=r.device.target?` target=${r.device.target}`:"";n.push(`context platform=${r.device.platform}${t} device=${aD(r.device.name)}${e} theme=unknown`)}for(let e of t){var a;n.push((a=e,aF(a,{runtimeIncludeAllPositionals:!0})))}let i=`${n.join("\n")}
90
+ `,o=`${e}.tmp-${process.pid}-${Date.now()}`;l.writeFileSync(o,i),l.renameSync(o,e)}(s,g,a.get(r)),{ok:!0,data:{replayed:g.length,healed:b,session:r,artifactPaths:[...u]}}}catch(t){let e=M(t);return cM(e.code,e.message,u.size>0?{artifactPaths:[...u]}:void 0)}}function IO(e,t,r,n,a=[]){let i;if(e.ok)return e;let o=r+1;return{ok:!1,error:{code:e.error.code,message:`Replay failed at step ${o} (${i=(t.positionals??[]).map(e=>ak(e)),[t.command,...i].join(" ")}): ${e.error.message}`,hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath,details:{...e.error.details??{},replayPath:n,step:o,action:t.command,positionals:t.positionals??[],artifactPaths:a}}}}function IR(e){if(!e.ok||!e.data)return[];let t=[];if("string"==typeof e.data.path&&t.push(e.data.path),"string"==typeof e.data.outPath&&t.push(e.data.outPath),Array.isArray(e.data.artifacts))for(let r of e.data.artifacts){if(!r||"object"!=typeof r)continue;let e="string"==typeof r.localPath?r.localPath:void 0,n="string"==typeof r.path?r.path:void 0;e?t.push(e):n&&t.push(n)}return[...new Set(t.filter(e=>(function(e){try{return l.statSync(e).isFile()}catch{return!1}})(e)))]}function IE(e){return"string"==typeof e?e.includes("${"):Array.isArray(e)?e.some(IE):!!e&&"object"==typeof e&&Object.values(e).some(IE)}async function IC(e){let{req:t,sessionName:r,logPath:n,sessionStore:a,invoke:i}=e;return"replay"===t.command?await IP({req:t,sessionName:r,logPath:n,sessionStore:a,invoke:i}):"test"===t.command?await yL({req:t,sessionName:r,runReplay:async({filePath:e,sessionName:r,platform:o,target:s,requestId:l,artifactsDir:u,artifactPaths:d})=>{let c=function(e){let{parentFlags:t,platform:r,target:n,artifactsDir:a}=e;return void 0===r&&void 0===n&&void 0===a?t:{...t??{},...void 0!==r?{platform:r}:{},...void 0!==n?{target:n}:{},...void 0!==a?{artifactsDir:a}:{}}}({parentFlags:t.flags,platform:o,target:s,artifactsDir:u});return await IP({req:{...t,command:"replay",session:r,positionals:[e],flags:c,meta:l?{...t.meta??{},requestId:l}:t.meta},sessionName:r,logPath:n,sessionStore:a,invoke:async e=>{var t;return t=await i(e),d&&IR(t).forEach(e=>d.add(e)),t}})},cleanupSession:async e=>{a.get(e)&&await gs({req:{token:t.token,session:e,command:"close",positionals:[],flags:{},meta:t.meta},sessionName:e,logPath:n,sessionStore:a})}}):null}let IL=ek.inventory,IT=ek.state,I$=ek.observability,IF=ek.replay;async function IU(e){let{req:t,sessionName:r,logPath:n,sessionStore:a,command:i,positionals:o,recordPositionals:s,deriveNextSession:l}=e,u=a.get(r),d=t.flags??{},c=ck(i,u,d);if(c)return c;let p=await cR({session:u,flags:d,ensureReady:!0});if(!cY(i,p))return cM("UNSUPPORTED_OPERATION",`${i} is not supported on this device`);let f=await ch(p,i,o,t.flags?.out,{...c5(n,t.flags,u?.appBundleId,u?.trace?.outPath)});if(u){let e=l?await l(u,f,p):u;a.recordAction(e,{command:i,positionals:s??o,flags:t.flags??{},result:f??{}}),e!==u&&a.set(r,e)}return{ok:!0,data:f??{}}}async function IV(e){let{req:t,sessionName:r,logPath:n,sessionStore:a}=e,i=a.get(r),o=t.flags??{},s=ck(eD.clipboard,i,o);if(s)return s;let l=(t.positionals?.[0]??"").toLowerCase();if("read"!==l&&"write"!==l)return cM("INVALID_ARGS","clipboard requires a subcommand: read or write");let u=await cR({session:i,flags:o,ensureReady:!0});if(!cY(eD.clipboard,u))return cM("UNSUPPORTED_OPERATION","clipboard is not supported on this device");let d=await ch(u,eD.clipboard,t.positionals??[],t.flags?.out,{...c5(n,t.flags,i?.appBundleId,i?.trace?.outPath)});return i&&a.recordAction(i,{command:t.command,positionals:t.positionals??[],flags:t.flags??{},result:d??{}}),{ok:!0,data:{platform:u.platform,...d??{}}}}async function IG(e){let{req:t,sessionName:r,logPath:n,sessionStore:a,invoke:i,invokeReplayAction:o,androidAdbExecutor:s}=e;if(IL.has(t.command))return await gf({req:t,sessionName:r,sessionStore:a});if("runtime"===t.command)return await wO({req:t,sessionName:r,sessionStore:a});if(IT.has(t.command))return await gy({req:t,sessionName:r,sessionStore:a});if(t.command===eD.clipboard)return await IV({req:t,sessionName:r,logPath:n,sessionStore:a});if(t.command===eD.keyboard){let e=a.get(r),i=t.positionals?.[0]?.trim().toLowerCase();return e||"dismiss"!==i&&"enter"!==i&&"return"!==i||"ios"!==(t.flags??{}).platform?await IU({req:t,sessionName:r,logPath:n,sessionStore:a,command:eD.keyboard,positionals:t.positionals??[]}):cM("SESSION_NOT_FOUND","iOS keyboard action requires an active session so the target app stays foregrounded. Run open first.")}if(I$.has(t.command))return await ya({req:t,sessionName:r,sessionStore:a,androidAdbExecutor:s});if(t.command===eD.install||t.command===eD.reinstall)return await gc({req:t,command:t.command,sessionName:r,sessionStore:a,deployOps:t.command===eD.install?gd:gu});if(t.command===eq.installSource)return await wt({req:t,sessionName:r,sessionStore:a});if(t.command===eq.releaseMaterializedPaths)return await wr({req:t});if(t.command===eD.push){let e,i=t.positionals?.[0]?.trim(),o=t.positionals?.[1]?.trim();return i&&o?await IU({req:t,sessionName:r,logPath:n,sessionStore:a,command:eD.push,positionals:[i,"file"===(e=cp(o,{subject:"Push payload",cwd:t.meta?.cwd,expandPath:(e,t)=>aq.expandHome(e,t)})).kind?e.path:e.text],recordPositionals:[i,o]}):cM("INVALID_ARGS","push requires <bundle|package> <payload.json|inline-json>")}return t.command===eD.triggerAppEvent?await IU({req:t,sessionName:r,logPath:n,sessionStore:a,command:eD.triggerAppEvent,positionals:t.positionals??[],deriveNextSession:async(e,t)=>{let r="string"==typeof t?.eventUrl?t.eventUrl:void 0,n=r?await w2(e.device,r,e.appBundleId,w0)??e.appBundleId:e.appBundleId;return{...e,appBundleId:n}}}):t.command===eD.open?await gr({req:t,sessionName:r,logPath:n,sessionStore:a}):IF.has(t.command)?await IC({req:t,sessionName:r,logPath:n,sessionStore:a,invoke:o??i}):t.command===eD.batch?await gp(t,r,i):t.command===eD.close?await gs({req:t,sessionName:r,logPath:n,sessionStore:a}):null}let Iq=new Set(["com.android.permissioncontroller","com.google.android.permissioncontroller","com.google.android.packageinstaller","com.android.packageinstaller"]),IB=new Set(["android","com.android.systemui"]),Ij=/^android:id\/(?:alertTitle|message|button[123]|parentPanel|buttonPanel|contentPanel)$/i,IH=/^android:id\/button[123]$/i,IW=/(?:^|:)id\/permission_/i,Iz=/\b(?:is(?:n't| not) responding|keeps stopping|has stopped|close app|app info)\b/i,IK=/^(?:ok|allow|allow all|while using the app|only this time|yes|continue|save|confirm|turn on|open settings)$/i,IJ=/^(?:cancel|deny|don.t allow|don’t allow|not now|no|dismiss|close|close app|later|skip)$/i;function IX(e,t){let r=t[0];if(!r)return;let n=IY(e,r.index);for(let r of t.slice(1)){let t=new Set(IY(e,r.index));for(let e=n.length-1;e>=0;e-=1)t.has(n[e])||n.splice(e,1)}return n[n.length-1]}function IY(e,t){let r=new Map(e.map(e=>[e.index,e])),n=[],a=r.get(t);for(;a;)n.push(a.index),a=void 0===a.parentIndex?void 0:r.get(a.parentIndex);return n.reverse()}function IZ(e,t){let r=new Map;for(let t of e){if(void 0===t.parentIndex)continue;let e=r.get(t.parentIndex)??[];e.push(t),r.set(t.parentIndex,e)}let n=new Set([t]),a=[t];for(let e of a)for(let t of r.get(e)??[])n.has(t.index)||(n.add(t.index),a.push(t.index));return e.filter(e=>n.has(e.index))}function IQ(e){let t=e.type??"",r=e.identifier??"";return!!(e.hittable||/\bbutton\b/i.test(t)||IH.test(r)||/(?:^|:)id\/permission_(?:allow|deny)/i.test(r))}function I0(e){if(!e)return"";let t=[e.label,e.value].filter(e=>"string"==typeof e&&e.trim().length>0);return t[0]?.trim()??""}async function I1(e,t,r={}){if("wait"===t)return await I2(e,r.timeoutMs??1e4);if("get"===t){var n;let t=await I4(e);return{kind:"alertStatus",platform:"android",action:"get",alert:n=t?.alert??null,...n?eJ("Alert visible"):eJ("No alert visible")}}return await I3(e,t)}async function I2(e,t){let r=Date.now(),n=await I5(e,t);if(!n)throw new D("COMMAND_FAILED","alert wait timed out");return{kind:"alertWait",platform:"android",action:"wait",alert:n.alert,waitedMs:Date.now()-r,...eJ("Alert visible")}}async function I3(e,t){var r;let n,a,i=await I5(e,2e3);if(!i)throw new D("COMMAND_FAILED","alert not found",{hint:"If a sheet is visible in snapshot but alert reports no alert, it is likely app-owned UI. Use snapshot -i and press the visible label/ref."});let o=(r=i.buttons,n="accept"===t?"accept":"dismiss",(a=r.find(e=>e.role===n))||("dismiss"===t?r.find(e=>"neutral"===e.role)??null:1===r.length?r[0]??null:null));if(o)return await sC(e,o.x,o.y),I8(t,i.alert,o.label);if("dismiss"===t)return await sT(e),I8(t,i.alert,"Back");throw new D("COMMAND_FAILED","alert accept found an alert but no accept button",{alert:i.alert,hint:"Inspect alert get --json for visible buttons, then use press by visible label/ref if needed."})}async function I5(e,t){let r=Date.now();for(;Date.now()-r<t;){let t=await I4(e);if(t)return t;await e8(300)}return null}async function I4(e){return function(e){var t,r,n,a;let i,o=function(e){let t=e.filter(e=>{var t;let r;return r=(t=e).bundleId??"",Iq.has(r)||IW.test(t.identifier??"")});if(t.length)return{nodes:t,source:"permission"};let r=function(e){let t=e.filter(e=>{var t;let r;return r=(t=e).bundleId??"",IB.has(r)&&Iz.test(I0(t))});if(0===t.length)return[];let r=IX(e,t);return void 0===r?t:IZ(e,r).filter(e=>e.bundleId&&IB.has(e.bundleId))}(e);return r.length?{nodes:r,source:"system-dialog"}:{nodes:function(e){var t;let r,n,a=e.filter(e=>{var t;return t=e.type??"",/(?:^|[.$])[^.]*Dialog$/i.test(t)}),i=e.filter(e=>Ij.test(e.identifier??"")),o=a.length?[...a,...i]:(r=(t=i).some(e=>IH.test(e.identifier??"")),n=t.some(e=>!IH.test(e.identifier??"")),r&&n?t:[]);if(0===o.length)return[];let s=IX(e,o);return void 0===s?o:IZ(e,s)}(e),source:"native-dialog"}}(e),s=o.nodes;if(0===s.length)return null;let l=function(e){let t=new Set,r=[];for(let n of e){let e=I0(n);if(!e||!n.rect||!IQ(n))continue;let a=e.trim().toLowerCase();if(!a||t.has(a))continue;t.add(a);let i=tH(n.rect);r.push({label:e,x:i.x,y:i.y,role:function(e,t){var r;let n=(r=e.identifier??"",/(?:^|:)id\/button1$/i.test(r)?"accept":/(?:^|:)id\/button2$/i.test(r)?"dismiss":/(?:^|:)id\/button3$/i.test(r)?"neutral":/(?:^|:)id\/permission_allow/i.test(r)?"accept":/(?:^|:)id\/permission_deny/i.test(r)?"dismiss":null);return n||(IK.test(t.trim())?"accept":IJ.test(t.trim())?"dismiss":"neutral")}(n,e)})}return r}(s),u=s.filter(e=>I0(e)&&!IQ(e)),d=I0((t=u).find(e=>/(?:^|:)id\/(?:alertTitle|permission_message)$/i.test(e.identifier??"")))||I0(t[0]),c=(r=u,n=d,(i=r.map(e=>I0(e)).filter(e=>e&&e!==n)).length?[...new Set(i)].join("\n"):void 0),p=(a=s,a.find(e=>e.bundleId)?.bundleId);return{alert:{...d?{title:d}:{},...c?{message:c}:{},buttons:l.map(e=>e.label),platform:"android",source:o.source,...p?{packageName:p}:{}},buttons:l}}((await e_("snapshot_capture",async()=>await sd(e,{helperWaitForIdleTimeoutMs:0,includeHiddenContentHints:!1}),{backend:"android",purpose:"alert"})).nodes)}function I8(e,t,r){return{kind:"alertHandled",platform:"android",action:e,handled:!0,alert:t,button:r,...eJ(`Alert ${e}ed`)}}async function I6(e){var t;let{req:r,logPath:n,session:a,device:i}=e,o="accept"===(t=r.positionals?.[0])||"dismiss"===t||"wait"===t?t:"get",s=a?"frontmost-app"===a.surface?{surface:"frontmost-app"}:{bundleId:a.appBundleId,surface:a.surface}:{};if(!cY("alert",i))return cM("UNSUPPORTED_OPERATION","alert is not supported on this device");if("android"===i.platform){let t=eE(r.positionals?.[1])??1e4;return bt(e,await I1(i,o,{timeoutMs:t}))}if("macos"===i.platform){let t=async e=>await l6(e,s);return await I9(e,o,t)}let l={verbose:r.flags?.verbose,logPath:n,traceLogPath:a?.trace?.outPath,requestId:r.meta?.requestId},u=async e=>await am(i,{command:"alert",action:e,appBundleId:a?.appBundleId},l);return await I9(e,o,u)}async function I9(e,t,r){if("wait"===t)return await I7(e,r);let n="accept"===t||"dismiss"===t?t:"get";return"accept"===n||"dismiss"===n?await be(e,n,r):bt(e,await r("get"))}async function I7(e,t){let r=eE(e.req.positionals?.[1])??1e4,n=Date.now();for(;Date.now()-n<r;){try{return bt(e,await t("get"))}catch{}await e8(300)}return cM("COMMAND_FAILED","alert wait timed out")}async function be(e,t,r){var n,a;let i,o,s=Date.now();for(;Date.now()-s<2e3;){try{return bt(e,await r(t))}catch(t){o=t;let e=String(t?.message??"").toLowerCase();if(!e.includes("alert not found")&&!e.includes("no alert"))break}await e8(300)}throw(n=o)instanceof D&&(a=n,(i=String(a?.message??"").toLowerCase()).includes("alert not found")||i.includes("no alert"))?new D(n.code,n.message,{...n.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."}):n}function bt(e,t){return f$(e.sessionStore,e.session,e.req,t),{ok:!0,data:t}}async function br(e){let{req:t,logPath:r,sessionStore:n,session:a,device:i,parsed:o}=e,{setting:s,state:l,permissionTarget:u,latitude:d,longitude:c}=o;if(!cY("settings",i))return cM("UNSUPPORTED_OPERATION","settings is not supported on this device");if("macos"===i.platform&&!ty(s))return cM("INVALID_ARGS",tC(s));let p=a?.appBundleId,f="permission"===s?[s,l,u??"",t.positionals?.[3]??"",p??""]:"location"===s&&"set"===l?[s,l,d??"",c??"",p??""]:[s,l,p??""],m=await ch(i,"settings",f,t.flags?.out,{...c5(r,t.flags,p,a?.trace?.outPath)});return f$(n,a,t,m??{setting:s,state:l}),{ok:!0,data:m??{setting:s,state:l}}}async function bn(e){var t,r;let n;if("snapshot"!==e.command||"android"!==e.device.platform)return;let a=k(e.error);if("COMMAND_FAILED"===(t=a).code&&(r=t,n=`${r.message}
91
+ ${r.hint??""}`,/Android UI hierarchy dump timed out/i.test(n)||/Stock UIAutomator fallback was skipped/i.test(n)||/Android accessibility snapshots can be blocked/i.test(n)||function(e){if(!e||"object"!=typeof e)return!1;let t=String(e.errorType??""),r=String(e.message??"");return/TimeoutException/i.test(t)||/timed out/i.test(r)}(t.details?.helper)||function(e){var t;if(!e)return!1;let r=e?.timeoutMs,n=e?.cmd,a=Array.isArray(t=e?.args)?t.map(String):"string"==typeof t?t.split(/\s+/):[];return"number"==typeof r&&"adb"===n&&a.includes("uiautomator")&&a.includes("dump")}(t.details)))return{ok:!1,error:{...a,details:{...a.details??{},androidSnapshotTimeoutScreenshot:await ba(e)}}}}async function ba(e){try{var t,r,n;let a=await d.mkdtemp(f.join(c.tmpdir(),"agent-device-android-snapshot-timeout-")),i=f.join(a,"snapshot-timeout-overlay-refs.png"),o=(t=await ch(e.device,"screenshot",[i],void 0,{...c5(e.logPath,{screenshotNoStabilize:!0},e.session?.appBundleId,e.session?.trace?.outPath),surface:e.session?.surface}),r=i,(n=t,"object"==typeof n&&null!==n&&"path"in n&&"string"==typeof n.path)?t.path:r);await d.access(o);let s=await bi(o,e.session);return eN({level:"warn",phase:"android_snapshot_timeout_screenshot_captured",data:{path:o,overlayRefCount:"overlayRefCount"in s?s.overlayRefCount:void 0,overlayRefsAnnotated:"overlayRefsAnnotated"in s?s.overlayRefsAnnotated:void 0}}),s}catch(t){let e=k(t);return eN({level:"warn",phase:"android_snapshot_timeout_screenshot_failed",data:{error:e.message}}),{captureFailed:!0,error:e.message}}}async function bi(e,t){if(!t?.snapshot)return{path:e,overlayRefsRequested:!0,overlayRefsAnnotated:!1,overlayRefSource:"unavailable",overlayRefCount:0};try{let r=await p5({screenshotPath:e,snapshot:t.snapshot});return{path:e,overlayRefsRequested:!0,overlayRefsAnnotated:r.length>0,overlayRefCount:r.length,overlayRefSource:"session-snapshot",overlayRefs:r}}catch(r){let t=k(r);return eN({level:"warn",phase:"android_snapshot_timeout_screenshot_overlay_failed",data:{path:e,error:t.message}}),{path:e,overlayRefsRequested:!0,overlayRefsAnnotated:!1,overlayRefSource:"session-snapshot",overlayRefCount:0,overlayAnnotationError:t.message}}}async function bo(e){return await bl({...e,command:"snapshot",unsupportedMessage:"snapshot is not supported on this device",execute:async({runtime:e,sessionName:t,req:r,snapshotScope:n})=>{let a=await e.capture.snapshot({session:t,interactiveOnly:r.flags?.snapshotInteractiveOnly,compact:r.flags?.snapshotCompact,depth:r.flags?.snapshotDepth,scope:n,raw:r.flags?.snapshotRaw,forceFull:r.flags?.snapshotForceFull});return{data:a,record:{kind:"snapshot",nodes:a.nodes.length,truncated:a.truncated}}}})}async function bs(e){return await bl({...e,command:"diff",unsupportedMessage:"diff is not supported on this device",execute:async({runtime:e,sessionName:t,req:r,snapshotScope:n})=>{let a=await e.capture.diffSnapshot({session:t,interactiveOnly:r.flags?.snapshotInteractiveOnly,compact:r.flags?.snapshotCompact,depth:r.flags?.snapshotDepth,scope:n,raw:r.flags?.snapshotRaw});return{data:a,record:{kind:"diff",mode:"snapshot",baselineInitialized:a.baselineInitialized,summary:a.summary}}}})}async function bl(e){let{req:t,sessionName:r,logPath:n,sessionStore:a}=e,{session:i,device:o}=await fL(a,r,t.flags);if(!cY(e.command,o))return cM("UNSUPPORTED_OPERATION",e.unsupportedMessage);let s=function(e,t){let r;if(!e||!e.trim().startsWith("@"))return{ok:!0,scope:e};if(!t?.snapshot)return cM("INVALID_ARGS","Ref scope requires an existing snapshot in session.");let n=tq(e.trim());if(!n)return cM("INVALID_ARGS",`Invalid ref scope: ${e}`);for(let e of[t.snapshot,...t.snapshotScopeSource?[t.snapshotScopeSource]:[]]){let t=tB(e.nodes,n);if(r=t?t1(t,e.nodes):void 0)break}return r?{ok:!0,scope:r}:cM("COMMAND_FAILED",`Ref ${e} not found or has no label`)}(t.flags?.snapshotScope,i);return s.ok?await fT(i,o,async()=>{var l,u;let d,c,p=function(e){let{req:t,sessionName:r,logPath:n,sessionStore:a,session:i,device:o,snapshotScope:s}=e;return tR({backend:function(e){let{req:t,logPath:r,session:n,device:a,snapshotScope:i}=e;return{platform:a.platform,captureSnapshot:async(e,o)=>{let s=await py({device:a,session:n,flags:t.flags,outPath:o?.outPath??t.flags?.out,logPath:r,snapshotScope:i});return{snapshot:s.snapshot,analysis:s.analysis,androidSnapshot:s.androidSnapshot,freshness:s.freshness,appName:n?.appBundleId?n.appName??n.appBundleId:void 0,appBundleId:n?.appBundleId}}}}({req:t,logPath:n,session:i,device:o,snapshotScope:s}),...fK("snapshot"),sessions:pD({sessionName:r,getSession:()=>a.get(r),recordOptions:{includeSnapshot:!0},setRecord:e=>{var n;let i=function(e){if(!e.snapshot)throw new D("UNKNOWN","snapshot runtime did not produce session state");return e}(e),s=a.get(r);a.set(r,function(e){var t,r;let{current:n,sessionName:a,device:i,record:o,refScopedSnapshot:s}=e,l=(t=n,r=o,s&&r.snapshot?.nodes.length===0&&t?.snapshot!==void 0),u=l?n.snapshot:o.snapshot,d=function(e){let{session:t,sessionName:r,device:n,snapshot:a,appBundleId:i}=e;return t?{...t,snapshot:a}:{name:r,device:n,createdAt:Date.now(),appBundleId:i,snapshot:a,actions:[]}}({session:n,sessionName:a,device:i,snapshot:u,appBundleId:o.appBundleId});return d.snapshotScopeSource=function(e){let{current:t,keepCurrentSnapshot:r,refScopedSnapshot:n}=e;if(n)return r?t?.snapshotScopeSource:t?.snapshotScopeSource??t?.snapshot}({current:n,keepCurrentSnapshot:l,refScopedSnapshot:s}),o.appName&&(d.appName=o.appName),d}({current:s,sessionName:r,device:o,record:i,refScopedSnapshot:(n=t,n.flags?.snapshotScope?.trim().startsWith("@")===!0)}))}})})}({req:t,sessionName:r,logPath:n,sessionStore:a,session:i,device:o,snapshotScope:s.scope});try{c=await e.execute({runtime:p,sessionName:r,req:t,snapshotScope:s.scope})}catch(r){let t=await bn({error:r,command:e.command,logPath:n,session:i,device:o});if(!t)throw r;return t}return(d=(l={req:t,sessionName:r,sessionStore:a,result:c.record}).sessionStore.get(l.sessionName))&&l.sessionStore.recordAction(d,{command:l.req.command,positionals:l.req.positionals??[],flags:l.req.flags??{},result:"snapshot"===(u=l.result).kind?{nodes:u.nodes,truncated:u.truncated}:{mode:u.mode,baselineInitialized:u.baselineInitialized,summary:u.summary}}),{ok:!0,data:c.data}}):s}let bu=ek.snapshot,bd={snapshot:async({req:e,sessionName:t,logPath:r,sessionStore:n})=>await bo({req:e,sessionName:t,logPath:r,sessionStore:n}),diff:async({req:e,sessionName:t,logPath:r,sessionStore:n})=>e.positionals?.[0]!=="snapshot"?cM("INVALID_ARGS","diff currently supports only: diff snapshot"):await bs({req:e,sessionName:t,logPath:r,sessionStore:n}),wait:async({req:e,sessionName:t,logPath:r,sessionStore:n})=>await me({req:e,sessionName:t,logPath:r,sessionStore:n}),alert:async({req:e,sessionName:t,logPath:r,sessionStore:n})=>{let{session:a,device:i}=await fL(n,t,e.flags);return await fT(a,i,async()=>await I6({req:e,logPath:r,sessionStore:n,session:a,device:i}))},settings:async({req:e,sessionName:t,logPath:r,sessionStore:n})=>{let a,i,o,s=(a=e.positionals?.[0]?.toLowerCase(),i=e.positionals?.[1]?.toLowerCase(),o=e.positionals?.[2]?.toLowerCase(),a&&i&&("permission"!==a||o)&&("location"!==a||"set"!==i||e.positionals?.[2]&&e.positionals?.[3])?{ok:!0,parsed:{setting:a,state:i,permissionTarget:o,latitude:e.positionals?.[2],longitude:e.positionals?.[3]}}:cM("INVALID_ARGS",tS));if(!s.ok)return s;let{session:l,device:u}=await fL(n,t,e.flags);return await fT(l,u,async()=>await br({req:e,logPath:r,sessionStore:n,session:l,device:u,parsed:s.parsed}))}};async function bc(e){let t=e.req.command;if(!bu.has(t))return null;let r=bd[t];return r?await r(e):cM("COMMAND_FAILED",`Snapshot command has no handler: ${t}`)}async function bp(e){let{req:t,sessionName:r,logPath:n,sessionStore:a,leaseRegistry:i,invoke:o,invokeReplayAction:s,androidAdbExecutor:l,contextFromFlags:u}=e,d=await m1({req:t,leaseRegistry:i});if(d)return d;let c=await IG({req:t,sessionName:r,logPath:n,sessionStore:a,invoke:o,invokeReplayAction:s,androidAdbExecutor:l});if(c)return c;let p=await bc({req:t,sessionName:r,logPath:n,sessionStore:a});if(p)return p;let f=await m2({req:t,sessionName:r,logPath:n,sessionStore:a,contextFromFlags:u});if(f)return f;let m=await h2({req:t,sessionName:r,sessionStore:a,logPath:n});if(m)return m;let h=await mm({req:t,sessionName:r,logPath:n,sessionStore:a,invoke:o});if(h)return h;let w=await mX({req:t,sessionName:r,logPath:n,sessionStore:a,contextFromFlags:u});return w||null}function bf(e,t){if(!t)return[];let r=[],n=e.device,a=t.platform;if(a&&!r6(n.platform,a)&&r.push({key:"platform",value:t.platform}),t.target&&t.target!==(n.target??"mobile")&&r.push({key:"target",value:t.target}),t.udid&&("ios"!==n.platform||t.udid!==n.id)&&r.push({key:"udid",value:t.udid}),t.serial&&("android"!==n.platform||t.serial!==n.id)&&r.push({key:"serial",value:t.serial}),t.device&&t.device.trim().toLowerCase()!==n.name.trim().toLowerCase()&&r.push({key:"device",value:t.device}),t.iosSimulatorDeviceSet){let e=t.iosSimulatorDeviceSet.trim(),a=n.simulatorSetPath?.trim();("ios"!==n.platform||"simulator"!==n.kind||e!==a)&&r.push({key:"iosSimulatorDeviceSet",value:t.iosSimulatorDeviceSet})}if(t.androidDeviceAllowlist){let e=ei(t.androidDeviceAllowlist);"android"===n.platform&&e.has(n.id)||r.push({key:"androidDeviceAllowlist",value:t.androidDeviceAllowlist})}return r}function bm(e){return`${function(e){switch(e){case"iosSimulatorDeviceSet":return"--ios-simulator-device-set";case"androidDeviceAllowlist":return"--android-device-allowlist";default:return`--${e}`}}(e.key)}=${e.value}`}let bh=["target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist"],bw=new Set([eD.apps,eD.devices]);function bg(e){return"string"==typeof e&&e.trim().length>0}let by=ek.selectorValidationExempt,bv=ek.leaseAdmissionExempt,bI=new Set(bv);async function bb(e){let{req:t,sessionName:r,sessionStore:n}=e,a=n.get(r);if(a)return`device:${a.device.id}`;if("open"===t.command||cD(t.flags))try{let e=await oO(t.flags??{});return`device:${e.id}`}catch{}return`session:${r}`}let bA=new WeakMap;async function bS(e){var t,r;let n,a,i,{sessionStore:o,leaseRegistry:s}=e,l=(n={...(t=function(e){let t=ej(e.meta?.sessionIsolation??e.flags?.sessionIsolation),r=e.meta?.tenantId??e.flags?.tenant,n=eO(r);if(r&&!n)throw new D("INVALID_ARGS","Invalid tenant id. Use 1-128 chars: letters, numbers, dot, underscore, hyphen.");if("tenant"!==t)return e;if(!n)throw new D("INVALID_ARGS","session isolation mode tenant requires --tenant (or meta.tenantId).");let a=e.session||"default";return a.startsWith(`${n}:`)?{...e,meta:{...e.meta,tenantId:n,sessionIsolation:t}}:{...e,session:`${n}:${a}`,meta:{...e.meta,tenantId:n,sessionIsolation:t}}}(e.req)).flags??{}},((a=tw(t.command,n))||!t.flags)&&a?{...t,flags:n}:t);eN({level:"info",phase:"request_start",data:{session:l.session,command:l.command,tenant:l.meta?.tenantId,isolation:l.meta?.sessionIsolation}});let u=l.command;!function(e,t){if(bv.has(e.command)||e.meta?.sessionIsolation!=="tenant")return;let r=m0(e);t.assertLeaseAdmission({tenantId:r.tenantId,runId:r.runId,leaseId:r.leaseId,backend:r.leaseBackend})}(l,s);let d=function(e,t){var r;let n,a=e.session||"default";if(r=e,"string"==typeof(n=r.flags?.session)&&n.trim().length>0||"default"!==a||t.has(a))return a;let i=t.toArray(),o=i[0];return void 0!==o&&1===i.length?o.name:a}(l,o),c=bI.has(u)?null:await bb({req:l,sessionName:d,sessionStore:o}),p=(r=s,(i=bA.get(r))||(i=new Map,bA.set(r,i)),i);return{req:l,command:u,sessionName:d,throwIfCanceled:()=>ry(l.meta?.requestId),runLocked:async e=>(ry(l.meta?.requestId),c)?await r4(p,c,async()=>(ry(l.meta?.requestId),await e())):await e()}}function bx(e){var t,r;let{scope:n,logPath:a,sessionStore:i,trackDownloadableArtifact:o}=e;n.throwIfCanceled();let s=i.get(n.sessionName);s&&(!function(e){var t,r;let n,a;if(!((a=(r=e).recording)&&"ios"===r.device.platform&&"ios"!==a.platform&&!1!==a.showTouches))return;let i=e.recording,o=(t=e.device.id,(n=n5.get(t))?{sessionId:n.sessionId,alive:an(n.child.pid)}:null);if(!i.runnerSessionId){o?.alive&&(i.runnerSessionId=o.sessionId);return}if(!o?.alive){i.invalidatedReason??="iOS runner session exited during recording";return}o.sessionId!==i.runnerSessionId&&(i.invalidatedReason??="iOS runner session restarted during recording")}(s),i.set(n.sessionName,s));let l=function(e,t){let r=e.meta?.lockPolicy;if(!r)return e;let n={...e.flags??{}},a=bw.has(e.command),i=a?[]:t?bf(t,n):function(e,t,r){var n,a;let i=[];if(void 0!==e.platform&&t&&(n=e.platform,a=t,n&&a&&n!==a&&("apple"===n?!r8(a):"apple"!==a||!r8(n)))&&i.push({key:"platform",value:e.platform}),"open"===r)return i;for(let t of bh){let r=e[t];bg(r)&&i.push({key:t,value:r})}return i}(n,e.meta?.lockPlatform,e.command),o=e.meta?.lockPlatform;if(0===i.length){var s,l,u;return s=a,l=t,u=n,!o||l||void 0!==u.platform||s&&bh.some(e=>bg(u[e]))||(n.platform=o),{...e,flags:n}}if("strip"===r)return function(e,t,r,n){if(n){(function(e,t){for(let r of t)delete e[r.key]})(e,t),e.platform=n.device.platform;return}var a=e,i=r;for(let e of bh)delete a[e];i&&(a.platform=i)}(n,i,o,t),{...e,flags:n};throw new D("INVALID_ARGS",`${e.command} cannot override session lock policy with ${i.map(bm).join(", ")}. Unset those selectors or remove the request lock policy.`)}(n.req,s),u=e=>(function(e,t,r){let n=eS();if(!t.ok){eN({level:"error",phase:"request_failed",data:{code:t.error.code,message:t.error.message}});let e=ex({force:!0})??void 0;return{ok:!1,error:k(new D(N(t.error.code),t.error.message,{...t.error.details??{},hint:t.error.hint,diagnosticId:t.error.diagnosticId,logPath:t.error.logPath}),{diagnosticId:n.diagnosticId,logPath:e})}}return eN({level:"info",phase:"request_success"}),ex(),{ok:!0,data:function(e,t,r){var n,a;let i;if(!t)return t;let o=(n=e,i=Array.isArray((a=t).artifacts)?[...a.artifacts]:[],"screenshot"!==n.command||i.some(e=>e?.field==="path")||"string"!=typeof a.path||i.push({field:"path",path:a.path,localPath:n.meta?.clientArtifactPaths?.path,fileName:f.basename(n.meta?.clientArtifactPaths?.path??a.path)}),i.filter(e=>!!(e&&"string"==typeof e.field&&"string"==typeof e.path&&"string"==typeof e.localPath&&e.localPath.length>0)));return 0===o.length?t:{...t,artifacts:o.map(t=>{let n=t.path;return{field:t.field,artifactId:r({artifactPath:n,tenantId:e.meta?.tenantId,fileName:t.fileName}),fileName:t.fileName,localPath:t.localPath}})}}(e,t.data,r)}})(l,e,o);if(s?.recording?.invalidatedReason&&"record"!==(t=n.command)&&"close"!==t)return{type:"response",response:u({ok:!1,error:{code:"COMMAND_FAILED",message:s.recording.invalidatedReason}})};!s||l.meta?.lockPolicy||(r=n.command,by.has(r))||function(e,t){let r=bf(e,t);if(0!==r.length){var n;let t,a,i;throw new D("INVALID_ARGS",`Session "${e.name}" is bound to ${(t=(n=e).device.platform,a=n.device.name.trim(),i=n.device.id,`${t} device "${a}" (${i})`)} and cannot be used with ${r.map(bm).join(", ")}. Use a different --session name or close this session first.`)}}(s,l.flags);let d=(e,t,r)=>{let n;return{...c5(a,e,t,r,n=eS().requestId),requestId:n}};return{type:"scope",scope:{req:l,sessionName:n.sessionName,existingSession:s,finalize:u,contextFromFlags:d,handlerContextFromFlags:(e,t,r)=>({...d(e,t,r),surface:i.get(n.sessionName)?.surface})}}}async function b_(e){let{lockedScope:t,logPath:r,sessionStore:n}=e,a=n.get(t.sessionName);if(!a)return t.finalize({ok:!1,error:{code:"SESSION_NOT_FOUND",message:"No active session. Run open first."}});let i=await fD({req:t.req,session:a,sessionName:t.sessionName,logPath:r,sessionStore:n,contextFromFlags:t.contextFromFlags});return t.finalize(i)}function bN(e){eN({level:"error",phase:"request_failed",data:{error:e instanceof Error?e.message:String(e)}});let t=eS(),r=ex({force:!0})??void 0;return{ok:!1,error:k(e,{diagnosticId:t.diagnosticId,logPath:r})}}async function bM(e,t=5e3){await Promise.all(e.map(async e=>{let r;await new Promise(n=>{r=setTimeout(()=>{!function(e){e.destroyConnections?.();let t="closeAllConnections"in e?e.closeAllConnections:void 0;if("function"==typeof t)return t.call(e);let r="closeIdleConnections"in e?e.closeIdleConnections:void 0;"function"==typeof r&&r.call(e)}(e),n()},t);try{e.close(()=>n())}catch{n()}}),r&&clearTimeout(r)}))}function bk(e){l.existsSync(e)&&l.unlinkSync(e)}function bD(e){if(!l.existsSync(e))return null;try{let t=JSON.parse(l.readFileSync(e,"utf8"));if(!Number.isInteger(t.pid)||t.pid<=0)return null;return t}catch{return null}}function bP(e){let t=bD(e);if(!t||t.pid===process.pid)try{l.existsSync(e)&&l.unlinkSync(e)}catch{}}function bO(e){if(void 0===e)return;let t=Number(e);if(Number.isInteger(t))return t}function bR(e,t){return new Promise((r,n)=>{e.once("error",n),e.listen(0,"127.0.0.1",()=>{e.off("error",n);let a=e.address();"object"==typeof a&&a?.port?r(a.port):n(new D("COMMAND_FAILED",t))})})}(async function(e={}){let t,r,n=e.env??process.env,a=e.stdout??process.stdout,i=e.stderr??process.stderr,s=e.exit??(e=>process.exit(e)),{baseDir:u,infoPath:d,lockPath:c,logPath:p,sessionsDir:h}=eQ(n.AGENT_DEVICE_STATE_DIR),w=e0(n.AGENT_DEVICE_DAEMON_SERVER_MODE);var g,y,v,I=h;if(l.existsSync(I))for(let e of l.readdirSync(I,{withFileTypes:!0})){if(!e.isDirectory())continue;let t=f.join(I,e.name,aB);if(l.existsSync(t))try{let e=aj(l.readFileSync(t,"utf8"));if(e&&function(e){let t,r=em(e.pid);if(!r||e.startTime&&r!==e.startTime)return!1;let n=ew(e.pid);return!!n&&!!((t=n.toLowerCase().replaceAll("\\","/")).includes("log stream")||t.includes("logcat")||t.includes("devicectl device log stream"))&&(!e.command||n===e.command)}(e))try{process.kill(e.pid,"SIGTERM")}catch{}}catch{}finally{aW(t)}}let b=new aq(h),A=new oa({maxActiveSimulatorLeases:bO(n.AGENT_DEVICE_MAX_SIMULATOR_LEASES),defaultLeaseTtlMs:bO(n.AGENT_DEVICE_LEASE_TTL_MS),minLeaseTtlMs:bO(n.AGENT_DEVICE_LEASE_MIN_TTL_MS),maxLeaseTtlMs:bO(n.AGENT_DEVICE_LEASE_MAX_TTL_MS)}),S=eH(),x=o.randomBytes(24).toString("hex"),_=em(process.pid)??void 0,N=eM(),P=function(e){let{logPath:t,token:r,androidAdbProvider:n,appleRunnerProvider:a,appleToolProvider:i,linuxToolProvider:o,appLogProvider:s,recordingProvider:l,deviceInventoryProvider:u,trackDownloadableArtifact:d}=e,{sessionStore:c,leaseRegistry:p}=e;async function f(e){let m=!!(e.meta?.debug||e.flags?.verbose);return await eb({session:e.session,requestId:e.meta?.requestId,command:e.command,debug:m,logPath:t},async()=>{if(e.token!==r)return{ok:!1,error:k(new D("UNAUTHORIZED","Invalid token"))};try{return await oC(u,async()=>{let u=await bS({req:e,sessionStore:c,leaseRegistry:p});return await u.runLocked(async()=>{let e=bx({scope:u,logPath:t,sessionStore:c,trackDownloadableArtifact:d});if("response"===e.type)return e.response;let m=e.scope;return await cU({req:m.req,existingSession:m.existingSession,providers:{androidAdbProvider:n,appleRunnerProvider:a,appleToolProvider:i,linuxToolProvider:o,appLogProvider:s,recordingProvider:l}},async e=>{let n=await bp({req:m.req,sessionName:m.sessionName,logPath:t,sessionStore:c,leaseRegistry:p,invoke:f,invokeReplayAction:function(e){let{parentScope:t,providerScope:r,handleRequest:n,deps:a}=e;return async e=>{var i,o;if(i=e,o=t,!(i.session===o.sessionName&&ek.replayScopedAction.has(i.command)))return await n(e);if(e.token!==a.token)return{ok:!1,error:k(new D("UNAUTHORIZED","Invalid token"))};try{let i=await bS({req:e,sessionStore:a.sessionStore,leaseRegistry:a.leaseRegistry});if(i.sessionName!==t.sessionName)return await n(e);let o=bx({scope:i,logPath:a.logPath,sessionStore:a.sessionStore,trackDownloadableArtifact:a.trackDownloadableArtifact});if("response"===o.type)return o.response;let s=o.scope,l=await bp({req:s.req,sessionName:s.sessionName,logPath:a.logPath,sessionStore:a.sessionStore,leaseRegistry:a.leaseRegistry,invoke:n,androidAdbExecutor:r.androidAdbExecutor,contextFromFlags:s.handlerContextFromFlags});if(l)return s.finalize(l);return await b_({lockedScope:s,logPath:a.logPath,sessionStore:a.sessionStore})}catch(e){return bN(e)}}}({parentScope:m,providerScope:e,handleRequest:f,deps:{logPath:t,token:r,sessionStore:c,leaseRegistry:p,trackDownloadableArtifact:d}}),androidAdbExecutor:e.androidAdbExecutor,contextFromFlags:m.handlerContextFromFlags});return n?m.finalize(n):await b_({lockedScope:m,logPath:t,sessionStore:c})})})})}catch(e){return bN(e)}})}return f}({logPath:p,token:x,sessionStore:b,leaseRegistry:A,trackDownloadableArtifact:iP}),O=async e=>{await eb({command:"daemon",session:"daemon",logPath:p,debug:!0},async()=>{eN({level:"error",phase:"daemon_fatal",data:{error:e instanceof Error?e.message:String(e)}}),ex({force:!0})})},R=async e=>{let t=go(e,e.name).catch(t=>{i.write(`Daemon session teardown error (${e.name}): ${t instanceof Error?t.message:String(t)}
92
+ `)});await Promise.race([t,e8(5e3).then(()=>{i.write(`Daemon session teardown timed out (${e.name}).
93
+ `)})]),b.writeSessionLog(e),b.delete(e.name)},E=async()=>{let e=b.toArray();await Promise.all(e.map(R))},C=async()=>{let e,t,r=[];if("http"!==w){let t,n,a=(t=new Set,(n=m.createServer(e=>{t.add(e),e.on("close",()=>t.delete(e));let r="",n=0,a=new Set,i=!1,o=()=>{if(!i&&0!==n){for(let e of(i=!0,a))rf(e);eN({level:"warn",phase:"request_client_disconnected",data:{inFlightRequests:n}}),(async()=>{try{let e=Date.now()+15e3;for(;n>0&&Date.now()<e&&(await at(),!(n<=0));)await e8(200)}catch(e){eN({level:"error",phase:"request_client_disconnect_abort_failed",data:{message:e instanceof Error?e.message:String(e),inFlightRequests:n}})}})()}};e.setEncoding("utf8"),e.on("close",o),e.on("error",o),e.on("data",async t=>{let i=eR(r,t);for(let t of(r=i.buffer,i.lines)){let r,i;n+=1;let o=!1;try{let n=JSON.parse(t);if(o=eU(n),i=rc(n.meta?.requestId,"socket"),n.meta={...n.meta,requestId:i},a.add(i),rp(i),rh(i))throw rg();r=await iq(o?t=>{e.destroyed||e.write(e5(t))}:void 0,async()=>await P(n))}catch(e){r={ok:!1,error:k(e)}}finally{n-=1,i&&(a.delete(i),rm(i))}e.destroyed||e.write(o?eF(r):`${JSON.stringify(r)}
94
+ `)}})})).destroyConnections=()=>{for(let e of t)e.destroy();t.clear()},n);r.push(a),e=await bR(a,"Failed to bind socket server")}if("socket"!==w){let e=await i8({handleRequest:P,token:x});r.push(e),t=await bR(e,"Failed to bind HTTP server")}return{servers:r,socketPort:e,httpPort:t}};if(!function(e,t,r){l.existsSync(e)||l.mkdirSync(e,{recursive:!0});let n=JSON.stringify(r,null,2),a=()=>{try{return l.writeFileSync(t,n,{flag:"wx",mode:384}),!0}catch(e){if("EEXIST"===e.code)return!1;throw e}};if(a())return!0;let i=bD(t);if(i?.pid&&i.pid!==process.pid&&ev(i.pid,i.processStartTime))return!1;try{l.unlinkSync(t)}catch{}return a()}(u,c,{pid:process.pid,version:S,startedAt:Date.now(),processStartTime:_}))return i.write("Daemon lock is held by another process; exiting.\n"),s(0),null;let L=[];try{let e,n=await C();L=n.servers,t=n.socketPort,r=n.httpPort,g=t,y=r,v={socketPort:g,httpPort:y,token:x,version:S,codeSignature:N,processStartTime:_},l.existsSync(u)||l.mkdirSync(u,{recursive:!0}),l.writeFileSync(p,""),e=v.socketPort&&v.httpPort?"dual":v.httpPort?"http":"socket",l.writeFileSync(d,JSON.stringify({port:v.socketPort,httpPort:v.httpPort,transport:e,token:v.token,pid:process.pid,version:v.version,codeSignature:v.codeSignature,processStartTime:v.processStartTime,stateDir:u},null,2),{mode:384}),g&&a.write(`AGENT_DEVICE_DAEMON_PORT=${g}
94
95
  `),y&&a.write(`AGENT_DEVICE_DAEMON_HTTP_PORT=${y}
95
- `)}catch(t){let e=D(t);for(let t of(i.write(`Daemon error: ${e.message}
96
- `),L))try{t.close(()=>{})}catch{}return bd(d),bp(c),s(1),null}let $=!1,T=async(e={})=>{$||($=!0,e.cause&&await k(e.cause),await bu(L),await C(),await n5(),bd(d),bp(c),s(e.exitCode??0))};return!1!==e.registerProcessHandlers&&(process.on("SIGINT",()=>{T()}),process.on("SIGTERM",()=>{T()}),process.on("SIGHUP",()=>{T()}),process.on("uncaughtException",e=>{let t=e instanceof O?e:D(e);i.write(`Daemon error: ${t.message}
97
- `),T({exitCode:1,cause:e})}),process.on("unhandledRejection",e=>{let t=e instanceof Error?e:Error(String(e)),r=t instanceof O?t:D(t);i.write(`Daemon error: ${r.message}
98
- `),T({exitCode:1,cause:t})})),{httpPort:r,shutdown:T,socketPort:t,token:_}})().catch(e=>{let t=D(e);process.stderr.write(`Daemon error: ${t.message}
96
+ `)}catch(t){let e=M(t);for(let t of(i.write(`Daemon error: ${e.message}
97
+ `),L))try{t.close(()=>{})}catch{}return bk(d),bP(c),s(1),null}let T=!1,$=async(e={})=>{T||(T=!0,e.cause&&await O(e.cause),await bM(L),await E(),await ar(),bk(d),bP(c),s(e.exitCode??0))};return!1!==e.registerProcessHandlers&&(process.on("SIGINT",()=>{$()}),process.on("SIGTERM",()=>{$()}),process.on("SIGHUP",()=>{$()}),process.on("uncaughtException",e=>{let t=e instanceof D?e:M(e);i.write(`Daemon error: ${t.message}
98
+ `),$({exitCode:1,cause:e})}),process.on("unhandledRejection",e=>{let t=e instanceof Error?e:Error(String(e)),r=t instanceof D?t:M(t);i.write(`Daemon error: ${r.message}
99
+ `),$({exitCode:1,cause:t})})),{httpPort:r,shutdown:$,socketPort:t,token:x}})().catch(e=>{let t=M(e);process.stderr.write(`Daemon error: ${t.message}
99
100
  `),process.exit(1)});